Skip to content

Technical Design

Purpose

Technical Design is the story-level implementation design artifact. Its unique job is to make one user story buildable by naming the concrete component changes, files, interfaces, data model changes, security implications, tests, rollback path, and implementation sequence.

Technical Design applies shared interface contracts; it does not define them. When exact API, CLI, event, schema, config, telemetry, or adapter surface is needed, reference the governing Contract ID. If the story uncovers a missing or changed shared surface, create or update the Contract first, then reference it from the TD.

It inherits Architecture and Solution Design. For what belongs at this level versus those higher levels, see the zoom-stack matrix in workflows/activities/02-design/README.md; if the story forces a change at a higher level, update that governing artifact first.

Example

Show a worked example of this artifact
---
ddx:
  id: example.technical-design.depositmatch.upload-csv
  authoring:
    home: repo
  depends_on:
    - example.user-story.depositmatch.upload-csv
    - example.solution-design.depositmatch.csv-import
    - example.contract.depositmatch.import-session-api
---

# Technical Design: TD-001-upload-csv-files

**User Story**: [[US-001-upload-csv-files]] | **Feature**:
[[FEAT-001-csv-import-column-mapping]] | **Solution Design**:
[[SD-001-csv-import-column-mapping]]

## Scope

- Story-level design for uploading one bank CSV and one invoice CSV for a
  selected client and creating a draft import session.
- Inherits API-001, ADR-001, and the FEAT-001 solution design.
- Does not implement column mapping, row validation, import confirmation, or
  match generation.

## Technical Approach

**Strategy**: Implement the API-001 upload contract in the Fastify API and add a
React upload step that calls it. Store encrypted originals through the existing
source-file storage adapter and persist draft session metadata in PostgreSQL.

**Key Decisions**:

- Use the API-001 response shape directly in the UI state so the mapping step
  receives `importSessionId` and `next.href` without client-side inference.
- Validate file extension and MIME hints in the UI for quick feedback, but
  enforce all contract rules in the API before storage.
- Keep row parsing out of this story; parsing begins in the mapping/validation
  stories.

**Trade-offs**:

- Duplicating light file-type checks in UI and API improves feedback but means
  API tests remain the source of truth.
- Creating the session before row validation lets the reviewer recover from
  upload issues but requires draft-session cleanup later.

## Component Changes

### Modified: Web Import Workflow

- **Current State**: No DepositMatch import workflow exists.
- **Changes**: Add upload controls for bank and invoice CSV files, call API-001,
  show upload errors, and route successful responses to mapping review.
- **Files**: `apps/web/src/features/import/ImportSessionUpload.tsx`,
  `apps/web/src/features/import/importApi.ts`,
  `apps/web/src/routes/clientImportRoutes.tsx`

### New: API Import Session Route

- **Purpose**: Implement the API-001 import session route.
- **Interfaces**: Input/output semantics are governed by API-001; this TD owns
  local route wiring only.
- **Files**: `apps/api/src/routes/importSessions.ts`,
  `apps/api/src/schemas/importSessionSchemas.ts`

### New: Import Upload Service

- **Purpose**: Authorize client access, enforce file rules, store encrypted
  originals, and persist draft session/file metadata.
- **Interfaces**: Input: client ID, authenticated user, two file streams;
  Output: draft import-session DTO.
- **Files**: `apps/api/src/services/importUploadService.ts`,
  `apps/api/src/storage/sourceFileStore.ts`,
  `apps/api/src/repositories/importSessionRepository.ts`

## API/Interface Design

| Surface | Governing Contract | Story-Level Usage |
|---------|--------------------|-------------------|
| Import session API | API-001 | Route handler, upload service, and UI client call the existing contract without changing its normative surface. |

## Data Model Changes

```sql
CREATE TABLE import_sessions (
    id UUID PRIMARY KEY,
    client_id UUID NOT NULL,
    status TEXT NOT NULL CHECK (status IN ('draft', 'mapping', 'confirmed')),
    created_by UUID NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE import_files (
    id UUID PRIMARY KEY,
    import_session_id UUID NOT NULL REFERENCES import_sessions(id),
    source_type TEXT NOT NULL CHECK (source_type IN ('bank_csv', 'invoice_csv')),
    original_name TEXT NOT NULL,
    size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),
    storage_key TEXT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
```

## Integration Points

| From | To | Method | Data |
|------|----|--------|------|
| Web Import Workflow | API Import Session Route | HTTPS multipart POST | bank CSV, invoice CSV |
| API Import Session Route | Import Upload Service | Internal call | authenticated user, client ID, files |
| Import Upload Service | Source File Store | S3 SDK | encrypted file stream and metadata |
| Import Upload Service | PostgreSQL | SQL transaction | session and file metadata |

### External Dependencies

- **S3 Source File Store**: Store encrypted originals. Fallback: return 503
  `import-storage-unavailable`; no draft session should be committed.

## Security

- **Authentication**: Require authenticated firm user.
- **Authorization**: User must have access to the requested client.
- **Data Protection**: Store files encrypted; never log raw row contents.
- **Threats**: Path leakage from uploaded filenames, oversized uploads, and
  unauthorized client access. Strip path components, enforce 10 MB per-file
  limit, and return 404 for inaccessible clients.

## Performance

- **Expected Load**: Pilot firms upload at most two 10 MB files per import
  session.
- **Response Target**: Return success or contract error in under 2 seconds
  before row parsing.
- **Optimizations**: Stream file upload to storage; do not buffer entire files
  in application memory.

## Testing

Each governing-story AC-ID is realized below (ADR-009 — AC text lives in [[US-001]], not here):

- [ ] **Unit** (US-001-AC1, US-001-AC2): `importUploadService` rejects missing
  files, non-CSV files, and inaccessible clients.
- [ ] **Integration** (US-001-AC1, US-001-AC3): API route returns API-001
  success shape and stores draft session/file metadata in one transaction.
- [ ] **API** (US-001-AC2): Contract tests for 201, 400 `missing-import-file`,
  415 `unsupported-import-file-type`, and 503 `import-storage-unavailable`.
- [ ] **Security**: Verify raw CSV row values are absent from logs for failed
  and successful uploads.
- [ ] **UI** (US-001-AC1): Upload component routes to `next.href` after
  successful upload and renders problem-details errors.

## Migration & Rollback

- **Backward Compatibility**: New tables and endpoint only; no existing API
  behavior changes.
- **Data Migration**: Create `import_sessions` and `import_files` tables.
- **Feature Toggle**: Hide upload entry point behind `csvImportV1`.
- **Rollback**: Disable `csvImportV1`; leave unused draft-session tables in
  place until cleanup migration.

## Implementation Sequence

1. Add database migration and repository. Files:
   `apps/api/migrations/001_import_sessions.sql`,
   `apps/api/src/repositories/importSessionRepository.ts`. Tests:
   `apps/api/test/repositories/importSessionRepository.test.ts`.
2. Add source-file storage adapter and upload service. Files:
   `apps/api/src/storage/sourceFileStore.ts`,
   `apps/api/src/services/importUploadService.ts`. Tests:
   `apps/api/test/services/importUploadService.test.ts`.
3. Add Fastify route and contract tests. Files:
   `apps/api/src/routes/importSessions.ts`,
   `apps/api/src/schemas/importSessionSchemas.ts`. Tests:
   `apps/api/test/routes/importSessions.test.ts`.
4. Add React upload UI and API client. Files:
   `apps/web/src/features/import/ImportSessionUpload.tsx`,
   `apps/web/src/features/import/importApi.ts`. Tests:
   `apps/web/src/features/import/ImportSessionUpload.test.tsx`.

**Prerequisites**: API-001 accepted; S3 bucket and database connection available
in development/test environments.

## Risks

| Risk | Prob | Impact | Mitigation |
|------|------|--------|------------|
| Multipart parsing buffers large files in memory | M | H | Use streaming parser configuration and add memory regression test. |
| UI and API validation drift | M | M | Treat API contract tests as authoritative; keep UI validation advisory only. |
| Draft sessions accumulate after abandoned uploads | M | L | Add cleanup task in a later story; do not block US-001 on cleanup automation. |

## Diagnostic Wiring

Upload service and object-storage adapter emit safe outcomes under the parent
SD and diagnostic Contract. The runner captures safe verification evidence;
privacy applies before console, file and export. The diagnostic Contract must
exist before diagnostic wiring is ready, rather than defining fields here.
Receiver/correlation and capture-failure proof remain required for that slice.

## Formal Specification

`formal-methods` is not selected for this straightforward CSV import slice; no
formal analysis claim is made. If a broader project selects it for a critical
coordination protocol, this import design records non-applicability: it does not
change that protocol or its mapped guards. Ordinary validation, security and
integration tests still apply; no analyzer/proof run is required for this slice.

Reference

ActivityDesign — Decide how to build it. Capture trade-offs, contracts, and architecture decisions.
Default locationdocs/helix/02-design/technical-designs/TD-{id}-{name}.md
RequiresNone
EnablesNone
InformsTest Plan
Implementation Plan
HELIX documentsdocs/helix/02-design/technical-designs/TD-012-artifact-types-navigation.md
Generation prompt
Show the full generation prompt
# Technical Design for User Story Prompt

Create a concise technical design for one user story.

## Purpose

Technical Design is the **story-level implementation design artifact**. Its
unique job is to make one user story buildable by naming the concrete component
changes, files, interfaces, data model changes, security implications, tests,
rollback path, and implementation sequence.

Technical Design applies shared interface contracts; it does not define them.
When exact API, CLI, event, schema, config, telemetry, or adapter surface is
needed, reference the governing Contract ID. If the story uncovers a missing or
changed shared surface, create or update the Contract first, then reference it
from the TD.

It inherits Architecture and Solution Design. For what belongs at this level
versus those higher levels, see the zoom-stack matrix in
`workflows/activities/02-design/README.md`; if the story forces a change at a
higher level, update that governing artifact first.

## Reference Anchors

Use these local resource summaries as grounding:

- `docs/resources/google-small-cls.md` grounds bounded implementation slices
  with related tests and rollback.
- `docs/resources/cucumber-executable-specifications.md` grounds mapping
  acceptance criteria to observable tests.

## Active Concerns

For each concern selected in `docs/helix/01-frame/concerns.md`, apply its declared
`## Artifact Impact` (from `workflows/concerns/<name>/concern.md`) to THIS technical design — realize the
TD-level obligations it names (domain-driven-design -> aggregates/value-objects/repositories; architecture-style -> layering + dependency direction; cqrs -> command/query split). A selected concern whose Artifact Impact names TD
but leaves no trace here is drift (reconcile-alignment Concern->Artifact Realization check).

## Focus
- Create a story-level artifact named `docs/helix/02-design/technical-designs/TD-XXX-[name].md`.
- Realize each governing-story AC-ID (US-{n}-AC{m}) through component changes, interfaces, data, security, and tests; reference AC-IDs, do not restate AC text (ADR-009 — AC ownership lives in user-stories).
- Stay on the vertical slice for the story, within the story scope defined in
  the zoom-stack matrix (`workflows/activities/02-design/README.md`).
- Reference Contract IDs for exact commands, endpoints, payloads, error
  semantics, config keys, telemetry fields, event schemas, and adapter
  signatures instead of defining those normative surfaces inline.
- Keep implementation sequence and rollout or migration notes only when they affect execution.

## Boundary Test

See the zoom-stack matrix in `workflows/activities/02-design/README.md` for
which decisions belong at the system, feature, and story levels.

## Completion Criteria
- The story is implementable.
- Key interfaces, changes, and test coverage are explicit.
- Shared interface changes are captured in Contract artifacts before this TD
  references them.
- The design stays compact.
- The output is clearly story-level and disambiguated from a solution design.
- The implementation sequence can be turned into one or more small,
  reviewable changes without losing test coverage.

## Boundary Application

Apply `modularity-and-encapsulation` from the source-code baseline: reference
Architecture's Module Boundaries and identify affected modules/types, export
changes, integration translation and construction locations, dependency rules,
and focused invariant tests. Shared signatures belong in Contracts. Missing
baseline/map evidence blocks dependent feature readiness; bounded adoption work
may establish it. Respect deliberate classic-layered coupling and any authorized
scoped exception rather than inventing a new architecture style.

## Diagnostic Wiring

For selected `o11y-otel` practices, name local instrumentation, context/capture
boundaries, independent console/storage projections and verification evidence.
Reference governing Contracts instead of defining log fields or query schemas
inline. Include receiver/conformance and privacy/failure tests for the changed
path. Run/attempt correlation must work even when no active span exists.

## Formal Specification

For selected `formal-methods`, follow its Artifact Impact and
`workflows/references/formal-methods.md`. Record affected slice and rigor;
specify state, initialization, guarded transitions, requirement-linked properties,
safety separately from liveness, assumptions/fairness, abstraction and bounds.
Name model/config/proof files and reproducible evidence, including reachable
success/recovery witnesses and applicable targeted negative controls. Map modeled
elements to actual code, enforcement and tests; name residual gaps and recheck
triggers. Shared normative surfaces remain in Contracts. Do not infer production
correctness from a model pass. Unaffected slices retain applicability context and
record why no analyzer/proof run applies; unselected projects need no section.

## UMF Schema Reuse

Apply `workflows/references/umf-schemas.md` for schema, structured-interface, or
domain-model work. Inspect applicable UMF core, extensions, and domain packs;
reuse or compose by default. Record pinned sources, local additions, specific
exceptions, and semantic/projection limits. Declare `ddx.schemas` references to
the authoritative local sources so publication can render them in the UMF
browser. Contracts own exact shared surfaces; designs reference them.
Template
Show the template structure
---
ddx:
  id: TD-XXX
  authoring:
    home: repo
---

# Technical Design: TD-XXX-[story-name]

**User Story**: [[US-XXX]] | **Feature**: [[FEAT-XXX]] | **Solution Design**: [[SD-XXX]]

## Scope

- Story-level design artifact
- Use for one vertical slice or one bounded implementation story
- Must inherit the broader approach from the parent solution design
- Do not redefine cross-component architecture here; that belongs in `SD-XXX`
- Governing artifacts: [User Story, Solution Design, Contracts, Concerns]

## Technical Approach

**Strategy**: [Brief description]

**Key Decisions**:
- [Decision]: [Rationale]

**Trade-offs**:
- [What we gain vs. lose]

## Component Changes

Apply Architecture's Module Boundaries: name affected modules and owned types,
public API impact, applicable dependency rules and the boundary-check command.
Reference governing Contracts for changed shared surfaces. Do not redefine the
system map here; update Architecture first if a durable boundary changes.

### Modified: [Component Name]
- **Current State**: [What exists]
- **Changes**: [What changes]
- **Files**: `[path]`

### New: [Component Name]
- **Purpose**: [Why needed]
- **Interfaces**: Input: [receives] / Output: [produces]
- **Files**: `[path]`

## API/Interface Design

Reference the governing Contract for any exact shared API, CLI, event, schema,
config, telemetry, or adapter surface. This TD may describe story-level usage
and local wiring, but it must not define endpoints, commands, flags, payload
fields, status codes, error semantics, or adapter signatures inline.

| Surface | Governing Contract | Story-Level Usage |
|---------|--------------------|-------------------|
| [API/CLI/event/schema] | [CONTRACT-XXX or API-XXX] | [How this story uses it] |

## Data Model Changes

```sql
-- New tables or schema modifications
CREATE TABLE [table_name] (
    id UUID PRIMARY KEY,
    [columns]
);
```

## Integration Points

| From | To | Method | Data |
|------|-----|--------|------|
| [Source] | [Target] | [REST/Event/Direct] | [What data] |

### External Dependencies
- **[Service]**: [Usage] | Fallback: [If unavailable]

## Security

- **Authentication**: [Required auth level]
- **Authorization**: [Required permissions]
- **Data Protection**: [Encryption/masking]
- **Threats**: [Specific threats and mitigations]

## Performance

- **Expected Load**: [Requests/sec, data volume]
- **Response Target**: [Milliseconds]
- **Optimizations**: [Caching, indexing, etc.]

## Testing

- [ ] **Unit**: [What to test]
- [ ] **Integration**: [What integrations to test]
- [ ] **Contract**: [CONTRACT/API IDs and story-specific cases to test]
- [ ] **Security**: [Security scenarios]

## Formal Specification (when applicable)

For selected `formal-methods`, record slice applicability and chosen rigor.
Affected slices name requirement/property IDs, state/initial conditions,
transitions/guards, safety and liveness, assumptions/fairness, abstraction/bounds,
model/config/proof files and evidence. Map elements to code/enforcement/tests;
name residual gaps and recheck triggers. Reference Contracts for shared surfaces.
Use `workflows/references/formal-methods.md`; bounded analysis never substitutes
for implementation verification. Unaffected slices record why no analyzer/proof
run applies. Omit this section when the concern is not selected.

## Migration & Rollback

- **Backward Compatibility**: [Strategy]
- **Data Migration**: [Required migrations]
- **Feature Toggle**: [Enable/disable mechanism]
- **Rollback**: [Steps to reverse]

## Implementation Sequence

1. [What to build first] -- Files: `[paths]` -- Tests: `[paths]`
2. [What to build next]
3. [Integration and verification]

**Prerequisites**: [Dependencies that must be complete first]

## Risks

| Risk | Prob | Impact | Mitigation |
|------|------|--------|------------|
| [Risk] | H/M/L | H/M/L | [Strategy] |

## Diagnostic Wiring (when applicable)

Reference the telemetry/capture/query Contracts and parent SD. Name local
instrumentation points, context propagation, runner/sink wiring, privacy controls
and tests for the applicable `o11y-otel` sections. Describe bounded capture/export
failure behavior and safe evidence references. Shared fields and interface rules
remain in Contracts; service SLO/endpoint rules apply only to actual services.

## Schema Basis (when applicable)

Follow `workflows/references/umf-schemas.md`. Name the inspected UMF core,
extensions/domain packs and versions; what is reused/composed/extended; or the
specific gap justifying an alternative. Reference the authoritative Contract
and source through `ddx.schemas`; explain unsupported semantics and tests.
Omit this section for work with no schema, structured interface, or domain model.
Innsigle seal: model-primary by HELIX

The signature covers the markdown source of this page, not these HTML bytes. This page quotes that seal; verify it against the source file.

Composition
model-primary
Issuer
HELIX helix
Signing key
ed25519:b0865d76d834a52c48506414d16f4e5a (build key)
Signed source
artifact-types/design/technical-design.md
Signed
2026-11-16T15:52:45Z
Content digest
sha256:ea82eebc…30e904e9

This build key is endorsed by the human key for build signing; the signature is not a detector and not a truth guarantee.

Raw attestation JSON
{
  "payload": {
    "innsigle": "1",
    "type": "https://innsigle.dev/claim/colophon/v1",
    "issued_at": "2026-11-16T15:52:45Z",
    "issuer": {
      "id": "helix",
      "name": "HELIX",
      "key_id": "ed25519:b0865d76d834a52c48506414d16f4e5a",
      "key_url": "https://documentdrivendx.github.io/helix/.well-known/innsigle/keys.json"
    },
    "subjects": [
      {
        "uri": "https://documentdrivendx.github.io/helix/artifact-types/design/technical-design/",
        "digest": {
          "alg": "sha256",
          "value": "ea82eebcd1e0a4b0b606d3c367671424a50fa168420542656a616dd430e904e9"
        }
      }
    ],
    "colophon": {
      "schema_version": "1",
      "composition": "model-primary",
      "ingredients": [
        {
          "kind": "model",
          "name": "Claude",
          "role": "draft"
        },
        {
          "kind": "tool",
          "name": "sloptimizer",
          "role": "rewrite"
        },
        {
          "kind": "human",
          "name": "operator",
          "role": "structure-edit"
        }
      ],
      "notes": null
    }
  },
  "payload_encoding": "json",
  "signatures": [
    {
      "key_id": "ed25519:b0865d76d834a52c48506414d16f4e5a",
      "alg": "ed25519",
      "sig": "SWvb-EXwfMJ0DaAQEkdpzWLEKfXPMV9dZsc0UTi4lEzYmcN-oke_i9eTPWgVLwhXtm-zjJjCVxAOOL6LTXTXDw",
      "signed_at": "2026-11-16T15:52:45Z"
    }
  ]
}