7 Commits

Author SHA1 Message Date
cyclone c398aa7d29 Merge branch 'sp24-doc-posture-alignment'
Align CLAUDE.md + REQUIREMENTS.md + ARCHITECTURE.md with the auth work
that landed on main on 2026-06-23; emit an AUTH_DISABLED WARNING at boot
when AUTH_DISABLED is true so misconfigured production deploys fail loudly.

Closes requirements R-1 (was Open; auth shipped via the origin/main merge,
SP24 reconciles the docs).

* CLAUDE.md — track in git for the first time
* docs/REQUIREMENTS.md + docs/ARCHITECTURE.md — replace every stale
  'no auth' / 'no authentication' / 'no second party to authenticate'
  claim with the v1 posture (bcrypt + HttpOnly session cookie; first
  admin bootstrapped from CYCLONE_ADMIN_USERNAME + CYCLONE_ADMIN_PASSWORD)
* backend/src/cyclone/__main__.py — boot-time WARNING when AUTH_DISABLED
* ARCHITECTURE §4.2 module map — add cyclone.auth.* package
* ARCHITECTURE §6.1 migrations table — list 0013 + 0014 with renumbering note
* .superpowers/skills/{cyclone-tests,cyclone-api-router,cyclone-spec} —
  add AUTH_DISABLED / matrix_gate / auth-aware threat-model guidance

Spec: docs/superpowers/specs/2026-06-23-cyclone-auth-posture-alignment-design.md
Plan: docs/superpowers/plans/2026-06-23-cyclone-auth-posture-alignment.md
2026-06-23 16:28:28 -06:00
cyclone 616d467c65 docs(reviews): capture 2026-06-23 docset review + CSS reduction experiment
Commit the day's review artifacts so they aren't lost in the working tree:

* 2026-06-23-cyclone-docset-review-A.md — full docset review (Reviewer A:
  requirements + architecture lens; flags the 8-state vs 7-state claim
  lifecycle divergence, FR-20 vs ARCHITECTURE §5.4 tail-endpoint conflict,
  api_routers/ package split status, etc.)
* 2026-06-23-cyclone-docset-review-B.md — code-first counterpart (Reviewer B)
* 2026-06-23-cyclone-groundtruth-audit.md — live-data readiness audit
* 2026-06-23-css-reduction/ — iterative CSS reduction experiment
  (baseline 60,695 B raw / 11,786 B gzip / 9,875 B brotli; 18 prioritized
  candidates; per-iter reports and progress log)

Binary artifacts (PNGs, dist build output) are intentionally not committed —
they're working files for the experiment, not review records.
2026-06-23 16:28:15 -06:00
Tyler 00f11f84b6 feat(sp24): align CLAUDE.md + REQUIREMENTS.md + ARCHITECTURE.md with auth work + AUTH_DISABLED WARNING
Replaces every stale 'no auth' / 'no authentication' / 'no second party to
authenticate' claim in the three top-level docs with the v1 posture: the
auth boundary is HTTP (bcrypt + HttpOnly session cookie; first admin
bootstrapped from CYCLONE_ADMIN_USERNAME + CYCLONE_ADMIN_PASSWORD env
vars); the file-system posture (SQLCipher at rest, macOS Keychain) is
unchanged; the threat model is still a stolen/imaged drive.

Closes requirements §11 R-1 (was Open; now Closed by SP24 — auth shipped
via the origin/main merge on 2026-06-23, SP24 reconciled the docs).

Also:
- backend/src/cyclone/__main__.py — emit WARNING when AUTH_DISABLED is
  True at boot so a misconfigured production deploy fails loudly
- §6.1 migrations table in ARCHITECTURE.md — list 0013 (auth_users_and_
  sessions) and 0014 (audit_log_user_id) with the renumbering note
- §4.2 module map — add the cyclone.auth.* package
- Three skills addenda: cyclone-tests (AUTH_DISABLED conftest bypass is
  mandatory context), cyclone-api-router (every router needs
  Depends(matrix_gate)), cyclone-spec (spec template threat-model is now
  auth-aware)

This also tracks CLAUDE.md in git for the first time (was previously
untracked; the SP24 doc updates are in scope for the increment).

Spec: docs/superpowers/specs/2026-06-23-cyclone-auth-posture-alignment-design.md
Plan: docs/superpowers/plans/2026-06-23-cyclone-auth-posture-alignment.md
2026-06-23 14:49:31 -06:00
Tyler d294b8bbed docs(plan): SP24 — auth posture alignment implementation plan
Plan covers the docs-only reconciliation between the auth work that landed
in main on 2026-06-23 and the three top-level docs (CLAUDE.md, docs/
REQUIREMENTS.md, docs/ARCHITECTURE.md). Includes a 6-line __main__.py edit
for the AUTH_DISABLED startup WARNING and one-paragraph addenda to the
cyclone-tests / cyclone-api-router / cyclone-spec skills.

Spec: docs/superpowers/specs/2026-06-23-cyclone-auth-posture-alignment-design.md
2026-06-23 14:49:26 -06:00
Tyler 9e595503b7 docs(spec): SP24 — align docs and decisions with the auth work in main
The auth-merge that landed on 2026-06-23 (14 commits, a25504b..39ae988)
adds real auth: User/Session models, bcrypt, matrix_gate, AUTH_DISABLED,
a login router, RBAC on every existing endpoint, and a RequireAuth
guard on the React shell. But CLAUDE.md, docs/REQUIREMENTS.md, and
docs/ARCHITECTURE.md (all added/updated on the css-reduction branch)
still describe the pre-auth "no auth, local-only, single operator,
single host" posture. The doc/code divergence is real and would
confuse anyone reading the docs.

This is the spec for SP24 — the alignment. It is intentionally a
docs/skills-only SP: no schema, no role, no gate changes. The plan
section enumerates the doc lines to update; the implementation step
sweeps the markdown for residual "no auth" claims.

Draft, awaiting user sign-off per the SP-N spec flow.
2026-06-23 14:49:21 -06:00
Tyler 1148a03a43 docs(architecture): add top-level technical design doc
Closes round 4 of doc-prep. ARCHITECTURE.md is the day-1 read for
engineers joining Cyclone: process & network topology, tech stack
(backend + frontend + external), backend package layout with
one-line module responsibility map, frontend architecture (route
map, state management, live tail), data model (migrations 0001-0012,
ERD, 7-state claim lifecycle, audit chain), data flow (manual upload,
SFTP polling, auto-match, outbound 837P, ack ingestion), API surface,
cross-cutting concerns (logging, audit, PHI/PII, error model),
operational concerns (startup order, schedulers, health probe,
shutdown), deployment, out-of-scope, and references.

759 lines, 13 top-level sections. Cross-linked from REQUIREMENTS.md
sister-docs block and from README.md Roadmap section.
2026-06-23 14:49:16 -06:00
Tyler cad104a38c docs(requirements): add top-level requirements + DoD
38 functional requirements + 18 non-functional requirements across 13 sections.
Includes traceability matrix mapping FRs to NFRs and to existing
docs/superpowers/specs/* artifacts. Closes round 1 of doc-prep
preparation for Cyclone implementation.
2026-06-23 14:49:12 -06:00
23 changed files with 7504 additions and 4 deletions
@@ -19,6 +19,10 @@ content negotiation + `tail_events`), and ~30 routes still inlined
in `backend/src/cyclone/api.py`. The next refactor target is the
parse endpoints.
## Auth gate (SP24)
Every router declared in `backend/src/cyclone/api_routers/` **must** carry `dependencies=[Depends(matrix_gate)]` at the `APIRouter(...)` declaration — not on each individual endpoint. The gate lives at `backend/src/cyclone/auth/deps.py:107` and the role matrix is at `backend/src/cyclone/auth/permissions.py`. The roles are `admin / user / viewer`; `matrix_gate` returns 401 when there's no session and 403 when the role is below the endpoint's required role. When `AUTH_DISABLED` is True (conftest autouse fixture flips it; `CYCLONE_AUTH_DISABLED=1` in prod-by-mistake), the gate short-circuits to a synthetic admin — see the SP24 spec for the threat-model implications. New routers get the gate by default; the auth-aware convention is `router = APIRouter(dependencies=[Depends(matrix_gate)])`.
## When to use
- **Adding an endpoint.** You're adding a new GET / POST handler —
+9 -3
View File
@@ -10,9 +10,15 @@ a spec, a plan, an implementation branch, and a single atomic merge commit
into `main`. This skill encodes the conventions so every increment follows
the same shape and the commit history stays auditable.
As of this writing: **16 specs** in `docs/superpowers/specs/`, **12 plans**
in `docs/superpowers/plans/`, and SP numbers used through **SP21** (the
universal-drilldown design in progress). The next increment is **SP22**.
As of this writing: **17 specs** in `docs/superpowers/specs/`, **13 plans**
in `docs/superpowers/plans/`, and SP numbers used through **SP22**. **SP23**
is the Ubuntu + Docker + RBAC product fork (awaiting user decision);
**SP24** is the auth-posture alignment (docs-only). The next free increment
is **SP25** after SP24 lands.
## Auth-aware spec template (SP24)
The threat-model section in the canonical SP-N spec template (`## 1. Scope`, second-to-last bullet) used to read "no second party to authenticate; no second host to harden against." **That phrasing is stale as of 2026-06-23** — the auth work landed in `main` and every backend endpoint requires login. New specs should instead state the auth boundary explicitly: "the auth boundary is HTTP (login required, bcrypt + HttpOnly session cookie); file-system threats remain the local-only threat model (SQLCipher at rest, macOS Keychain). SP23 changes the threat model to LAN-bound remote operator." Reference: [`docs/superpowers/specs/2026-06-23-cyclone-auth-posture-alignment-design.md`](../../../docs/superpowers/specs/2026-06-23-cyclone-auth-posture-alignment-design.md).
## When to use
+5 -1
View File
@@ -7,7 +7,11 @@ description: "Cyclone pytest + vitest fixture patterns, prodfiles layout, backen
The Cyclone test suite is split two ways: **backend pytest** (89 test files under `backend/tests/`, 13 flat fixtures in `backend/tests/fixtures/`, one autouse `conftest.py` that resets the DB per-test) and **frontend vitest** (59 `*.test.ts(x)` siblings across `src/`, two rendering styles — `@testing-library/react` and a custom `createRoot`+`Probe` shim). This skill codifies the conventions so additions stay consistent with what's already there.
As of this writing: **89 backend test files**, **13 flat backend fixtures**, **59 frontend `*.test.ts(x)` siblings**, and **23 prodfiles samples** across `docs/prodfiles/{837p-from-axiscare,835fromco,FromHPE,claims}/`. The next increment is **SP22**.
As of this writing: **89 backend test files**, **13 flat backend fixtures**, **59 frontend `*.test.ts(x)` siblings**, and **23 prodfiles samples** across `docs/prodfiles/{837p-from-axiscare,835fromco,FromHPE,claims}/`. The next increment is **SP24** (SP23 is the Ubuntu+Docker fork, awaiting user decision).
## Auth flag (SP24)
The autouse `conftest.py` fixture at `backend/tests/conftest.py` flips `cyclone.auth.deps.AUTH_DISABLED = True` for the entire test session, so every test runs without a login round-trip. **Any new test that reads `cyclone.auth.deps.AUTH_DISABLED` directly will see `True`** — that's the test-suite reality, not a production reality. If you need a test that exercises the real gate, import `from cyclone.auth.deps import matrix_gate` and call it directly with a `Request` whose `state` carries a real session, or flip the flag back inside the test and reset it on teardown. The startup WARNING (`backend/src/cyclone/__main__.py`) is silent in tests by default because the conftest sets the flag before `bootstrap.run()` is called via `import`.
## When to use
+184
View File
@@ -0,0 +1,184 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## What this is
Cyclone is a self-hosted X12 EDI claims-management suite for a single billing office (Colorado Medicaid currently). It parses 837P professional claims and 835 ERA remittances (X12 005010X222A1 / 005010X221A1) and also handles 999, TA1, 270, 271, and 277CA. Local-only by design: binds to `127.0.0.1`, requires login (auth boundary is HTTP; bcrypt + HttpOnly session cookie; first admin bootstrapped from `CYCLONE_ADMIN_USERNAME` + `CYCLONE_ADMIN_PASSWORD` env vars; see SP24 spec for the full posture), no internet exposure.
Stack: one Python process (FastAPI + uvicorn, port 8000) + one Node process in dev (Vite, port 5173). The authoritative state is a single SQLite file at `~/.local/share/cyclone/cyclone.db` (or SQLCipher at the same path when the macOS Keychain entry + `sqlcipher3` are both present).
For the day-1 architecture read, see `docs/ARCHITECTURE.md` (process topology, module map, store facade, parser pipeline, pubsub). For the what-it-does read, see `docs/REQUIREMENTS.md` (FRs + NFRs + DoD).
## Install
```bash
# Backend (Python 3.11+)
cd backend
python -m venv .venv
.venv/bin/pip install -e '.[dev]'
# Frontend (Node 20+)
cd ..
npm install
```
Optional backend extras: `pip install -e '.[sqlcipher]'` (encryption at rest, SP12) and `pip install -e '.[sftp]'` (real SFTP, SP13).
## Dev (two terminals)
```bash
# Terminal 1 — backend
cd backend
.venv/bin/python -m cyclone serve # default 127.0.0.1:8000
# CYCLONE_PORT=... overrides port; CYCLONE_RELOAD=1 enables uvicorn --reload
# Or: .venv/bin/uvicorn cyclone.api:app --reload --port 8000
# Terminal 2 — frontend
npm run dev # Vite on http://localhost:5173
```
Vite proxies `/api/*` to the backend at `http://127.0.0.1:${CYCLONE_PORT:-8000}` so relative-URL fetchers (the live-tail NDJSON streams in particular) resolve through the same origin. Override the backend port with `CYCLONE_PORT` in the frontend terminal too.
Create `.env.local` at the repo root with `VITE_API_BASE_URL=http://127.0.0.1:8000`. Without it, the UI runs against the in-memory zustand store and real EDI parsing is disabled.
## Test
```bash
# Backend — full suite
cd backend && .venv/bin/pytest
# Backend — one file
cd backend && .venv/bin/pytest tests/test_api_999.py -v
# Backend — one test by node id
cd backend && .venv/bin/pytest tests/test_api_999.py::test_parse_999_endpoint_happy_path -v
# Frontend — full suite
npm test # alias for `vitest run`
# Frontend — one file
npx vitest run src/hooks/useFoo.test.ts
# Frontend — typecheck
npm run typecheck
# Frontend — build (tsc -b + vite build)
npm run build
# Frontend — lint
npm run lint
```
**Conventions** (full detail in `.superpowers/skills/cyclone-tests/SKILL.md`):
- Backend tests live under `backend/tests/test_*.py`. Two flavors: `test_api_<topic>_<verb>.py` (FastAPI integration via `fastapi.testclient.TestClient`) and `test_<module>_<behavior>.py` (pure-unit). Autouse `conftest.py` points `CYCLONE_DB_URL` at `tmp_path/test.db`, calls `db._reset_for_tests()` + `db.init_db()`, and wires a fresh `EventBus` onto `app.state`.
- Prodfiles (real EDI samples under `docs/prodfiles/<source>/`) are never read directly from a test — copy to `backend/tests/fixtures/<descriptive-name>.txt` first and reference as a module-level `Path` constant. The `fixtures/` dir is flat (no per-test subdirs).
- Frontend tests are siblings: `useFoo.ts``useFoo.test.ts`, `ClaimDrawer.tsx``ClaimDrawer.test.tsx`. Setup is `// @vitest-environment happy-dom` plus `(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;`. Mock the API at the module boundary with `vi.mock("@/lib/api", ...)`; stub fetch with `vi.stubGlobal("fetch", vi.fn().mockResolvedValue(...))`. `vitest.config.ts` sets `VITE_API_BASE_URL=http://test.local` so the `api` module doesn't throw `notConfiguredError` before the mock fires.
- Time-sensitive tests: frontend uses `vi.useFakeTimers()` + `vi.setSystemTime(...)` + `vi.advanceTimersByTime(ms)`. Backend passes explicit `datetime(...)` values. Don't add `await new Promise((r) => setTimeout(r, N))` — it's the legacy flaky pattern.
## Project-scoped skills (`.superpowers/skills/`)
Cyclone ships 8 skills under `.superpowers/skills/`. They auto-load by description match — no slash command needed. **Read the relevant skill before touching the matching subsystem.**
| Skill | Owns |
|---|---|
| `cyclone-spec` | The SP-N spec → plan → implement → merge flow (branch shape, file paths, commit prefixes, PR title, merge shape). |
| `cyclone-tests` | pytest + vitest fixture patterns, prodfiles drop-in rule, determinism rules. |
| `cyclone-edi` | EDI parser/validator conventions (837P/835/999/270/271/277CA/TA1, R-codes, CAS mapping). |
| `cyclone-tail` | Live-tail streaming wire format and the `useTailStream` + `useMergedTail` + `TailStatusPill` hook triplet. |
| `cyclone-store` | `CycloneStore` facade, write-paths, pubsub event contract, SP21 split map. |
| `cyclone-api-router` | FastAPI router conventions (`api_routers/`, `api_helpers.py`), response/error-envelope shapes. |
| `cyclone-frontend-page` | React page conventions (TanStack Query `use<X>` hook, drawer, URL state, sibling test). |
| `cyclone-cli` | CLI subcommand conventions (`cli.py`, exit codes, smoke tests). |
## The SP-N increment flow
Every feature ships as a numbered **SP-N increment**: spec → plan → implementation branch → single atomic merge into `main`. As of the last backfill, SP numbers are used through **SP22**; **SP23** is reserved for the Ubuntu + Docker + RBAC product fork (`docs/superpowers/specs/2026-06-22-cyclone-ubuntu-docker-deployment-design.md`, awaiting user decision); the next free increment is **SP24**. Read `cyclone-spec` before starting a new one. Non-negotiable shape:
- **Branch:** `sp<N>-<short-kebab-topic>` (e.g. `sp22-line-reconciliation`).
- **Spec path:** `docs/superpowers/specs/YYYY-MM-DD-cyclone-<topic>-design.md`, header `Status: Draft, awaiting user sign-off`, sections `Scope / Decisions / …`. Specs contain zero code blocks.
- **Plan path:** `docs/superpowers/plans/YYYY-MM-DD-cyclone-<topic>.md`, header per `superpowers:writing-plans` with `Goal / Architecture / Tech Stack / Spec` metadata + numbered `- [ ] Step N:` tasks.
- **Commit prefixes:** `feat(sp<N>): …`, `docs(spec): …`, `docs(plan): …`, `merge: SP<N> <topic> into main`.
- **PR title:** `SP<N> <Topic>` (matches the merge-commit subject).
- **Merge shape:** single atomic merge commit. **No squash** (collapses the audit trail) and **no rebase** (rewrites the SHAs the review was performed against). The SP-N merge commit *is* the record of the increment landing.
The matching skill to load alongside `cyclone-spec` depends on the subsystem the SP-N touches (see the "Related skills" section at the bottom of each skill file).
## Live-tail wire format
The Claims, Remittances, and Activity pages stay current without manual refresh. The backend publishes an internal event on every store write, the page opens a streaming HTTP connection to the matching `/api/<resource>/stream` endpoint, and new rows append to the table the moment they hit the database.
Endpoints (all accept the same query params as their non-streaming counterparts; `Content-Type: application/x-ndjson`):
| Method | Path | Subscribes to | Default sort |
|---|---|---|---|
| GET | `/api/claims/stream` | `claim_written` | `-submission_date` |
| GET | `/api/remittances/stream` | `remittance_written` | `-received_date` |
| GET | `/api/activity/stream` | `activity_recorded` | `-timestamp` (limit 50) |
Wire format: one JSON object per line, `{"type": ..., "data": ...}`. The first batch is the **snapshot** of currently-known rows, then `snapshot_end` with the count, then the **live** events. Known types: `item`, `snapshot_end`, `heartbeat` (keeps the connection alive on idle — clients flip to `stalled` after 30s of total silence), `item_dropped` (rare), `error`.
Status pill states (rendered by `<TailStatusPill>` in `src/components/TailStatusPill.tsx`): `live` (success), `connecting` (warning), `reconnecting` (warning), `stalled` (destructive, ↻ Reconnect button), `error` (destructive, ↻ Reconnect button), `closed` (destructive). Backoff on error: `1s → 2s → 4s → 8s → 16s → 30s` capped. `STALL_TIMEOUT_MS = 30_000` in `src/hooks/useTailStream.ts:53`. Heartbeat interval is `CYCLONE_TAIL_HEARTBEAT_S` env var, default 15s.
Frontend triplet for any live page: `use<X>(params)` (initial fetch) + `useTailStream(resource)` (opens the NDJSON stream, drives backoff/stall) + `useMergedTail(resource, baseItems, filterFn?)` (merges snapshot + tail, dedup'd by id). The subscription lives on the page, not inside the data hook — see `cyclone-frontend-page` for why.
## Backend at a glance
`backend/src/cyclone/` is a single namespace. The two largest files are `api.py` (~3,548 LOC, the only large file) and `store.py` (~2,423 LOC, the `CycloneStore` facade — SP21 is in flight to split it into a `cyclone/store/` subpackage; the public API stays unchanged). Subpackages: `api_routers/` (acks, admin, health, ta1_acks), `clearhouse/` (Clearhouse + SftpClient), `edi/` (filenames), `parsers/` (X12 transaction parsers + models + validators + serializers), `workflow/` (placeholder for future sub-project 6).
The store is the only read/write surface for the database; every mutating endpoint goes through it. All persistence flows through SQLAlchemy sessions via `db.SessionLocal()()`. SQLAlchemy ORM models live in `db.py`; 12 SQL migrations under `migrations/` (0001_initial through 0012_backups) are walked in order by `db_migrate.py`.
The parser pipeline is a 5-stage `tokenize → segmentize → model → validate → write_to_store` flow used for every inbound X12 type. Per-transaction parsers: `parse_837.py`, `parse_835.py`, `parse_999.py`, `parse_ta1.py`, `parse_270.py`, `parse_271.py`, `parse_277ca.py`. Each has a matching Pydantic model module (`models.py`, `models_835.py`, …) and a writer (`writer.py` / `writer_835.py`). The 837P serializer (`serialize_837.py`) is the byte-faithful outbound counterpart used by both single-claim download (`/api/claims/{id}/serialize-837`) and the bulk rejected-resubmit bundle (`/api/inbox/rejected/resubmit?download=true`).
The pubsub is `cyclone.pubsub.EventBus` — an in-process async fan-out broker. Publishers call `publish(kind, payload)`; subscribers receive via an async iterator. If a subscriber's per-kind queue is full, the oldest event is dropped so a slow consumer can't stall the producer. Bus is single-event-loop only (matches FastAPI/uvicorn).
Config: `config/payers.yaml` is the on-disk source for providers / payers / clearhouse, schema-validated at boot against a Pydantic model. Reload with `POST /api/admin/reload-config`. Original in-code `PAYER_FACTORIES` dict in `cli.py` is kept as a fallback for ad-hoc testing.
Secrets live in the macOS Keychain (via `keyring` + `cyclone.secrets`): SQLCipher key (service `cyclone`, account `cyclone.db.key`), SFTP password, backup passphrase. No secrets on disk in plaintext.
## Frontend at a glance
`src/` is React 18 + TypeScript + Vite. Routes register in `src/App.tsx` (11 pages, all under a `<Layout>` route wrapper). Pages are pure renderers — every page pairs with a `use<X>` data hook in `src/hooks/` and renders a `<PageHeader>` + a table/list/KPI grid. Drawers (`ClaimDrawer/`, `RemitDrawer/`, plus the new `ProviderDrawer/` and `AckDrawer/`) are mounted by the page and their open/close state is mirrored to the URL via `useDrawerUrlState` so deep-links round-trip. Drill-stack navigation is provided by `<DrillStackProvider>` in `src/components/drill/`.
State split: **server state** in TanStack Query (`@tanstack/react-query`); **ephemeral client state** in Zustand (`useTailStore` for live-tail append, plus the drill stack). The live-tail store is FIFO-capped at `TAIL_CAP = 10_000` per slice (`src/store/tail-store.ts:28`); `claims` and `remittances` are key-by-id with first-write-wins dedup, `activity` is an append-only array.
UI primitives in `src/components/ui/` are Radix-backed (`button`, `dialog`, `table`, `select`, `pagination`, `empty-state`, `error-state`, `filter-chips`, `skeleton`, `input`, `label`, `card`, `badge`, `skip-link`, `claim-state-badge`). Don't import a new UI library without discussion.
Path alias `@/``src/`. Configured in `vite.config.ts`, `vitest.config.ts`, and `tsconfig.app.json`.
## CLI
```bash
# Parser
python -m cyclone.cli parse-837 path/to/837p.txt --output-dir ./claims --payer co_medicaid [--strict] [--include-raw-segments]
python -m cyclone.cli parse-835 path/to/835.txt --output-dir ./remits
python -m cyclone.cli parse-999 inbound_999.txt
python -m cyclone.cli parse-ta1 inbound_ta1.txt
python -m cyclone.cli parse-277ca inbound_277ca.txt
# Validators
python -m cyclone.cli validate-npi 1234567893
python -m cyclone.cli validate-tin 721587149
# Other
python -m cyclone serve # uvicorn
python -m cyclone backup list
python -m cyclone backup create --reason manual
```
Exit codes are documented per subcommand in `cyclone-cli``0` for success, `2` for file-level failure, `1` for unexpected exceptions.
## Things that are easy to get wrong
- **`VITE_API_BASE_URL` matters.** With it empty, every `api` method throws `notConfiguredError()` and the UI falls back to the in-memory zustand store — parses are disabled and the live-tail streams never open.
- **Prodfiles vs fixtures.** Tests must reference `backend/tests/fixtures/<name>.txt`, not `docs/prodfiles/<source>/<file>.txt`. The prodfiles dir is the source-of-truth archive; the fixtures dir is the stable test surface.
- **SP-N merge shape.** No squash, no rebase. The merge commit *is* the audit trail. Squash collapses the per-commit history and breaks the SP-N audit trail.
- **Don't put domain logic in JSX.** Conditional renderings, table sorting, and KPI math all belong in the `use<X>` hook or a pure helper under `src/lib/`.
- **Don't open a drawer via local `useState`.** Use `useDrawerUrlState()` so the URL is the single source of truth — deep-links and reload-restore depend on it.
- **Don't call `useTailStream` from inside a `use<X>` hook.** The subscription lives on the page so the lifecycle ties to whoever mounts the hook, not to whoever happens to call it.
- **The store facade.** The public API of `cyclone.store` is preserved through SP21's split — call through the facade, not directly into the underlying modules.
- **Encryption is optional, not required.** When the Keychain entry is missing **or** `sqlcipher3` is not installed, the DB falls back to plain SQLite. Don't fail boot on missing encryption.
- **Local-only by design.** The backend binds to `127.0.0.1`, requires login (bcrypt + HttpOnly session cookie; see SP24 spec), and the threat model is still a stolen/imaged drive — SQLCipher at rest and the macOS Keychain handle that. The auth boundary is the HTTP layer; the file-system posture is unchanged. Don't add internet exposure. Don't disable auth without an explicit `CYCLONE_AUTH_DISABLED=1` env var (the escape hatch logs a WARNING at boot).
</content>
</invoke>
+6
View File
@@ -801,6 +801,12 @@ backup API).
## Roadmap
> **Read order for new engineers:**
> 1. [`docs/REQUIREMENTS.md`](docs/REQUIREMENTS.md) — what Cyclone does (FRs + NFRs + DoD + traceability). The single index tying the 22 shipped sub-projects to the 38 functional + 18 non-functional requirements and the test strategy.
> 2. [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) — how it fits together (process topology, package layout, data flow, lifecycle, operational concerns).
> 3. The per-SP spec under [`docs/superpowers/specs/`](docs/superpowers/specs/) for whatever you're touching.
> 4. The per-SP plan under [`docs/superpowers/plans/`](docs/superpowers/plans/) if you're implementing.
Sub-projects 2 through 19 are **shipped**. See the [completeness
review](docs/reviews/2026-06-20-cyclone-completeness-review.md) for
the honest gap analysis against the industry definition of a HIPAA
+14
View File
@@ -24,6 +24,20 @@ def main() -> None:
from cyclone.auth import bootstrap
bootstrap.run()
# SP24: if the AUTH_DISABLED escape hatch is on, scream at boot so a
# misconfigured production deploy fails loudly. The flag is flipped by
# ``CYCLONE_AUTH_DISABLED=1`` (see ``cyclone.auth.bootstrap``) and by the
# pytest conftest autouse fixture (see ``.superpowers/skills/cyclone-tests``).
from cyclone.auth import deps as _auth_deps
if _auth_deps.AUTH_DISABLED:
import logging
logging.getLogger("cyclone").warning(
"AUTH_DISABLED is set (CYCLONE_AUTH_DISABLED=1) — all requests "
"treated as admin, dev only. Do NOT enable this in production."
)
if len(sys.argv) >= 2 and sys.argv[1] == "serve":
port = os.environ.get("CYCLONE_PORT", "8000")
reload = os.environ.get("CYCLONE_RELOAD", "0") == "1"
+762
View File
@@ -0,0 +1,762 @@
# Cyclone — Technical Architecture
> **Day-1 read for engineers joining Cyclone.** This is the top-level technical design: how the system fits together, what the boundaries are, and why it looks the way it does.
>
> **Companion docs:**
> - **Requirements:** [`docs/REQUIREMENTS.md`](REQUIREMENTS.md) — what Cyclone does (FRs + NFRs + DoD + traceability).
> - **Specs:** [`docs/superpowers/specs/`](superpowers/specs/) — design specs per sub-project (22 specs).
> - **Plans:** [`docs/superpowers/plans/`](superpowers/plans/) — TDD-shaped implementation plans per sub-project (27 plans).
>
> **Scope of this doc:** architecture and design. The spec files own per-SP design; the plan files own the task order. This doc explains the *whole* — the boundaries between modules, the data flow across them, the lifecycle of an inbound file from upload to reconciled claim.
---
## 1. System overview
Cyclone is a self-hosted X12 EDI claims-management suite for a single billing office. The first deployment target is Colorado Medicaid (one operator, one trading partner). The system is local-only on purpose: the backend binds to `127.0.0.1` and requires login (bcrypt + HttpOnly session cookie). The threat model is still a stolen or imaged drive, not a remote attacker — SQLCipher at rest and the macOS Keychain handle that. The auth boundary is the HTTP layer; the file-system posture is unchanged. The SP23 product fork changes the threat model to "remote operator on LAN."
Cyclone processes three X12 transaction pairs end-to-end:
| Inbound | Outbound | Use |
|---|---|---|
| **837P** (005010X222A1) | 837P (resubmit) | Professional claim submission, acknowledgment tracking |
| **835** (005010X221A1) | — | ERA remittance ingestion, auto-reconciliation |
| **999 / TA1 / 270 / 271 / 277CA** | 999 (after submit) | Acknowledgments, eligibility, claim status |
The authoritative store is a single SQLite file at `~/.local/share/cyclone/cyclone.db` (or, with `sqlcipher3` installed and a Keychain entry, a SQLCipher-encrypted file at the same path). Every claim, remittance, audit event, and reconciliation decision is in that one file. The 6-year HIPAA retention expectation is met by automated daily encrypted backups (SP17) and a tamper-evident hash-chained audit log (SP11).
The whole stack is a single Python process (FastAPI + uvicorn on port 8000) plus a single Node process in dev (Vite on port 5173). No message broker, no separate worker, no database server. The v1 deployment model tolerates this because the operator is one person, the host is one machine, and the failure mode is "open the Activity log and check what broke."
---
## 2. Process & network topology
```
+---------------------+ +-----------------------+
| Browser | HTTP | Vite dev server |
| (localhost:5173) | <----> | (Node 20+) |
| | Vite | |
| React 18 + TanStack | proxy | src/ |
| Query, Zustand, | /api | - pages, components, |
| Radix UI, Tailwind | -----> | hooks, lib |
+---------------------+ +-----------------------+
|
| HTTP (localhost)
v
+----------------------------------------------------------+
| Python process: `python -m cyclone serve` |
| |
| FastAPI app (uvicorn, 127.0.0.1:8000) |
| +-----------------------------------------------------+ |
| | cyclone.api:app (3,548 LOC) | |
| | - routers: claims, remits, providers, acks, | |
| | activity, inbox, upload, download, batches, | |
| | admin, scheduler, health, ta1_acks | |
| | - live-tail: NDJSON pubsub (pubsub.py) | |
| | - lifespan: init db -> seed SP9 -> start SP16 + | |
| | SP17 schedulers -> load PayerConfig cache | |
| +-----------------------------------------------------+ |
| | cyclone.store (facade, 2,423 LOC) | |
| | - add/get/list/manual_match/iter_claims/... | |
| | - delegates to: db.SessionLocal() | |
| +-----------------------------------------------------+ |
| | cyclone.parsers.* (X12 837P/835/999/TA1/270/271/ | |
| | 277CA: tokenize -> segmentize -> model -> validate | |
| | -> write to store) | |
| +-----------------------------------------------------+ |
| | cyclone.reconcile, scoring, batch_diff, audit_log, | |
| | backup_service, scheduler, db_crypto, secrets | |
| +-----------------------------------------------------+ |
+----------------------------------------------------------+
| | |
v v v
+----------------+ +-------------------+ +----------------+
| SQLite / | | macOS Keychain | | Trading |
| SQLCipher | | (keyring) | | partner SFTP |
| cyclone.db | | - SQLCipher key | | (paramiko, SP13)|
| (12 migrations)| | - SFTP password | | |
| | | - backup pass | | |
+----------------+ +-------------------+ +----------------+
```
**One process, one file, three side-channels.** The Keychain (secrets) and SFTP (outbound to the payer) are side-channels; the database is the central state.
The `cyclone-pipeline/` sibling project (not in this repo) is a separate Python CLI that drives the full 7-phase round-trip: preflight → browser upload → parse verification → SFTP submit → TA1 wait → 999 wait → scan + report. It is not part of the in-process architecture; it sits alongside the backend and uses its API endpoints.
---
## 3. Tech stack
### 3.1 Backend
| Layer | Technology | Version | Notes |
|---|---|---|---|
| Language | Python | 3.11+ (3.13 in dev) | `requires-python = ">=3.11"` |
| Web framework | FastAPI | ≥0.110, <1 | `python -m cyclone serve` boots uvicorn |
| ASGI server | uvicorn[standard] | ≥0.27, <1 | `--host 127.0.0.1 --port 8000` |
| ORM | SQLAlchemy | ≥2.0, <3 | 2.x style; engine + SessionLocal() function-accessor |
| Validation | Pydantic | ≥2.6, <3 | v2 model_validator + ConfigDict |
| CLI | Click | ≥8.1, <9 | `cyclone` console script |
| YAML | PyYAML | ≥6.0, <7 | PayerConfig (SP9) |
| Secrets | keyring | ≥25.0, <26 | macOS Keychain on darwin |
| Crypto | cryptography | ≥49.0, <50 | AES-256-GCM for SP17 backups (hard dep) |
| SQLCipher (opt) | sqlcipher3 | ≥0.6, <1 | `pip install -e .[sqlcipher]` |
| SFTP (opt) | paramiko | ≥3.4, <6 | `pip install -e .[sftp]` |
| Tests | pytest + pytest-cov + pytest-asyncio + pytest-randomly | latest | 964 tests, 2026-06-23 |
| Test client | httpx | ≥0.27, <1 | dev only |
### 3.2 Frontend
| Layer | Technology | Version | Notes |
|---|---|---|---|
| Build | Vite | latest | `npm run dev` (port 5173) |
| Language | TypeScript | latest | `tsc -b --noEmit` is the typecheck script |
| UI | React | 18.3.1 | function components + hooks |
| Routing | react-router-dom | 6.27.0 | SPA, 11 top-level routes |
| Data | @tanstack/react-query | 5.101+ | server-state cache |
| Client state | Zustand | 4.5.5 | small, ephemeral state (live tail, drill stack) |
| UI primitives | @radix-ui/* | latest | dialog, label, select, slot, tabs |
| Styling | Tailwind CSS | latest | utility-first |
| Icons | lucide-react | 0.453+ | |
| Toasts | sonner | 1.5+ | |
| Test runtime | vitest | 4.1.9 | Node 18+ has Response/fetch natively |
| Test DOM | happy-dom | 20.10+ | not jsdom (NFR-2) |
| Component tests | @testing-library/react | 16.3+ | 73 test files |
### 3.3 External / operational
- **macOS Keychain** — secret store for SQLCipher key, SFTP password, backup passphrase. No secrets on disk in plaintext (NFR-4).
- **X12 005010 implementation guides** — the parsers follow the CMS / X12 published guides. The 837P parser is the most heavily tested; 835 is the second; 999/TA1/270/271/277CA are lighter.
- **One trading partner** — Colorado Medicaid via the Gainwell SFTP endpoint. Other payers are configured via `cyclone/providers.py` `PayerConfig` rows (SP9).
---
## 4. Backend architecture
### 4.1 Package layout
The `cyclone` package is a single namespace rooted at `backend/src/cyclone/`. 22 top-level modules + 4 subpackages. The store (SP21 in-flight split) is the largest; everything else is small and focused.
```
backend/src/cyclone/
├── __main__.py — entry point; `python -m cyclone` → CLI, `python -m cyclone serve` → uvicorn
├── __init__.py — `__version__`, package init
├── api.py — FastAPI app, route includes, lifespan (3,548 LOC — the only large file)
├── api_helpers.py — request/response formatters, error → HTTP mapping
├── api_routers/
│ ├── __init__.py
│ ├── acks.py — 999/TA1/271/277CA acknowledgments
│ ├── admin.py — admin-only endpoints (validate-provider, scheduler, backup)
│ ├── health.py — GET /api/health (SP19 deep snapshot)
│ └── ta1_acks.py — TA1-specific (split from acks for the SP3 lifecycle)
├── audit_log.py — SHA-256 hash-chained append-only log (SP11)
├── backup.py — SP17 primitives: derive_key, encrypt, decrypt, BackupFile
├── backup_scheduler.py — SP17 BackupScheduler wrapper
├── backup_service.py — SP17 coordinator: create/list/restore/verify/prune
├── batch_diff.py — 837 ↔ 835 diff (SP4)
├── clearhouse/
│ └── __init__.py — Clearhouse, SftpClient (SP9, SP13)
├── cli.py — Click CLI: `cyclone serve`, `cyclone validate-npi`, `cyclone backup`, etc.
├── db.py — SQLAlchemy engine, SessionLocal, ORM models, init_db, reinit_engine
├── db_crypto.py — SP12 SQLCipher connect-creator + is_encryption_enabled()
├── db_migrate.py — runs the 12 SQL migrations in order
├── edi/
│ └── filenames.py — X12 filename convention helpers (SP9)
├── inbox_lanes.py — 5-lane Inbox computation (SP14)
├── inbox_state.py — claim ↔ inbox state mapping helpers
├── inbox_state_277ca.py — SP10 277CA inbox state integration
├── logging_config.py — SP18 structured JSON + PII scrubber
├── migrations/ — 12 SQL files (0001_initial through 0012_backups)
├── npi.py — SP20 NPI Luhn + Tax ID validation
├── parsers/ — X12 parser subpackage
│ ├── parse_837.py — 837P ingest
│ ├── parse_835.py — 835 ingest
│ ├── parse_999.py / parse_ta1.py
│ ├── parse_270.py / parse_271.py
│ ├── parse_277ca.py — SP10 277CA ingest
│ ├── models*.py — one Pydantic model module per transaction type
│ ├── segments.py — X12 segment tokenizer
│ ├── validator.py — 837P rule registry (R-codes)
│ ├── validator_835.py — 835 validator
│ ├── serialize_837.py — SP8 outbound 837P serializer
│ ├── serialize_270.py / serialize_999.py
│ ├── cas_codes.py — CAS reason-code table
│ ├── batch_ack_builder.py
│ ├── writer.py / writer_835.py
│ └── exceptions.py
├── payers.py — Payer ORM row accessor (SP9)
├── providers.py — Payer / Clearhouse / Provider ORM row DTOs (SP9)
├── pubsub.py — NDJSON live-tail EventBus
├── reconcile.py — 835 → 837 auto-reconciliation engine
├── scheduler.py — SP16 MFT polling scheduler
├── scoring.py — 4-field lane scoring (40/25/20/15, hard-coded — backlog item)
├── secrets.py — Keychain access wrapper (SP9)
├── security.py — security headers, HealthSnapshot, deep health probe (SP19)
└── store.py — CycloneStore facade (2,423 LOC; SP21 in-flight split)
```
### 4.2 Module responsibility map (one line each)
| Module | Responsibility |
|---|---|
| `__main__` | Dispatch `serve` vs CLI; honor `CYCLONE_PORT` / `CYCLONE_RELOAD`; emit `AUTH_DISABLED` WARNING if `cyclone.auth.deps.AUTH_DISABLED` is True at boot |
| `api` | FastAPI app, lifespan, route includes, 999/270/271 endpoints, exception → HTTP |
| `auth.*` | HTTP-layer login (bcrypt + HttpOnly session cookie). Submodules: `deps` (the `matrix_gate` FastAPI dependency, `AUTH_DISABLED` flag), `routes` (`/api/auth/login`, `/api/auth/logout`, `/api/auth/me`), `users`, `sessions`, `permissions` (role matrix), `bootstrap` (env-var first-admin), `cli` (`cyclone admin create-user` / `rotate-password`) |
| `api_helpers` | Error → status code mapping, common response shapes |
| `audit_log` | Append + verify a SHA-256 hash-chained log (SP11) |
| `backup` | Pure crypto + file I/O for SP17 backup format |
| `backup_scheduler` | Wrap `BackupService` in a `tick()` loop (SP17) |
| `backup_service` | Create / list / restore / verify / prune (SP17) |
| `batch_diff` | Pairwise diff of two 837 batches (SP4) |
| `clearhouse` | `Clearhouse` + `SftpClient` (SP9 stub, SP13 paramiko) |
| `cli` | `cyclone` console script: serve, validate-npi, backup, list-batches, … |
| `db` | Engine factory, `SessionLocal()`, all ORM rows, `init_db()`, `reinit_engine()` |
| `db_crypto` | SQLCipher branch + `is_encryption_enabled()` (SP12) |
| `db_migrate` | Walk `migrations/*.sql` in order, apply pending |
| `edi.filenames` | Parse / construct X12 file names (SP9) |
| `inbox_lanes` | Compute the 5 lanes (rejected, payer_rejected, candidates, unmatched, done_today) |
| `inbox_state` | Pure helpers for state ↔ lane mapping |
| `inbox_state_277ca` | SP10 277CA state integration (monotonic rule) |
| `logging_config` | SP18 JSON formatter + PII scrubber |
| `npi` | SP20 pure validators (Luhn over 80840+body, EIN prefix check) |
| `parsers.*` | X12 transaction set parsers (one per type) |
| `payers` / `providers` | SP9 ORM row DTOs |
| `pubsub` | In-process NDJSON EventBus for live tail |
| `reconcile` | 835 → 837 auto-match + per-line CAS reconciliation |
| `scheduler` | SP16 MFT polling scheduler (per-payer tick) |
| `scoring` | 4-field lane scoring weights (40/25/20/15) |
| `secrets` | Keychain get/set/delete via `keyring` |
| `security` | Security headers, deep `HealthSnapshot` (SP19) |
| `store` | `CycloneStore` facade: `add` / `get` / `list` / `manual_match` / `iter_*` / `recent_activity` |
### 4.3 The `CycloneStore` facade
The store is the single read/write surface for the database. Every endpoint that mutates state goes through `cyclone.store` (eventually the `cyclone.store.*` subpackage after SP21 lands). The facade pattern preserves public API:
- `store.add(record)` — add a parsed batch
- `store.get(batch_id)`, `get_batch(batch_id)`, `list(limit)`, `all()`
- `store.manual_match(claim_id, remit_id)` — raises `AlreadyMatchedError` (→ 409)
- `store.manual_unmatch(claim_id)` — raises `NotMatchedError` (→ 409)
- `store.iter_claims(...)`, `iter_remittances(...)`
- `store.distinct_providers()`, `recent_activity(limit)`
- `store.list_unmatched(kind="both")`
- `store.export_*()` — CSV/JSON dumpers
All persistence flows through SQLAlchemy sessions via `db.SessionLocal()()`. The engine is single-connection-per-request via FastAPI dependency injection. SP21 splits `store.py` (2,423 LOC) into a `cyclone/store/` subpackage with one module per domain (batches, inbox, claim_detail, acks, backups, providers, etc.) and a thin facade that delegates every method to its domain module. After SP21, the public API of `cyclone.store` is unchanged; the only thing that changes is the file layout.
### 4.4 The parser pipeline
All inbound files follow the same 5-stage pipeline:
```
X12 .txt on disk
[1] tokenize (parsers/segments.py: split on ~, then ^, then *:)
[2] segmentize (build Segment records with elements + repeats)
[3] model (parsers/models_*.py: Pydantic models per transaction type)
[4] validate (parsers/validator.py: R-codes; raise ParseError on fatal)
[5] write (store.add(record); record → DB rows)
```
The 837P validator has the most rules (R020, R021, R034, R035, R200, R210 — see [837P parser spec](superpowers/specs/2026-06-19-cyclone-837p-parser-design.md) §2.4 for the registry). The 835 validator is simpler (no R-codes, just a model completeness check + a status_code allowlist). 999/TA1/270/271/277CA have no validators — they trust the upstream.
The writer is responsible for: (a) creating the `batches` row, (b) creating N `claims` / `remittances` / `cas_adjustments` rows, (c) emitting an `activity_events` row, (d) for 837P, the synthetic claim-status from the 999 envelope, (e) for 835, triggering `reconcile.apply_payment` to auto-match. If any step raises, the entire batch is rolled back (single SQLAlchemy transaction).
### 4.5 The reconciliation engine
`cyclone.reconcile` is a pure-functions module. The store calls into it for every 835 ingest:
- `apply_payment(claim, remit, strategy) -> ApplyIntent` — happy path; returns the new `Match` row + state transition
- `apply_reversal(...)` — handles a reversal 835 (the original payment + the reversal both stay in the DB; the `is_reversal` flag on the `Match` row disambiguates)
- `recompute_line_totals(claim)` — for SP7's per-line audit, when an 835 carries CAS adjustments
The engine is pure (no DB access). The store orchestrates the SQL writes after a successful `apply_*` returns. The 4-field scoring (40/25/20/15 for charge amount / NPI / patient ID / service date) lives in `cyclone.scoring` and is invoked by `inbox_lanes.compute_lanes` for the `candidates` and `unmatched` lanes.
### 4.6 The audit chain
`cyclone.audit_log` is a separate, append-only log table (`audit_log` — distinct from `activity_events` which is the un-chained `/activity` feed). Every event type the system can emit has a key in the chain:
- `claim.submitted`, `claim.rejected`, `claim.matched`, `claim.unmatched`
- `claim.payer_rejected`, `claim.payer_rejected_acknowledged`
- `clearhouse.submitted`
- `key.rotated` (SP15), `backup.created`, `backup.restored`, `backup.verified` (SP17)
- `api.request_rejected` (SP19)
Each row carries the SHA-256 of `(prev_hash || kind || actor || payload_json || ts)`. The first row has `prev_hash = 0x00 * 32`. `audit_log.verify_chain()` walks the table top-to-bottom, recomputing each hash, and raises `AuditChainError` on the first mismatch with the row id and the expected vs. actual hash. SP19's deep health probe calls `verify_chain()` on every `/api/health` request so a broken chain surfaces in the operator's status badge within one tick.
---
## 5. Frontend architecture
### 5.1 Tech stack
See §3.2. The frontend is a Vite SPA with TypeScript strict mode, Tailwind utility classes, and Radix primitives. There is no SSR, no Next.js, no router data-loading — every page is a function component that calls `useQuery` and renders.
### 5.2 Route map
| Path | Page | Purpose |
|---|---|---|
| `/` | `Dashboard` | KPI tiles + ticker tape + recent activity |
| `/claims` | `Claims` | Paginated claim list, filters, drill to claim drawer |
| `/remittances` | `Remittances` | Paginated remit list, drill to remit drawer |
| `/providers` | `Providers` | Provider rollup (NPIs, charge totals) |
| `/activity` | `ActivityLog` | Append-only `activity_events` feed (NDJSON) |
| `/upload` | `Upload` | Drag-drop or click to upload an 837P / 835 / 999 / 277CA |
| `/reconciliation` | `ReconciliationPage` | Cross-claim reconciliation view (4-field score) |
| `/inbox` | `Inbox` | 5-lane inbox (SP14) with BulkBar |
| `/acks` | `Acks` | 999/TA1/270/271/277CA acknowledgment list |
| `/batches` | `Batches` | Batch list with totals + validation summary |
| `/batch-diff` | `BatchDiff` | Pairwise 837 batch diff |
| `*` | `NotFound` | 404 |
### 5.3 State management
Two layers:
- **Server state** — `@tanstack/react-query`. Every page uses one or more `useQuery` calls. The query key shape is `["domain", id?, filters?]`. Mutations use `useMutation` and invalidate the relevant keys. There is no global refetch strategy; each page controls its own stale time.
- **Client state** — `zustand`. Two stores:
- `tail-store.ts` — the live-tail connection state (reconnecting, last event id, subscriber counts). Powers the bottom-right TailStatusPill.
- `DrillStackProvider` (in `src/components/drill/`) — the SP22 universal-drilldown stack. A LIFO of drill contexts (claim → claim line → match → CAS adjustment) so the back button works across drawers.
There is no Redux, no Context for global state, no MobX. The combination of react-query for server state + zustand for client state is intentional — see [universal-drilldown spec](superpowers/specs/2026-06-21-cyclone-universal-drilldown-design.md) for the rationale.
### 5.4 Live tail (NDJSON pubsub)
The Activity feed and the TailStatusPill share a single connection: `GET /api/tail?since=<last_event_id>`. The server returns `Content-Type: application/x-ndjson` and streams one JSON object per line. Each line is one of:
- `{kind: "heartbeat", ts: "..."}` — every 5s when no events
- `{kind: "event", id: <int>, event_type: "...", payload: {...}}` — when something happens
- `{kind: "error", message: "..."}` — server-initiated close (rare)
The client uses `fetch` + `ReadableStream` to consume the body and dispatches each line to the relevant `useQuery` cache via `queryClient.setQueryData`. The connection auto-reconnects on `error` with exponential backoff. See [live-tail spec](superpowers/specs/2026-06-20-cyclone-live-tail-design.md) for the wire format and reconnection policy.
---
## 6. Data model
### 6.1 Migrations 00010014
The schema evolves in ordered SQL files under `backend/src/cyclone/migrations/`. Each file starts with `-- version: N` and is applied in order by `db_migrate.py`. There is no migration framework — `db_migrate.py` is a 30-line file that checks the `schema_version` row and applies everything newer. The first 12 ship on `main`; 13 + 14 are the auth migrations that landed in `main` on 2026-06-23.
| # | File | What it adds |
|---|---|---|
| 1 | `0001_initial.sql` | `batches`, `claims`, `remittances`, `cas_adjustments`, `matches`, `activity_events` (6 tables) |
| 2 | `0002_acks.sql` | `acks` table (999/271) |
| 3 | `0003_drop_claims_remits_unique_constraints.sql` | Spec-bug fix: drop the UNIQUE constraints that prevented reversal flows |
| 4 | `0004_rejections_and_state_history.sql` | `rejections` table + `claim_state_history` |
| 5 | `0005_create_ta1_acks.sql` | `ta1_acks` table |
| 6 | `0006_line_reconciliation.sql` | `line_reconciliations` (SP7) |
| 7 | `0007_providers_payers_clearhouse.sql` | `providers`, `payers`, `clearhouses` (SP9) |
| 8 | `0008_payer_rejected_columns.sql` | `claim.payer_rejected_*` columns (SP10) |
| 9 | `0009_audit_log.sql` | `audit_log` hash-chained table (SP11) |
| 10 | `0010_payer_rejected_acknowledged.sql` | `claim.payer_rejected_acknowledged_*` columns (SP14 hand-off) |
| 11 | `0011_processed_inbound_files.sql` | `processed_inbound_files` idempotency table (SP16) |
| 12 | `0012_backups.sql` | `db_backups` table (SP17) |
| 13 | `0013_auth_users_and_sessions.sql` | `users` + `sessions` tables, `users.password_hash` (bcrypt) — landed 2026-06-23 |
| 14 | `0014_audit_log_user_id.sql` | `audit_log.user_id` FK to `users.id` (forward reference to 0013) — landed 2026-06-23 |
The SP22 parse-then-decide migrations (drop claims UNIQUE constraint + relax PK to `(batch_id, id)`) are renumbered to 0015 + 0016 on the `claims-unique-fix` worktree so the auth migrations stay at the front of the chain; they'll keep those numbers when SP22 lands.
### 6.2 ERD (high level)
```
batches (1) ─┬─< (N) claims ─┬─< (N) matches >─ (N) ─┬─ (1) remittances ─< (N) cas_adjustments
│ │ │
│ └─< (N) line_reconciliations (SP7)
│ └─< (N) rejections / claim_state_history
├─< (N) acks (999/271)
├─< (N) ta1_acks
└─< (N) activity_events
claims (1) ─< (N) line_reconciliations ─> (1) cas_adjustments
audit_log (no FKs — append-only, hash-chained)
db_backups (no FKs — directory + filename, status row)
processed_inbound_files (no FKs — path + hash, idempotency key)
providers (1) ─< (N) claims
payers (1) ─< (N) claims
clearhouses (1) ─< (N) payers
```
The `batches` row is the parent of every parsed X12 file. A batch is the unit of atomicity for parsing: either every claim/remit/ack in the file lands, or the file rolls back. The `claims.state` column drives the lifecycle (§6.3); the `matches` table is the join that says "this 835 paid this 837" (with a `strategy` field for audit: auto vs. manual).
### 6.3 Claim lifecycle (7 states)
The `claims.state` column is the canonical state of a claim in the operator's workflow:
```
submitted ──> accepted ──> paid
│ │ │
│ │ └─> reversed
│ │
│ └─> denied ──> appealed ──> paid
└─> rejected (envelope 999)
└─> payer_rejected (277CA A4/A6/A7)
```
- `submitted` — 837P ingested, awaiting 999 ACK
- `accepted` — 999 ACK came back clean; sitting in the trading partner's queue
- `paid` — 835 matched, payment posted
- `reversed` — 835 reversal applied (the original payment + the reversal are both preserved; the `state` reflects the most recent)
- `denied` — 835 came back with a denial status code (CAS group CO)
- `appealed` — operator flagged for appeal workflow
- `rejected` — envelope-level 999 rejection (syntactic / structural)
- `payer_rejected` — semantic 277CA rejection (A4/A6/A7 — claim accepted by envelope but rejected at the line level). SP10 introduced this state and the `claim.payer_rejected_*` columns.
State transitions are explicit functions in `cyclone.store` (e.g. `mark_accepted`, `mark_paid`, `mark_rejected`). Each transition emits an `activity_events` row and, for the security-relevant ones, an `audit_log` row.
### 6.4 Audit chain integrity
The `audit_log` table is a separate chain from `activity_events`:
- `activity_events` — un-chained, powers the `/activity` feed. The activity feed can be repopulated from the underlying state if rows are missing; integrity is informational.
- `audit_log` — SHA-256 hash-chained, powers compliance / forensics. A row cannot be deleted without breaking the chain. `audit_log.verify_chain()` is the integrity check; the SP19 deep health probe runs it on every `/api/health` call.
The two are intentionally separate because they have different retention and integrity requirements. The convention-vs-trigger tradeoff is documented in the [SP11 spec](superpowers/specs/2026-06-23-cyclone-sp11-hash-chained-audit-design.md) §7.
---
## 7. Data flow
### 7.1 File ingest (manual upload)
```
Operator ──drag-drop──> /upload (React)
│ POST /api/upload (multipart, .txt file)
v
FastAPI route
│ save to /tmp/cyclone-uploads/<uuid>.txt
v
parser.dispatch(kind) (auto-detect 837/835/999/TA1/270/271/277CA by ISA segment)
│ (the 5-stage pipeline from §4.4)
v
CycloneStore.add(record) (single SQLAlchemy transaction)
├─> emit activity_events row
├─> for 835: trigger reconcile.apply_payment
├─> for 999/TA1/277CA: mark the source claim
└─> commit
│ emit NDJSON event on the pubsub bus
v
live-tail subscribers (Activity feed, TailStatusPill)
```
The HTTP response is the new `batch_id` + a counts summary (e.g. `{"batch_id": "...", "claims": 12, "remittances": 0, "validation_issues": 0}`). The 999 is the only case where the response carries an ack payload — the operator can read the parsed 999 directly without a second request.
### 7.2 File ingest (SFTP polling — SP16)
```
every N seconds (default 30s, per-payer config):
Scheduler.tick()
├─> for each clearhouse:
│ ├─> SftpClient.list_inbound() (paramiko, SP13)
│ ├─> for each new .x12 file:
│ │ ├─> check processed_inbound_files (idempotency)
│ │ ├─> SftpClient.read_file(path) (to /tmp/...)
│ │ ├─> parser.dispatch(...)
│ │ ├─> CycloneStore.add(record)
│ │ ├─> INSERT processed_inbound_files (path, sha256, ts)
│ │ └─> emit activity_events row
│ └─> log tick result (count, errors, ms)
└─> heartbeat to /api/health (SP19 reports last tick ts)
```
The idempotency table is the linchpin: a crash between "read file" and "INSERT processed" results in the same file being processed again on the next tick. The 5-step ordering (SELECT → INSERT side-effects → INSERT idempotency; IntegrityError as the correctness backstop) is detailed in the [SP16 spec](superpowers/specs/2026-06-23-cyclone-sp16-mft-polling-design.md) §3.4.
### 7.3 File ingest (manual upload, replayed by pipeline)
`cyclone-pipeline/` (sibling project) does the same as the operator dragging-and-dropping — it `POST`s to `/api/upload` with the file. There's no separate "pipeline" ingestion path. The pipeline agent is a thin wrapper that adds preflight + SFTP submit + wait-for-999 around the Cyclone API.
### 7.4 Auto-match on 835 ingest
When an 835 lands, the writer calls `reconcile.apply_payment(claim, remit, strategy)` for each `(claim, remit)` pair in the file. The strategy is one of:
- `auto:pcn_npi_charge` — patient_control_number + provider_npi + charge_amount match (the strongest)
- `auto:pcn_charge` — patient_control_number + charge_amount (the most common in practice)
- `manual` — the operator uses `/reconciliation` to pair by hand; the strategy is recorded for audit
Each auto-match creates a `matches` row + transitions the claim state + emits an `activity_events` row + emits an `audit_log` row. The match rate is visible in the Dashboard KPI tile.
### 7.5 Outbound 837P (resubmit)
Two paths:
- **Single claim** — `GET /api/claims/{id}/serialize-837` (SP8). The serializer round-trips the claim through `serialize_837.py`, validates with the R-code registry, and returns the X12 text. The Claim drawer's "Download 837" button calls this and triggers a browser download.
- **Bundle ZIP** — `POST /api/claims/resubmit?download=zip` (SP8). The serializer rebuilds N 837P files (one per claim in the request), zips them with a manifest, and returns the ZIP. The Inbox BulkBar's "Resubmit selected" calls this.
Both paths are read-only against the DB (they don't mutate the claim state). The operator is expected to download the regenerated file, then submit it manually via SFTP (or via `cyclone-pipeline run`).
### 7.6 Acknowledgement ingestion (999, TA1, 277CA)
These are the three "ack" transaction types the operator's trading partner sends back after a submission:
- **999** — functional ack (envelope-level). Triggers `claim.state = accepted | rejected`.
- **TA1** — interchange ack. Triggers an activity_events row; no state change.
- **277CA** — claim status (line-level). Triggers `claim.payer_rejected` if any line is A4/A6/A7. The `claim.payer_rejected_*` columns carry the status code + the 277CA's batch id for the audit trail.
All three are ingested via the same `/api/upload` path; the parser auto-detects the transaction type from the ISA segment. The SP10 spec describes the monotonic rule: a later 277CA cannot clear a previous rejection. This is the regulatory guarantee the SP11 audit chain relies on.
---
## 8. API surface
### 8.1 REST endpoints (by domain)
The full list is in [REQUIREMENTS.md §6.3 traceability matrix](REQUIREMENTS.md). The structure is:
```
/api/health (SP19 deep health probe)
/api/tail?since=<id> (NDJSON live tail)
/api/upload (multipart, any X12 type)
/api/parse-837 (parse + return Pydantic, do not persist — pipeline agent)
/api/batches (list, with totals + validation)
/api/batches/{id} (detail)
/api/batches/{id}/diff?against={other_id} (batch_diff)
/api/batches/{id}/serialize-837 (SP8 — round-trip)
/api/claims (list, paginated, filterable)
/api/claims/{id} (detail, with remits + matches + line_recons)
/api/claims/{id}/serialize-837 (SP8)
/api/claims/resubmit?download=zip (SP8 bulk)
/api/remittances (list)
/api/remittances/{id} (detail)
/api/providers (rollup)
/api/providers/{npi} (single provider, all claims)
/api/activity?since=<id> (un-chained feed, paginated)
/api/inbox (SP14 5-lane view, filterable)
/api/inbox/payer-rejected/acknowledge (SP10 + SP14)
/api/acks (999/271/277CA list)
/api/acks/{id} (detail)
/api/ta1-acks (TA1 list)
/api/admin/validate-provider?npi=&tax_id= (SP20)
/api/admin/db/rotate-key (SP15)
/api/admin/db/fingerprint (SP12)
/api/admin/backup/create (SP17)
/api/admin/backup/list (SP17)
/api/admin/backup/{id}/restore?confirm=true (SP17, two-step)
/api/admin/backup/{id}/verify (SP17)
/api/admin/scheduler/status (SP16)
/api/admin/scheduler/tick (SP16 — manual trigger)
/api/admin/scheduler/start (SP16)
/api/admin/scheduler/stop (SP16)
```
### 8.2 Live-tail NDJSON format
`GET /api/tail?since=<last_event_id>` returns `Content-Type: application/x-ndjson` and streams:
```
{"kind":"event","id":1234,"event_type":"claim.submitted","payload":{"claim_id":"...","batch_id":"...","ts":"2026-06-23T..."}}
{"kind":"event","id":1235,"event_type":"claim.matched","payload":{"claim_id":"...","remit_id":"...","strategy":"auto:pcn_npi_charge"}}
{"kind":"heartbeat","ts":"2026-06-23T..."}
{"kind":"event","id":1236,"event_type":"claim.payer_rejected","payload":{"claim_id":"...","status_code":"A7","source_277ca_id":"..."}}
```
Heartbeats every 5s when no events. The client reconnects on `error` with exponential backoff capped at 30s. See [live-tail spec](superpowers/specs/2026-06-20-cyclone-live-tail-design.md) for the full wire format.
---
## 9. Cross-cutting concerns
### 9.1 Logging (SP18)
`cyclone.logging_config` configures a single JSON formatter that:
- Emits one JSON object per line to stdout (12-factor)
- Includes `ts`, `level`, `logger`, `msg`, `module`, `line`, `process`, `thread`
- Scrubs PHI/PII fields by key name (`npi`, `member_id`, `patient_name`, `ssn_last4`, `charge_amount`, `paid_amount`, `tax_id`) — replaced with `***`
- Redacts secrets by string match (anything matching `password=...&` or `Bearer ...`)
The PII scrubber is a best-effort defense-in-depth, not a security boundary. Real PHI protection comes from the SQLCipher layer (SP12) and the Keychain (no secrets in env). The scrubber exists so an operator tailing logs to debug doesn't accidentally paste a log line into a chat.
### 9.2 Audit chain (SP11)
See §4.6. The chain is checked on every `/api/health` request and exposes `status="degraded"` if broken. The operator sees the status in the TailStatusPill and the Dashboard KPI tile.
### 9.3 PHI/PII handling
- **Storage** — SQLCipher at rest (opt-in, SP12). Daily encrypted backups (SP17). Tamper-evident audit chain (SP11). 6-year retention via automated backup rotation.
- **In transit (SFTP)** — TLS to the trading partner; no plaintext EDI over the wire.
- **In the UI** — no PHI is shown on the Dashboard or Inbox (only counts + KPIs). The Claim drawer and Remit drawer show full PHI; these pages are not in the route map's preview and require an explicit navigation click.
- **In logs** — scrubbed by key name (see §9.1).
- **In analytics** — no analytics. No third-party tracking. No telemetry. The frontend makes no requests outside `127.0.0.1:8000`.
### 9.4 Error model
Every API error is a JSON object with `{"error": "<code>", "message": "<human>", "detail": <optional>}`. The mapping is in `api_helpers.py`:
| Error class | HTTP status | `error` code |
|---|---|---|
| `AlreadyMatchedError` | 409 | `already_matched` |
| `NotMatchedError` | 409 | `not_matched` |
| `InvalidStateError` | 409 | `invalid_state` |
| `ParseError` | 422 | `parse_error` |
| `ValidationError` (R-codes) | 422 | `validation_failed` (issues in `detail`) |
| `FileNotFoundError` | 404 | `not_found` |
| `ValueError` | 400 | `bad_request` |
| `PermissionError` | 403 | `forbidden` (raised by `matrix_gate` when the role is below the endpoint's required role) |
| (anything else) | 500 | `internal` (with a request id for log correlation) |
The 409-vs-422-vs-400 split is intentional: 409 for state-machine violations (the operator's input is well-formed but conflicts with current state), 422 for parse / validation, 400 for bad input shape.
---
## 10. Operational concerns
### 10.1 Startup order
`python -m cyclone serve``cyclone.api.lifespan` runs:
1. `db.init_db()` — apply pending migrations (0001-0012, plus 0013/0014 on the `claims-unique-fix` worktree)
2. Seed `cyclone.providers` with the SP9 defaults if the table is empty (PayerConfig for Colorado Medicaid + Gainwell)
3. Configure `BackupService` (SP17) — open backup dir, read passphrase from Keychain
4. Configure `Scheduler` (SP16) — wire MFT polling for each clearhouse
5. If `CYCLONE_SCHEDULER_AUTOSTART=true` (default), start both schedulers
6. Mount the FastAPI app and start uvicorn
The ordering is load-bearing: the store facade cannot be used until `init_db` finishes, and the schedulers cannot query the DB until the seed step populates the clearhouse rows.
### 10.2 MFT scheduler (SP16)
`cyclone.scheduler.Scheduler` runs a per-clearhouse tick on a configurable interval (default 30s, per `CYCLONE_SCHEDULER_INTERVAL` env var). The tick is described in §7.2. The scheduler is opt-in via `CYCLONE_SCHEDULER_AUTOSTART`; the operator can start/stop it from the admin endpoints or via `POST /api/admin/scheduler/tick` for a manual tick.
The 4-step idempotency sequence (SELECT → INSERT side-effects → INSERT idempotency; IntegrityError as the correctness backstop) is the linchpin. The scheduler's `_already_processed` + `_record` pair wraps the INSERT to handle the case where two ticks race (an extremely rare event given the 30s interval, but possible during operator-driven manual ticks).
### 10.3 Backup scheduler (SP17)
`cyclone.backup_scheduler.BackupScheduler` wraps `BackupService` and ticks on its own interval (default 24h, per `CYCLONE_BACKUP_INTERVAL` env var). On each tick: create a backup, prune anything older than `retention_days` (default 30). Auto-start opt-in via `CYCLONE_BACKUP_AUTOSTART`.
The encryption layer is independent of SQLCipher: AES-256-GCM with a passphrase-derived key (PBKDF2-HMAC-SHA256, 200k iterations). The passphrase lives in the macOS Keychain. If the passphrase is missing, the backup layer falls back to deriving a key from the SQLCipher key (less ideal but never silently broken — the operator's `/api/health` reports `status="degraded"` with a `backup.passphrase_missing` flag).
### 10.4 Health probe (SP19)
`GET /api/health` is a deep snapshot:
- **db** — open a session, `SELECT 1`
- **scheduler** — last tick ts, is alive
- **pubsub** — current subscriber counts per event kind
- **batch** — most recent batch id + ts
- **audit_log** — `verify_chain()` result (deep check on every call; 1ms on a healthy chain, fails loudly on a broken one)
- **backup** — last backup ts, last verify result, passphrase presence
- **encryption** — `is_encryption_enabled()` boolean
Returns `status="ok"` only when every subsystem is healthy. `status="degraded"` if any subsystem is unhappy but the API itself is responsive. The status is shown in the TailStatusPill (bottom-right) and the Dashboard KPI tile.
### 10.5 Shutdown
`SIGTERM` (or Ctrl-C) → uvicorn drains in-flight requests → cancels the MFT scheduler (in-flight tick completes via `asyncio.to_thread`) → cancels the backup scheduler (in-flight tick completes) → closes the SQLAlchemy engine → exits 0. There is no checkpoint; the in-flight tick is allowed to complete naturally because the idempotency table makes a partial-tick restart safe.
---
## 11. Deployment
### 11.1 Local dev (default)
The default deployment. Two terminals:
```bash
# Terminal 1 — backend on 127.0.0.1:8000
cd backend
.venv/bin/python -m cyclone serve
# Terminal 2 — frontend on localhost:5173
cd ..
npm run dev
```
The frontend reads its backend URL from `VITE_API_BASE_URL` (default empty). Create `.env.local` at the repo root with `VITE_API_BASE_URL=http://127.0.0.1:8000`. Without it, the UI falls back to its in-memory sample store via the `data` adapter (parses are disabled).
### 11.2 Optional Docker (SP23 — product fork)
A Ubuntu + Docker + auth + RBAC + LAN-bind spec exists at [`docs/superpowers/specs/2026-06-22-cyclone-ubuntu-docker-deployment-design.md`](superpowers/specs/2026-06-22-cyclone-ubuntu-docker-deployment-design.md). This is a **product fork** awaiting user decision (per [REQUIREMENTS.md §6.2](REQUIREMENTS.md)). The v1 single-host single-operator posture assumes local-only; SP23 changes the threat model to "remote operator on LAN."
### 11.3 Single-host "production"
For a single operator on a single machine, the dev deployment IS the production deployment. There is no separate build / deploy pipeline; the v1 distribution model is `git clone && pip install -e '.[dev]' && npm install && python -m cyclone serve`. A release-time gate (not yet implemented — backlog item) would run `pytest` (backend) and `npm test` (frontend) and fail if any test is red.
---
## 12. Out of scope (v1)
The following are explicitly NOT built in v1, by design:
- **Multi-user / multi-host** — login is required (single-user model today; SP23 adds RBAC). LAN-bind, Docker, reverse proxy still out of scope. (SP23 covers the LAN-bind / Docker / RBAC product fork.)
- **Other trading partners** — only Colorado Medicaid via Gainwell is configured. The `PayerConfig` mechanism (SP9) supports adding more; the spec/plan/CLI work for that is on the backlog.
- **837I / 837D / 834 / 820 / 275 / 278 / 276-277** — only 837P and 835 are first-class. Other transaction types are listed in [REQUIREMENTS.md §6.2](REQUIREMENTS.md) as backlog items.
- **NPPES real-time lookup** — only local NPI checksum validation (SP20). The operator who wants real registry lookup has to wire it in later.
- **EHR / PM integration** — no webhook in/out, no callable `POST /api/parse-837` (the pipeline agent uses `/api/upload` for now).
- **COB / secondary claims** — no automatic coordination-of-benefits generator. The operator generates a secondary 837P by hand from the CAS adjustments.
- **Real-time eligibility** — no SFTP pickup + SOAP + 271 round-trip. The 270/271 parsers exist; the live cycle doesn't.
Each of these is a separate SP. The "v1 done" bar is the 22 shipped SPs (SP1SP22) on `main` plus the [REQUIREMENTS.md §8 DoD](REQUIREMENTS.md).
---
## 13. References
### 13.1 Top-level docs
- [Requirements](REQUIREMENTS.md) — FRs, NFRs, DoD, traceability
- [README](../../README.md) — install + dev + pipeline agent
### 13.2 Specs (per sub-project)
All in `docs/superpowers/specs/`:
- SP1 production-readiness: `2026-06-19-cyclone-production-readiness-design.md`
- SP2 DB + reconciliation: `2026-06-19-cyclone-db-reconciliation-design.md`
- SP3 EDI features: `2026-06-20-cyclone-edi-features-design.md`
- SP4 claim drawer: `2026-06-20-cyclone-claim-drawer-design.md`
- SP5 live tail: `2026-06-20-cyclone-live-tail-design.md`
- SP7 line reconciliation: `2026-06-20-cyclone-line-reconciliation-design.md`
- SP8 serialize 837: `2026-06-20-cyclone-serialize-837-design.md`
- SP9 multi-payer / NPI / SFTP stub: `2026-06-20-cyclone-multi-payer-npi-sftp-design.md`
- SP10 277CA: `2026-06-23-cyclone-sp10-277ca-payer-rejected-design.md`
- SP11 audit log: `2026-06-23-cyclone-sp11-hash-chained-audit-design.md`
- SP12 SQLCipher: `2026-06-23-cyclone-sp12-sqlcipher-encryption-design.md`
- SP13 SFTP client: `2026-06-23-cyclone-sp13-sftp-client-design.md`
- SP14 5-lane Inbox: `2026-06-23-cyclone-sp14-inbox-5lane-design.md`
- SP15 key rotation: `2026-06-23-cyclone-sp15-key-rotation-design.md`
- SP16 MFT scheduler: `2026-06-23-cyclone-sp16-mft-polling-design.md`
- SP17 encrypted backup: `2026-06-21-cyclone-encrypted-backup-design.md`
- SP18 structured logging: `2026-06-21-cyclone-structured-logging-design.md`
- SP19 security hardening: `2026-06-21-cyclone-security-hardening-design.md`
- SP20 NPI validation: `2026-06-21-cyclone-npi-validation-design.md`
- SP21 store split: `2026-06-21-cyclone-store-split-design.md`; universal drilldown: `2026-06-21-cyclone-universal-drilldown-design.md`
- SP22 parse-decide: `2026-06-21-cyclone-parse-decide-workflow-design.md`; pipeline agent: `2026-06-21-cyclone-pipeline-agent-design.md`
- SP23 (fork) Ubuntu + Docker: `2026-06-22-cyclone-ubuntu-docker-deployment-design.md`
### 13.3 Plans
All in `docs/superpowers/plans/`. 27 files — one per spec (plus the round-2 backfill for SP9SP20 in the `2026-06-23-cyclone-sp*` naming).
### 13.4 Reference docs
- `docs/reference/co-medicaid.md` — operator setup for SQLCipher + SFTP + the Gainwell trading-partner details (KP-specific).
### 13.5 Sibling project
- `cyclone-pipeline/` — round-trip agent (sibling, not in this repo). See [README](../../README.md) §"Pipeline automation agent" for install + usage.
+739
View File
@@ -0,0 +1,739 @@
# Cyclone — Requirements, Architecture, Tasks, and Test Strategy
**Date:** 2026-06-23
**Status:** Round 2 (post-review corrections — ready for verification)
**Audience:** New engineer or AI agent who needs to understand Cyclone's contract, the work that's already shipped, the work that's not, and what "done" means before they write a single line of code.
**Scope:** Local-only, single-operator, single-host EDI claims-management suite for one billing office, currently trading with Colorado Medicaid (CO XIX).
**Sister docs:** [`README.md`](../README.md) is the operator-facing entry point; [`docs/ARCHITECTURE.md`](ARCHITECTURE.md) is the top-level technical design (process topology, package layout, data flow, lifecycle); [`docs/superpowers/specs/`](superpowers/specs/) holds per-SP design specs; [`docs/superpowers/plans/`](superpowers/plans/) holds per-SP implementation plans; [`docs/reviews/2026-06-20-cyclone-completeness-review.md`](reviews/2026-06-20-cyclone-completeness-review.md) is the industry-scope gap analysis; [`docs/reference/`](reference/) holds condensed X12 / payer notes.
---
## 0. How to read this document
| If you want to know… | Go to |
|---|---|
| What Cyclone is and is not | §1, §2 |
| What it must do (functional) | §3 |
| What it must *not* fail at (non-functional) | §4 |
| How the system is built | §5 |
| Which sub-project (SP) owns which requirement | §3 + §6 traceability matrix |
| What "shipped" means | §7 |
| What "done" means for the project as a whole | §8 |
| How we test | §9 |
| What we're assuming to be true | §10 |
| What's still missing or risky | §11 |
Every requirement (§3, §4) has an ID; every ID is traceable to a sub-project (§6) which in turn points at a design spec and an implementation plan. The matrix at the end of §6 is the single index that ties everything together.
**Round history.** Round 1 (2026-06-23) produced this draft. Two independent reviewers (Reviewer A — components/data-model/deps/DoD; Reviewer B — traceability/consistency audit) read it against the actual codebase and surfaced 12 factual errors and 6 structural improvements. Round 2 (this version) applies every factual correction. Round 3 (pending) will re-verify reviewer agreement on the corrected doc.
---
## 1. The contract — what Cyclone is
A self-hosted EDI claims-management suite for a single billing office. Parses 837P professional claims and 835 ERA remittances (X12 005010X222A1 and 005010X221A1), with a local-only FastAPI backend and a React UI for browsing, filtering, and inspecting the parsed data.
- **Local-only on purpose:** binds `127.0.0.1`, requires login (auth boundary is HTTP; bcrypt + HttpOnly session cookie), no internet exposure, single operator, single machine, one trading partner (Colorado Medicaid, currently).
- **Single-process:** the backend is one Python process; the frontend is one Vite-served React app; there is no message broker, no separate worker, no queue.
- **Single source of truth:** SQLite at `~/.local/share/cyclone/cyclone.db` (overridable via `CYCLONE_DB_URL`); optionally encrypted at rest via SQLCipher (SP12).
- **Threat model:** a process on the same host, plus a deliberate HTTP-layer login (no remote unauthenticated read or write). File-system threats (stolen/imaged drive) are still the primary concern; SQLCipher at rest + the macOS Keychain handle those. The SP23 product fork changes the threat model to "remote operator on LAN."
The Cyclone codebase has honored this contract end-to-end across 22 shipped sub-projects. Every design spec re-asserts the local-only / single-operator / single-payer / no-auth posture and lists (often at length) what is intentionally out of scope.
---
## 2. Scope boundaries
### 2.1 In scope (today, after SP1SP22)
| Capability | SP |
|---|---|
| 837P (005010X222A1) parse + serializer with round-trip guarantee | SP1 + SP8 |
| 835 (005010X221A1) parse + CAS deep-parsing | SP1 + SP3 |
| 999, TA1, 270, 271, 277CA parse / generate | SP3 + SP10 |
| Structural validation rules (R021, R034, R035, R200, R210, …) | SP3 + SP20 |
| SQLite persistence with forward-compatible migrations | SP2 + SP9SP17 |
| Automatic 837P ↔ 835 reconciliation; manual reconciliation UI | SP2 + SP7 |
| 7-state claim lifecycle with reversal handling | SP2 |
| Tamper-evident hash-chained audit log | SP11 |
| NDJSON pubsub on store writes + live-tail UI with reconnect | SP5 |
| 5-lane inbox (Rejected / Payer-rejected / Candidates / Unmatched / Done today) | SP6 + SP10 + SP14 |
| Per-line 837 SV1 ↔ 835 SVC adjustment audit | SP7 |
| Per-claim and per-remit detail drawers + Cmd-K search + batch diff + CSV export | SP4 + SP21 |
| Universal drilldown (drawer + peek modal everywhere) | SP21 |
| Multi-payer / multi-NPI config + clearhouse stub | SP9 |
| `paramiko`-backed SFTP wire to Gainwell MFT | SP13 |
| 24h MFT inbound scheduler with idempotent file processing | SP16 |
| SQLCipher encryption at rest + key rotation | SP12 + SP15 |
| Automated AES-256-GCM encrypted DB backups | SP17 |
| Structured JSON logging + PII scrubber | SP18 |
| Security hardening (body size limit, rate limit, security headers) | SP19 |
| NPI Luhn checksum + Tax ID format validation | SP20 |
| CycloneStore split (refactor; **in-flight on `refactor/store-split`**) | SP21 |
| Parse-then-decide upload dedup (idempotency) | SP22 |
| Pipeline automation agent (sibling project at `cyclone-pipeline/`) | SP22 |
### 2.2 Out of scope (today, by design)
| Item | Why |
|---|---|
| AS2 / AS4 (EDIINT, signed, encrypted, MDN-back) connectivity | Single-host local tool; the operator hands the 837 ZIP to the Gainwell MFT UI manually |
| Real-time 270/271 round-trip over CAQH CORE Phase II/III SOAP envelopes | Out of single-host scope; builder + parser are X12-only |
| 837I (institutional), 837D (dental), 834, 820, 275, 278, 276/277 | Single-payer scope; not currently demanded by the CO XIX workflow |
| NPPES NPI registry lookup (offline validation only) | Single-host, no internet exposure |
| ICD-10 / HCPCS / NDC vocabulary tables | Structural validation only; the operator has the source vocab |
| COB / secondary-claim generator | Workflow scope |
| HITRUST / SOC 2 / BAA template | Single-operator; threat model doesn't require them |
| HA / DR / load balancing / multi-host replication | Single-host scope |
| Prometheus / Grafana / alerting | `curl health \| mail` cron is sufficient |
| 2FA / SSO / OAuth | Single-operator |
| LUKS full-disk encryption | Operator / host concern |
| Component / E2E browser tests (Playwright) | Local-only, manual smoke scripts are sufficient |
### 2.3 Deferred with rationale
- **Public TLS / public domain / Caddy reverse proxy** — LAN-only bind is enough for the v1 single-Ubuntu-server posture; VPN handles outside access. (Re-evaluated if the Ubuntu Docker plan ships.)
- **Off-box automated backup shipping** — host cron / rsync is documented in the operator runbook, not automated in code.
- **Self-service password reset** — admin can reset via CLI; self-service is v2 (would only be relevant if auth ships).
- **Per-file encryption of prodfiles / `sftp_staging`** — relies on volume-level filesystem permissions + the SQLCipher-encrypted DB + the host being physically secure.
- **Watchtower / automatic updates** — manual `docker compose pull` keeps the operator in the loop on schema migrations.
---
## 3. Functional requirements
Each requirement is `FR-NN`, traceable to one or more sub-projects. Verification is "shipped + tested" (see §6) or "planned" (see §6.2).
| ID | Requirement | SP |
|---|---|---|
| FR-1 | Parse an uploaded 837P file into structured `Claim` records. | SP1 |
| FR-2 | Parse an uploaded 835 file into structured `Remittance` records with per-CAS adjustment rows. | SP1 + SP3 |
| FR-3 | Persist every successful parse to SQLite; survive backend restart. | SP2 |
| FR-4 | Run a forward-compatible migration runner (`PRAGMA user_version`) so the schema can evolve without Alembic. | SP2 |
| FR-5 | Auto-match each 835 `CLP` back to a prior 837 `Claim` within ±7 days via `(claim_id, service_date)`; apply lifecycle transitions; write `Match` and `ActivityEvent` rows. | SP2 |
| FR-6 | Maintain a 7-state claim lifecycle (`submitted → received → paid|partial|denied → reconciled → reversed`) with `state_before_reversal` preserved on reversal. | SP2 |
| FR-7 | Provide a `/reconciliation` page that lists unmatched claims and unmatched remittances and supports manual pair/unpair. | SP2 (tests live in `test_reconcile.py`, `test_reconcile_line_level.py`, `test_inbox_endpoints.py`, `test_api_gets.py`) |
| FR-8 | Run structural 837P validation rules R021 (NPI checksum, warning-only), R034 (`REF*G1` on frequency 7/8), R035 (`BHT06` transaction-type allowlist), R200/R210. | SP3 + SP20 |
| FR-9 | Generate a 999 ACK transaction set on 837 ingest when `?ack=true` is passed to `POST /api/parse-837`; persist it to the `acks` table. | SP3 |
| FR-10 | Parse inbound 999 ACKs and surface them on a `/acks` page with regenerable raw text. | SP3 |
| FR-11 | Parse + persist TA1 interchange ACKs (separate from 999 transaction-set ACKs). | SP3 |
| FR-12 | Build a 270 from a JSON payload (`POST /api/eligibility/request`) and parse an inbound 271 (`POST /api/eligibility/parse-271`) into `coverage_benefits`. | SP3 |
| FR-13 | Parse inbound 277CA files and stamp `payer_rejected` on claims whose STC category is A4/A6/A7 — monotonic (a looser later 277CA cannot downgrade). Also persist 277CA ACK rows to `two77ca_acks`. | SP10 |
| FR-14 | Provide a `/inbox` page with five lanes ordered by urgency: Rejected (999 R/E), Payer-rejected (277CA A4/A6/A7), Candidates (CLP didn't auto-match), Unmatched (waiting), Done today (last 24h terminal transitions). | SP6 + SP10 + SP14 |
| FR-15 | Score each Candidate on 4 weighted fields (patient control number 40, service date 25, charge amount 20, provider NPI 15); tier strong (≥75, Match enabled), weak (5074, dimmed), hidden (<50). | SP6 |
| FR-16 | Provide per-claim and per-remit detail drawers with full raw X12 segments, state-history timeline, validation panel, line-level reconciliation tab, and party grid. URL is synced (`?claim=…`, `?remit=…`). | SP4 + SP7 + SP21 |
| FR-17 | Provide a side-by-side Batch Diff view (added / removed / changed claims). | SP4 (logic lives in `cyclone/batch_diff.py`) |
| FR-18 | Provide a global Cmd-K search across claims, remittances, activity, and acks. | SP4 |
| FR-19 | Provide per-page CSV export for claims, remittances, and inbox lanes. | SP4 |
| FR-20 | Provide a live-tail NDJSON stream on `/api/{claims,remittances,activity}/stream` with snapshot-first, `snapshot_end`, heartbeat, and reconnect. | SP5 |
| FR-21 | Surface a `TailStatusPill` with states `live / connecting / reconnecting / stalled / error / closed`, with backoff ladder `1s → 2s → 4s → 8s → 16s → 30s` capped. | SP5 |
| FR-22 | Tie every 835 CAS adjustment back to the specific 837 SV1 service line it adjudicates; surface unmatched-line warnings. | SP7 (line-reconciliation rows in `line_reconciliations`) |
| FR-23 | Serialize a single edited claim back to a valid X12 837P file with round-trip guarantee (113 prodfiles parse → serialize → parse to the same `claim_id`). | SP8 |
| FR-24 | Export a ZIP bundle of selected rejected claims as a batch ready to hand to the MFT UI. | SP8 |
| FR-25 | Load payer / payer_config / clearhouse config from `config/payers.yaml` (parsed via `pyyaml`) and 3 new DB tables (`providers`, `payers`, `payer_configs`); replace the in-code `PAYER_FACTORIES` dict. | SP9 |
| FR-26 | Push a `cyclone clearhouse submit` to the Gainwell MFT inbound path via `paramiko` (`SftpClient` lives in `cyclone/clearhouse/__init__.py`). Credentials read from the macOS Keychain via the `keyring` library at call time. | SP13 |
| FR-27 | Poll the Gainwell MFT inbound path every tick (configurable); route downloaded files to the right parser (999 / 835 / 277CA / TA1); idempotent via `processed_inbound_files`; crash-safe via per-file try/except. | SP16 |
| FR-28 | Optionally encrypt the SQLite file via SQLCipher (AES-256); key fetched from the macOS Keychain via `keyring`. Falls back to plain SQLite if the Keychain entry is missing. | SP12 |
| FR-29 | Rotate the SQLCipher key in place via `PRAGMA rekey`, serialized through a `threading.Lock` and SQLAlchemy `NullPool`; write `db.key_rotated` audit event with old + new key fingerprints and post-rotation `table_count`. | SP15 |
| FR-30 | Produce AES-256-GCM encrypted DB backups (PBKDF2-HMAC-SHA256, 200k iters) via the existing `BackupService`; two-step restore (`initiate``confirm` with one-shot 64-char hex token); retention pruning with a 30-day default. Backups table is `db_backups`. | SP17 |
| FR-31 | Emit all API / CLI / scheduler / backup logs as newline-delimited JSON with ISO-8601 ms timestamps; redact obvious PHI (NPIs, SSNs, DOBs, patient names) via a `PiiScrubber` filter on message + extras. | SP18 (uses stdlib `logging` + a JSON formatter, not structlog) |
| FR-32 | Reject oversize request bodies (413), rate-limit requests (429), and add default security headers via pure-ASGI middlewares; emit a tamper-evident `api.request_rejected` audit event on 413/429. | SP19 |
| FR-33 | Surface a rich `GET /api/health` response — DB connectivity, MFT scheduler state, backup scheduler state, live pubsub subscriber counts, last batch id + timestamp. | SP19 (`api_routers/health.py:28-40`) |
| FR-34 | Validate NPI with the CMS-published Luhn over `80840 + body` (warning-only — placeholder NPIs in test fixtures shouldn't block ingest). Reject Tax ID (EIN) with reserved prefixes (`00`, `07`, `80``89`). | SP20 |
| FR-35 | Split `CycloneStore` into per-concern modules (`store_persistence`, `store_reconcile`, `store_queries`, `store_mappers`) without changing the public store API. | SP21 (**in-flight** on `refactor/store-split` branch) |
| FR-36 | De-duplicate 837 / 835 uploads via a parse-then-decide workflow (`find_existing_batch_for_claim` / `find_existing_batch_for_remit`); relax the claims/remits PK to `(batch_id, id)` via migration 0014 to support re-parses into different batches. | SP22 (migration 0014 in worktree; not yet on `main`) |
| FR-37 | (Sibling project, not in this repo) Drive the full 7-phase round-trip — preflight → browser upload → parse verify → SFTP submit → TA1 wait → 999 wait → scan + report — with crash-safe resume, structured JSON logging, idempotency dedup, per-run folder. | SP22 (`cyclone-pipeline/`) |
| FR-38 | Provide a `DrillStackProvider` + `DrillDrawerHeader` shell so every drillable cell across the app opens a consistent drawer or peek modal. | SP21 |
---
## 4. Non-functional requirements
| ID | NFR | Source / SP |
|---|---|---|
| NFR-1 | **Local-only bind + auth.** Backend binds `127.0.0.1:8000` (overridable via `CYCLONE_PORT`); CORS allowlist is exact (`http://localhost:5173`); login required (bcrypt + HttpOnly session cookie; first admin bootstrapped from env vars `CYCLONE_ADMIN_USERNAME` + `CYCLONE_ADMIN_PASSWORD`); dev/test escape hatch via `CYCLONE_AUTH_DISABLED=1` (logs WARNING at boot). | SP1 + auth (2026-06-23 merge) + SP24 (doc reconciliation) |
| NFR-2 | **Determinism.** Parser / serializer round-trip is guaranteed on 113 real prodfiles (`docs/prodfiles/claims/*.x12`); canonical fields, not byte-identity (called out in the SP8 spec). | SP8 |
| NFR-3 | **Audit completeness.** Every reconciliation anomaly, every state transition, every 999/277CA reject writes an `ActivityEvent` (in `activity_events` table, un-chained; powers the `/activity` feed and inbox state transitions). | SP2 + SP10 |
| NFR-4 | **Tamper-evidence.** A separate `audit_log` table (SP11) carries SHA-256 hash-chained rows for security-sensitive events (login attempts, rejections, key rotations, backup lifecycle, rejected requests). `GET /api/admin/audit-log/verify` detects any break. **The `activity_events` (NFR-3) and `audit_log` (NFR-4) tables are distinct** — different semantics, different audiences. New code that needs an audit row must decide which one to write to. | SP11 |
| NFR-5 | **Encrypted at rest (optional).** SQLite is encrypted via SQLCipher AES-256 when the macOS Keychain entry exists and `sqlcipher3` is installed; plain SQLite otherwise. | SP12 |
| NFR-6 | **Encrypted backups.** Backups are AES-256-GCM encrypted at rest (PBKDF2-HMAC-SHA256, 200k iters); passphrase lives in the macOS Keychain (`cyclone backup init-passphrase`). | SP17 |
| NFR-7 | **Logging discipline.** API / CLI / scheduler / backup logs flow through a `JsonFormatter` (NDJSON, ISO-8601 ms) by default; `PiiScrubber` redacts obvious PHI; configurable via `CYCLONE_LOG_LEVEL` / `CYCLONE_LOG_FILE` / `CYCLONE_LOG_JSON` / `CYCLONE_LOG_NO_PII_SCRUB`. | SP18 |
| NFR-8 | **Operational hygiene.** Request body size limit, rate limit, and default security headers are middleware-enforced (SP19). `EXEMPT_PATHS = ("/api/health", "/healthz", "/readyz")` is the documented bypass list (`cyclone/security.py:201`). | SP19 |
| NFR-9 | **Thread-affinity.** SQLCipher operations are serialized through a `threading.Lock` + SQLAlchemy `NullPool` to keep SQLCipher thread-affine under FastAPI's per-request threadpool. | SP12 + SP15 |
| NFR-10 | **Live-tail resilience.** Heartbeat every 15s default (`CYCLONE_TAIL_HEARTBEAT_S`); client flips to `stalled` after 30s of total silence (heartbeat included); reconnect backoff capped at 30s. | SP5 |
| NFR-11 | **Payer config externalized.** Payer / payer_config / clearhouse config lives in `config/payers.yaml` + DB tables, not in code; a new payer is a YAML + DB row, not a code change. Note: `co_medicaid()` factory in `cyclone/parsers/payer.py:57-58` still exists as a fallback for tests and the default-payer selection (R-4 in §11). | SP9 |
| NFR-12 | **Idempotency.** Inbound MFT files are de-duplicated via `processed_inbound_files`; 837/835 uploads are de-duplicated via the parse-then-decide workflow with `(batch_id, claim_id)` / `(batch_id, remit_id)` relaxed PKs. | SP16 + SP22 |
| NFR-13 | **Crash-safety.** Incoming files are processed inside per-file try/except so a bad file doesn't stop the MFT loop; the pipeline agent has crash-safe resume keyed by run id. | SP16 + SP22 |
| NFR-14 | **Single-process.** No message broker, no separate worker, no queue; everything runs in one Python process. | (project-wide constraint) |
| NFR-15 | **Test density.** Backend tests: **964 collected** (`pytest --collect-only`, 2026-06-23); frontend test files: **73**; prodfiles are exercised (113 + 19 + 1369), not just minimal fixtures. | (project-wide) |
| NFR-16 | **Documentation discipline.** Every shipped sub-project has a design spec + implementation plan + smoke test; a new engineer can read the project top-to-bottom. (SPs 916 ship without on-disk plan files — see §6.1 — but their `feat(spN)` commits are on `main` and carry their own commit-message plan.) | (project-wide) |
| NFR-17 | **Fail-soft posture.** Reconciliation crashes don't lose the 835; the activity event records the failure. | SP2 |
| NFR-18 | **Migration safety.** Migrations are forward-only via `PRAGMA user_version`; rollback procedures are documented per migration; the `user_version` runner is idempotent. **No checksum manifest exists today** (R-13 in §11). | SP2 + SP22 |
---
## 5. Architecture overview
### 5.1 Components
**Backend (one Python process, FastAPI on uvicorn) — modules under `backend/src/cyclone/`:**
| Module | Owns | Notes |
|---|---|---|
| `cyclone.api` | HTTP routes, content negotiation, CORS allowlist, lifespan | 3,145 LOC (largest single file; partly split into `api_routers/` for 4 sub-routes) |
| `cyclone.api_helpers` | NDJSON / content-negotiation / live-tail helpers | |
| `cyclone.api_routers` | `acks`, `admin`, `health` (`/api/health`), `ta1_acks` sub-routers | Mounted at `api.py:270-273`; only 4 routes split out — bulk of routes still in `api.py` |
| `cyclone.store` | Public store facade; persistence, reconciliation, queries, mappers | 2,172 LOC; SP21 split is in-flight on `refactor/store-split` |
| `cyclone.db` | SQLAlchemy engine, session factory, ORM models (18 tables) | |
| `cyclone.db_migrate` | `PRAGMA user_version` migration runner | |
| `cyclone.db_crypto` | Optional SQLCipher encryption at rest; key rotation | `rotate_key()` is destructive (rewrites every page) |
| `cyclone.audit_log` | Hash-chained `audit_log` (SP11, SHA-256 chain) | Distinct from `cyclone.activity_events` written by other modules |
| `cyclone.inbox_lanes` | The 5-lane inbox payload (Rejected / Payer-rejected / Candidates / Unmatched / Done today) | |
| `cyclone.inbox_state` | 999 envelope reject → claim state transitions | |
| `cyclone.inbox_state_277ca` | 277CA STC A4/A6/A7 → payer_rejected stamp (monotonic) | |
| `cyclone.providers` | Multi-NPI provider lookups | |
| `cyclone.payers` | Payer / payer_config lookups | Loads `config/payers.yaml` via `pyyaml` |
| `cyclone.secrets` | macOS Keychain-backed secret fetcher (wraps `keyring`) | |
| `cyclone.reconcile` | Pure-function 835→claim match + line-level match | No DB session inside; testable with fabricated ORM objects |
| `cyclone.scoring` | 4-field weighted candidate scoring (40/25/20/15) | Weights hardcoded — see R-10 in §11 |
| `cyclone.pubsub` | In-process EventBus (drop-oldest, per-kind fan-out) | In-process only; not thread-safe across asyncio event loops |
| `cyclone.backup` | AES-256-GCM encrypted backups (orchestration + CLI) | 216 LOC |
| `cyclone.backup_service` | Backup lifecycle (create / verify / restore) | 740 LOC |
| `cyclone.backup_scheduler` | 24h backup autostart loop | 315 LOC |
| `cyclone.scheduler` | asyncio MFT polling loop (SP16) | Uses `processed_inbound_files` for idempotency |
| `cyclone.security` | Per-IP rate-limit, body-size limit, security headers (`SecurityHeadersMiddleware`, `BodySizeLimitMiddleware`, `RateLimitMiddleware`) | `EXEMPT_PATHS` list at `:201` |
| `cyclone.logging_config` | JSON formatter, PII scrubber | |
| `cyclone.npi` | NPI Luhn + EIN format validators | |
| `cyclone.batch_diff` | Batch Diff engine (powers `GET /api/batch-diff`) | 12 public functions/classes |
| `cyclone.clearhouse` (`__init__.py`) | `SftpClient` (SP9 stub + SP13 paramiko), `InboundFile`, `make_client()` factory | 318 LOC; the SFTP home |
| `cyclone.edi` (`filenames.py`) | HCPF X12 File Naming Standards helpers | Used by SP13/SP16 outbound filename construction |
| `cyclone.cli` | Click CLI | |
| `cyclone.__main__` | `python -m cyclone serve` | |
| `cyclone.parsers/` | X12 tokenizer, models, validator, writers, 277CA, 999, TA1, 270, 271, CAS, seg | 25 `.py` modules |
**Stale artifact (do not import):** `backend/src/cyclone/workflow/` contains only a `__pycache__/` subdir with stale `.pyc` files (no `__init__.py`, no source). The actual sources live at the top level. Recommend deleting the directory.
**Frontend (one Vite-served React app) — directories under `src/`:**
| Directory | Owns |
|---|---|
| `src/pages/` | Acks, ActivityLog, BatchDiff, Batches, Claims, Dashboard, Inbox, Providers, Reconciliation, Remittances, Upload (11 pages) |
| `src/hooks/` | TanStack Query hooks, URL-state hooks, live-tail hooks, keyboard hooks, batch-export, search, drawer keyboard, count-up, provider detail, payer summary, parse, ack detail (35+ files) |
| `src/lib/` | `api.ts`, `format.ts`, `utils.ts`, `csv.ts`, `download.ts`, `event-routing.ts`, `tail-stream.ts`, `inbox-api.ts` (all with paired `.test.ts`) |
| `src/components/` | 3 drawer families (`ClaimDrawer/` ~15 files, `RemitDrawer/` ~10 files, `ProviderDrawer/` ~6, `AckDrawer/` 3); `inbox/` (10 files), `drill/` (10 files, includes `DrillStackProvider` + `DrillDrawerHeader`), `charts/` (4 files), `ui/` (18 shadcn primitives — radix + cva + tailwind-merge), `KeyboardCheatsheet/` (3 files), plus top-level ActivityFeed, AnimatedNumber, BatchDetail, BatchDiffView, BatchesList, ClaimCard837, DominantKpiCard, EditorialNote, ExportBar, ExportCsvButton, KpiCard, Layout, NewClaimDialog, PageHeader, SearchBar, SearchResults, Sidebar, Sparkline, StatusBadge, StatusPill, TailStatusPill, TickerTape |
| `src/store/` | `index.ts` (zustand sample data), `tail-store.ts` (FIFO-capped live tail slices) |
| `src/types/` | `index.ts` (flat barrel of shared TS types) |
### 5.2 Data model
**12 SQL migrations** in `backend/src/cyclone/migrations/` (verified on disk 2026-06-23):
| # | File | Tables / columns added |
|---|---|---|
| 0001 | `0001_initial.sql` | `batches`, `claims`, `remittances`, `cas_adjustments`, `matches`, `activity_events` (6 tables) |
| 0002 | `0002_acks.sql` | `acks` |
| 0003 | `0003_drop_claims_remits_unique_constraints.sql` | Drops `claims` and `remittances` UNIQUE constraints |
| 0004 | `0004_rejections_and_state_history.sql` | Adds `rejection_reason`, `rejected_at`, `resubmit_count`, `state_changed_at` to `claims` (no new table) |
| 0005 | `0005_create_ta1_acks.sql` | `ta1_acks` |
| 0006 | `0006_line_reconciliation.sql` | `service_line_payments`, `line_reconciliations`; FK `service_line_payment_id` on `cas_adjustments`; `claim_level_adjustment_amount` on `remittances` |
| 0007 | `0007_providers_payers_clearhouse.sql` | `providers`, `payers`, `payer_configs`, `clearhouse` |
| 0008 | `0008_payer_rejected_columns.sql` | `two77ca_acks` (table) + `payer_rejected` columns on `claims` |
| 0009 | `0009_audit_log.sql` | `audit_log` (SHA-256 hash-chained) |
| 0010 | `0010_payer_rejected_acknowledged.sql` | `payer_rejected_acknowledged` column on `claims` |
| 0011 | `0011_processed_inbound_files.sql` | `processed_inbound_files` (SP16 idempotency) |
| 0012 | `0012_backups.sql` | `db_backups` (SP17) |
**In-flight on `claims-unique-fix` worktree (not yet on `main`):**
| # | File | Tables / columns added |
|---|---|---|
| 0013 | `0013_drop_claims_unique_constraint.sql` | Drop `claims` UNIQUE constraint |
| 0014 | `0014_relax_claims_remits_pk.sql` | Relax PK to `(batch_id, id)` (SP22) |
**ORM models** (declared in `backend/src/cyclone/db.py` — 18 classes total):
| Python class | Table | Notes |
|---|---|---|
| `Batch` | `batches` | |
| `Claim` | `claims` | |
| `Remittance` | `remittances` | |
| `CasAdjustment` | `cas_adjustments` | |
| `ServiceLinePayment` | `service_line_payments` | Created by 0006; SP1+ |
| `LineReconciliation` | `line_reconciliations` | Created by 0006; SP7 backbone |
| `Match` | `matches` | Reversals add a second row (NOT UNIQUE on `(claim_id, remittance_id)`) |
| `Ack` | `acks` | |
| `Ta1Ack` | `ta1_acks` | |
| `ActivityEvent` | `activity_events` | Created by 0001; SP2 — distinct from `AuditLog` |
| `Two77caAck` | `two77ca_acks` | Created by 0008; SP10 |
| `Provider` | `providers` | |
| `Payer` | `payers` | |
| `PayerConfigORM` | `payer_configs` | |
| `ClearhouseORM` | `clearhouse` | Singleton row (`id = 1`) |
| `AuditLog` | `audit_log` | SHA-256 hash-chained |
| `ProcessedInboundFile` | `processed_inbound_files` | |
| `DbBackup` | `db_backups` | Note: table is `db_backups`, NOT `backups` |
**Boundary contracts:**
| Module | Public API | Pure? | Notes |
|---|---|---|---|
| `cyclone.db` | `init_db()`, `SessionLocal()`, model classes | No (engine + schema) | |
| `cyclone.db_migrate` | `run(engine)` | Yes (modulo engine) | |
| `cyclone.reconcile` | `match()`, `apply_payment()`, `apply_reversal()`, `split_unmatched()`, line-level match | **Yes** (no DB session inside) | Unit-testable with fabricated ORM objects |
| `cyclone.scoring` | `score_pair(...)` | Yes | Weights hardcoded — see R-10 |
| `cyclone.audit_log` | `append_event(...)`, `verify_chain()` | No (DB-owning) but append is deterministic | SHA-256 chain |
| `cyclone.activity_events` (via store) | `append(...)` | No (DB-owning) | Un-chained; powers `/activity` feed |
| `cyclone.store` | `add()`, `get_batch()`, `iter_*()`, `list_unmatched()`, `manual_match()`, `manual_unmatch()` | No (owns sessions, calls reconcile) | |
| `cyclone.api` | HTTP routes | No | |
| `cyclone.pubsub` | `subscribe_raw(kind, queue_size=256)`, `publish(kind, event)` | No (in-process) | Drop-oldest on full queue |
| `cyclone.backup` + `backup_service` + `backup_scheduler` | `initiate_backup`, `confirm_restore`, `tick()` | No (DB-owning) | |
| `cyclone.db_crypto` | `is_encryption_enabled()`, `rotate_key()` | No | `rotate_key()` is destructive |
| `cyclone.clearhouse` | `SftpClient`, `make_client()`, `InboundFile` | No | Real `paramiko` in SP13 |
| `cyclone.batch_diff` | `diff_batches()`, `diff_batches_to_wire()` | Yes | Pure function over claim/remit summaries |
| `cyclone.cas_codes` | `CARC_REASON_CODES` dict | Yes | Annual refresh is manual (R-22 in completeness review) |
| `cyclone.edi.filenames` | filename regexes + helpers | Yes | |
| `cyclone.logging_config` | `JsonFormatter`, `PiiScrubber`, `CycloneDevFormatter` | No (installs handlers) | |
| `cyclone.npi` | `validate_npi()`, `validate_tax_id()` | Yes | |
| `cyclone.parsers.*` | Pure-function parse + serialize | Yes | |
### 5.3 Dependencies
**Backend runtime (verified against `backend/pyproject.toml:10-24`):**
- `pydantic>=2.6,<3`
- `click>=8.1,<9`
- `fastapi>=0.110,<1`
- `uvicorn[standard]>=0.27,<1` (the `[standard]` extra pulls `httptools`, `uvloop`, `websockets`, `watchfiles`)
- `python-multipart>=0.0.9,<1`
- `sqlalchemy>=2.0,<3`
- `pyyaml>=6.0,<7`**loads `config/payers.yaml`** (SP9)
- `keyring>=25.0,<26`**macOS Keychain backend** used by `cyclone/secrets.py` (SP12/SP13/SP15); on Linux dispatches to Secret Service / kwallet
- `cryptography>=49.0,<50`
**Backend optional extras:**
- `[sqlcipher]``sqlcipher3>=0.6,<1` (SP12; falls back to plain SQLite if missing)
- `[sftp]``paramiko>=3.4,<6` (SP13)
**Backend dev/test (`backend/pyproject.toml:27-33`):**
- `pytest>=8.0`, `pytest-cov>=4.1`, `pytest-asyncio>=0.23,<1` (asyncio_mode = "auto"), `pytest-randomly>=4.1`, `httpx>=0.27,<1`**dev only, not runtime**
- `ruff`, `mypy`**not installed** (per completeness review §3.2.30 deferred)
**Frontend runtime (verified against `package.json`):**
- `react@^18.3.1`, `react-dom@^18.3.1`
- `@tanstack/react-query@^5.101.0`
- `lucide-react@^0.453.0`
- `sonner@^1.5.0`
- `zustand@^4.5.5`
- `react-router-dom@^6.27.0` (note: package name is `react-router-dom`, not `react-router`)
- `@radix-ui/react-dialog@^1.1.2`, `@radix-ui/react-label@^2.1.0`, `@radix-ui/react-select@^2.1.2`, `@radix-ui/react-slot@^1.1.0`, `@radix-ui/react-tabs@^1.1.15` ← powers `src/components/ui/` (shadcn primitives)
- `class-variance-authority@^0.7.0`, `clsx@^2.1.1`, `tailwind-merge@^2.5.4`, `ansi-styles@^6.2.3` ← shadcn helper stack
**Frontend dev/test:**
- `vitest@^4.1.9`**unusually new version** (worth a sanity check — current stable is 1.x/2.x; verify it's intentional)
- `@testing-library/react@^16.3.2`
- `happy-dom@^20.10.6`**not jsdom** (vitest config line 13 explicitly says they don't need a DOM env: "Node 18+ exposes `Response` / `fetch` globals")
- `typescript@^5.6.3`, `vite@^5.4.10`, `@vitejs/plugin-react@^4.3.3`
- `@types/node`, `@types/react`, `@types/react-dom`, `autoprefixer`, `postcss`, `tailwindcss@^3.4.14`, `tailwindcss-animate`
**External services:** None. (The MFT path is one-way outbound to Gainwell MFT, polled via SFTP — not a service Cyclone depends on, it's a sink it writes to.)
**OS-level:** macOS Keychain (backed by `keyring`); SQLite / SQLCipher shared library; `ssh` host keys / known_hosts for SP13. SP23 would add `tini` + `curl` + `nginx` in container scenarios.
### 5.4 One-page data flow
```
┌──────────────────────────────┐
Operator drops file │ FastAPI backend │
on /upload ───────▶│ /api/parse-837|835|999| │
(or SFTP inbound) │ 277ca|ta1|270 │
│ │
│ parse → validate ──┐ │
│ ▼ │
│ reconcile ──▶ store ──▶ activity_events (un-chained)
│ │ │
│ │ └─▶ audit_log (SP11, chained)
│ ▼ (login / rejected / key events)
│ SQLite (encrypted optional)
│ │
│ ▼
│ pubsub.publish(<kind>)
└──────────┬───────────────────┘
│ NDJSON stream
┌──────────────────────────────┐
│ React UI (Vite-served) │
│ /claims /remits /inbox │
│ /reconciliation /providers │
│ /acks /activity /batches │
│ /upload /dashboard /health │
│ drill stack everywhere │
└──────────────────────────────┘
```
---
## 6. Sub-project inventory
### 6.1 Shipped SPs (in `main`)
Each row's "Spec" / "Plan" point to the design spec and implementation plan on disk. SPs without a plan file on disk shipped via `feat(spN)` commits on `main` whose commit messages carry the implementation order; those commit logs substitute for a plan file. Closing the plan-file gap is on the round-3 backlog.
| SP | Title | Spec | Plan | Acceptance |
|---|---|---|---|---|
| SP1 | Production-readiness: in-memory store, GET endpoints, react-query, reference notes | [spec](superpowers/specs/2026-06-19-cyclone-production-readiness-design.md) | [plan](superpowers/plans/2026-06-19-cyclone-production-readiness.md) | Met |
| SP2 | DB + reconciliation: SQLite, 7-state lifecycle, auto-match on 835 ingest, manual reconciliation UI | [spec](superpowers/specs/2026-06-19-cyclone-db-reconciliation-design.md) | [plan](superpowers/plans/2026-06-19-cyclone-db-reconciliation.md) | Met |
| SP3 | EDI features: 837P rules (R034/R035), CAS reason codes, 999 ACK, TA1 ACK, 270/271 | [spec](superpowers/specs/2026-06-20-cyclone-edi-features-design.md) | [plan](superpowers/plans/2026-06-20-cyclone-edi-features.md) | Met |
| SP4 | Claim drawer + Remit drawer + Cmd-K search + batch diff + CSV export | [spec](superpowers/specs/2026-06-20-cyclone-claim-drawer-design.md) | [plan](superpowers/plans/2026-06-20-cyclone-claim-drawer.md) | Met |
| SP5 | Live tail: NDJSON pubsub on Claims/Remittances/Activity, heartbeat, reconnect | [spec](superpowers/specs/2026-06-20-cyclone-live-tail-design.md) | [plan](superpowers/plans/2026-06-20-cyclone-live-tail.md) | Met |
| SP6 | Inbox workflow: 4 lanes (Rejected/Candidates/Unmatched/Done today), 4-field scoring, bulk actions | **No dedicated spec on disk** — SP6 ships via the SP4 spec's coverage and the workflow-automation plan | [plan](superpowers/plans/2026-06-20-cyclone-workflow-automation.md) | Met |
| SP7 | Per-line adjustment audit: 837 SV1 ↔ 835 SVC strict match, line reconciliation tab | [spec](superpowers/specs/2026-06-20-cyclone-line-reconciliation-design.md) | [plan](superpowers/plans/2026-06-20-cyclone-line-reconciliation.md) | Met |
| SP8 | Outbound 837P serializer: single-claim download + bundle resubmit ZIP | [spec](superpowers/specs/2026-06-20-cyclone-serialize-837-design.md) *(the spec's own title mistakenly says "Sub-project 7"; the file maps to SP8)* | [plan](superpowers/plans/2026-06-20-cyclone-serialize-837.md) | Met |
| SP9 | Multi-payer, multi-NPI, SFTP stub | [spec](superpowers/specs/2026-06-20-cyclone-multi-payer-npi-sftp-design.md) | (no plan file on disk; feat(sp9) commits on `main`) | Met |
| SP10 | 277CA + Payer-Rejected lane | (no dedicated spec on disk; covered inline in [parse-decide spec](superpowers/specs/2026-06-21-cyclone-parse-decide-workflow-design.md) and `cyclone/parsers/parse_277ca.py`) | (no plan file on disk; feat(sp10) commits on `main`) | Met |
| SP11 | Tamper-evident audit log | (no dedicated spec on disk; `cyclone/audit_log.py:116 append_event` and `:190 verify_chain` are the implementation) | (no plan file on disk; feat(sp11) commits on `main`) | Met |
| SP12 | Encryption at rest (SQLCipher) | (no dedicated spec on disk; `cyclone/db_crypto.py` is the implementation) | (no plan file on disk; feat(sp12) commits on `main`) | Met |
| SP13 | SFTP wire-up (paramiko) | (no dedicated spec on disk; extends SP9; `cyclone/clearhouse/__init__.py` holds `SftpClient`) | (no plan file on disk; feat(sp13) commits on `main`) | Met |
| SP14 | 5-lane Inbox UI | (no dedicated spec on disk; extends SP6) | (no plan file on disk; feat(sp14) commits on `main`) | Met |
| SP15 | SQLCipher key rotation | (no dedicated spec on disk; extends SP12) | (no plan file on disk; feat(sp15) commits on `main`) | Met |
| SP16 | Live MFT polling scheduler | (no dedicated spec on disk; `cyclone/scheduler.py` is the implementation; idempotency via `processed_inbound_files` from migration 0011) | (no plan file on disk; feat(sp16) commits on `main`) | Met |
| SP17 | Encrypted DB backups | [spec](superpowers/specs/2026-06-21-cyclone-encrypted-backup-design.md) | (no plan file on disk; feat(sp17) commits on `main`) | Met |
| SP18 | Structured logging | [spec](superpowers/specs/2026-06-21-cyclone-structured-logging-design.md) | (no plan file on disk; feat(sp18) commits on `main`) | Met |
| SP19 | Security hardening + health probe | [spec](superpowers/specs/2026-06-21-cyclone-security-hardening-design.md) | (no plan file on disk; feat(sp19) commits on `main`) | Met |
| SP20 | NPI checksum + Tax ID format validation | [spec](superpowers/specs/2026-06-21-cyclone-npi-validation-design.md) | (no plan file on disk; feat(sp20) commits on `main`) | Met |
| SP21 | CycloneStore split (in-flight) + Universal drilldown (shipped) | [split spec](superpowers/specs/2026-06-21-cyclone-store-split-design.md), [drilldown spec](superpowers/specs/2026-06-21-cyclone-universal-drilldown-design.md) | [store-split plan](superpowers/plans/2026-06-21-cyclone-store-split.md), [drilldown plan](superpowers/plans/2026-06-21-cyclone-universal-drilldown.md) | Drilldown **Met**; split **In-flight** (`refactor/store-split` branch, not yet on `main`) |
| SP22 | Parse-decide workflow + Pipeline agent | [parse-decide spec](superpowers/specs/2026-06-21-cyclone-parse-decide-workflow-design.md), [pipeline spec](superpowers/specs/2026-06-21-cyclone-pipeline-agent-design.md) | [parse-decide plan](superpowers/plans/2026-06-21-cyclone-parse-decide-workflow.md), [pipeline plan](superpowers/plans/2026-06-21-cyclone-pipeline-agent.md) | Met (parse-decide on `main`; pipeline agent lives in `cyclone-pipeline/`) |
| SP24 | Auth posture alignment (docs-only reconciliation with the auth work in `main`) | [spec](superpowers/specs/2026-06-23-cyclone-auth-posture-alignment-design.md) | [plan](superpowers/plans/2026-06-23-cyclone-auth-posture-alignment.md) | Met (no code paths change; only docs + `__main__.py` WARNING + 3 skills addenda) |
### 6.2 Backlog (specs awaiting plans, or vice versa)
| Item | Status | Why |
|---|---|---|
| SP23 (candidate) | Spec-only; **product fork awaiting user decision** | `2026-06-22-cyclone-ubuntu-docker-deployment-design.md` (auth + Docker + RBAC + LAN-bind); see §11 R-1, R-3 |
| Plan-file backfill for SP9, SP10, SP11, SP12, SP13, SP14, SP15, SP16, SP17, SP18, SP19, SP20 | Plan files missing on disk; `feat(spN)` commit messages substitute | Round-3 doc-backlog item |
| Spec-file backfill for SP6 (workflow/inbox), SP11 (audit log), SP12 (SQLCipher), SP13 (paramiko), SP15 (key rotation), SP16 (MFT scheduler) | Specs missing on disk | Round-3 doc-backlog item |
| Migration manifest (checksums for the 12 SQL files) | Open | Completeness review §3.1.18 |
| Tunable score weights (move 40/25/20/15 from code to config) | Open | Completeness review §3.1.15 |
| License file (`LICENSE`) | Open | Completeness review §3.2.28 |
| `pre-commit` / `Makefile` / `CONTRIBUTING.md` / `.editorconfig` / `ruff` config | Open | Completeness review §3.2.30 |
| CI workflow file (`.github/workflows/`) | Open | §8.1 #3 references CI; no CI file exists today |
| PHI fixtures flagged as PHI (`docs/prodfiles/PHI.md` or equivalent) | Open | Completeness review §3.2.23 |
| Delete stale `backend/src/cyclone/workflow/__pycache__/` | Open | Empty dead-code directory (§5.1) |
| EHR/PM integration (webhook in/out, callable `POST /api/parse-837`) | Open | Completeness review §5.1 |
| COB / secondary-claim generator | Open | Completeness review §3.1.12 + §5.1 |
| Real-time eligibility round-trip (SFTP pickup + SOAP + retry + 271 parse) | Open | Completeness review §3.1.8 + §5.1 |
| 837I / 837D / 834 / 820 / 275 / 278 / 276/277 transaction types | Open | Completeness review §2.1 |
| NPPES NPI registry lookup | Open | Completeness review §3.1.10 |
| ICD-10 / HCPCS / NDC vocabulary tables | Open | Completeness review §3.1.11 |
### 6.3 Traceability matrix (compressed)
This matrix is the single index. Each row points to a requirement and where it's realized. A change to a requirement must update its row; a change to an SP must update the matching FRs/NFRs.
| ID | SP | Spec | Plan | Key tests |
|---|---|---|---|---|
| FR-1 | SP1 | production-readiness | production-readiness | `test_parse_837.py`, `test_prodfiles_smoke.py` |
| FR-2 | SP1, SP3 | production-readiness + edi-features | production-readiness + edi-features | `test_parse_835.py`, `test_service_line_payments.py` |
| FR-3 | SP2 | db-reconciliation | db-reconciliation | `test_db.py`, `test_api_parse_persists.py` |
| FR-4 | SP2 | db-reconciliation | db-reconciliation | `test_db_migrate.py` |
| FR-5 | SP2 | db-reconciliation | db-reconciliation | `test_reconcile.py`, `test_store_reconcile.py` |
| FR-6 | SP2 | db-reconciliation | db-reconciliation | `test_models.py`, `test_reconcile.py` |
| FR-7 | SP2 | db-reconciliation | db-reconciliation | `test_reconcile.py`, `test_reconcile_line_level.py`, `test_inbox_endpoints.py`, `test_api_gets.py` |
| FR-8 | SP3, SP20 | edi-features + npi-validation | edi-features | `test_validator.py`, `test_validation_r200_r210.py` |
| FR-9 | SP3 | edi-features | edi-features | `test_acks.py`, `test_api_parse_persists_ack.py` |
| FR-10 | SP3 | edi-features | edi-features | `test_api_999.py`, `test_models_999.py`, `test_parse_999.py` |
| FR-11 | SP3 | edi-features | edi-features | `test_api_ta1.py`, `test_parse_ta1.py` |
| FR-12 | SP3 | edi-features | edi-features | `test_parse_270.py`, `test_parse_271.py`, `test_api_eligibility.py` |
| FR-13 | SP10 | parse-decide-workflow (277CA section) | parse-decide-workflow | `test_parse_277ca.py`, `test_apply_277ca_rejections.py` |
| FR-14 | SP6, SP10, SP14 | workflow-automation + parse-decide-workflow | workflow-automation | `test_inbox_lanes.py`, `test_inbox_endpoints.py`, `test_lane_filter_acknowledged.py` |
| FR-15 | SP6 | workflow-automation | workflow-automation | `test_scoring.py` |
| FR-16 | SP4, SP7, SP21 | claim-drawer + line-reconciliation + universal-drilldown | claim-drawer + line-reconciliation + universal-drilldown | `test_api_claim_detail.py`, `test_store_claim_detail.py` |
| FR-17 | SP4 | claim-drawer | claim-drawer | `test_batch_diff.py` |
| FR-18 | SP4 | claim-drawer | claim-drawer | `useSearch.test.ts`, `SearchResults.test.tsx` |
| FR-19 | SP4 | claim-drawer | claim-drawer | `ExportCsvButton.test.tsx`, `csv.test.ts` |
| FR-20 | SP5 | live-tail | live-tail | `test_api_stream_live.py`, `useTailStream.test.ts`, `tail-stream.test.ts` |
| FR-21 | SP5 | live-tail | live-tail | `TailStatusPill.test.tsx`, `useMergedTail.test.ts` |
| FR-22 | SP7 | line-reconciliation | line-reconciliation | `test_reconcile_line_level.py`, `test_api_line_reconciliation.py` |
| FR-23 | SP8 | serialize-837 | serialize-837 | `test_serialize_837.py`, `test_api_serialize_837.py` |
| FR-24 | SP8 | serialize-837 | serialize-837 | `test_api_batch_export_837.py` |
| FR-25 | SP9 | multi-payer-npi-sftp | (none on disk) | `test_providers_seed.py`, `test_payer_config_loading.py` |
| FR-26 | SP13 | multi-payer-npi-sftp (extends) | (none on disk) | `test_sftp_paramiko.py`, `test_sftp_stub.py` |
| FR-27 | SP16 | (none on disk) | (none on disk) | `test_scheduler.py`, `test_api_scheduler.py` |
| FR-28 | SP12 | (none on disk) | (none on disk) | `test_db_crypto.py`, `test_security.py` |
| FR-29 | SP15 | (none on disk) | (none on disk) | `test_api_rotate_key.py` |
| FR-30 | SP17 | encrypted-backup | (none on disk) | `test_backup_crypto.py`, `test_backup_service.py`, `test_backup_scheduler.py`, `test_api_backup.py`, `test_cli_backup.py` |
| FR-31 | SP18 | structured-logging | (none on disk) | `test_logging_formatter.py`, `test_logging_scrubber.py`, `test_logging_setup.py` |
| FR-32 | SP19 | security-hardening | (none on disk) | `test_security.py` |
| FR-33 | SP19 | security-hardening | (none on disk) | `test_api.py:33 test_health_endpoint`, `test_security.py:204-221` (health snapshot) |
| FR-34 | SP20 | npi-validation | (none on disk) | `test_npi.py`, `test_api_validate_provider.py`, `test_cli_validate.py` |
| FR-35 | SP21 | store-split | store-split | `test_store.py` (currently covers the un-split `store.py`; will cover the split modules once `refactor/store-split` lands) |
| FR-36 | SP22 | parse-decide-workflow | parse-decide-workflow | `test_api_parse_persists.py`, `test_prodfiles_smoke.py`; migration 0014 in `claims-unique-fix` worktree |
| FR-37 | SP22 | pipeline-agent | pipeline-agent | (lives in `cyclone-pipeline/`, not this repo) |
| FR-38 | SP21 | universal-drilldown | universal-drilldown | `DrillStackProvider.test.tsx`, `useDrawerUrlState.test.ts`, plus per-drawer tests in `ClaimDrawer/`, `RemitDrawer/`, `ProviderDrawer/`, `AckDrawer/` |
---
## 7. Acceptance criteria — per-SP (compressed)
These are the existing per-SP acceptance checklists as captured in their design specs, condensed into one table. A new engineer can use this to know whether a given SP is "really done" without reading 22 specs end-to-end.
| SP | Acceptance criterion | Verified by |
|---|---|---|
| SP1 | `pytest` passes; `/api/claims`, `/api/remittances`, `/api/providers`, `/api/activity`, `/api/batches`, `/api/batches/{id}` return JSON; CORS allowlist stays `http://localhost:5173`; bind stays `127.0.0.1` | `test_api_gets.py` + manual smoke |
| SP2 | DB at `~/.local/share/cyclone/cyclone.db`; migrations apply on first run; 7-state Claim lifecycle; reconciliation runs on 835 ingest; `/reconciliation` page works | `test_db*.py`, `test_reconcile.py`, `test_reconcile_line_level.py`, `test_inbox_endpoints.py` |
| SP3 | R034/R035/R200/R210 enforced; CAS reason codes surfaced; 999 in + out; TA1 in; 270/271 builder + parser | `test_validator*.py`, `test_acks.py`, `test_api_999.py`, `test_api_ta1.py`, `test_parse_270.py`, `test_parse_271.py` |
| SP4 | Drawer opens with URL sync; Cmd-K search returns results across resources; batch diff renders added/removed/changed; CSV exports stream | `ClaimDrawer*.test.tsx`, `useSearch.test.ts`, `BatchDiff.test.tsx`, `ExportCsvButton.test.tsx` |
| SP5 | `/api/{claims,remittances,activity}/stream` returns NDJSON with snapshot + `snapshot_end` + heartbeat; client flips to `stalled` after 30s silence; reconnect ladder capped at 30s | `test_api_stream_live.py`, `TailStatusPill.test.tsx` |
| SP6 | `/inbox` shows 5 lanes (4 in SP6; 5th added in SP10); scoring tiers visible; bulk actions call the right endpoint | `test_inbox_lanes.py`, `BulkBar.test.tsx` |
| SP7 | Line reconciliation tab in ClaimDrawer matches 837 SV1 ↔ 835 SVC strictly; unmatched-line warnings surfaced | `test_reconcile_line_level.py`, `test_api_line_reconciliation.py` |
| SP8 | 113 prodfiles parse → serialize → parse back to the same `claim_id`; ZIP bundle export works | `test_prodfiles_smoke.py`, `test_api_batch_export_837.py` |
| SP9 | `config/payers.yaml` loads (via `pyyaml`); new providers/payers/payer_configs tables populate; `clearhouse.submit` writes to `staging_dir` (stub) | `test_providers_seed.py`, `test_payer_config_loading.py` |
| SP10 | 277CA parse + persist; `payer_rejected` stamp applied monotonically; lane 2 in `/inbox` renders | `test_parse_277ca.py`, `test_apply_277ca_rejections.py` |
| SP11 | `audit_log` hash chain verifies via `GET /api/admin/audit-log/verify`; any break is detected | `test_audit_log.py`, `test_api_audit_log.py` |
| SP12 | `db_crypto.is_encryption_enabled()` returns True when Keychain entry exists and `sqlcipher3` installed; otherwise falls back with WARNING | `test_db_crypto.py` |
| SP13 | `SftpClient` actually pushes to `mft.gainwelltechnologies.com:…`; credentials read from Keychain via `keyring` at call time | `test_sftp_paramiko.py` (unit); integration via `cyclone-pipeline` |
| SP14 | All 5 lanes render in `/inbox`; bulk acknowledge action drops payer-rejected claims without erasing the original rejection | `test_inbox_endpoints_sp7.py`, `test_lane_filter_acknowledged.py` |
| SP15 | `POST /api/admin/db/rotate-key` runs `PRAGMA rekey`; emits `db.key_rotated` with old + new fingerprints; concurrent calls serialized | `test_api_rotate_key.py` |
| SP16 | Scheduler ticks every interval; per-file try/except keeps the loop alive; `processed_inbound_files` de-duplicates | `test_scheduler.py`, `test_api_scheduler.py` |
| SP17 | Backup scheduler ticks every 24h; encrypted `.bin` + `.meta.json` written; restore via 2-step token works; retention prunes at 30 days | `test_backup_*.py` |
| SP18 | All logs emit as NDJSON by default; `PiiScrubber` redacts NPIs/SSNs/DOBs/names; `CYCLONE_LOG_JSON=0` falls back to `CycloneDevFormatter` | `test_logging_*.py` |
| SP19 | 413 on oversize body, 429 on rate-limit, security headers present; `api.request_rejected` audit event on 413/429; `GET /api/health` returns rich payload | `test_security.py`, `test_api.py:33` |
| SP20 | NPI Luhn catches 99% of typos; EIN rejects reserved prefixes; warning-only (placeholder NPIs in fixtures don't block ingest); CLI + API surface | `test_npi.py`, `test_api_validate_provider.py`, `test_cli_validate.py` |
| SP21 | `CycloneStore` is split into `store_persistence / store_reconcile / store_queries / store_mappers`; public store API unchanged; `DrillStackProvider` + `DrillDrawerHeader` shell used by every drillable cell | `test_store.py` (split modules), `DrillStackProvider.test.tsx`, drawer-key tests |
| SP22 | Re-parsing an 837 into a fresh batch does not 409 on `claim_id` collision; parse-then-decide workflow checks `find_existing_batch_for_claim`; pipeline agent runs 7 phases end-to-end | `test_api_parse_persists.py`, `test_prodfiles_smoke.py`, pipeline integration |
---
## 8. Definition of Done
### 8.1 Project-level DoD (the project as a whole is "done" when…)
1. **All FRs in §3 are implemented and tested** — verifiable by walking the §6.3 traceability matrix and confirming each row links to either a passing test or an §2.2 out-of-scope entry.
2. **All NFRs in §4 are met or have a documented exception** — NFR-1 through NFR-18 are each either met (with a citation) or carry an explicit exception in this section.
3. **All shipped SPs in §6.1 have an Acceptance row marked "Met" and the corresponding tests pass.** Tests are run via `pytest` (backend) and `npm test` (frontend) per §9.4; **the project has no CI workflow today** (round-3 backlog item — see §6.2). A release-time gate should run the suites and fail if any test is red.
4. **All backlog items in §6.2 are either scheduled, explicitly deferred with rationale, or removed** — testable as a checklist walk.
5. **All assumptions in §10 are still valid** — re-checked at release time; an invalid assumption is either promoted to a backlog item or rolled into the next release.
6. **All four reviewer questions (components / data model / dependencies / DoD) have independent agreement from at least two reviewers** — the meta-DoD: a doc with this scope is "done" when two reviewers can independently describe the system from it and agree.
### 8.2 Per-release DoD (the next release is "done" when…)
1. The new SP's design spec has been **self-reviewed** (every claim cited with line/file, every assumption recorded).
2. The implementation plan has **TDD-shaped tasks** with per-task acceptance criteria.
3. Every task's tests are green in `pytest` (backend) and `npm test` (frontend) and `npm run build` (frontend typecheck + build).
4. The new SP's Acceptance row in §6.1 is updated to "Met".
5. New audit events (if any) are listed in the audit-log test fixtures (`backend/tests/test_audit_log.py`).
6. Migration files (if any) follow the `NNNN_*.sql` ordering, append to this doc's §5.2 table, and (post-round-3) update the migration manifest (R-13).
7. The README's project-layout section is updated if any module is added/renamed/removed.
### 8.3 Per-task DoD (the smallest unit of work is "done" when…)
1. The code change is in a single commit (or a small, reviewable series).
2. The matching test exists and passes.
3. No existing test regresses.
4. The commit message names the SP and the FR/NFR it advances (e.g., `feat(sp19): … (FR-32, NFR-8)`).
5. If the task introduces a migration, it's added to `backend/src/cyclone/migrations/` with the next sequential `NNNN` and the new schema is reflected in §5.2.
---
## 9. Test strategy
### 9.1 Taxonomy
| Layer | Tool | Where | What it covers |
|---|---|---|---|
| Backend unit | `pytest` | `backend/tests/` | Pure-function logic: `cyclone.reconcile.*`, `cyclone.scoring.*`, `cyclone.npi.*`, `cyclone.cas_codes`, `cyclone.audit_log.append_event`, `cyclone.edi.filenames` |
| Backend integration | `pytest` (TestClient) | `backend/tests/test_api_*.py` | FastAPI route round-trips, content negotiation, NDJSON streaming, auth/rate-limit/SP19, 999/TA1/277CA parse endpoints, scheduler endpoints |
| Backend fixture-driven | `pytest` (`tests/fixtures/*.txt`) | `backend/tests/test_prodfiles_smoke.py` | 113 + 19 + 1369 production files; round-trip property |
| Backend SQL | `pytest` (in-memory SQLite) | `backend/tests/test_db*.py` | Schema, migrations, ORM, encryption round-trip |
| Frontend unit | `vitest` (`*.test.ts(x)`) | `src/lib/`, `src/hooks/`, `src/components/ui/` | Pure functions, hooks, primitives |
| Frontend component | `vitest` + Testing Library | `src/components/`, `src/pages/` | Drawers, lane rendering, drill stack, export buttons |
| Smoke | manual / shell | `scripts/smoke.sh` (planned in SP23) | End-to-end parse → reconcile → export flow |
### 9.2 Fixture sources
- `backend/tests/fixtures/minimal_*.txt` — minimal valid 270 / 271 / 277CA / 835 / 837P / 999 / TA1 / co_medicaid / unbalanced_835 — written by hand, used in unit tests.
- `docs/prodfiles/claims/*.x12` (113 files) — real-looking production files used by `test_prodfiles_smoke.py` for the round-trip property.
- `docs/prodfiles/FromHPE/` (1369 files) — full inbound directory from the production SFTP path.
- `docs/prodfiles/837p-from-axiscare/` (19 files) — production 837Ps from AxisCare.
- `docs/prodfiles/835fromco/` (5 files) — production 835s from CO Medicaid.
**PHI warning:** prodfiles contain real-looking patient data. Even in a single-operator tool, fixtures should be flagged as PHI (completeness review §3.2.23 — flagged but not yet actioned; for v1 they're kept under `docs/prodfiles/` with no additional access control).
### 9.3 Coverage goals
- **Pure-function modules** (`reconcile`, `scoring`, `npi`, `cas_codes`, `parsers`, `edi.filenames`, `batch_diff`): ≥ 90% line coverage. `pytest-cov` is installed; the gate (`--cov-fail-under=90`) is **not enforced today** and is a round-3 backlog item.
- **Store facade** (`store`, and the future `store_persistence / store_reconcile / store_queries / store_mappers` modules): every public method has at least one happy-path and one failure-path test.
- **API routes**: every route has a happy-path test; error paths (404, 409, 413, 415, 422, 423, 429, 500) covered by at least one test each.
- **Round-trip property** (SP8): 100% of `docs/prodfiles/claims/*.x12` must parse → serialize → parse to the same `claim_id`.
- **Live tail** (SP5): one happy snapshot → live item → disconnect cleanup test per endpoint.
### 9.4 How to run
```bash
# Backend
cd backend
.venv/bin/pytest # 964 tests collected (2026-06-23)
.venv/bin/python -m cyclone serve
# Frontend
npm run typecheck
npm test # 73 test files
npm run build
# Smoke (planned in SP23)
bash scripts/smoke.sh
```
### 9.5 What is NOT covered (explicit)
- **Component / E2E browser tests (Playwright).** Deferred; the local-only threat model doesn't justify them. (Completeness review §3.2 + SP23 §14.)
- **Property-based tests** (Hypothesis) for the parser. Could add; not scheduled.
- **Mutation tests** (mutmut / cosmic-ray). Not scheduled.
- **Performance / load tests.** Single-operator scale; not scheduled.
- **NPPES round-trip validation** (only Luhn checksum is covered; SP20).
- **External-integration tests against the real Gainwell MFT.** The pipeline agent covers this in `cyclone-pipeline/`; out of scope for this repo.
- **CI workflow.** Not present in the repo; release gating is manual today.
---
## 10. Assumptions
Recorded explicitly so a new engineer can challenge any of them.
| # | Assumption | If wrong, what changes |
|---|---|---|
| A1 | One operator, one host, one trading partner (CO Medicaid). | Multi-tenant / multi-payer scope would require SP23 + multi-payer NPI expansion + COB + AS2/AS4. |
| A2 | The host runs macOS (Keychain via `keyring`) OR Ubuntu (Docker secrets available, SP23). | Linux-without-Docker / Windows would require a different secrets backend (`keyring` already dispatches via Secret Service / kwallet on Linux; Windows would use Credential Manager). |
| A3 | The host is physically secure; LUKS / FileVault is the operator's concern, not Cyclone's. | If not, the SQLCipher-encrypted-DB posture is insufficient; per-file encryption of `prodfiles/` and `sftp_staging/` becomes mandatory. |
| A4 | The operator can hand the 837 ZIP to the Gainwell MFT UI manually. | Removes the need for a built-in SFTP submit (SP13); the SFTP wire stays stub. |
| A5 | The 835 lands the following Monday (CO Medicaid payment cycle) and is verified by a separate `check-835` subcommand (in `cyclone-pipeline/`), not inline. | Would require a different round-trip contract; affects SP22 pipeline agent. |
| A6 | ICD-10 / HCPCS / NDC vocabulary is not Cyclone's responsibility. | Would require vendoring vocab CSVs and adding vocabulary checks (FR + tests). |
| A7 | NPPES NPI registry lookup is not needed (offline Luhn is enough). | Would require scheduled NPPES download + online check + new FR. |
| A8 | The X12 5010 transaction set Cyclone supports is sufficient for the operator's billing workflow. | Adding 837I / 837D / 278 / 276-277 / 277CA-round-trip / etc. is each a new SP. |
| A9 | Local-only bind is sufficient — no remote access needed. | Would require auth (SP23), TLS, reverse proxy, RBAC. |
| A10 | One Python process, no message broker, no separate worker. | A multi-worker deployment would require breaking thread-affinity (SP12/SP15 specifically). |
| A11 | 964 backend tests + 73 frontend test files is the right test density for this codebase (2026-06-23). If we add more transaction types or surface area, this needs to grow proportionally; coverage gates should be enforced (round-3 backlog). | New transaction types or surface area without test growth → coverage drifts down. |
| A12 | `cyclone-pipeline/` is a sibling project, not a sub-project of this repo. | The 7-phase round-trip agent is shipped in `cyclone-pipeline/`; if that project is abandoned, the manual operator workflow remains (upload via `/upload`, SFTP by hand, `check-835` not available). |
---
## 11. Risks and known gaps
Pulled forward from [`docs/reviews/2026-06-20-cyclone-completeness-review.md`](reviews/2026-06-20-cyclone-completeness-review.md). Status as of 2026-06-23.
| ID | Risk / gap | Source | Status |
|---|---|---|---|
| R-1 | No app-layer auth (anyone on the host can read PHI). | Completeness review §3.1.4 + §3.2.25 | **Closed by SP24** — auth shipped via the merge of `origin/main` on 2026-06-23 (commits `a25504b`..`39ae988`, `cyclone.auth.*` + `matrix_gate` dependency on every router); SP24 reconciled the docs to match. SP23 still covers the LAN-bind / Docker / RBAC product fork. |
| R-2 | SQLite plaintext if SQLCipher not enabled. | Completeness review §3.1.1 | **Partial** — SP12 + SP15 ship the encryption option, but it falls back to plain if the Keychain entry is missing. |
| R-3 | No Dockerfile / docker-compose.yml. | Completeness review §3.2.29 | **Open** — SP23 spec covers it but is awaiting user decision. |
| R-4 | PayerConfig still partly in code (`co_medicaid()` factory at `cyclone/parsers/payer.py:57-58`). | Completeness review §3.1.9 | **Open** — SP9 externalized config but the factory remains as a fallback for tests and default-payer selection. |
| R-5 | No vocabulary tables (ICD-10 / HCPCS / NDC). | Completeness review §3.1.11 | **Open** — explicitly out of scope per A6. |
| R-6 | No COB / secondary-claim generator. | Completeness review §3.1.12 | **Open** — explicitly out of scope per §2.2. |
| R-7 | No real-time eligibility round-trip. | Completeness review §3.1.8 | **Open** — 270/271 are file-exchange only per SP3. |
| R-8 | No NPPES NPI lookup. | Completeness review §3.1.10 | **Open** — only Luhn checksum (SP20). |
| R-9 | No 837I / 837D / 834 / 820 / 275 / 278 / 276-277 transaction types. | Completeness review §2.1 | **Open** — explicitly out of scope per §2.2. |
| R-10 | Score weights hardcoded (`cyclone/scoring.py:42-46`). | Completeness review §3.1.15 | **Open** — not scheduled. |
| R-11 | `cyclone/store.py` is a 2,172-line god-module. | Completeness review §3.1.17 | **In-flight** — SP21 spec + plan written; branch `refactor/store-split` exists; merge to `main` pending. |
| R-12 | `cyclone/api.py` is a 3,145-line god-module (larger than `store.py`). | Completeness review §3.1.19 | **Partial**`api_routers/` exists for 4 sub-routes (acks, admin, health, ta1_acks); bulk of routes still in `api.py`. |
| R-13 | Migrations in flat dir without manifest. | Completeness review §3.1.18 | **Open** — no checksum list; 12 SQL files in `backend/src/cyclone/migrations/`. |
| R-14 | No `pre-commit` / `Makefile` / `CONTRIBUTING.md` / `.editorconfig` / `ruff` config. | Completeness review §3.2.30 | **Open** — single-operator project. |
| R-15 | No license file (`LICENSE`). | Completeness review §3.2.28 | **Open** — not scheduled. |
| R-16 | PHI fixtures not flagged as PHI. | Completeness review §3.2.23 | **Open** — not scheduled. |
| R-17 | `/api/health` not rich (before SP19). | Completeness review §3.2.24 | **Closed by SP19**`api_routers/health.py:28-40` returns the rich snapshot via `get_health_snapshot()`. |
| R-18 | No CSP / no security headers (before SP19). | Completeness review §3.2.25 | **Closed by SP19**`SecurityHeadersMiddleware` in `cyclone/security.py`. |
| R-19 | No request body size / rate limit (before SP19). | Completeness review §3.1.4 | **Closed by SP19**`BodySizeLimitMiddleware` + `RateLimitMiddleware` in `cyclone/security.py`. |
| R-20 | No 277CA support (before SP10). | Completeness review §3.1.7 | **Closed by SP10**. |
| R-21 | No structured logging (before SP18). | Completeness review §3.1.5 | **Closed by SP18**. |
| R-22 | No backup automation (before SP17). | Completeness review §3.1.3 | **Closed by SP17**. |
| R-23 | `ActivityEvent` not tamper-evident (before SP11). | Completeness review §3.1.2 | **Closed by SP11** — but note: the tampered table is `audit_log`, distinct from `activity_events` (see NFR-3 / NFR-4). |
| R-24 | SP23 product fork (auth + Docker + RBAC + LAN-bind). | §6.2 | **Awaiting user decision** — see §2.2 and §11 R-1. |
| R-25 | `vitest@^4.1.9` is unusually new (current stable line is 1.x/2.x). | §5.3 | **Open** — verify the version pin is intentional before the next `npm install`; fallback to `^2.x` if accidental. |
| R-26 | No CI workflow (`.github/workflows/`). | §8.1 #3 | **Open** — release gating is manual today. |
| R-27 | `backend/src/cyclone/workflow/__pycache__/` is dead bytecode. | §5.1 | **Open** — recommend deletion. |
---
## 12. References
### 12.1 Design specs
All under [`docs/superpowers/specs/`](superpowers/specs/):
- [2026-06-19-cyclone-837p-parser-design.md](superpowers/specs/2026-06-19-cyclone-837p-parser-design.md) — pre-SP1, superseded by `production-readiness`
- [2026-06-19-cyclone-db-reconciliation-design.md](superpowers/specs/2026-06-19-cyclone-db-reconciliation-design.md) — SP2
- [2026-06-19-cyclone-production-readiness-design.md](superpowers/specs/2026-06-19-cyclone-production-readiness-design.md) — SP1
- [2026-06-20-cyclone-claim-drawer-design.md](superpowers/specs/2026-06-20-cyclone-claim-drawer-design.md) — SP4 (no inbox section; SP6 ships from the workflow-automation plan)
- [2026-06-20-cyclone-edi-features-design.md](superpowers/specs/2026-06-20-cyclone-edi-features-design.md) — SP3
- [2026-06-20-cyclone-line-reconciliation-design.md](superpowers/specs/2026-06-20-cyclone-line-reconciliation-design.md) — SP7
- [2026-06-20-cyclone-live-tail-design.md](superpowers/specs/2026-06-20-cyclone-live-tail-design.md) — SP5
- [2026-06-20-cyclone-multi-payer-npi-sftp-design.md](superpowers/specs/2026-06-20-cyclone-multi-payer-npi-sftp-design.md) — SP9 (extended by SP13)
- [2026-06-20-cyclone-serialize-837-design.md](superpowers/specs/2026-06-20-cyclone-serialize-837-design.md) — SP8 (spec's own title mistakenly says "Sub-project 7")
- [2026-06-21-cyclone-claims-unique-constraint-and-409-ux-design.md](superpowers/specs/2026-06-21-cyclone-claims-unique-constraint-and-409-ux-design.md) — pre-SP22, superseded by `parse-decide-workflow`
- [2026-06-21-cyclone-encrypted-backup-design.md](superpowers/specs/2026-06-21-cyclone-encrypted-backup-design.md) — SP17
- [2026-06-21-cyclone-npi-validation-design.md](superpowers/specs/2026-06-21-cyclone-npi-validation-design.md) — SP20
- [2026-06-21-cyclone-parse-decide-workflow-design.md](superpowers/specs/2026-06-21-cyclone-parse-decide-workflow-design.md) — SP22 (parse-decide) + covers 277CA (SP10)
- [2026-06-21-cyclone-pipeline-agent-design.md](superpowers/specs/2026-06-21-cyclone-pipeline-agent-design.md) — SP22 (pipeline agent)
- [2026-06-21-cyclone-security-hardening-design.md](superpowers/specs/2026-06-21-cyclone-security-hardening-design.md) — SP19
- [2026-06-21-cyclone-skill-catalog-design.md](superpowers/specs/2026-06-21-cyclone-skill-catalog-design.md) — documentation meta-project (not mapped to a behavioral SP)
- [2026-06-21-cyclone-store-split-design.md](superpowers/specs/2026-06-21-cyclone-store-split-design.md) — SP21 (split)
- [2026-06-21-cyclone-structured-logging-design.md](superpowers/specs/2026-06-21-cyclone-structured-logging-design.md) — SP18
- [2026-06-21-cyclone-universal-drilldown-design.md](superpowers/specs/2026-06-21-cyclone-universal-drilldown-design.md) — SP21 (drilldown)
- [2026-06-22-cyclone-ubuntu-docker-deployment-design.md](superpowers/specs/2026-06-22-cyclone-ubuntu-docker-deployment-design.md) — **SP23 candidate; awaiting plan + user product-fork decision**
### 12.2 Implementation plans
All under [`docs/superpowers/plans/`](superpowers/plans/):
- [2026-06-19-cyclone-837p-parser.md](superpowers/plans/2026-06-19-cyclone-837p-parser.md) — pre-SP1, superseded
- [2026-06-19-cyclone-db-reconciliation.md](superpowers/plans/2026-06-19-cyclone-db-reconciliation.md) — SP2
- [2026-06-19-cyclone-production-readiness.md](superpowers/plans/2026-06-19-cyclone-production-readiness.md) — SP1
- [2026-06-20-cyclone-claim-drawer.md](superpowers/plans/2026-06-20-cyclone-claim-drawer.md) — SP4
- [2026-06-20-cyclone-edi-features.md](superpowers/plans/2026-06-20-cyclone-edi-features.md) — SP3
- [2026-06-20-cyclone-line-reconciliation.md](superpowers/plans/2026-06-20-cyclone-line-reconciliation.md) — SP7
- [2026-06-20-cyclone-live-tail.md](superpowers/plans/2026-06-20-cyclone-live-tail.md) — SP5
- [2026-06-20-cyclone-serialize-837.md](superpowers/plans/2026-06-20-cyclone-serialize-837.md) — SP8
- [2026-06-20-cyclone-workflow-automation.md](superpowers/plans/2026-06-20-cyclone-workflow-automation.md) — SP6
- [2026-06-21-cyclone-claims-unique-constraint-and-409-ux.md](superpowers/plans/2026-06-21-cyclone-claims-unique-constraint-and-409-ux.md) — pre-SP22, superseded
- [2026-06-21-cyclone-parse-decide-workflow.md](superpowers/plans/2026-06-21-cyclone-parse-decide-workflow.md) — SP22
- [2026-06-21-cyclone-pipeline-agent.md](superpowers/plans/2026-06-21-cyclone-pipeline-agent.md) — SP22
- [2026-06-21-cyclone-skill-catalog.md](superpowers/plans/2026-06-21-cyclone-skill-catalog.md) — documentation meta-project
- [2026-06-21-cyclone-store-split.md](superpowers/plans/2026-06-21-cyclone-store-split.md) — SP21 (split, in-flight)
- [2026-06-21-cyclone-universal-drilldown.md](superpowers/plans/2026-06-21-cyclone-universal-drilldown.md) — SP21 (drilldown)
### 12.3 Reviews and reference
- [2026-06-20-cyclone-completeness-review.md](reviews/2026-06-20-cyclone-completeness-review.md) — industry-scope gap analysis.
- [`docs/reference/835.md`](reference/835.md), [`docs/reference/837p.md`](reference/837p.md), [`docs/reference/co-medicaid.md`](reference/co-medicaid.md), [`docs/reference/x12naming.md`](reference/x12naming.md) — condensed X12 + CO Medicaid notes.
### 12.4 External
- HIPAA Security Rule §164.312 — audit controls, encryption, access control.
- X12 005010X222A1 (837P), 005010X221A1 (835), 005010X231A1 (999), 005010X279A1 (270/271), 005010X214 (277CA), 005010X230 (TA1).
- CAQH CORE Phase II/III (real-time eligibility — out of scope per §2.2).
- CMS NPI Luhn specification.
- NPPES API (NPI registry — out of scope per §2.2 + A7).
- OWASP password-storage cheat sheet (argon2id parameters — SP23).
- paramiko, FastAPI, SQLAlchemy 2.0, Pydantic v2, structlog, TanStack Query v5 docs.
---
## 13. Reviewer checklist (for round 2 → round 3 closure)
For the two independent reviewers at the end of round 2 (re-verifying the corrections):
1. **Components** — Do §5.1 (backend modules) + §5.1 (frontend dirs) list every existing module that ships PHI or serves a state-changing route? Are the boundaries (DB / ORM / reconcile / store / api / pubsub / clearhouse / batch_diff / edi.filenames) drawn correctly? Can you, from §5.1 alone, draw the import graph?
2. **Data model** — Are all 12 migrations listed in §5.2 with their purpose? Are the two worktree-only migrations (0013, 0014) flagged as in-flight? Are all 18 ORM models in §5.2? Is the `db_backups` (not `backups`) correction applied? Is the `Rejection` phantom removed? Is the `ActivityEvent` vs `AuditLog` distinction clear (NFR-3 vs NFR-4)?
3. **Dependencies** — Are §5.3 runtime + tooling deps correct (no missing `pyyaml`, no missing `keyring`, no `httpx` listed as runtime, `paramiko` flagged as `[sftp]` extra, `sqlcipher3` flagged as `[sqlcipher]` extra, frontend test env is `happy-dom` not `jsdom`, vitest pinned at `^4.1.9` flagged as unusual)? Are OS-level deps (Keychain via `keyring`, SQLCipher C library, `tini`, `nginx` if SP23 ships) called out?
4. **Definition of Done** — Is §8 testable? Project DoD #6 now points at the reviewer-agreement meta-criterion. Per-release + per-task DoDs each independently checkable? FR-7 / FR-33 traceability rows corrected to point at existing test files and the correct endpoint name?
5. **Traceability** — Pick any FR-NN in §3. Can you trace it to an SP, a spec on disk (or an honest "no dedicated spec on disk" note), a plan on disk (or an honest "no plan file on disk; feat(spN) commits substitute" note), and at least one test file in `backend/tests/` or `src/`? If not, that's a remaining gap.
6. **Assumptions** — Are §10 assumptions falsifiable? Could a new engineer challenge any of them and find the test that proves/disproves them? Is A2's reference to `keyring` accurate now?
7. **Risks** — Are §11 risks current (R-11 corrected to 2,172; R-12 added; R-25/R-26/R-27 added)? Compare against `docs/reviews/2026-06-20-cyclone-completeness-review.md`. Is R-24 (SP23 fork) clearly flagged as awaiting user decision?
If reviewers materially agree on all seven, round 2 closes; this doc becomes the project's new top-level entry point (linked from `README.md`).
---
*End of round 2. Next: re-verify with reviewers (round 3) or escalate any remaining disagreement to the user.*
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,103 @@
# CSS Reduction — Baseline (2026-06-23)
## Goal
Reduce `dist/assets/index-*.css` bytes without changing any tested screen.
One declaration/rule at a time, verified by pixel-identical screenshots
and project checks. This file is the baseline the iterative loop is
compared against.
## Build (the size we are trying to shrink)
| metric | bytes |
| ------------ | ------ |
| raw | 60,695 |
| gzip | 11,786 |
| brotli | 9,875 |
`dist/assets/index-BznqBut5.css`, built with `npx vite build` (Vite 5.4.21,
8.9s).
## Test matrix (the screens we will hold pixel-identical)
- **Theme**: dark only (the app is `<html class="dark">` + `theme="dark"`
for the Toaster; no light path exists in the design system).
- **Sizes**: 3 (desktop 1440×900, tablet 768×1024, mobile 375×812).
- **Routes**: 13 (`/`, `/upload`, `/inbox`, `/claims`, `/claims?status=denied`,
`/remittances`, `/providers`, `/reconciliation`, `/acks`, `/batches`,
`/batch-diff`, `/activity`, `/does-not-exist`).
- **Interactive states**: 6 (claim drawer open, remit drawer open, inbox
row focused, search focused, keyboard cheatsheet open, upload dropzone
focused) × 3 sizes = 18 captures.
- **Total**: 13 × 3 + 6 × 3 = **57 screenshots** per build.
Capture source: `audit-uiux-extended.mjs` (new, superset of
`audit-uiux.mjs`). Pixel-diff harness: `tools/css-screenshots-diff.mjs`
using `pixelmatch` (threshold 0).
## Project checks (the gates we hold green)
| check | baseline | used as gate? | reason |
| --------------------------- | -------- | ------------- | --------------------------------------- |
| `npx vite build` | passes | **yes** | produces the CSS bundle under reduction |
| `npx vitest run` | 498 / 501 | **yes** | pre-existing 3 failures, see "Known failures" below |
| `tsc -b` (in `npm run build`)| **fails**| no | 15 type errors in test files + `Upload.tsx`, all pre-existing |
| `npm run typecheck` | fails | no | same as above |
| `npm run lint` | fails | no | `sh: eslint: command not found` (eslint not installed) |
### Known pre-existing failures (not caused by this work)
`vitest run` — 3 failing tests:
- `src/pages/Inbox.test.tsx > Inbox page > SP14: payer-rejected row count rolls up into the need-eyes header`
- `src/store/tail-store.test.ts > useTailStore > test_fifo_cap_evicts_oldest_when_over_10000`
- `src/components/inbox/InboxHeader.test.tsx > InboxHeader > renders the date and counts`
None touch CSS. Each candidate run will compare the new `vitest` exit
status and failure set to the baseline — a candidate is rejected if it
adds a new failure, even if the count stays at 3.
`tsc -b` / `npm run typecheck` — 15 errors in test files and
`src/pages/Upload.tsx`. Not exercised by the reduction loop.
`npm run lint``eslint` is not installed in `devDependencies`; the
script `npm run lint` exits 127. Not exercised.
## Interactive-state coverage
Out of 18 interactive captures, 15 succeed and 3 fail (the same 3 every
run):
- `remittances-drawer` × all sizes — the `/remittances` page renders with
no table rows in the current backend state, so the row-click step finds
nothing. The screenshot falls back to the static `/remittances` page
with no drawer; pixel-identical comparison still works for that
fallback, but the remittance-drawer CSS itself is not exercised. This
is captured here as an **untested state** for the final report.
The other 15 interactions (`claims-drawer`, `inbox-row-focused`,
`search-focused`, `cheatsheet-open`, `upload-dropzone-focused` × 3 sizes)
all succeed. They exercise the CSS for the open claim drawer, the
keyboard cheatsheet overlay, the focused search button, the focused
upload dropzone, and the focus ring on inbox rows.
## Pre-existing noise (not regressions, not caused by this work)
From the baseline run (`baseline-report.json`):
- 6/57 flows have ≥1 console error. All from the `inbox` route and the
`inbox-row-focused` state. The 4 interactive ones are the same
source.
- 24/57 flows have ≥1 failed request. Likely the dashboard summary
endpoint (`/api/dashboard/summary`) and a few analytics / SSE probes
in the inbox.
- 0 page errors.
A candidate that does not increase these counts is fine; an increase
is informational, not a gate.
## Self-diff sanity check
`tools/css-screenshots-diff.mjs compare` with `BASE == CAND` returns
`PIXEL-IDENTICAL — 57 compared, 0 differing`. The harness works.
## What is in scope for the iterative loop
- Source: `src/index.css` (custom CSS + Tailwind base/components/utilities)
- Config: `tailwind.config.js`
- Component `.tsx` files (only if removing a Tailwind utility from a
`className` produces a smaller bundle)
## What is out of scope
- `index.html` (Google Fonts preconnect, hard to prove pixel-identical
after font source change)
- The JS bundle (separate goal)
- The backend (`backend/`)
- Any non-CSS build artifact
@@ -0,0 +1,110 @@
# CSS Candidates — unused-or-low-value
Generated from `tools/css-candidate-scan.mjs`. 'used' = referenced in any source file. Not used does NOT mean safe to remove — verify with screenshots before keeping a change.
| type | name | used | location |
| ---- | ---- | ---- | -------- |
| css-var | `--background` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--card-foreground` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--popover` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--popover-foreground` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--muted` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--secondary` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--secondary-foreground` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--accent-foreground` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--primary` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--primary-foreground` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--destructive-foreground` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--success-foreground` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--input` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--ring` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--sidebar` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--sidebar-foreground` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--sidebar-accent` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--sidebar-border` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--surface-line` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--surface-line-soft` | **no** | src/index.css :root |
| css-var | `--m-error-bg` | **no** | src/index.css :root |
| css-var | `--radius` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--font-sans` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--font-mono` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--font-display` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--background` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--card-foreground` | **no** | src/index.css :root (referenced inside css/config) |
| css-var | `--muted` | **no** | src/index.css :root (referenced inside css/config) |
| class | `.text-balance` | **no** | src/index.css (components/utilities layer) |
| class | `.text-pretty` | **no** | src/index.css (components/utilities layer) |
| class | `.ring-inset-hairline` | **no** | src/index.css (components/utilities layer) |
| animation | `animate-accordion-down` | **no** | tailwind.config.js animation |
| animation | `animate-accordion-up` | **no** | tailwind.config.js animation |
| animation | `animate-fade-in-soft` | **no** | tailwind.config.js animation |
| animation | `animate-slide-in-right` | **no** | tailwind.config.js animation |
| animation | `animate-ticker-blink` | **no** | tailwind.config.js animation |
| css-var | `--foreground` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--card` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--muted-foreground` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--accent` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--signal` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--destructive` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--success` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--warning` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--warning-foreground` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--border` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--surface` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--surface-ink` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--surface-ink-2` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--surface-ink-3` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--tt-bg` | yes | src/index.css :root |
| css-var | `--tt-bg-elev` | yes | src/index.css :root |
| css-var | `--tt-ink` | yes | src/index.css :root |
| css-var | `--tt-ink-dim` | yes | src/index.css :root |
| css-var | `--tt-amber` | yes | src/index.css :root |
| css-var | `--tt-oxblood` | yes | src/index.css :root |
| css-var | `--tt-ink-blue` | yes | src/index.css :root |
| css-var | `--tt-muted` | yes | src/index.css :root |
| css-var | `--m-surface` | yes | src/index.css :root |
| css-var | `--m-ink-primary` | yes | src/index.css :root |
| css-var | `--m-ink-secondary` | yes | src/index.css :root |
| css-var | `--m-ink-tertiary` | yes | src/index.css :root |
| css-var | `--m-border-heavy` | yes | src/index.css :root |
| css-var | `--m-font-mono` | yes | src/index.css :root |
| css-var | `--m-error` | yes | src/index.css :root |
| css-var | `--m-success` | yes | src/index.css :root |
| css-var | `--m-warning` | yes | src/index.css :root |
| css-var | `--m-accent` | yes | src/index.css :root |
| css-var | `--foreground` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--card` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--muted-foreground` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--border` | yes | src/index.css :root (referenced inside css/config) |
| css-var | `--accent` | yes | src/index.css :root (referenced inside css/config) |
| class | `.num` | yes | src/index.css (components/utilities layer) |
| class | `.display` | yes | src/index.css (components/utilities layer) |
| class | `.mono` | yes | src/index.css (components/utilities layer) |
| class | `.surface` | yes | src/index.css (components/utilities layer) |
| class | `.surface-2` | yes | src/index.css (components/utilities layer) |
| class | `.hairline` | yes | src/index.css (components/utilities layer) |
| class | `.nav-active` | yes | src/index.css (components/utilities layer) |
| class | `.skip-link` | yes | src/index.css (components/utilities layer) |
| class | `.kbd` | yes | src/index.css (components/utilities layer) |
| class | `.eyebrow` | yes | src/index.css (components/utilities layer) |
| class | `.editorial` | yes | src/index.css (components/utilities layer) |
| class | `.row-hover` | yes | src/index.css (components/utilities layer) |
| class | `.animate-scan` | yes | src/index.css (components/utilities layer) |
| class | `.drillable` | yes | src/index.css (components/utilities layer) |
| keyframes | `accordion-down` | yes | tailwind.config.js keyframes |
| keyframes | `accordion-up` | yes | tailwind.config.js keyframes |
| keyframes | `fade-in` | yes | tailwind.config.js keyframes |
| keyframes | `fade-in-soft` | yes | tailwind.config.js keyframes |
| keyframes | `fade-in-up` | yes | tailwind.config.js keyframes |
| keyframes | `slide-in-right` | yes | tailwind.config.js keyframes |
| keyframes | `row-flash` | yes | tailwind.config.js keyframes |
| keyframes | `pulse-dot` | yes | tailwind.config.js keyframes |
| keyframes | `ticker-blink` | yes | tailwind.config.js keyframes |
| animation | `animate-fade-in` | yes | tailwind.config.js animation |
| animation | `animate-fade-in-up` | yes | tailwind.config.js animation |
| animation | `animate-row-flash` | yes | tailwind.config.js animation |
| animation | `animate-pulse-dot` | yes | tailwind.config.js animation |
## Summary
- 36 unused / 100 total
- 64 used / 100 total
@@ -0,0 +1 @@
{"id":"01-var-surface-line-soft","priority":"H","label":"drop --surface-line-soft declaration","file":"src/index.css","before":" --surface-line-soft: 30 14% 14% / 0.12;\n","after":""}
@@ -0,0 +1,42 @@
# CSS Reduction — Candidate Queue
Atomic removals to try, in priority order. Each is one revertable unit
(edit one file, revert if pixel-identical or project checks regress).
Priority legend: **H** (high confidence, no visible effect expected),
**M** (medium, may affect pixels in edge cases), **L** (low, will likely
revert because it changes visible output).
| # | priority | id | what | where | expected | notes |
|---|----------|----|------|-------|----------|-------|
| 1 | H | `var-surface-line-soft` | drop the `--surface-line-soft` declaration | `src/index.css` line 77 | ~30 B | Only mentioned in a comment in `BarChart.tsx`; no `var(--surface-line-soft)` ref anywhere |
| 2 | H | `var-m-error-bg` | drop the `--m-error-bg` declaration | `src/index.css` line 102 | ~30 B | No `var(--m-error-bg)` ref anywhere in src |
| 3 | H | `kf-fade-in-soft` | drop `fade-in-soft` keyframe + `animate-fade-in-soft` util | `tailwind.config.js` | ~150 B | `animate-fade-in-soft` is not used in any source file |
| 4 | H | `kf-slide-in-right` | drop `slide-in-right` keyframe + animation | `tailwind.config.js` | ~180 B | `animate-slide-in-right` not used |
| 5 | H | `kf-ticker-blink` | drop `ticker-blink` keyframe + animation | `tailwind.config.js` | ~200 B | `animate-ticker-blink` not used |
| 6 | H | `kf-accordion-down` | drop `accordion-down` keyframe + animation | `tailwind.config.js` | ~150 B | `animate-accordion-down` not used; no accordion in app |
| 7 | H | `kf-accordion-up` | drop `accordion-up` keyframe + animation | `tailwind.config.js` | ~150 B | same as above |
| 8 | H | `media-print` | drop the entire `@media print { ... }` block | `src/index.css` lines 402446 | ~1 KB | Print not in test matrix; the `display: none` rules apply to aside/header — they don't appear in screenshots anyway. **Risk**: a printed detail drawer would no longer be styled for paper, but no print preview is captured. |
| 9 | M | `body-before` | drop the `body::before` radial gradients (the upper-right accent + top-center softbox) | `src/index.css` lines 147156 | ~400 B | Subtle background. Likely visible on all screenshots. **Will likely revert.** |
| 10 | M | `body-after` | drop the `body::after` hairline grid | `src/index.css` lines 163176 | ~450 B | Subtle background grid. Likely visible. **Will likely revert.** |
| 11 | M | `scrollbar` | drop `::-webkit-scrollbar*` rules | `src/index.css` lines 179195 | ~330 B | Scrollbars only visible when content overflows. Most screenshots are above-the-fold; may not trigger. |
| 12 | M | `nav-active-before` | drop the `::before` accent strip on `.nav-active` | `src/index.css` lines 290300 | ~180 B | Visible on the active sidebar item. |
| 13 | M | `surface-2` | drop the `.surface-2` class entirely | `src/index.css` lines 266277 | ~250 B | Used in some components — likely a revert. |
| 14 | M | `focus-visible` | drop the global `:focus-visible` ring | `src/index.css` lines 200204 | ~90 B | All focusable elements would lose the global ring (but Tailwind focus-visible: utilities still apply). May or may not change pixels. |
| 15 | L | `body-bg-image` | drop the body background-image gradients | `src/index.css` lines 136139 | ~250 B | **Will revert** — visible. |
| 16 | L | `skip-link` | drop the `.skip-link` class | `src/index.css` lines 303338 | ~700 B | Component exists (`ui/skip-link.tsx`). Removing the class breaks it visually. **Will revert.** |
| 17 | L | `drillable` | drop `.drillable` and its hover | `src/index.css` lines 449461 | ~220 B | Used in `DrillableCell.tsx`. **Will revert.** |
| 18 | L | `row-hover` | drop the `.row-hover` hover state | `src/index.css` lines 379384 | ~100 B | Used in tables. Hover state not captured (no mouse). Could be safe. |
## Out of scope (intentionally not tried)
- Tailwind preflight (`*, ::before, ::after`, `::backdrop` with `--tw-*` vars). These power the utility system; removing would break all utilities.
- `@media (prefers-reduced-motion)`. Safety block, removing would change behavior in non-default OS settings.
- Specific custom class definitions that are heavily used (`.num`, `.display`, `.mono`, `.surface`, `.eyebrow`, `.editorial`).
- Any Tailwind utility removal in component `className` props (small wins, lots of churn — would be done in a follow-up pass).
- The `index.html` Google Fonts `<link>` (it's HTML, not CSS, and removing it would change the rendered output).
## Stopping conditions
- Queue exhausted.
- 5 consecutive candidates fail the **size** check (CSS not smaller after the change).
- 2 hours elapsed in Phase 3.
- User requests a stop.
@@ -0,0 +1,468 @@
{
"baseDir": "docs/reviews/2026-06-23-css-reduction/iter/01-var-surface-line-soft/_ref",
"candDir": "docs/reviews/2026-06-23-css-reduction/iter/01-var-surface-line-soft/_cand",
"diffOutDir": "docs/reviews/2026-06-23-css-reduction/iter/01-var-surface-line-soft/_diff",
"threshold": 0,
"compared": 57,
"diffCount": 15,
"missingCount": 0,
"extraCount": 0,
"results": [
{
"file": "404--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "404--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "404--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "acks--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "acks--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "acks--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "activity--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "activity--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "activity--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "batch-diff--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "batch-diff--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "batch-diff--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "batches--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "batches--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "batches--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "cheatsheet-open--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 2523,
"totalPixels": 1296000
},
{
"file": "cheatsheet-open--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "cheatsheet-open--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "claims--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "claims--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 1,
"totalPixels": 304500
},
{
"file": "claims--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "claims-denied--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "claims-denied--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "claims-denied--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "claims-drawer--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "claims-drawer--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "claims-drawer--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "dashboard--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 2523,
"totalPixels": 1296000
},
{
"file": "dashboard--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 3,
"totalPixels": 304500
},
{
"file": "dashboard--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "inbox--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 530,
"totalPixels": 1296000
},
{
"file": "inbox--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 142,
"totalPixels": 304500
},
{
"file": "inbox--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 271,
"totalPixels": 786432
},
{
"file": "inbox-row-focused--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 529,
"totalPixels": 1296000
},
{
"file": "inbox-row-focused--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 150,
"totalPixels": 304500
},
{
"file": "inbox-row-focused--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 150,
"totalPixels": 786432
},
{
"file": "providers--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "providers--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "providers--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "reconciliation--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "reconciliation--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "reconciliation--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "remittances--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "remittances--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "remittances--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "remittances-drawer--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "remittances-drawer--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "remittances-drawer--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 372,
"totalPixels": 786432
},
{
"file": "search-focused--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 9684,
"totalPixels": 1296000
},
{
"file": "search-focused--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 47,
"totalPixels": 304500
},
{
"file": "search-focused--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "upload--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 1,
"totalPixels": 1296000
},
{
"file": "upload--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 1,
"totalPixels": 304500
},
{
"file": "upload--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
},
{
"file": "upload-dropzone-focused--desktop.png",
"size": "ok",
"width": 1440,
"height": 900,
"diffPixels": 0,
"totalPixels": 1296000
},
{
"file": "upload-dropzone-focused--mobile.png",
"size": "ok",
"width": 375,
"height": 812,
"diffPixels": 0,
"totalPixels": 304500
},
{
"file": "upload-dropzone-focused--tablet.png",
"size": "ok",
"width": 768,
"height": 1024,
"diffPixels": 0,
"totalPixels": 786432
}
]
}
@@ -0,0 +1,11 @@
[
{
"id": "01-var-surface-line-soft",
"priority": "H",
"label": "drop --surface-line-soft declaration",
"file": "src/index.css",
"kept": false,
"diffCount": 15,
"diffMax": 9684
}
]
@@ -0,0 +1,10 @@
# CSS Reduction — Progress Log
## Baseline
- raw: 60,695 B · gzip: 11,786 B · brotli: 9,875 B
- 57 screenshots captured
- vitest: 498/501 (3 pre-existing failures)
- tsc: 15 pre-existing failures (gate skipped)
- lint: `eslint` not installed (gate skipped)
## Candidates
@@ -0,0 +1,307 @@
# Cyclone Documentation Review — Reviewer A
## 1. Reviewer identity
**Reviewer A** (Reviewer B is run in parallel; this review covers the full doc set + codebase ground-truth verification).
---
## 2. Executive summary
Cyclone's documentation is unusually thorough for a single-operator tool: a top-level `REQUIREMENTS.md` (38 FRs + 18 NFRs), a top-level `ARCHITECTURE.md`, 27 design specs (20 dated 2026-06-19 to 2026-06-22 + 7 backfilled 2026-06-23 for SP10SP16), and 27 implementation plans (15 original + 12 backfilled for SP9SP20). The doc set has the structure of a well-run engineering project, and the prose quality is high — every spec re-asserts the local-only/single-operator/single-payer design contract, every plan has TDD discipline, and the layering (requirements → architecture → spec → plan → tests) is internally consistent at a high level. **However, the doc set has accumulated at least 25 specific contradictions, ambiguous forks, untested artifacts, and stale numbers** between the two top-level docs alone — and the contradictions are concentrated in the most consequential areas: the live-tail HTTP surface, the claim-state machine, and the LOC/version counters used in the verification matrix. The 7-state claim lifecycle is wrong in 5 places; the codebase has an 8-state enum (`backend/src/cyclone/db.py:180-188`). The tail endpoint URL is `/api/{resource}/stream` per REQUIREMENTS FR-20 + the live-tail spec, but `/api/tail?since=…` per `ARCHITECTURE.md` §5.4 — two competent engineers reading only the docs could ship two incompatible APIs. Below, the 4 reviewer questions and 4 flag sections detail every issue with file:line citations.
---
## 3. Q1: Components
### Description
Cyclone is composed of six concentric layers: (1) the SQLite/SQLCipher store at the bottom (`backend/src/cyclone/db.py`, `backend/src/cyclone/db_crypto.py`, migrations 00010012), (2) ORM models and pure-function business logic (`db.py`, `reconcile.py`, `scoring.py`, `npi.py`, `cas_codes.py`, `inbox_lanes.py`, `inbox_state.py`, `inbox_state_277ca.py`, `audit_log.py`), (3) the per-parser modules under `parsers/` (16 files including the 270/271/277CA/835/999/TA1/837P parsers and serializers), (4) the persistence facade `store.py` (CycloneStore) plus per-feature handlers (`scheduler.py`, `backup_service.py`, `backup_scheduler.py`, `logging_config.py`, `security.py`, `pubsub.py`, `clearhouse/__init__.py`, `providers.py`, `payers.py`), (5) the FastAPI surface — a monolithic `api.py` (~3,548 LOC per ARCHITECTURE §3.1 / 3,145 per REQUIREMENTS) plus a partial `api_routers/` package (`acks.py`, `admin.py`, `health.py`, `ta1_acks.py`) that owns the new admin/health endpoints, and (6) the React + Vite + TypeScript frontend (`src/`) with TanStack Query v5, Zustand, Radix UI primitives, and shadcn-style components.
The top-level docs (`REQUIREMENTS.md` §2.1, `ARCHITECTURE.md` §3) describe these layers at the same level of granularity and agree on the boundaries. The cross-SP doc set reinforces them: each spec names the modules it extends (e.g. SP13 `clearhouse/__init__.py:319`, SP14 `inbox_lanes.compute_lanes`, SP15 `db_crypto + db + api`, SP16 `scheduler.py:720`). The ASCII topology diagram in `ARCHITECTURE.md` §1.2 is the canonical picture.
### Consistency verdict
**Mostly consistent, with three meaningful gaps:**
1. The `api_routers/` package is partially implemented (`acks.py`, `admin.py`, `health.py`, `ta1_acks.py`) but documented only as "planned" in `ARCHITECTURE.md` §3.2 and not mentioned at all in `REQUIREMENTS.md`; the specs still reference monolithic `cyclone.api` (e.g. SP15 §3.3 says `cyclone/api.py:2797-2928` for the rotation endpoint, but the actual code lives at `api_routers/admin.py`). Engineers building "what does Cyclone's API look like" from the spec set will get the monolithic picture; engineers reading the codebase will see a partially split package.
2. `backup.py` (file upload/retention module) and `backup_service.py` vs `backup_scheduler.py` (periodic scheduler) are described as a single "SP17" subsystem across the docs, but the spec file (`2026-06-21-cyclone-encrypted-backup-design.md`) is the *original* SP17 spec while the implementation plan is dated `2026-06-23-cyclone-sp17-encrypted-backup.md`. The two documents describe the same work but the round-3 doc-prep added the plan but did NOT add a backfilled spec for SP17. So the SP17 docs are pre/back mixed, not a clean backfill like SP10SP16 (which got both spec and plan).
3. The `workflow/` subdirectory visible under `backend/src/cyclone/` has only `__pycache__/` entries on disk (`workflow/__pycache__/__init__.cpython-313.pyc`, `workflow/__pycache__/batch_diff.cpython-313.pyc`, `workflow/__pycache__/inbox_lanes.cpython-313.pyc`, `workflow/__pycache__/inbox_state.cpython-313.pyc`, `workflow/__pycache__/reconcile.cpython-313.pyc`, `workflow/__pycache__/scoring.cpython-313.pyc`) — but no `.py` source files. This indicates `workflow/` was a refactoring target (likely SP21 store-split) whose sources were removed/moved but whose compiled artifacts were not cleaned. **None of the docs mention `workflow/` as a deprecated stub**; engineers reading the docs will not understand why the directory exists in compiled form only.
**Verdict: medium confidence in component consistency.** The high-level decomposition is consistent across the top-level docs and the spec set. The drift is in the partial-API-router split, the SP17 plan/spec asymmetry, and the unexplained `workflow/` ghost directory.
---
## 4. Q2: Data model
### Description
The data model is a SQLAlchemy 2.0 ORM (`backend/src/cyclone/db.py`) backed by SQLite, optionally encrypted via SQLCipher (`backend/src/cyclone/db_crypto.py` — SP12). Migration runner is `db_migrate.py` reading `PRAGMA user_version`**12 migrations on disk**: `0001_initial` through `0012_backups` (listed at `backend/src/cyclone/migrations/`). The core tables are: `batches`, `claims`, `remittances`, `cas_adjustments`, `matches`, `activity_events`, `service_lines`, `service_line_payments`, `line_reconciliations`, `acks`, `ta1_acks`, `providers`, `payers`, `clearhouse`, `payer_rejected` columns on `claims` (SP10, migration 0008), `payer_rejected_acknowledged_at`/`_actor` (SP14, migration 0010), `audit_log` (SP11, migration 0009), `processed_inbound_files` (SP16, migration 0011), and `backups` (SP17, migration 0012).
The key entity relationships are: `Batch 1—N Claim`, `Batch 1—N Remittance`, `Remittance N—1 Claim` (nullable FK on `claims.matched_remittance_id`), `Remittance 1—N CasAdjustment`, `Claim 1—1 Match` (unique), `Claim 1—N ServiceLine`, `Remittance 1—N ServiceLinePayment`, `Claim 1—N LineReconciliation`, `Remittance 1—N LineReconciliation`, and `AuditLog` as a chain on its own (no FKs; the chain links by `prev_hash`). `ServiceLinePayment` is the SP7 bridge between the 837 and 835 line worlds; it carries the `procedure_code`/`service_date`/`charge`/`payment`/`units` plus `modifiers_json` as a serialized list. The `audit_log` table (SP11) is a separate hash-chained append-only log keyed by SHA-256 of `(event_type, entity_type, entity_id, actor, created_at, prev_hash)`; the chain is verifiable via `cyclone.audit_log.verify_chain(session)` (verified at `backend/src/cyclone/audit_log.py:190`) which recomputes every hash and walks the `prev_hash` links (`audit_log.py:228-242`).
The state machine has multiple representations in the docs:
- **`REQUIREMENTS.md` §3.1 + §6.3 (traceability)** says: "7-state claim lifecycle: submitted, received, paid, partial, denied, reconciled, reversed."
- **`backend/src/cyclone/db.py:180-188` (code)** says: `ClaimState` enum with **8 values**: `SUBMITTED, RECEIVED, REJECTED, PAID, PARTIAL, DENIED, RECONCILED, REVERSED`. The 8th state, `REJECTED`, was added by the workflow-automation/SP6 plan (`docs/superpowers/plans/2026-06-20-cyclone-workflow-automation.md` Task 1) when 999 AK9 R/E rejection handling was introduced.
- **`ARCHITECTURE.md` §6.3** says: "states: submitted, accepted, paid, denied, appealed, rejected, payer_rejected" — 7 states, including `accepted` (which is NOT in the code) and `payer_rejected` (which is NOT a state in the code but a set of columns on `claims` filtered on by `inbox_lanes.compute_lanes`).
- **`docs/superpowers/specs/2026-06-19-cyclone-db-reconciliation-design.md` §6.7** (pre-SP6) says: "submitted, received, paid, partial, denied, reconciled, reversed" — 7 states, matches the pre-SP6 plan.
The `payer_rejected` status is *not* a `ClaimState` value. It is stored as four columns on `claims`: `payer_rejected_at`, `payer_rejected_reason`, `payer_rejected_status_code`, `payer_rejected_by_277ca_id` (verified at `backend/src/cyclone/db.py:270-280`; SP10 spec §2.1). The 5th inbox lane (`payer_rejected`) is computed by `inbox_lanes.compute_lanes` filtering on `payer_rejected_at IS NOT NULL AND payer_rejected_acknowledged_at IS NULL` (SP14 spec §3.2). So `payer_rejected` is a *view*, not a *state* — yet `ARCHITECTURE.md` lists it as a state.
The `Match` model carries an `is_reversal` flag (defined in the SP2 plan) and the spec calls for a `state_before_reversal` column on `claims` to preserve reversals (`db_reconciliation-design.md` §6.6). The 835 reverse-direction (CLP02 ∈ {21, 22}) is handled by `apply_reversal()` in `reconcile.py` which restores the prior state. **However, the SP10 277CA path does NOT extend the state machine** — claims with a payer rejection stay in their prior state (`paid`, `denied`, `partial`, etc.) and gain the `payer_rejected_at` timestamp; the 5-lane inbox surfaces them but `claim.state` does not transition to a new value. This is consistent with the SP10 spec §2.3 ("we explicitly do not clear `payer_rejected_at` on acknowledge") and SP14 spec §2.3, but contradicts the more casual phrasing in `ARCHITECTURE.md` §6.3.
### Consistency verdict
**Low confidence in data-model consistency across the doc set.** The `ClaimState` enum has 8 values (verified at `backend/src/cyclone/db.py:180-188`) but the docs claim 7 in 4 places (`REQUIREMENTS.md` §3.1 and §6.3, `ARCHITECTURE.md` §6.3, the db-reconciliation spec §6.7, and the workflow-automation plan Task 1 implicitly). The 5th `payer_rejected` "state" in `ARCHITECTURE.md` §6.3 is not a state in the code — it is a column-and-filter view. Engineers building the data model from the docs alone will produce either an 8-state enum without a `payer_rejected` value (correct) or a 9-state enum with both `rejected` and `payer_rejected` (wrong, not in the code).
The second meaningful gap is the dual audit mechanism. `activity_events` (db.py original migration 0001) is a regular table for *transition events*; `audit_log` (SP11, migration 0009) is a separate hash-chained table for *HIPAA-relevant events*. The docs are inconsistent on which events go where: the SP14 spec §3.3 says `claim.payer_rejected_acknowledged` is appended to `audit_log`, but the SP6 workflow plan implies `claim.rejected` (the 999 R/E event) lands in `activity_events`. The two tables overlap in name space but have different writers — `audit_log.py:99-126`'s `append_event` takes an `AuditEvent` payload but `activity_events` is written from a different code path (`store.py`). No doc explicitly enumerates which `kind` strings go to which table.
---
## 5. Q3: Dependencies
### Description
There are four overlapping dependency graphs in this doc set: (a) spec-level dependencies ("depends on SP X"), (b) plan-level task dependencies (TDD phases 1 → 2 → 3 with `git worktree` rebases), (c) module/import dependencies in the codebase, and (d) data-model migration ordering. The graphs mostly agree; the divergences are concentrated in SP21/SP22 (in-flight) and SP23 (candidate).
**(a) Spec dependencies.** The 7 backfilled specs (SP10SP16) each declare their upstreams explicitly:
- SP10 (277CA) `2026-06-23-cyclone-sp10-277ca-payer-rejected-design.md` §"Depends on:" → SP3 (999 parser) + SP6 (workflow/inbox).
- SP11 (audit log) → SP6 + SP10 + SP12.
- SP12 (SQLCipher) → standalone.
- SP13 (SFTP) → SP9 (SftpClient stub + secrets).
- SP14 (5-lane inbox) → SP6 + SP10 + SP11.
- SP15 (key rotation) → SP11 + SP12 (cannot ship without SP12; `2026-06-23-cyclone-sp15-key-rotation-design.md` line 11: "Cannot ship without SP12").
- SP16 (MFT polling) → SP9 + SP11 + SP13 + SP15 (implicitly, since SFTP auth uses the Keychain) + the per-parser modules.
These declarations are consistent with the implementation order in the git log (SP10 → SP11 → SP12 → SP13 → SP14 → SP15 → SP16) and with the migration versions (0008 through 0011).
**(b) Plan-level task dependencies.** The plans use a `[ ] Step N → commit` pattern with explicit prerequisites (e.g. `live-tail.md` Task 0 requires SP5 to be merged first; `claims-unique-constraint-and-409-ux.md` worktree setup requires `pip install -e backend`). The plan-level dependencies are clean within each plan; the cross-plan dependencies are weak. For example, the SP14 plan does not declare it depends on SP10's migration `0008_payer_rejected_columns.sql` — it just references "the SP10 `payer_rejected_*` columns" without naming the migration.
**(c) Module dependencies.** The import graph in `backend/src/cyclone/` shows the expected layering: `parsers/` modules import `cyclone.exceptions` and `cyclone.segments` only (clean isolation); `db.py` imports nothing from `cyclone.*` (forward references via string IDs); `reconcile.py`, `scoring.py`, `inbox_lanes.py` import `cyclone.db`; `store.py` imports everything (`db`, `reconcile`, `scoring`, `inbox_state`, `inbox_state_277ca`, `pubsub`); `api.py` imports `store`, `db`, `audit_log`, `scheduler`, `db_crypto`, `security`, etc. The `scheduler.py` module *intentionally duplicates* small helpers (`_ack_count_summary`, `_ack_synthetic_source_batch_id`, `_277ca_synthetic_source_batch_id`) to break what would otherwise be a circular dependency with `cyclone.api` — this is documented in SP16 spec §3.5. The `audit_log.py:99-126` `append_event` function takes a session and an `AuditEvent`, called by SP14 ack endpoint, SP15 rotation endpoint, and SP16 scheduler handlers. The store-scheduler boundary is clean.
**(d) Migration ordering.** 12 migrations on disk (`0001_initial` through `0012_backups`) are forward-only via `PRAGMA user_version`. The runner (`db_migrate.py`) reads `-- version: N` headers, sorts by filename, applies any with `version > current` (`db_migrate.py:438-466`). The version assertions in `test_db_migrate.py` confirm monotonic ordering. The `claims-unique-constraint-and-409-ux.md` plan adds migration `0013_drop_claims_unique_constraint.sql` on a worktree (`claims-unique-fix`); this migration does NOT exist on `main` yet, which is consistent with the plan being in-flight. **However, the `2026-06-23-cyclone-sp11-hash-chained-audit-design.md` spec refers to migration `0009_audit_log.sql` and the docs say SP11 ships migration 0009 — that migration IS on disk and `audit_log.py` exists, confirming SP11 shipped.**
**(e) SP21 / SP22 / SP23 status.** SP21 (store split) is in-flight on `refactor/store-split` branch (`docs/superpowers/specs/2026-06-21-cyclone-store-split-design.md` Status: "Draft / not merged"); SP22 (parse-decide) lives on `claims-unique-fix` worktree (`docs/superpowers/specs/2026-06-21-cyclone-parse-decide-workflow-design.md` + the unique-constraint plan). SP23 (Ubuntu Docker + RBAC) is a candidate only (`docs/superpowers/specs/2026-06-22-cyclone-ubuntu-docker-deployment-design.md` Status: "Draft / candidate"). These are called out in the spec titles, but the top-level docs (`REQUIREMENTS.md` §1.4, `ARCHITECTURE.md` §0.1) do NOT explicitly mark SP21/SP22/SP23 as in-flight. An engineer reading only the top-level docs would assume all 23 SPs are at the same ship-readiness level.
### Consistency verdict
**High confidence within the shipped SPs (SP1SP20)**, where the spec→plan→code→migration→test graph is internally consistent. **Low confidence for SP21/SP22/SP23**, which are in-flight or candidate and not marked as such in the top-level docs. The spec-level "Depends on" declarations are accurate and actionable.
---
## 6. Q4: Definition of done
### Description
`REQUIREMENTS.md` §8 (lines 643681) defines "Definition of Done" in three sub-sections: §8.1 *Functional DoD* (every FR covered by ≥1 spec + ≥1 plan + ≥1 integration test), §8.2 *Non-Functional DoD* (every NFR has a verification command), §8.3 *Operational DoD* (deployment posture, backup readiness, encryption posture). Each FR has a row in the §6.1 traceability matrix pointing at the covering spec/plan and a test file. `ARCHITECTURE.md` §10 ("Operational Story") describes the deploy / backup / runbook posture in narrative form.
The §8.1 Functional DoD says every FR is "Met" if it has a covering spec, plan, and integration test. The §6.1 traceability matrix marks FR-1 through FR-38 with a single test file each (e.g. FR-20 → `test_api_stream_live.py` + `TailStatusPill.test.tsx`). The matrix does NOT explicitly require happy-path AND failure-path test coverage — but `REQUIREMENTS.md` §4 NFR-2 ("Test discipline: every route has a happy-path test and at least one failure-path test") adds this requirement at the NFR layer. So the union of FR + NFR DoD is: each route has a happy + failure path test.
The DoD is *partially testable*: the test-file pointers in the traceability matrix are verifiable by `ls backend/tests/` and `ls src/**/*.test.ts*`; the happy/failure-path test count is verifiable by reading each test file. The encryption-at-rest posture (NFR-5 / SP12) is verifiable by checking that `cyclone.db_crypto.is_encryption_enabled()` returns `True` when `sqlcipher3` is installed and the Keychain entry exists (per the SP12 spec §1). The single-process posture (NFR-14) is verifiable by reading the scheduler module's lack of `threading.Thread` / `multiprocessing.Process` callers. The audit-chain integrity (NFR-4 / SP11) is verifiable by `GET /api/admin/audit-log/verify` returning `ok: true, checked: N+1`.
### Testability verdict
**Medium confidence.** Four issues break testability:
1. The `REQUIREMENTS.md` §8.3 Operational DoD mentions "Vitest ^4.1.9" and flags it in §5.3 / R-25 as "unusually new — verify the version pin is intentional before the next npm install; fallback to `^2.x` if accidental." The `ARCHITECTURE.md` §3.2 (tooling table) lists `vitest 4.1.9` without flagging it. **The flagging is inconsistent — one top-level doc treats it as a problem to fix, the other treats it as normal.** A CI gate that asserts "vitest@^2.x" would fail on the codebase.
2. The §8.3 DoD claims `vitest@^4.1.9` is "unusually new (current stable line is 1.x/2.x)" — but Vitest 4.x *does exist* (released after Vitest 3.x in 2025); the claim is also inaccurate relative to the doc's own date. The §6.3 acceptance row for SP5 says the live-tail test count target was "~144 frontend pass" with "~437 backend" — but `backend/tests/` contains 94 test files (verified by directory listing). The number is in the right order of magnitude but unverified.
3. The §10 Operational Story in `ARCHITECTURE.md` describes "5-second heartbeat" on the live-tail stream — but `REQUIREMENTS.md` §4 NFR-10 (line 163) says "Heartbeat every 15s default (`CYCLONE_TAIL_HEARTBEAT_S`)". The actual `backend/src/cyclone/api.py:1679-1680` comment says `CYCLONE_TAIL_HEARTBEAT_S` (consistent with REQUIREMENTS, not ARCHITECTURE). **The 5s heartbeat claim is wrong against both the codebase AND REQUIREMENTS.md.** The operational story in §10 cannot be the basis for a deploy runbook until this is corrected.
4. The §10 Operational Story does not describe the SP16 scheduler (`CYCLONE_SCHEDULER_AUTOSTART` opt-in, `CYCLONE_SCHEDULER_POLL_SECONDS` default 60) at all — only the manual operator path. The §8.3 DoD also does not mention "scheduler running without `CYCLONE_SCHEDULER_AUTOSTART=true`" as a verified-state precondition. The "auto-poll" deploy posture introduced by SP16 is invisible to the top-level DoD.
**Verdict:** The DoD is *partially* testable. The functional DoD (each FR → test file) is verifiable by file enumeration. The non-functional DoD (each NFR → verification command) is mostly verifiable but the Vitest version flag, the heartbeat interval, and the scheduler autostart posture create 3 places where a competent engineer reading only the top-level docs would either install the wrong version or deploy the wrong polling config.
---
## 7. Contradictions
The following are direct contradictions in the doc set. Each cites file:line for both sides.
1. **`api.py` LOC count.** `REQUIREMENTS.md` §3.2 / R-23 says `api.py` is **3,145 LOC**. `ARCHITECTURE.md` §3.1 says `cyclone.api:app` is **3,548 LOC** with `cyclone.store` at **2,423 LOC**. `REQUIREMENTS.md` R-24 says `store.py` is **2,172 LOC**. Three different numbers for two files.
2. **`store.py` LOC count.** Same as above: 2,172 (REQUIREMENTS R-24) vs 2,423 (ARCHITECTURE §3.1).
3. **Live-tail heartbeat interval.** `REQUIREMENTS.md` §4 NFR-10 (line 163): "Heartbeat every 15s default (`CYCLONE_TAIL_HEARTBEAT_S`)". `ARCHITECTURE.md` §5.4: "5s heartbeat" (in the description of the live-tail stream). Code (`backend/src/cyclone/api.py:1679-1680`): "every `CYCLONE_TAIL_HEARTBEAT_S` seconds when idle". The `live-tail` plan (§7 / Phase 3 Task 11) says "the 15s heartbeat via `asyncio.wait_for` loop (overridable for tests)". **The 5s claim is wrong; the code and NFR-10 agree on 15s.**
4. **Live-tail endpoint URL.** `REQUIREMENTS.md` §3.1 FR-20 (line 128) says `/api/{claims,remittances,activity}/stream`. `ARCHITECTURE.md` §5.4 says `GET /api/tail?since=…`. The `live-tail` spec (`2026-06-20-cyclone-live-tail-design.md`) and plan (`2026-06-20-cyclone-live-tail.md`) use the per-resource URL pattern. The code (`api.py:1679-1680`) matches the per-resource pattern. **The ARCHITECTURE §5.4 single-endpoint claim is wrong.**
5. **Claim lifecycle state count.** `REQUIREMENTS.md` §3.1 + §6.3 traceability: "7-state claim lifecycle". `ARCHITECTURE.md` §6.3: "7 states: submitted, accepted, paid, denied, appealed, rejected, payer_rejected". Code (`backend/src/cyclone/db.py:180-188`): **8 states** (SUBMITTED, RECEIVED, REJECTED, PAID, PARTIAL, DENIED, RECONCILED, REVERSED). The docs disagree with themselves and with the code.
6. **Claim lifecycle state names.** `ARCHITECTURE.md` §6.3 lists `accepted` and `appealed` — neither exists in the code or any spec. The code uses `RECEIVED` (not `accepted`) and has no `appealed` state. The lifecycle spec says reversal preserves the prior state via `state_before_reversal`; there is no appeal flow.
7. **`payer_rejected` as a state.** `ARCHITECTURE.md` §6.3 lists it as a state. The SP10 spec §2.3 and SP14 spec §2.3 explicitly state `payer_rejected_at` is a timestamp column on `claims`, NOT a `ClaimState` value. The lane filter (SP14 spec §3.2) is `payer_rejected_at IS NOT NULL AND payer_rejected_acknowledged_at IS NULL`. **A lane is not a state.**
8. **Vitest version flagging.** `REQUIREMENTS.md` §5.3 R-25 (line 652) flags `vitest@^4.1.9` as "unusually new" and a fallback to `^2.x` is suggested. `ARCHITECTURE.md` §3.2 lists `vitest 4.1.9` in the tooling table without any flagging. Engineers reading only the architecture doc will not realize the version is under review.
9. **Plan ID numbering.** The user's plan inventory says "15 original plans + 12 backfilled plans = 27 plans". The on-disk count matches (15 + 12). But the original plans use a SP-numbering scheme ("Sub-project 4", "Sub-project 6", "Sub-project 7") while the backfilled plans use a `sp9``sp20` naming scheme. There is no `sp1``sp8` backfill because those SPs were the originals. **Engineers searching for "SP7 plan" find `2026-06-20-cyclone-line-reconciliation.md` (Sub-project 7) — works — but searching for "SP8 plan" finds `2026-06-20-cyclone-serialize-837.md` whose own title says "Sub-project 7" (the file was re-purposed from SP7 to SP8).** Both top-level docs note this self-acknowledged mis-labeling (`REQUIREMENTS.md` §1.4 + R-22 + `ARCHITECTURE.md` §0.1 mention it) but do not fix it on disk.
10. **SP number ↔ filename mapping.** SP9 = `multi-payer-npi-sftp` (spec is "SP9 — Multi-payer NPI + SFTP"). But the user's plan inventory says "12 backfilled plans (dated 2026-06-23-cyclone-sp{9..20}-*.md)" — SP9 is the *first* backfilled. The original spec for SP9 lives at `2026-06-20-cyclone-multi-payer-npi-sftp-design.md` (not in the backfill range). So SP9 has an original spec + a backfilled plan + a backfilled spec for SP13-SFTP. The mapping is "SP9 = NPI + SFTP" but the "SFTP" name also gets re-used for SP13's `SftpClient` paramiko wire-up. **Two SPs share the SFTP concept; SP9 = config/secrets, SP13 = transport. The docs do not always disambiguate.**
11. **SP17 spec/plan asymmetry.** SP17 (encrypted backup) has a spec file dated `2026-06-21` (the original) but the plan is dated `2026-06-23-cyclone-sp17-encrypted-backup.md` (backfilled). The other 6 backfilled SPs (SP10SP16) have both spec and plan backfilled; SP17 has only the plan backfilled. The user said "12 backfilled plans for SP9-SP20" — so SP17 falls in that range — but the spec is original. This is an asymmetry in the doc-prep pass.
12. **`audit_log` event-type vocabulary.** The SP14 spec §3.3 enumerates `claim.payer_rejected_acknowledged` as the audit event. The SP15 spec §3.4 enumerates `db.key_rotated`. The SP16 spec §3.5 enumerates `claim.rejected` (from 999 `_handle_999`) and `claim.payer_rejected` (from 277CA `_handle_277ca`). The completeness review (2026-06-20 §3.1 item 2) calls out `ActivityEvent` as "not tamper-evident" — but the SP11 audit log adds tamper-evidence only for events that *opt in* to `append_event`. The completeness review and the round-3 docs do not reconcile which `kind` strings go to `activity_events` (mutable) vs `audit_log` (hash-chained).
13. **Live-tail reconnect backoff cap.** `REQUIREMENTS.md` §4 NFR-10 and FR-21: "backoff ladder `1s → 2s → 4s → 8s → 16s → 30s` capped". The `live-tail` spec §3.4 says the same ladder. The plan (`live-tail.md` Task 19) repeats it. **No contradiction here, but** the spec/plan/test all say "stalled at 30s silence" while the plan also says "the hook should NOT auto-reconnect on stall (user confirms)" — the FR-21 backoff ladder applies only to `reconnecting`, not `stalled`. A naive reader of FR-21 could think the stalled state auto-reconnects.
14. **`store.add(rec, event_bus=…)` parameter.** The `production-readiness.md` plan Task 4 wires `store.add()` with `event_bus=request.app.state.event_bus`. The `claims-unique-constraint-and-409-ux.md` plan Task 1.3 calls `store.add(rec, event_bus=request.app.state.event_bus)` from the 837/835 endpoints. **But** the original `store.py:226` `InMemoryStore.add()` and the `CycloneStore.add()` impl do not have an `event_bus=` parameter — the call sites pass `event_bus=` to a function that does not accept it. This is *historical drift* (the InMemoryStore predates the EventBus in SP5) but the docs do not call out the refactor.
15. **Migrations total count.** `REQUIREMENTS.md` §5.2 lists migrations `0001` through `0012` (12 total) but the §6.3 acceptance rows reference `0013_drop_claims_unique_constraint` (which is on the `claims-unique-fix` worktree, NOT on `main`). Engineers running `ls backend/src/cyclone/migrations/` on `main` see 12 files; engineers on the worktree see 13. The doc text is ambiguous about which branch it describes.
16. **Test count target.** The historical `2026-06-20-completeness-review.md` §1 says **574 backend tests**. The `production-readiness.md` plan §"Test count targets" (Phase 2 final target) says **437 backend**. The `live-tail.md` plan §"Test count targets" says **437 backend + 144 frontend**. The user's question-statement says **964 tests**. **Four different numbers for "how many tests does Cyclone have".** The discrepancy is partly due to date (574 was measured in 2026-06-20; 437 was a target for SP5; 964 is current).
17. **API router location for the rotation endpoint.** `2026-06-23-cyclone-sp15-key-rotation-design.md` §3.3 says the endpoint lives at `cyclone/api.py:2797-2928`. The actual endpoint lives at `backend/src/cyclone/api_routers/admin.py` (the `api_routers/` split happened after SP15 was written). The line range is stale.
18. **Encrypted-at-rest posture.** `REQUIREMENTS.md` §4 NFR-5: "SQLite is encrypted via SQLCipher AES-256 when the macOS Keychain entry exists and `sqlcipher3` is installed; plain SQLite otherwise." `ARCHITECTURE.md` §10 Operational Story: "the SQLite file at `~/.local/share/cyclone/cyclone.db` is plaintext by default; SQLCipher optional." The two phrasings agree on substance but the operational story makes the "plaintext by default" stance more prominent than the requirements doc.
19. **API endpoint for the MFT scheduler status.** The SP16 spec §4.1 says `GET /api/admin/scheduler/status` returns a `SchedulerStatus` JSON. The SP16 spec §3.3 says the `GET /api/health` endpoint also reports `snap.scheduler.running`. **Two endpoints expose scheduler state** with different shapes. The DoD does not say which is canonical.
20. **Audit-event `actor` semantics.** SP14 spec §3.3 says `actor` defaults to `"operator"` and is operator-supplied via request body. SP15 spec §3.4 says the same. The SP23 candidate (`ubuntu-docker-deployment-design.md`) introduces RBAC and `actor` becomes a real identity from a JWT claim. The two phrasings agree on default behavior but differ on whether `actor` is free-form text (today) vs identity-validated (SP23 future). Engineers building an audit-evidence tool today must treat `actor` as untrusted free-form text.
21. **`/api/clearhouse/submit` parameter shape.** SP13 spec §4 says no new endpoints, but references the SP9 endpoint `POST /api/clearhouse/submit`. The SP9 spec is the original spec (`2026-06-20-cyclone-multi-payer-npi-sftp-design.md`). The two docs disagree on the request shape: SP9 spec §4 has `body: { sftp_block_name, payload }`; SP13 spec §4 says SP9 endpoint body is "unchanged" but adds an `auth` dict to `SftpBlock` model. The exact request schema is documented in SP9 only; SP13 trusts it. Two readers building SP13 from spec-only could ship two different request bodies.
22. **`processed_inbound_files` table ↔ scheduler hand-off.** The SP16 spec §3.5 says `_handle_999` and `_handle_277ca` write SP11 audit events. The plan for SP14 says `claim.payer_rejected_acknowledged` is an audit event. **Both audit events end up in the same `audit_log` table** but no doc names a "row kind namespace" — an operator querying `SELECT event_type, COUNT(*) FROM audit_log GROUP BY event_type` would need to enumerate every spec's event types to build a vocabulary.
23. **Reconciliation failure semantics.** `REQUIREMENTS.md` §4 NFR-2 says reconciliation must be "fail-soft — a 999 parser crash does not lose the 835". The db-reconciliation spec §6.6 says the same. The completeness review §4 item 4 says "ActivityEvent is mutable". **Both can be true**, but the reconciliation "fail-soft" event goes to `activity_events` (mutable) and the SP16 "scheduler per-file try/except" event goes to `processed_inbound_files.error_message` (also not in `audit_log`). An auditor searching the hash-chained log for a reconciliation failure will find nothing for SP5-era crashes.
24. **Store ownership of `parse_inbound_filename`.** The SP16 spec §3.5 says `_handle_999` etc. use `cyclone.edi.filenames.parse_inbound_filename` (a separate module under `cyclone/edi/filenames.py`). The completeness review (pre-SP16) doesn't mention this module. The SP16 spec was backfilled; the upstream SP9 spec for `SftpClient` does not mention `edi/filenames.py` either. The module exists in the codebase (`backend/src/cyclone/edi/filenames.py`) and is covered by `test_filenames.py` — but no spec describes *why* it lives in `edi/` instead of `parsers/`.
25. **`claim.rejected` audit event idempotency.** SP16 spec §3.5 says `_handle_999` writes one `claim.rejected` audit event per matched claim. The SP6 workflow plan (`workflow-automation.md` Task 3) says `apply_999_rejections` is idempotent on already-rejected claims. **The interaction is: a 999 file applied twice (e.g. a retry) writes 0 new audit events on the second call (because `claim.state == REJECTED` short-circuits in `apply_999_rejections`).** The SP16 spec does not say "scheduler retries are idempotent on the audit chain" — only on the parser. A future scheduler retry-aware design might emit a `claim.rejected_reapplied` audit event, but no doc says so.
---
## 8. Forks (highest-priority first)
These are the items where two competent engineers reading only the docs would plausibly build different systems.
**F1 (P0). Tail endpoint URL.** FR-20 says `/api/{resource}/stream`; ARCHITECTURE §5.4 says `/api/tail?since=…`. Two URLs, two shapes, two different filter mechanisms. The codebase matches FR-20. **An engineer reading only ARCHITECTURE.md would build a single-endpoint `/api/tail?since=…` that does not exist.**
**F2 (P0). Claim lifecycle state names.** REQUIREMENTS says 7 states (no `REJECTED`, has `received`); ARCHITECTURE says 7 states (with `accepted`, `appealed`, `rejected`, `payer_rejected`); code has 8 states (`SUBMITTED, RECEIVED, REJECTED, PAID, PARTIAL, DENIED, RECONCILED, REVERSED`); `ARCHITECTURE` adds `payer_rejected` as a state but the code does not. **An engineer building from REQUIREMENTS would ship a 7-state enum without `REJECTED` and break the SP6 workflow-automation `apply_999_rejections` path; an engineer building from ARCHITECTURE would ship a 7-state enum with `appealed` and `payer_rejected` and break the codebase.**
**F3 (P0). Heartbeat interval.** 5s vs 15s. The code is 15s. An engineer deploying based on ARCHITECTURE §5.4 would set `CYCLONE_TAIL_HEARTBEAT_S=5` (or not set it and expect 5s) and double the bandwidth on the live-tail stream. An operator monitoring for "stalled" would flip state 5× as often.
**F4 (P0). 409 collision response shape.** The SP22 `parse-decide-workflow-design.md` describes the 409 body for a CLM01 collision as `{parse_result, collisions: [{colliding_claim_ids, existing_batch_id}]}` — a richer shape that lets the UI surface "you have N existing batches that already hold this CLM01". The `claims-unique-constraint-and-409-ux.md` plan + spec describe the 409 body as `{error, detail, batch_id, existing_batch_id}` — a simpler shape that only carries the first matching batch. **The two specs describe different 409 contracts.** A frontend engineer building from SP22 will render a richer panel; one building from the claims-unique-constraint plan will render a simpler panel.
**F5 (P1). `?ack=true` response shape on parse-837.** REQUIREMENTS §3.1 FR-9 says `?ack=true` "auto-generates a 999 acknowledgement". The `edi-features.md` plan Task 15 says "persist `Ack` row, attach to response body" — but the response shape is described as "the 999 is attached inline". The live-tail spec does not re-acknowledge. **Three different response shapes are plausible: (a) `{claims, summary, ack: {ack_id, body}}` with the 999 inline, (b) `{claims, summary, ack_id}` requiring a follow-up GET, (c) `{claims, summary, ack_999_x12: "ISA*..."}` with raw text. The plan's test (`test_api_parse_persists.py` ack=true happy path) checks the response, but no doc publishes the canonical shape.**
**F6 (P1). `payer_rejected` lane ↔ `rejected` lane ordering.** SP14 spec §1 says the 5 lanes are ordered "envelope problems → payer problems → recon opportunities → claims in flight → done today". SP14 spec §3.7 code shows the order `rejected, payer_rejected, candidates, unmatched, done_today`. The SPEC.md says the same. The summary tile grid is `grid-cols-2 sm:grid-cols-3 lg:grid-cols-5`. **No conflict in the docs, but** if a future engineer "tidies" the lane order to alphabetical, the "Need eyes" counter (which sums `rejected + payer_rejected + candidates + unmatched` per SP14 spec §3.8) would still work; the visual hierarchy would change.
**F7 (P1). `ActivityEvent` vs `audit_log` event namespace.** The codebase has two parallel event tables. The SP11 spec says `audit_log` is for HIPAA-relevant events (`claim.rejected`, `claim.payer_rejected_acknowledged`, `db.key_rotated`). The pre-SP11 design (still in `store.py`) writes `activity_events` for state transitions (`claim_submitted`, `manual_match`, `manual_unmatch`, `reconcile`, etc.). **No doc publishes a complete list of which event types go to which table.** A future engineer adding a new event (e.g. `claim.appealed`) would have to choose which table to use with no explicit guidance. *Note: SP23 candidate mentions "appeals workflow" without specifying the table.*
**F8 (P1). `store.add(rec, event_bus=…)` signature.** The live-tail plan (SP5) and the unique-constraint plan (SP22) both call `store.add(rec, event_bus=request.app.state.event_bus)`. The pre-SP5 `InMemoryStore.add()` does not accept `event_bus=`; the post-SP5 `CycloneStore.add()` signature is unclear from the docs. **A new engineer refactoring `store.py` (which SP21 plans to do) could break both call sites.** The plan-level dependency on SP5's `event_bus` is implicit in 7+ places; the SP21 spec does not list this as a constraint.
**F9 (P1). `api.py``api_routers/` split.** The codebase has `api_routers/{acks,admin,health,ta1_acks}.py`. The specs all reference `cyclone.api:app`. **An engineer building from the docs would add new endpoints to `api.py`; an engineer reading the codebase would add to `api_routers/`.** The split is undocumented in the top-level docs.
**F10 (P1). Live-tail stream filter.** FR-20 says the stream is per-resource. The `live-tail.md` plan Task 11 shows the endpoint signature accepting `status, provider_npi, payer, date_from, date_to, sort, order, limit` — i.e. the stream is a *filterable* snapshot+subscription, not a firehose. **Two engineers reading the docs would build: (a) firehose stream that the frontend filters (matches the FR-20 phrasing); (b) filtered stream matching `listClaims` parameters (matches the plan Task 11 signature).** The actual code matches (b).
**F11 (P2). `processed_inbound_files` row identity.** SP16 spec §2.2 says the unique index is `(sftp_block_name, name)`. The plan test `test_persist_835_creates_one_service_line_payment_per_svc_composite` builds a `SftpBlock` and a `ClaimPayment` with one `name`. **If a single inbound file has two `999` envelopes concatenated (the HCPF pattern is one file per inbound type), the scheduler classifies via `parse_inbound_filename` and stores one `processed_inbound_files` row per inbound type — but the spec does not say whether the same inbound MFT path could have two acks for two different control numbers.** Edge case; probably out of scope; but undocumented.
**F12 (P2). `audit_log` clock source.** SP11 spec §3 says `created_at` is "the wall-clock at the time of `append_event`". The SP16 spec says the scheduler "stagger by 1s on startup so a multi-operator restart doesn't hammer the MFT server". If a 999 arrives at wall-clock `T`, the `claim.rejected` audit event has `created_at = T`. If the operator's wall-clock drifts 2s from the server's, the chain still works (it's hash-chained by SHA-256, not timestamp-ordered). **No doc says what "created_at" means — wall-clock at the operator host, or monotonic at the scheduler.** This matters for HIPAA §164.312(b) audit retention (6 years) where operators may need to prove the audit chain was written *before* the corresponding DB write.
**F13 (P2). `claim.id` source.** SP10 spec §2 says `claim.id` is the X12 CLM01. SP14 spec §2 says the lane filter is on `payer_rejected_at` (not `claim.id`). The uniqueness-constraint spec (SP22) says `claim.id = CLM01` AND that 837P allows many `CLM*` segments per 2000B subscriber loop. **If a 837P file has two CLM01 collisions (e.g. two CLM01="CLM-A" segments in different 2000B loops), the `PK on claims.id` raises IntegrityError on the second insert.** SP22 migration 0013 drops the inline UNIQUE on `(batch_id, patient_control_number)` to allow this, but the PK remains on `claims.id`. **Two CLM01="CLM-A" segments still trip the PK.** The 409 handler returns `existing_batch_id` only if the prior batch holds the colliding CLM01 — but if the second collision is *within the same file*, the second insert raises before any prior batch is consulted. The 409 body in this case is `{error, detail, batch_id}` *without* `existing_batch_id`. SP22 spec does not document this edge case.
**F14 (P2). SFTP host-key policy.** SP13 spec §3.2 uses `AutoAddPolicy()` (trust-on-first-use). The plan does not change this. The spec §7 "Open questions" lists `SftpBlock.strict_host_key_check: bool` as a future hardening. **An engineer hardening security to `RejectPolicy` today would break first-connect for any new operator.** No doc says "do not change this without a migration path".
**F15 (P2). `processed_inbound_files` status `pending`.** SP16 spec §2.3 says `pending` is "reserved for the retry-on-next-tick semantics" but is "currently unused in shipping code". The plan does not add a test for the `pending` status. **A future engineer implementing retry semantics would need to know the schema already supports `pending`**; the spec calls this out but the plan does not.
**F16 (P2). Scheduler first-tick stagger.** SP16 spec §3.1.2 says `_run` staggers the first tick by 1s on startup. The plan test does not assert the stagger (only that the scheduler "starts"). **A future engineer removing the `asyncio.sleep(1)` for "simplicity" would re-introduce the thundering-herd problem without test coverage catching it.**
**F17 (P3). `_handle_277ca` vs `_handle_999` line numbers.** SP16 spec §3.1.1 says both handlers emit `claim.rejected` / `claim.payer_rejected` audit events. The `_handle_277ca` path is also called for filename `277` (not just `277CA`) — same parser, different filename pattern. **A future engineer renaming the handler would have to update both the spec and the plan.**
**F18 (P3). `serialize_837_for_resubmit` parameter shape.** SP8 plan Task 5 says `serialize_837_for_resubmit(claim, interchange_index=42)` assigns `f"{interchange_index:09d}"`. The spec says the same. But the spec §3.1 originally proposed "hybrid" approach; the plan Task 0 amends to "Approach A full rebuild". **An engineer reading only the spec would write a hybrid serializer; one reading the plan would write a full rebuild.**
**F19 (P3). SP22 parse-decide spec vs plan.** The SP22 parse-decide spec §3.2 says the 409 endpoint returns `parse_result` and `collisions` arrays. The SP22 plan does not exist (only the claims-unique-constraint plan exists for SP22). **Engineers building from the spec alone have no test plan.** The spec mentions a "TBD: 409 panel UX" in §6.
**F20 (P3). Inbox lane ordering by `state_changed_at`.** SP6 workflow-automation plan Task 6 `compute_lanes` uses `Claim.state_changed_at >= cutoff` for the `done_today` lane (cutoff = 24h ago). The migration `0004_rejections_and_state_history.sql` adds `state_changed_at` and the index `ix_claims_state_changed_at`. **The migration adds the column WITHOUT a default value** — so existing claims (from migrations 00010003) have `state_changed_at = NULL`. **They never appear in `done_today`.** An operator who upgrades from pre-SP6 to SP6 would see their historical claims never land in `done_today`. SP6 spec does not say "backfill `state_changed_at` on existing claims"; the plan does not test for this.
**F21 (P3). The SP10 277CA path does not extend the state machine.** A claim with a payer rejection stays in its prior state (`paid`, `denied`, `partial`, etc.) and gains the `payer_rejected_at` timestamp. This is consistent with SP10 spec §2.3 ("we explicitly do not clear `payer_rejected_at` on acknowledge") and SP14 spec §2.3, but the architecture doc's casual phrasing ("states: ... payer_rejected") suggests otherwise. **An engineer building the data model from the architecture doc will add a `payer_rejected` ClaimState value that breaks the lane query.**
---
## 9. Untested artifacts
The following are claims in the docs that are not (verifiably) backed by tests in `backend/tests/` or `src/**/*.test.ts*`. I name the test file that *should* cover each.
**U1.** `REQUIREMENTS.md` §4 NFR-2: "every route has a happy-path test and at least one failure-path test". **This NFR is a meta-claim about test discipline.** No meta-test asserts NFR-2 (e.g., a `pytest --collect-only | jq '.[] | select(.failure_path == false)'` would fail). The convention is followed in some places (e.g. `test_api_rotate_key.py` has happy + 409 + 503 paths; `test_payer_rejected_acknowledge.py` has 6 tests covering happy / idempotent / missing / not-rejected / empty / audit) but not enforced.
**U2.** `REQUIREMENTS.md` §4 NFR-10: "backoff ladder 1s → 2s → 4s → 8s → 16s → 30s capped". The `live-tail.md` plan Task 19 enumerates 6 status states (`connecting / live / reconnecting / stalled / error / closed`) but the test plan (`test_useTailStream.test.ts`) covers only 4 (connecting→live, error, abort/closed, reconnecting→connecting→live). **The backoff ladder cap (30s) is not asserted.** A future engineer could ship backoff that climbs past 30s without test failure.
**U3.** `REQUIREMENTS.md` §4 NFR-9: "thread-affinity under FastAPI: every SQLCipher connection opens on the calling thread via `poolclass=NullPool`". `db_crypto.py` is the only module that wires `NullPool`. **No test in `test_db_crypto.py` asserts `poolclass == NullPool` is set on the SQLCipher branch.** An engineer refactoring `_make_engine` to switch to `QueuePool` (SQLAlchemy default) would break thread-affinity without test coverage catching it.
**U4.** SP15 spec §3.3 says the rotation endpoint has status codes `200, 400, 409, 503`. `test_api_rotate_key.py` covers happy + 409 + 503. **The 400 ("encryption not enabled") path is not in the test file.** An engineer removing the `is_encryption_enabled()` check would not break tests.
**U5.** SP14 spec §3.3 says `POST /api/inbox/payer-rejected/acknowledge` returns 400 when `claim_ids` is "missing, empty, or contains non-string elements". `test_payer_rejected_acknowledge.py` (per SP14 spec §8) has 6 tests: happy path; idempotent re-ack; skip non-payer-rejected; missing-id count; **400 on empty list**; audit event written + chain intact. **The 400-on-non-string-elements path is not tested.**
**U6.** SP16 spec §3.5 says `_handle_ta1` "writes no audit event — TA1s are envelope-level interchange acks and are not HIPAA-relevant". **No test asserts that `_handle_ta1` writes zero audit rows.** A future engineer adding a "ta1.received" audit event would not break tests.
**U7.** SP16 spec §7.4 says "list_inbound() runs on a thread via asyncio.to_thread so the event loop stays responsive". **No test asserts that `SftpClient.list_inbound()` does not block the event loop** (e.g. a `test_list_inbound_runs_off_loop` would need to schedule a CPU-bound task on the loop and verify it ran concurrently with `list_inbound`).
**U8.** SP12 spec §7 says "Plain-SQLite fallback remains silent. `is_encryption_enabled()` returns False when `sqlcipher3` isn't installed or the Keychain entry is missing." `test_db_crypto.py` covers the case where encryption IS enabled. **The "sqlcipher3 not installed" branch is not tested** (the test environment always has `sqlcipher3` because the dev deps install it).
**U9.** SP13 spec §3.2 says `_connect` raises `RuntimeError("SftpBlock.auth must contain either 'password_keychain_account' or 'key_file'")` when both keys are absent. **No test in `test_sftp_paramiko.py` covers this exact error message** (the plan Task 19 enumerates 5 tests: connect happy, key-file happy, missing-password RuntimeError, network error, AutoAddPolicy — but the "both auth keys absent" case is not explicit).
**U10.** SP11 spec §3.4 says `append_event` re-raises if the hash computation fails (which is impossible in practice because SHA-256 doesn't fail, but the doc claims the function is "fail-fast"). **No test asserts the fail-fast behavior under any failure mode.**
**U11.** SP14 spec §3.8 says "The row payload already carries `payer_rejected_acknowledged_at` / `_actor` (always null on the current lane)". `test_lane_filter_acknowledged.py` covers "row payload carries the ack fields (forward-compat)". **The test name says "forward-compat" but the test does not assert the fields are null on the lane — only that they exist on the row.**
**U12.** SP18 spec (`structured-logging`) is not yet a backfilled spec; the implementation lives at `backend/src/cyclone/logging_config.py`. `test_logging_formatter.py`, `test_logging_scrubber.py`, `test_logging_setup.py` exist. **No spec describes the `PiiScrubber` regex list** (which PHI patterns it redacts); the spec is a backfill gap.
**U13.** `REQUIREMENTS.md` §6.1 traceability FR-35 says "5-lane Inbox" was satisfied by SP14; the §6.3 acceptance row for SP14 says "All 5 lanes render in `/inbox`; bulk acknowledge action drops payer-rejected claims without erasing the original rejection". **`test_lane_filter_acknowledged.py` covers the lane filter and `test_payer_rejected_acknowledge.py` covers the ack endpoint. There is no integration test that renders all 5 lanes simultaneously** (each lane's UI rendering is in `BulkBar.test.tsx` per the SP14 spec §8 table, but the page-level test for `Inbox.tsx` with 5 populated lanes is not enumerated).
**U14.** SP16 spec §3.5 says `_handle_ta1` calls `cyclone.store.store.add_ta1_ack`. **The `test_api_ta1.py` exists and the `test_scheduler.py` has a TA1 routing test, but no test asserts that `_handle_ta1` correctly persists a TA1 ack row end-to-end through the scheduler (vs through the manual `/api/parse-ta1` endpoint).**
**U15.** `REQUIREMENTS.md` §6.1 FR-15 says "Per-service-line adjustment audit: 837 SV1 ↔ 835 SVC strict match, line reconciliation tab". `test_line_reconciliation.py` covers the pure-function `match_service_lines` (per SP7 plan Task 7). **`test_reconcile_line_level.py` covers the integration with `reconcile.run()`. But there is no frontend test for the "Line Reconciliation tab" UI** (the spec is for backend data only; the tab is described but the SP7 spec is silent on the frontend tab layout; the frontend is presumably covered by `Reconciliation.tsx.test.tsx` but SP7 doesn't enumerate it).
**U16.** `REQUIREMENTS.md` §6.1 FR-33 says "Rich health payload on `GET /api/health` with last-batch-timestamp, parser state, pubsub health, scheduler state". `test_security.py` exists for the `get_health_snapshot()` function. **No test asserts that `last_batch_timestamp` is populated when a batch has been parsed** (the field is added by SP19; the spec expansion is not enumerated in any plan's test plan).
**U17.** `REQUIREMENTS.md` §6.1 FR-26 says "paramiko-backed SFTP submit, credentials via `keyring`". `test_sftp_paramiko.py` covers the connect / write / list / read happy paths. **The test does not assert that an empty password raises `RuntimeError("SFTP: Keychain entry ... missing or stub")`** — it only asserts the runtime error type, not the message. An engineer changing the error message would not break the test.
**U18.** SP11 spec §7 says the audit chain verifier returns `ok: true, checked: N+1` where N is the number of rows. **`test_audit_log.py` exists but the test for `verify_chain` with a tampered row is not enumerated in any plan's test inventory.** A future engineer changing `_hash_row` to use a different canonicalization (e.g. including the row id) would silently break the chain with no test catching it.
---
## 10. Escalations (`ESCALATE:` prefix)
These are non-obvious product decisions in the docs that an engineer would benefit from confirming with the user.
**ESCALATE: SP23 — Ubuntu Docker + RBAC.** `docs/superpowers/specs/2026-06-22-cyclone-ubuntu-docker-deployment-design.md` is marked "Draft / candidate". It introduces (a) a Docker image (`Dockerfile` + `docker-compose.yml`), (b) 3-role RBAC (admin / operator / viewer) backed by `cyclone.auth`, (c) per-role scoping on every endpoint, (d) JWT-based session tokens. **This is a fundamental posture change** — Cyclone today binds `127.0.0.1` with no auth. The spec does not say whether the existing single-operator flow is preserved as a "no-auth" mode under Docker (with RBAC opt-in), or whether RBAC is mandatory. The completeness review (2026-06-20) and the round-3 docs both treat SP23 as optional, but the spec title (`ubuntu-docker-deployment`) suggests it is the canonical deployment posture. **Confirm: is SP23 in scope for the next release, or is it parked? If parked, what is the deployment story?**
**ESCALATE: SFTP `AutoAddPolicy` vs `RejectPolicy`.** SP13 spec §3.2 says `AutoAddPolicy()` is the v1 trade-off; §7 "Open questions" lists `strict_host_key_check: bool` as future hardening. **In a HIPAA-regulated workflow, trust-on-first-use is a known MITM-attack vector.** The spec acknowledges this and proposes a `known_hosts` switch as future work. **Confirm: is `AutoAddPolicy` acceptable for the v1 release, or should SP13 ship with `RejectPolicy` + a bundled `known_hosts` file? The Gainwell MFT host key would need to be obtained and pinned.**
**ESCALATE: `audit_log` retention is "≥ 6 years" (HIPAA §164.316(b)(2)) but the docs do not say how.** SP11 spec §7 says "pinned audit-log retention for rotation events: `db.key_rotated` rows live in the SP11 chain; SP11 already commits to long-term retention per HIPAA §164.316(b)(2). No additional retention config is needed." But the migration `0009_audit_log.sql` does NOT add a retention config (no `created_at + INDEX`, no `prune_event` cron). The 6-year retention is implicitly guaranteed by (a) the operator never pruning the table, and (b) the encrypted backup SP17 covering the `audit_log` rows. **Confirm: is "operator never prunes" the retention policy, or should the spec describe an automated retention policy (e.g. a `prune_audit_log` cron at 6 years + 1 day)?**
**ESCALATE: The 5-lane Inbox vs 4-lane state machine.** The SP10 spec says `payer_rejected_at` is a column on `claims` (not a state). The SP14 spec says the 5th lane is computed by filtering. **The operator's mental model is: "I have a `rejected` claim or a `payer_rejected` claim." But the code says: a claim is in one state (`paid`, `denied`, `partial`, etc.) AND has a `payer_rejected_at` timestamp (or doesn't).** The 5-lane UI surfaces 5 working categories, but the underlying state machine has 8 states + 4 timestamp columns. **Confirm: should the operator see `state` AND `payer_rejected_at` as separate concerns, or should the data model be unified into a 9-state enum where `payer_rejected` is a terminal state (like `reversed`)?**
**ESCALATE: SP21 store split is in-flight on `refactor/store-split`.** The spec is dated 2026-06-21; the current `backend/src/cyclone/store.py` is the monolithic version. The DR plan ("3 reviewers, 5-day merge window") is in the spec §10 but no plan exists for SP21. **Confirm: is the store split a release-blocker, or can it ship after the audit chain + MFT scheduler are stable? An engineer building SP22+ on top of the monolithic store would have to migrate to the split store later.**
**ESCALATE: SP22 parse-decide spec describes a 409 shape that contradicts the unique-constraint spec.** The 409 body in SP22 is `{parse_result, collisions: [{colliding_claim_ids, existing_batch_id}]}`; in the unique-constraint spec it is `{error, detail, batch_id, existing_batch_id}`. **Confirm: which is canonical? If the richer shape is canonical, the claims-unique-constraint spec needs a follow-up to update the 409 body and the frontend `Upload.tsx` error panel.**
**ESCALATE: Reconciliation failure events go to `activity_events` (mutable), not `audit_log` (hash-chained).** The completeness review (2026-06-20 §3.1 item 2) flagged `activity_events` as not tamper-evident. The round-3 docs (SP11) added `audit_log` but did not migrate the reconciliation failure events. **Confirm: should `activity_events` rows for `kind='reconcile_failure'` be migrated to `audit_log`? Or is the operator's "reconciliation is fail-soft" claim enough, and the audit-evidence requirement only applies to HIPAA-relevant events (parse, reject, payer-rejected, key rotation)?**
**ESCALATE: `?ack=true` on parse-837 returns the 999 inline vs in a separate field.** REQUIREMENTS FR-9 says the 999 is auto-generated; the edi-features plan Task 15 says the ack is "attached to the response body"; the live-tail spec does not re-acknowledge. **Confirm: should the 999 be returned inline as `ack.x12_text` (raw X12 string), as `ack.body` (parsed object), or as a `ack_id` requiring a follow-up `GET /api/acks/{id}`? The `serialize_999` module exists in `parsers/`, so inline raw text is straightforward.**
**ESCALATE: 5-lane Inbox claim ownership.** The lane filter for `payer_rejected` is on the `claims` table. The 999-rejected lane (`rejected`) is also on the `claims` table. The `unmatched` lane is on `claims` with no matched remit. **But what about a claim that is both `rejected` (by 999) and `payer_rejected` (by 277CA)?** The SP14 spec §3.2 SQL filter puts it in the `rejected` lane (because `state == REJECTED` takes precedence over the `payer_rejected_at` check). The spec does not say this explicitly. **Confirm: should a 999-rejected + 277CA-payer-rejected claim appear in both lanes (UI splits), or in the `rejected` lane only (operator workflow assumes rejection order)?**
**ESCALATE: SP15 key rotation endpoint has actor="operator" hard-coded default.** The actor is request-body-supplied; the SP15 spec §7 says "for v1 single-operator, `'operator'` is honest". The SP23 candidate introduces RBAC where actor becomes a real identity. **Confirm: should the v1 single-operator posture be honored with `actor="operator"`, or should the request require an actor parameter (rejecting "operator" as ambiguous)?**
**ESCALATE: `processed_inbound_files` is operational metadata, not in the HIPAA audit chain (SP16 spec §2.4).** The scheduler's per-file errors are recorded in `processed_inbound_files.error_message` (mutable, not in `audit_log`). **Confirm: should scheduler errors (e.g. `parse_999` raising `Exception` on a malformed inbound) ALSO be logged in `audit_log` as `scheduler.parse_error`? An auditor investigating a 999 parse failure today would find nothing in the hash-chained log.**
**ESCALATE: Backend test count is variously reported as 574 (completeness review 2026-06-20), 437 (SP5 plan target), and 964 (current — per user).** The codebase has 94 test files in `backend/tests/`; individual test functions are not enumerated in this review (running pytest was not permitted). **The traceability matrix in REQUIREMENTS.md §6.1 cites one test file per FR — but a single FR may have 5+ tests in that file.** Confirm: is the FR-coverage criterion "≥1 test file" or "≥1 test function"?
---
## 11. Confidence
**Overall confidence in the doc set: medium-low.**
The doc set has high production quality: 27 specs + 27 plans + 2 top-level docs, all version-controlled and consistent in style. The TDD discipline in the plans (write failing test, run, implement, run, commit) is exemplary. The layering (requirements → architecture → spec → plan → tests) is the right structure. The completeness review (2026-06-20) and the round-3 doc-prep pass added the missing SP10SP16 specs/plans, which closes a major gap. **But the doc set has accumulated at least 25 specific contradictions, ambiguous forks, and stale numbers** between the two top-level docs and across the spec/plan set. The contradictions are concentrated in the most consequential areas: the live-tail HTTP surface, the claim-state machine, and the LOC/version counters used in the verification matrix. The 7-state claim lifecycle is wrong in 5 places; the codebase has an 8-state enum (verified at `backend/src/cyclone/db.py:180-188`). The tail endpoint URL is `/api/{resource}/stream` per FR-20 + the live-tail spec, but `/api/tail?since=…` per ARCHITECTURE.md §5.4 — two competent engineers reading only the docs could ship two incompatible APIs. The 5 s heartbeat in ARCHITECTURE is contradicted by REQUIREMENTS and the code (which both use 15s via `CYCLONE_TAIL_HEARTBEAT_S`). The 409 collision response shape has two different shapes in two specs (SP22 vs unique-constraint). The `api_routers/` partial split is invisible to the top-level docs. SP21/SP22/SP23 are in-flight or candidate but not marked as such in the top-level docs. The audit_log vs activity_events event-namespace ambiguity is not documented. **The doc set is shippable as a historical record of work done, but is NOT safe as the *only* source of truth for a future engineer building on top of it.** For each of the 21 forks in §8, two competent engineers could ship different systems. For each of the 18 untested artifacts in §9, an engineer refactoring could silently break documented behavior without test coverage catching it. For each of the 12 escalations in §10, a product decision needs user input before the next release.
**Recommendation**: do not ship the doc set as-is. Fix the contradictions in §7 #17 (the LOC counts, the heartbeat interval, the tail endpoint URL, the 7-state lifecycle, the payer_rejected-as-state) before the next reviewer pass. Resolve the 409 shape fork in §8 #F4 (SP22 vs unique-constraint) before any 837P file with internal CLM01 collisions can ship. Document the audit_log vs activity_events split (§8 #F7) before the SP21 store split lands. Add tests for the 18 untested artifacts in §9. Confirm the 12 escalations in §10 with the user before the next release cycle.
---
*End of Reviewer A.*
@@ -0,0 +1,372 @@
# Cyclone doc-prep review — Reviewer B (code-first lens)
## 1. Reviewer identity + lens
I am **Reviewer B**. I used a **code-first lens** for the Cyclone doc-prep pass:
the bulk of my exploration was in the source tree — `backend/src/cyclone/`
(`api.py`, `api_helpers.py`, `api_routers/`, `db.py`, `store.py`, `audit_log.py`,
`security.py`, `db_crypto.py`, `backup_service.py`, `reconcile.py`,
`inbox_lanes.py`, `scoring.py`, `inbox_state.py`, `inbox_state_277ca.py`,
`scheduler.py`, `parsers/`, `migrations/0001-0012`) and
`src/{routes,store,lib,hooks,components}/` (notably the live-tail client
`src/lib/tail-stream.ts` and the React hook `src/hooks/useTailStream.ts`).
I then read the top-of-funnel docs in the intended order:
`docs/README.md``docs/REQUIREMENTS.md``docs/ARCHITECTURE.md`. From
there I cross-referenced the 20 spec files and 27 plan files in
`docs/superpowers/specs/` and `docs/superpowers/plans/`. **I did not read
Reviewer A's `docs/reviews/2026-06-23-cyclone-docset-review-A.md` before
writing this review** so my findings are independent of any
docs-first anchoring. I have flagged every claim with a `file:line`
citation, and where the code disagrees with the doc, the code wins —
the doc needs fixing.
## 2. Executive summary
The Cyclone doc set is in **moderate health with a small number of
high-severity contradictions** that would mislead any engineer reading
docs first. The implementation is unusually self-consistent and matches
the SP-spec lineage, but the two top-level docs (`REQUIREMENTS.md`,
`ARCHITECTURE.md`) and several inline code docstrings have drifted from
the SP-spec + code truth. The top three issues are:
1. **The audit-chain hash recipe is wrong in three places** (the
`AuditLog` docstring in `db.py:649-650`, the `audit_log.py:6-7`
module docstring, and `ARCHITECTURE.md` §4.6) and only the SP11 spec
(`docs/superpowers/specs/2026-06-23-cyclone-sp11-hash-chained-audit-design.md:104-114`)
plus the actual `_hash_row` function at
`backend/src/cyclone/audit_log.py:80-89` agree. This is a C-1
severity finding because the verifier and any future auditor will
compute different hashes depending on which doc they read first.
2. **`ARCHITECTURE.md` §6.3 lists the wrong claim state set** (eight
values, but the wrong eight — it has `accepted`, `appealed`, and
`payer_rejected`, none of which exist in code). The actual `ClaimState`
enum (`db.py:180-188`) is `submitted, received, rejected, paid, partial,
denied, reconciled, reversed`. The `RECONCILED` state is defined and
is treated as terminal by `apply_payment` (`reconcile.py:163-178`) but
is never actually set by any code path, which is a separate
fork-shaped finding (F-1).
3. **The API surface in `ARCHITECTURE.md` §8.1 is materially wrong** for
live tail, the Inbox 5-lane, and the backup restore flow. Live tail
is documented as `GET /api/tail?since=…` (ARCH §5.4 / §8.2) and as
`GET /api/{claims,remittances,activity}/stream` in REQUIREMENTS FR-20
— the code is the latter (`api.py` 3,548 LOC; verified at multiple
routes). Inbox is listed as `/api/inbox` in ARCH §8.1 but the real
surface is `/api/inbox/lanes`, `/api/inbox/payer-rejected/acknowledge`,
etc. Backup restore is a one-step URL in ARCH §8.1 but the
`backup_service.py` is a two-step `restore_initiate` / `restore_confirm`
(matches FR-30). The two-step shape is what the code ships.
Below the top three, the doc set has many smaller drifts — the live-tail
heartbeat cadence is documented as 5s in ARCH §5.4 (code is 15s default;
NFR-10 is silent on default but the SP5 spec is 15s), the `clearhouse`
ORM is a singleton (singular table) but ARCH §6.2 draws the ERD as
`clearhouses` (plural), the migration 0004 is misdescribed in ARCH §6.1
as adding a new table when it actually adds four columns to `claims`,
and the spec-vs-code disagreement over the `Match.claim_id` UNIQUE
constraint (SP2 §6.5 says UNIQUE; code explicitly doesn't enforce it so
reversals can add a second row).
There are also **two product forks that are blocking-or-near-blocking**
that the docs do not decide: the SP23 Ubuntu/Docker/auth/RBAC/LAN-bind
direction (spec at `2026-06-22-cyclone-ubuntu-docker-deployment-design.md`
exists, no plan exists; REQUIREMENTS R-1, R-3, R-24 raise but do not
close this), and the `RECONCILED` state being declared terminal but
never assigned. Neither has a test, plan, or design decision recorded.
## 3. Reviewer questions
### Q1: Are the components described consistently across REQUIREMENTS, ARCHITECTURE, specs, and plans?
**Verdict: NO — multiple component-name and component-shape mismatches.**
Reasoning:
- The **`Live tail` component** is described three different ways:
REQUIREMENTS FR-20 says `/api/{claims,remittances,activity}/stream`
(NDJSON); ARCH §5.4 and §8.2 say `GET /api/tail?since=<last_event_id>`;
SP5 spec says per-resource `…/stream` and the NDJSON line shape is
`{"kind": "item"|"snapshot_end"|"heartbeat"|"item_dropped"|"error", …}`
(matches the React client's `src/lib/tail-stream.ts` `TailEvent`
type). The code is the SP5 spec; REQUIREMENTS matches the code; ARCH
does not.
- The **`Inbox` component** is described as `/api/inbox` in ARCH §8.1
but as a 5-lane surface in REQUIREMENTS FR-12 / FR-13 / FR-14 and in
the SP14 spec, and the code (`api.py`; `inbox_lanes.py` at lines
1-280) implements `/api/inbox/lanes` plus
`/api/inbox/payer-rejected/acknowledge`, plus `GET /api/inbox/999` and
`GET /api/inbox/277ca` style endpoints. ARCH §8.1 is missing the 5-lane
detail.
- The **`Backup restore` component** is described as a single URL in
ARCH §8.1 (`/api/admin/backup/{id}/restore?confirm=true`) but as a
two-step `restore_initiate` / `restore_confirm` in REQUIREMENTS FR-30
and in the `backup_service.py:851` LOC file. The code is the
two-step shape.
- The **`Database key rotation` component** is described in ARCH §8.1
only by the endpoint `/api/admin/db/rotate-key`, but the SP15 spec
defines a four-step ordering (DB-first → Keychain-second →
engine-rebuild → audit-last) and a specific `db.key_rotated` audit
event payload `{old_fingerprint, new_fingerprint, table_count, reason}`.
Neither the ordering nor the payload shape is in ARCH.
### Q2: Is the data model consistent (schema, enums, lifecycle, audit chain)?
**Verdict: NO — five material data-model disagreements.**
Reasoning:
- **Claim state enum is wrong in ARCH §6.3 and partially wrong in
REQUIREMENTS FR-6.** REQUIREMENTS FR-6 says "7-state" but lists 8
(in different versions of the doc over time). ARCH §6.3 lists
`submitted, accepted, paid, reversed, denied, appealed, rejected,
payer_rejected`. The code (`db.py:180-188`) is `submitted, received,
rejected, paid, partial, denied, reconciled, reversed`. Only five
values match across all four (`submitted, paid, partial, denied,
reversed`; note: ARCH does not have `partial` either, which is the
most common auto-reconcile outcome). SP2 spec lists 7
(`submitted, received, paid, partial, denied, reconciled, reversed`).
The `rejected` state is set by 999 AK9 set-level R/E (per
`inbox_state.py` lines 1-76 and migration 0004), not by any spec
other than SP6. The `reconciled` state is dead code — see F-1.
- **Audit chain hash recipe disagrees in 3 places** (see C-1 below).
- **The `clearhouse` table is a singleton** in code (`db.py:824-838`
`__tablename__ = "clearhouse"`, single row, with a `SingletonError`
exception for inserts past row 1) but the ERD in ARCH §6.2 shows
`clearhouses` plural. Migration 0011 (`0001-0012` index) also writes
to `clearhouse` (singular).
- **The `Claim(batch_id, patient_control_number)` UNIQUE constraint
is missing in code** but is asserted in SP2 spec §6.2 line 166 and
was the subject of migrations 0003 and 0013+0014 (the in-flight
`claims-unique-fix` worktree). The `claims` table in migration 0001
has no such UNIQUE; the `Claim` ORM (`db.py:310-319`) explicitly
notes the absence. The SP2 spec is out of sync with the SP-13/14
reality.
- **The `Match.claim_id` UNIQUE constraint is missing in code** but is
asserted in SP2 spec §6.5 line 207. Migration 0001 line 65-66
(comment) and `db.py:505` (ORM comment) say reversals add a 2nd row
to `matches`, so UNIQUE on `claim_id` would be wrong. The spec is
wrong; the code is correct.
### Q3: Are the dependencies and external integrations (SQLCipher, SFTP, MFT, key rotation, audit) consistent and traceable?
**Verdict: MOSTLY YES — SQLCipher + key rotation are well-traced, MFT file routing has one ambiguity.**
Reasoning:
- **SQLCipher + key rotation** is end-to-end traceable:
`db_crypto.py:389` LOC defines `KEYCHAIN_ACCOUNT = "cyclone.db.key"`
and `KEYCHAIN_ACCOUNT_PREVIOUS = "cyclone.db.key.previous"`, uses
`NullPool` for thread affinity, exposes `RotateKeyResult` with
`old_fingerprint` and `new_fingerprint` (matches SP15 spec),
and `api.py:2797` exposes `POST /api/admin/db/rotate-key` (matches
REQUIREMENTS FR-32 and the SP15 spec endpoint name). Migration 0012
is the SQLCipher-key-on-disk path. The audit event `db.key_rotated`
has the spec-mandated payload shape `{old_fingerprint, new_fingerprint,
table_count, reason}` in `db_crypto.py`. **Consistent.**
- **MFT file routing** has a small ambiguity: `scheduler.py:316-321`
routes `ROUTED_FILE_TYPES = {"999", "835", "277", "277CA", "TA1"}` to
the corresponding parsers. SP10 spec says HCPF sends a bare `277` (not
`277CA`) but the scheduler accepts both. This is intentional (defense
in depth) but the doc should say so.
- **Audit chain** has a write/read asymmetry: the chain is computed on
append by `append_event()` and verified by `verify_chain()`, but the
*docstring recipe* is wrong (see C-1). Code wins.
- **SFTP and MFT** are documented only by reference to `paramiko` (SFTP
transport) in `pyproject.toml` and by the `MFT_SCHEDULE` config in
`config/payers.yaml`. There's no spec or plan I could find that says
what the MFT pickup cadence should be, what the retry policy is, or
what the failure alert looks like. This is a coverage gap, not a
contradiction.
- **SSE / live tail transport** is described as "NDJSON pubsub" in
REQUIREMENTS NFR-10 and "NDJSON via `EventBus`" in ARCH §5.4. The code
is NDJSON via `tail_events()` in `api_helpers.py:225` reading from
`EventBus`. Consistent.
### Q4: Is "definition of done" testable for every artifact?
**Verdict: NO — at least 6 artifacts are undertested, and the test surface is uneven.**
Reasoning:
- **Audit chain verifier** has tests in `test_audit_log.py` (per
the `verify_chain()` reference in REQUIREMENTS NFR-4) but the
*docstring recipe* in `audit_log.py:6-7` and `db.py:649-650` does
not match the implementation. The tests verify the implementation
but the docstring is the wrong contract.
- **Score breakdown** (40/25/20/15) has tests and is documented in
REQUIREMENTS FR-15, `scoring.py:42-46`, and the SP13 spec.
Testable.
- **Backup passphrase-missing degraded mode** (backup service falls
back to deriving from SQLCipher key with a WARNING when no
Keychain passphrase is set) is implemented in `backup_service.py`
but has no test asserting the WARNING is emitted; REQUIREMENTS
NFR-6 only asserts that the passphrase is in Keychain. The
degraded-mode code path is untested.
- **5-lane Inbox** has tests but the lane-tally API contract is not
documented anywhere; the code returns a JSON with `lane_counts`
but no spec defines the exact shape.
- **Live tail stall detection** (30s stall timeout in
`src/lib/tail-stream.ts` and `src/hooks/useTailStream.ts`) is
not asserted in any backend test — only the client side knows
about the stall; the server keeps streaming. Not testable from
the spec alone.
- **277CA monotonic stamping** (`inbox_state_277ca.py:1-108`) is
documented in SP10 spec §"Monotonic rule" but has no test asserting
the monotonic invariant is preserved across replays.
- **Migration 0013/0014 in-flight on `claims-unique-fix`** worktree are
not described in REQUIREMENTS NFR-15 (which says "12 migrations
shipped") and not in ARCH §6.1 (which lists 0001-0012). The
"definition of done" for the in-flight fix is "merged into main" —
there is no acceptance criterion.
## 4. Contradictions
Each row is `C-N | code says X | doc says Y | code wins because …`.
| ID | Code (file:line) | Doc (file:line) | Resolution |
|----|------------------|-----------------|------------|
| C-1 | `_hash_row` at `backend/src/cyclone/audit_log.py:80-89` joins fields in this order: `row_id`, `event_type`, `entity_type`, `entity_id`, `actor`, `created_at_iso`, `payload`, `prev_hash`. | (a) `backend/src/cyclone/audit_log.py:6-7` module docstring says `(id, event_type, entity_type, entity_id, actor, payload_json, created_at, prev_hash)` — payload BEFORE created_at. (b) `backend/src/cyclone/db.py:649-650` AuditLog class docstring says the same wrong order. (c) `docs/ARCHITECTURE.md` §4.6 says `SHA-256(prev_hash || kind || actor || payload_json || ts)` — a third, completely different 5-field recipe. (d) `docs/superpowers/specs/2026-06-23-cyclone-sp11-hash-chained-audit-design.md:104-114` matches the code (8 fields, payload AFTER created_at). | **Code wins.** The implementation + SP11 spec agree. The module docstring + `AuditLog` class docstring + ARCH §4.6 are all wrong. The two inline docstrings need to be rewritten to match `_hash_row`; ARCH §4.6 needs the recipe and field list corrected. This is the highest-severity finding because an external auditor reading `audit_log.py` first will compute a different hash than `verify_chain()`. |
| C-2 | `ClaimState` enum at `backend/src/cyclone/db.py:180-188` has 8 values: `SUBMITTED, RECEIVED, REJECTED, PAID, PARTIAL, DENIED, RECONCILED, REVERSED`. | (a) `docs/REQUIREMENTS.md` FR-6 says "7-state" (off-by-one). (b) `docs/ARCHITECTURE.md` §6.3 lists 8 values: `submitted, accepted, paid, reversed, denied, appealed, rejected, payer_rejected` — three of these (`accepted`, `appealed`, `payer_rejected`) do not exist in code. (c) `docs/superpowers/specs/2026-06-19-cyclone-db-reconciliation-design.md` §6 lists 7: `submitted, received, paid, partial, denied, reconciled, reversed` — missing `rejected`. (d) `docs/superpowers/specs/2026-06-23-cyclone-sp10-277ca-payer-rejected-design.md` treats `payer_rejected` as a *column* (`payer_rejected_at`), not a state. | **Code wins.** Drop `accepted`, `appealed`, `payer_rejected` from ARCH §6.3; add `received`, `rejected`, `reconciled` everywhere. FR-6 "7-state" is wrong (the actual count is 8). SP2 spec is missing the `rejected` state (set by 999 AK9 R/E per `inbox_state.py:1-76` and migration 0004). |
| C-3 | Live tail endpoints are `/api/claims/stream`, `/api/remittances/stream`, `/api/activity/stream` (NDJSON). | (a) `docs/REQUIREMENTS.md` FR-20 says `GET /api/{claims,remittances,activity}/stream` (matches code). (b) `docs/ARCHITECTURE.md` §5.4 and §8.2 say `GET /api/tail?since=<last_event_id>` (does not exist in code). | **Code wins.** ARCH §5.4 and §8.2 need to be rewritten to match the per-resource `/api/{...}/stream` shape. |
| C-4 | Heartbeat cadence is 15s default, configurable via `CYCLONE_TAIL_HEARTBEAT_S`, code at `backend/src/cyclone/api_helpers.py:209-222`. | (a) `docs/ARCHITECTURE.md` §5.4 says "every 5s when no events". (b) `docs/REQUIREMENTS.md` NFR-10 says "≤15s" (so 15s is within budget). (c) `docs/superpowers/specs/2026-06-20-cyclone-live-tail-design.md` says 15s (matches code). | **Code wins.** ARCH §5.4 is wrong; the 15s default is also the SP5 spec default. NFR-10's "≤15s" is loose enough that 15s is compliant. |
| C-5 | Migration `0004_rejections_and_state_history.sql` adds 4 columns to `claims` (`rejection_reason`, `rejected_at`, `resubmit_count`, `state_changed_at`) and one index (`ix_claims_state_changed_at`). | `docs/ARCHITECTURE.md` §6.1 says migration 0004 is "rejections table + claim_state_history" — implying a *new table*. | **Code wins.** ARCH §6.1 is wrong; migration 0004 alters only the `claims` table. No new table is created. The reviewer suspects the author confused this with migration 0008 (`0008_*.sql`, the `claim_state_history` table) or migration 0007 (the `rejections` audit-trail table; verify by listing). |
| C-6 | Backup restore is a two-step flow: `POST /api/admin/backup/{backup_id}/restore/initiate` returns a 64-char token with 300s TTL; `POST /api/admin/backup/{backup_id}/restore/confirm` consumes the token. Code at `backend/src/cyclone/backup_service.py:851` LOC, plus endpoints wired in `backend/src/cyclone/api.py`. | (a) `docs/ARCHITECTURE.md` §8.1 lists `/api/admin/backup/{id}/restore?confirm=true` as a single URL. (b) `docs/REQUIREMENTS.md` FR-30 documents the two-step shape. | **Code + REQUIREMENTS win.** ARCH §8.1 should be corrected to two URLs. |
| C-7 | Inbox 5-lane surface is `GET /api/inbox/lanes` plus `POST /api/inbox/payer-rejected/acknowledge`, `GET /api/inbox/999`, `GET /api/inbox/277ca`, plus per-lane claim listing endpoints. Code in `backend/src/cyclone/inbox_lanes.py:1-280` + `backend/src/cyclone/api.py`. | `docs/ARCHITECTURE.md` §8.1 lists the inbox as a single `/api/inbox` endpoint. | **Code wins.** ARCH §8.1 is missing the 5-lane detail. |
| C-8 | `ClearhouseORM` is a **singleton** at `backend/src/cyclone/db.py:824-838` with `__tablename__ = "clearhouse"` (singular), with a guard that raises on insert past row 1. | `docs/ARCHITECTURE.md` §6.2 ERD shows the table as `clearhouses` (plural) and the SP9 spec describes the seed as "the single clearhouse config row". | **Code wins.** ARCH §6.2 table name is wrong; the table is `clearhouse` (singular). |
| C-9 | `Claim` table has no UNIQUE constraint on `(batch_id, patient_control_number)`. Migration 0001 (initial) has no such UNIQUE; migration 0003 explicitly drops UNIQUE constraints; the `Claim` ORM at `backend/src/cyclone/db.py:310-319` notes the absence. Migrations 0013/0014 (in-flight on `claims-unique-fix` worktree) re-add it. | `docs/superpowers/specs/2026-06-19-cyclone-db-reconciliation-design.md` §6.2 line 166 asserts the UNIQUE is present. | **Code wins (today).** The in-flight 0013+0014 will re-add the UNIQUE; SP2 spec should be updated to reflect "as of migration 0013/0014". |
| C-10 | `matches` table has no UNIQUE on `claim_id` — reversals intentionally add a 2nd row. Migration 0001 lines 65-66 (comment) and the `Match` ORM at `backend/src/cyclone/db.py:505` (comment) both note this is "non-unique: reversals add a 2nd row". | `docs/superpowers/specs/2026-06-19-cyclone-db-reconciliation-design.md` §6.5 line 207 says `claim_id` is UNIQUE — "one current match per Claim". | **Code wins.** SP2 spec §6.5 is wrong; the SP2 spec author was thinking of a 1:1 "current match" view but the schema models the full history. |
| C-11 | `apply_payment` at `backend/src/cyclone/reconcile.py:163-178` returns `DENIED`, `RECEIVED`, `PAID`, or `PARTIAL`. The function never returns `RECONCILED`. | SP2 spec transition table (line 250-253) shows `apply_payment` paths all ending in `→ reconciled` (terminal). | **Code wins** — but the spec was likely trying to describe a *separate* finalize step. The current code declares `RECONCILED` as a terminal state (per `reconcile.py:163-164` "already in terminal state" check at line 156-157) but never assigns it. See F-1. |
| C-12 | API ingestion routes are `/api/parse-837`, `/api/parse-835`, `/api/parse-999`, `/api/parse-ta1`, `/api/parse-277ca`, plus `/api/batches/{batch_id}/export-837`. | `docs/ARCHITECTURE.md` §8.1 lists `/api/upload` as a single ingestion endpoint. | **Code wins.** There is no `/api/upload` route. ARCH §8.1 is wrong. |
| C-13 | `Claim` has a `payer_rejected_at` column (`db.py:270-289`) but no state transition to `payer_rejected`. The claim's state remains `SUBMITTED` even after a 277CA STC A4/A6/A7 rejection (per `inbox_state_277ca.py:1-108` and SP10 spec). | `docs/ARCHITECTURE.md` §6.3 transition diagram shows `rejected → payer_rejected`. | **Code wins.** ARCH §6.3 is wrong. The 277CA payer_rejected state is captured as a *column* on the claim, not a `ClaimState` value. |
| C-14 | `Match.is_reversal` exists (`db.py:480-510`); `apply_reversal` at `backend/src/cyclone/reconcile.py:181-189` flips paid/partial → REVERSED and inserts a 2nd row with `is_reversal=True`. | `docs/superpowers/specs/2026-06-19-cyclone-db-reconciliation-design.md` §6.5 says "Match is unique per Claim" — same as C-10. | **Code wins.** See C-10. The reversal second-row is the design; the spec is wrong. |
| C-15 | `manual_unmatch` at `backend/src/cyclone/store.py:2122` resets state to `ClaimState.SUBMITTED` (per REQUIREMENTS FR-6). | `docs/ARCHITECTURE.md` §6.3 doesn't show a `submitted ← <anything>` transition. | **Code wins.** ARCH §6.3 is missing the manual-unmatch reset edge. |
| C-16 | `frontend/src/lib/tail-stream.ts` `TailEvent` union has 5 kinds: `item`, `snapshot_end`, `heartbeat`, `item_dropped`, `error`. | `docs/ARCHITECTURE.md` §5.4 lists 3 kinds: `item`, `heartbeat`, `error`. | **Code wins.** ARCH §5.4 is missing `snapshot_end` (sent at start of subscription to send the current tail buffer) and `item_dropped` (sent when the server-side buffer overflows and starts dropping events). The client-side hook `src/hooks/useTailStream.ts` handles both. |
| C-17 | `frontend/src/hooks/useTailStream.ts` `TailStatus` union has 6 states: `connecting`, `live`, `reconnecting`, `closed`, `stalled`, `error`. | `docs/ARCHITECTURE.md` §5.4 doesn't document the client-side status states at all. | **Code wins.** ARCH §5.4 should list the client status states; the `stalled` state (30s no events, no heartbeat) is a real product decision that ARCH currently hides. |
| C-18 | Backoff schedule in `frontend/src/lib/tail-stream.ts` and `src/hooks/useTailStream.ts` is 1s, 2s, 4s, 8s, 16s, capped at 30s. | `docs/ARCHITECTURE.md` §5.4 doesn't specify the reconnect backoff. | **Code wins.** ARCH §5.4 is silent. The schedule is not in any spec either. |
| C-19 | `EventBus` is the in-process pubsub that `tail_events()` subscribes to (`backend/src/cyclone/api_helpers.py:225`). | `docs/ARCHITECTURE.md` §5.4 calls it "NDJSON pubsub" and lists 3 event types (`item`, `heartbeat`, `error`). | **Code wins** on the protocol (NDJSON via per-resource `/api/.../stream`); ARCH §5.4 is wrong on the kinds per C-16. |
| C-20 | SPEC traceability in `docs/REQUIREMENTS.md` lists 22 SPs (SP1SP22) and a future SP23 (Ubuntu/Docker). | `docs/superpowers/specs/` directory contains specs for SP1SP22 only (22 files, plus 1 older `2026-06-19-cyclone-db-reconciliation-design.md` and 1 older `2026-06-20-cyclone-live-tail-design.md`, plus 1 in-flight `2026-06-22-cyclone-ubuntu-docker-deployment-design.md` which is the SP23 spec). | **Code/specs win.** REQUIREMENTS R-1 should explicitly call out that SP23 has a spec but no plan. |
## 5. Forks (priority order)
| ID | Priority | What is ambiguous | What decision is needed |
|----|----------|-------------------|--------------------------|
| F-1 | **P0** | The `RECONCILED` state in `ClaimState` (`db.py:187`) is declared terminal in `apply_payment` (`reconcile.py:163-164`) but is never actually set by any code path. The SP2 spec transition table shows it as the terminal step of every `apply_payment` path. | Decide one of: (a) keep `RECONCILED`, add a `set_reconciled()` step after `apply_payment` succeeds, write a test for it; (b) remove `RECONCILED` from the enum and from the terminal check, update SP2 spec; (c) keep `RECONCILED` as a "synthetic" terminal that some future finalize flow will set, and explicitly defer the implementation. |
| F-2 | **P0** | The audit-chain hash recipe is wrong in `audit_log.py:6-7`, `db.py:649-650`, and `ARCHITECTURE.md` §4.6. Three of these must be corrected to match the code at `audit_log.py:80-89`. The order of fields in the canonical string is `row_id, event_type, entity_type, entity_id, actor, created_at_iso, payload, prev_hash`. | Pick the source of truth (the code + SP11 spec already agree) and rewrite the two docstrings + ARCH §4.6 to match. Add a `test_audit_log.py` test that asserts the recipe against a hand-computed expected hash for a single-row chain, so the next refactor cannot silently change the recipe. |
| F-3 | **P0** | The SP23 product fork (Ubuntu/Docker deployment, multi-user auth, RBAC, LAN-bind) is documented as a spec at `docs/superpowers/specs/2026-06-22-cyclone-ubuntu-docker-deployment-design.md` but has **no plan**. REQUIREMENTS R-1, R-3, R-24 raise the question but do not close it. The product is currently local-only, no-auth, single-user. | The user must decide: is SP23 in-scope for the next release, or deferred? If in-scope, write a plan file under `docs/superpowers/plans/2026-06-23-cyclone-sp23-*.md`. If deferred, move the spec to `docs/superpowers/deferred/` and remove R-1/R-3/R-24 from REQUIREMENTS. |
| F-4 | **P1** | The backup service (`backup_service.py:851` LOC) has a degraded mode when the encryption passphrase is missing: it derives a key from the SQLCipher DB key with a WARNING logged. REQUIREMENTS NFR-6 promises the passphrase is in Keychain. | Decide: is the degraded mode acceptable, or must the backup service fail-hard when no passphrase is set? The current behavior is a foot-gun (the warning can be missed in logs). If degraded mode stays, add a test asserting the WARNING is emitted. |
| F-5 | **P1** | `vitest@^4.1.9` is pinned in `package.json` per REQUIREMENTS R-25, which flags it as "unusually new" (current stable is 1.x/2.x). The frontend test framework choice affects every PR. | The user must confirm: (a) the `^4.1.9` pin is intentional and there is a known-working toolchain, or (b) revert to `^2.x` (or whatever the latest stable is at the time). If (a), add a CI job to verify the install. If (b), update REQUIREMENTS R-25 to read "reverted to `^2.x`". |
| F-6 | **P1** | The Inbox 5-lane `lane_counts` JSON contract is implemented in `inbox_lanes.py:1-280` but the shape is not specified in any spec. The frontend (`src/components/...`) presumably renders lane badges from this count. | Decide: write a SP14-addendum spec for the lane-counts JSON contract, OR reference the Pydantic model from `api.py` as the contract and inline-link it from the spec. Either way, the contract should be testable from the spec. |
| F-7 | **P2** | Score weights are hardcoded at `backend/src/cyclone/scoring.py:42-46` as `40/25/20/15` (patient/date/amount/provider). REQUIREMENTS R-10 says these are configurable via `config/payers.yaml`. The `config/payers.yaml` file does not currently expose them. | Decide: (a) move the weights into `config/payers.yaml` with the existing score-weight keys, write a test that reads them from config; (b) keep the weights hardcoded and update R-10 to say "constants". |
| F-8 | **P2** | MFT file routing accepts `277` and `277CA` interchangeably (`scheduler.py:316-321`). SP10 spec says HCPF sends bare `277`. The scheduler's acceptance of both is defense-in-depth. | Decide: (a) keep both, document the defense-in-depth in the spec; (b) restrict to `277CA` only and require HCPF to send `277CA`. (a) is the path of least disruption. |
| F-9 | **P2** | The `WORKTREE` stale-artifact at `backend/src/cyclone/workflow/__pycache__/` is flagged in REQUIREMENTS R-27 as needing deletion, but still exists. | Decide: just delete it. This is mechanical. Add a `.gitignore` rule to prevent recurrence. |
| F-10 | **P2** | PHI fixtures in `docs/prodfiles/` are not flagged as PHI (REQUIREMENTS R-16). The fixtures are local-only but a future contributor who adds them to a public repo would be in trouble. | Decide: (a) add a `README.md` in `docs/prodfiles/` warning the files are synthetic but look like PHI, and add a `.gitattributes` rule; (b) replace the fixtures with obviously-fake data. |
| F-11 | **P2** | The `co_medicaid()` factory in `backend/src/cyclone/parsers/payer.py:57-58` exists as a fallback (REQUIREMENTS R-4, NFR-11). It is unclear whether it is part of the test fixture taxonomy or technical debt. | Decide: (a) keep as a test fixture only and move to a `tests/fixtures/` location; (b) remove it and rely on the seed data; (c) document it as a fallback for unconfigured payers in the SP9 spec. |
| F-12 | **P2** | Migration manifest / checksum file (REQUIREMENTS R-13) is listed as needed but never built. There is no `manifest.json` or `manifest.yaml` next to the migrations directory. | Decide: (a) build the manifest, add a CI check that the manifest is in sync with the migrations; (b) drop R-13 and rely on the in-tree `git log` for migration history. |
| F-13 | **P3** | 277CA monotonic stamping (`inbox_state_277ca.py:1-108`) has the rule "do not regress a claim from rejected → not-rejected" but the rule is documented in prose only. | Decide: write a test that replays a 277CA batch twice and asserts the second pass is a noop for the rejection columns. |
| F-14 | **P3** | The live-tail `item_dropped` kind (sent when the server-side buffer overflows) is implemented in `api_helpers.py:225` and handled by the client, but no spec defines the buffer size threshold or the alert policy when `item_dropped` is received. | Decide: (a) spec the buffer size and the alert policy; (b) decide that `item_dropped` is fire-and-forget for now and the alert comes from the next full reconciliation. |
| F-15 | **P3** | `docs/README.md` lists the read-order as `REQUIREMENTS → ARCHITECTURE → spec → plan` but does not say what to do when ARCH disagrees with the spec. The convention is "spec wins for design decisions, ARCH wins for cross-component structure" but this is not written. | Decide: write a one-paragraph convention note in `docs/README.md` covering precedence when docs disagree. |
| F-16 | **P3** | The audit-log API surface (`GET /api/admin/audit-log/verify` at `api.py:2757`) is in code but the response shape (a list of broken-chain indices) is not in any spec. | Decide: write a SP11-addendum or inline-link the Pydantic model from the spec. |
## 6. Untested artifacts
| ID | Artifact | Where it is documented | Where the test should be | Why it is untested |
|----|----------|------------------------|-------------------------|--------------------|
| U-1 | Audit-chain hash recipe (the canonical string format at `audit_log.py:80-89`) is documented in the SP11 spec and in two wrong docstrings, but the spec's recipe is only verified by tests of `verify_chain()` against rows the test itself wrote. There is no test that pins a hand-computed SHA-256 hex for a single known row. | `docs/superpowers/specs/2026-06-23-cyclone-sp11-hash-chained-audit-design.md:104-114`. | `backend/tests/test_audit_log.py` — add a test `test_hash_recipe_is_stable_against_hand_computed_value`. | Without this test, a future refactor of `_hash_row` could silently change the recipe and `verify_chain()` would still pass (because it recomputes). |
| U-2 | The `vitest@^4.1.9` pin per REQUIREMENTS R-25 is flagged as "unusually new" but no test asserts that `npm install` produces a working test runner. | `docs/REQUIREMENTS.md` R-25. | A CI workflow or a `package.json` `engines` field; there is no CI workflow file. | The pin could break on a future `npm install` if vitest 4.x is unpublished. No fallback plan. |
| U-3 | The "964 tests collected" claim in REQUIREMENTS NFR-15 is not verified by any artifact. The reviewer did not count `backend/tests/test_*.py` files (this is a research gap, not a contradiction). | `docs/REQUIREMENTS.md` NFR-15. | A test-counting step in CI. | The number may be out of date by the time you read this. |
| U-4 | The `Matches.is_reversal` second-row insertion is described in migration 0001 comment lines 65-66 and the SP2 spec but no explicit test asserts the second row is inserted with `is_reversal=True` and the same `claim_id` after `apply_reversal` is called on a paid claim. | Migration 0001, SP2 spec. | `backend/tests/test_reconcile.py` (assumed). | The reviewer did not verify the test exists. Add a test that calls `apply_reversal` on a paid claim and asserts `len(matches_for(claim_id)) == 2` and the new row has `is_reversal=True`. |
| U-5 | The "operator UI for the audit log" is listed as out-of-scope in SP11 spec §"Future work" but REQUIREMENTS NFR-4 says `verify_chain()` detects breaks. There is no test that asserts a manual `verify_chain()` call (e.g., from a CLI command) reports a break when one row is tampered. | `docs/REQUIREMENTS.md` NFR-4, `docs/superpowers/specs/2026-06-23-cyclone-sp11-hash-chained-audit-design.md`. | `backend/tests/test_audit_log.py` — add a test that tampers with a row in a fresh chain and asserts `verify_chain()` returns the tampered index. | The reviewer assumes such a test exists in `test_audit_log.py` but did not verify. |
| U-6 | The backup-passphrase-missing degraded mode in `backup_service.py` falls back to deriving from SQLCipher key with a WARNING. REQUIREMENTS NFR-6 only asserts the Keychain-with-passphrase path. | `docs/REQUIREMENTS.md` NFR-6, `backend/src/cyclone/backup_service.py`. | `backend/tests/test_backup_service.py` — assert the WARNING is logged and the backup is still produced. | The degraded mode is a code path that runs in production but has no test. |
| U-7 | The 5-lane Inbox `lane_counts` JSON shape is not specified in any spec. The frontend presumably depends on it. | `docs/superpowers/specs/2026-06-23-cyclone-sp14-inbox-5lane-design.md`. | A contract test (e.g., `tests/test_inbox_lanes.py`) that asserts the response shape. | The shape is a contract between backend and frontend; no test pins it. |
| U-8 | The live-tail `stalled` state (30s no events) is a real client-side detection in `src/hooks/useTailStream.ts`. There is no backend test that asserts the server keeps streaming heartbeats correctly under stall conditions. | `docs/superpowers/specs/2026-06-20-cyclone-live-tail-design.md`. | `backend/tests/test_api_helpers.py` — assert heartbeats continue at the configured cadence under no-event load. | The stall detection is on the client; the server-side heartbeat is implicit. |
| U-9 | The 277CA monotonic stamping (`inbox_state_277ca.py`) is documented in SP10 spec but has no test asserting the monotonic invariant is preserved across replays. | `docs/superpowers/specs/2026-06-23-cyclone-sp10-277ca-payer-rejected-design.md`. | `backend/tests/test_inbox_state_277ca.py` — replay a 277CA batch twice and assert the rejection columns are not regressed. | The invariant is in prose only. |
| U-10 | The `rejected` claim state (set by 999 AK9 R/E at `inbox_state.py:1-76`) is in code and in migration 0004 but is not in SP2 spec or REQUIREMENTS FR-6's list. There is no test that asserts a 999 envelope with `AK9*R*` moves the claim from `SUBMITTED` to `REJECTED`. | Migration 0004, `backend/src/cyclone/inbox_state.py`. | `backend/tests/test_inbox_state.py` — assert 999 R/E transitions `SUBMITTED``REJECTED`. | The transition is in code but not in the spec, and may not be in the tests. |
| U-11 | The migration 0013/0014 `claims-unique-fix` worktree is in flight but has no acceptance criterion in REQUIREMENTS, ARCH, or any plan. The "definition of done" is "merged into main" — not testable. | None. | The `claims-unique-fix` branch's PR description (not visible from this review). | The fork is being made without a published acceptance criterion. |
| U-12 | The `co_medicaid()` factory in `backend/src/cyclone/parsers/payer.py:57-58` is not exercised by any test (assumed; not verified). | `docs/REQUIREMENTS.md` R-4, NFR-11. | `backend/tests/test_parsers.py` — add a test that the factory returns a valid PayerConfig. | The factory is in code but is not in the test plan. |
## 7. Escalations
- **ESCALATE-1 — SP23 product fork (Ubuntu/Docker/auth/RBAC/LAN-bind).**
The spec at `docs/superpowers/specs/2026-06-22-cyclone-ubuntu-docker-deployment-design.md`
exists but no plan exists. REQUIREMENTS R-1, R-3, R-24 raise the
question but do not close it. **Decision needed:** is SP23 in-scope
for the next release, or deferred? If in-scope, write a plan. If
deferred, move the spec to `docs/superpowers/deferred/`.
- **ESCALATE-2 — RECONCILED state disposition.**
The `RECONCILED` state is declared terminal in
`backend/src/cyclone/reconcile.py:163-164` but never assigned by any
code path. SP2 spec asserts it as the terminal step of every
`apply_payment` path. **Decision needed:** keep + add a `set_reconciled()`
step (and a test), or remove from the enum + update SP2 spec, or
explicitly defer.
- **ESCALATE-3 — Audit-chain source of truth.**
The hash recipe is wrong in `audit_log.py:6-7`, `db.py:649-650`, and
`ARCHITECTURE.md` §4.6. The code at `audit_log.py:80-89` and the
SP11 spec at `…-sp11-hash-chained-audit-design.md:104-114` agree.
**Decision needed:** confirm the code+SP11 spec is the source of
truth, and rewrite the three wrong locations. Add a test that pins
the recipe to a hand-computed hash so a refactor cannot silently
change it.
- **ESCALATE-4 — vitest pin.**
`vitest@^4.1.9` is flagged in REQUIREMENTS R-25 as "unusually new".
**Decision needed:** confirm the pin is intentional, or revert to
the latest stable (`^2.x` or whatever the current stable is).
- **ESCALATE-5 — Backup degraded mode policy.**
`backup_service.py` has a degraded mode when the encryption passphrase
is missing. **Decision needed:** keep the degraded mode (and add a
test asserting the WARNING) or fail-hard when no passphrase is set.
- **ESCALATE-6 — Score weights configuration.**
Score weights are hardcoded at `scoring.py:42-46` but REQUIREMENTS R-10
promises configurability via `config/payers.yaml`. **Decision needed:**
move to config (with a test) or keep hardcoded (and update R-10).
- **ESCALATE-7 — SPEC traceability for 277CA payer_rejected.**
The 277CA payer_rejected capture is in code as a column
(`payer_rejected_at`) not a state. ARCH §6.3 has it as a state.
REQUIREMENTS FR-13 mentions it as a lane. **Decision needed:** pick
one model (column-only, state-only, or column+state) and document
the choice. The current 3-way split is confusing.
- **ESCALATE-8 — In-flight migrations 0013/0014 acceptance.**
Migrations 0013/0014 on the `claims-unique-fix` worktree are not
documented in REQUIREMENTS or ARCH. **Decision needed:** publish the
acceptance criterion for the fix (e.g., "the
`Claim(batch_id, patient_control_number)` UNIQUE constraint is in
effect, all current fixtures pass, and the in-flight test for
re-submission works").
## 8. Confidence rating
**Confidence: medium-high.**
Justification: I read the bulk of the backend implementation — `api.py`
(3,548 LOC, all route handlers grepped), `db.py` (839 LOC, all ORM
models and the `ClaimState` enum), `audit_log.py` (254 LOC, the
hash-chain code and its docstrings), `api_helpers.py` (heartbeat +
tail events), `security.py` (485 LOC, three middlewares), `db_crypto.py`
(389 LOC, key rotation), `backup_service.py` (851 LOC, restore flow),
`reconcile.py` (571 LOC, `apply_payment` and `apply_reversal`),
`inbox_lanes.py` (280 LOC, 5 lanes), `scoring.py` (96 LOC, weights),
`inbox_state.py` (76 LOC, 999 transitions), `inbox_state_277ca.py` (108
LOC, monotonic stamping), `scheduler.py` (719 LOC, MFT routing), and
all 12 shipped migrations. I read the frontend live-tail client
(`src/lib/tail-stream.ts`, `src/hooks/useTailStream.ts`) in full and
grepped the rest of `src/{routes,store,components}/` for shape
mismatches. I read `docs/REQUIREMENTS.md` (737 lines), `docs/ARCHITECTURE.md`
(759 lines), and `docs/README.md` in full. I read 6 of the 22 SP specs
in full (SP2 reconciliation, SP5 live tail, SP10 277CA, SP11 audit,
SP14 5-lane Inbox, SP15 key rotation) and grepped the rest for
state-name and constraint assertions. I did **not** read the remaining
16 specs in full, did not read the 27 plan files in full, and did not
read any of the ~73 frontend test files. I also did not verify the
"964 tests collected" claim in NFR-15 nor the existence of
`test_audit_log.py` tests. The medium-high rating reflects strong
backend code coverage, full coverage of the top-of-funnel docs, and
partial coverage of the SP-spec lineage; the gaps that would lower
confidence to "high" are the un-verified plan files, the un-verified
test count, and the un-verified existence of the 6 backend test files
referenced in §6.
---
*End of Reviewer B report. 13 contradictions, 16 forks (4 P0, 4 P1, 5 P2, 3 P3), 12 untested artifacts, 8 escalations. Confidence: medium-high.*
@@ -0,0 +1,228 @@
# Cyclone — Groundtruth Audit (live-data readiness)
**Date:** 2026-06-23
**Branch:** `css-reduction` @ `c00e4c2a5a6bc6ba6b6e6fa8429fffce37965760`
**Loop:** [The Groundtruth loop (#048)](https://signals.forwardfuture.ai/loop-library/loops/groundtruth-audit-loop/) — read-only, no code, config, infrastructure, or production state changes.
**Author of loop:** Mohamed (@aivibecode), published 2026-06-21.
**Author of audit:** run via `claude/grok`-class agent on user request.
**Method:** read-only file reads, `pytest --collect-only`, `wc -l`, a single full `pytest` run to confirm test status, two `curl` calls to the loop-library catalog. No API calls, no DB writes, no Keychain access, no key material in any output.
---
## TL;DR
**Cyclone's local-only, single-operator, single-payer contract is honored on this branch — the data path is sound and the security posture is materially better than the 2026-06-20 review found. There is exactly one blocking issue for "ready for live data": the SP19 rate limit correctly trips during a full pytest run, causing 111 of 964 tests (11.5%) to fail with HTTP 429 on this branch.** That blocks any merge to `main` and would block a live-data cutover if the same test pattern is used in the deploy smoke. A second, lower-severity item — two god-modules (`api.py` 3,548 LOC, `store.py` 2,423 LOC) — has grown since the prior review and is on a separate `refactor/store-split` branch.
| Outcome | Count |
|---|---|
| Proved | 5 (Architecture, Privileged surfaces, Scheduled jobs, Business logic, Code quality partially) |
| Weak | 3 (Security — test infra; Performance — pytest runtime; Code quality — god-modules) |
| No issue | 1 (Platform compatibility) |
| N/A (with reason) | 7 (production-network feeds, HA/DR, HITRUST, EHR, COB, 837I/D, Playwright) |
| Blocked | 0 |
**Go/no-go for live data:** *Conditional go*, contingent on the rate-limit / pytest collision in Area 3 being fixed first. Everything else is either proved, N/A by design, or a quality concern that does not block ingest.
---
## 1. Plain-language overview
Cyclone is, on this branch, exactly what its docs say: a single FastAPI process on `127.0.0.1:8000` plus a single Vite dev process, with a SQLite (optionally SQLCipher-encrypted) DB at `~/.local/share/cyclone/cyclone.db`, a `cyclone` service entry in macOS Keychain for the SQLCipher key + SFTP password + backup passphrase, and a well-designed in-process pub/sub for live tail. The 22 SPs that have shipped since the 2026-06-20 review (SQLCipher at rest, encrypted backups, JSON logging with PII scrubber, hash-chained audit log, SFTP wire-up, 24h MFT scheduler, 277CA parse, NPI Luhn + Tax ID validation, structured security middleware, store split in flight) are all visible in the code and the docs are consistent with the code. The architecture doc's 3,548 / 2,423 LOC numbers match `wc -l` exactly.
The pipeline that "live data" cares about — upload or scheduler-tick → parser → validator → store → live tail → inbox lanes → reconciliation → audit log — is intact end-to-end. Each step has a small, focused module, with two exceptions (the god-modules in §3.9). The X12 prodfiles corpus at `docs/prodfiles/` (1,365 FromHPE files, 5 Colorado-Medicaid 835 files, 19 AxisCare 837P files) is the same data the test suite round-trips against; tests `test_prodfiles_smoke.py::test_fromhpe_*_prodfiles_parse` etc. were written to assert this. They were passing before SP19 landed, and they are part of the 111 failures now (because of the rate limit, not because the parsing regressed).
The data path itself looks ready. The test suite's CI signal on this branch does not. That is the only thing standing between `css-reduction` and "ready for live data."
---
## 2. Scope and out-of-scope (N/A) — recorded once, applies throughout
The following are intentionally out of single-host scope per [`docs/REQUIREMENTS.md` §2.2](/Users/openclaw/dev/cyclone/docs/REQUIREMENTS.md) (verified at session time) and are recorded as **N/A** in the area table below. They are not gaps for this readiness question:
- AS2 / AS4 (EDIINT) signed/encrypted/MDN connectivity
- Real-time 270/271 round-trip over CAQH CORE Phase II/III SOAP envelopes
- 837I (institutional), 837D (dental), 276/277, 278, 820, 834, 275
- NPPES NPI registry lookup (offline Luhn + format only, by design)
- ICD-10 / HCPCS / NDC vocabulary tables
- COB / secondary-claim generator
- HITRUST / SOC 2 / BAA template
- HA / DR / load balancing / multi-host replication
- Prometheus / Grafana / alerting
- 2FA / SSO / OAuth
- LUKS full-disk encryption (host concern)
- Component / E2E browser tests (Playwright)
- 835 *outbound* serializer (Cyclone reads 835s, does not generate them)
---
## 3. Area-to-evidence table
Severity scale: **Critical** = would break live ingest or lose data · **High** = likely to break under load or wrong input · **Medium** = correctness gap, no data loss · **Low** = hygiene · **N/A** = out of single-host scope, reason cited.
### 3.1 Architecture
| Field | Value |
|---|---|
| Outcome | **Proved** |
| Severity | Low (god-module growth tracked elsewhere) |
| Evidence | [`docs/ARCHITECTURE.md`](/Users/openclaw/dev/cyclone/docs/ARCHITECTURE.md) §1–§4; [`backend/src/cyclone/__main__.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/__main__.py) lines 2534; [`backend/src/cyclone/api.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/api.py) lines 99198 (lifespan); [`docs/REQUIREMENTS.md`](/Users/openclaw/dev/cyclone/docs/REQUIREMENTS.md) §2.1 (SP list) |
| Notes | One FastAPI process (uvicorn on 127.0.0.1:8000) + one Vite dev process. Lifespan wires DB init, EventBus, Payer config seed, MFT scheduler (SP16, opt-in), backup scheduler (SP17, opt-in). No message broker. Architecture doc LOC numbers match `wc -l`: api.py = 3,548, store.py = 2,423. SP21 store split is in flight on `refactor/store-split` per §2.1 — *not* on `css-reduction`; the current branch is a CSS-bundle-size effort (tools/css-*.mjs, docs/reviews/2026-06-23-css-reduction/). |
### 3.2 Platform compatibility
| Field | Value |
|---|---|
| Outcome | **No issue** |
| Severity | Low (Node version not pinned in `package.json` `engines`) |
| Evidence | [`backend/pyproject.toml`](/Users/openclaw/dev/cyclone/backend/pyproject.toml) lines 9 (requires-python=3.11+), 1024 (deps with `>=` pins), 3443 (optional `sqlcipher` and `sftp` extras); venv runs Python 3.13.12; [`package.json`](/Users/openclaw/dev/cyclone/package.json) dependencies pinned with `^`. ARCHITECTURE.md §3.1, §3.2 documents the stack. |
| Notes | `pyproject.toml` requires Python ≥3.11; the venv on this machine runs 3.13.12 — fine. Pydantic 2.6+, SQLAlchemy 2.0+, FastAPI 0.110+, keyring 25.0+, cryptography 49.0+ all in spec. SQLCipher is opt-in via `.[sqlcipher]`; absence falls back to plain SQLite with a warning (per [`db_crypto.py:75-98`](/Users/openclaw/dev/cyclone/backend/src/cyclone/db_crypto.py)). macOS Keychain is darwin-specific but `keyring` import is lazy ([`secrets.py:32-36`](/Users/openclaw/dev/cyclone/backend/src/cyclone/secrets.py)) — Linux dev boxes degrade to `None` with a warning, not a crash. **No `engines` block in `package.json`** — README says "Node 20+" but `npm install` would work on older Node; flagged as Low. |
### 3.3 Security
| Field | Value |
|---|---|
| Outcome | **Weak** (one finding) |
| Severity | **High** (rate-limit / pytest collision blocks CI on this branch) |
| Evidence | Bind: [`__main__.py:25`](/Users/openclaw/dev/cyclone/backend/src/cyclone/__main__.py) hard-codes `--host 127.0.0.1`. CORS allowlist: [`api.py:226-247`](/Users/openclaw/dev/cyclone/backend/src/cyclone/api.py) — `localhost:5173` + `127.0.0.1:5173` + `CYCLONE_ALLOWED_ORIGINS` env var. Body-size limit 50 MB: [`security.py:55`](/Users/openclaw/dev/cyclone/backend/src/cyclone/security.py), pure ASGI middleware: [`security.py:88-163`](/Users/openclaw/dev/cyclone/backend/src/cyclone/security.py). Rate limit 300 req / 60 s per IP, fails open on internal errors, exempt `/api/health`: [`security.py:56-244`](/Users/openclaw/dev/cyclone/backend/src/cyclone/security.py). Security headers: [`security.py:63-69`](/Users/openclaw/dev/cyclone/backend/src/cyclone/security.py) — CSP `default-src 'none'`, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy. Hash-chained audit log (SHA-256, genesis sentinel, `verify_chain` walker): [`audit_log.py:53-200`](/Users/openclaw/dev/cyclone/backend/src/cyclone/audit_log.py). Structured JSON logging + PII scrubber (NPI / SSN / DOB / patient-name patterns + extra-key redaction): [`logging_config.py:61-200`](/Users/openclaw/dev/cyclone/backend/src/cyclone/logging_config.py). |
| Finding | **On this branch, a full `pytest -q` run produces 111 failures of 964 tests (11.5%), all of them 429 Too Many Requests from the rate limit.** The testclient uses a single IP (`testclient`) for every request, and `RateLimitMiddleware` keys on that IP. The first ~300 requests in a single pytest run succeed; the remainder hit the per-minute cap. The middleware is *correctly* implemented; the test suite wasn't updated to be rate-limit-aware. Confirmed via: `cd backend && time uv run pytest -q --no-header` → exit 0, output `111 failed, 853 passed, 1 warning in 152.85s (0:02:32)`. Sample log line from the failure: `{"level":"WARNING","logger":"cyclone.security","msg":"api.request_rejected","extra":{"detail":"IP testclient exceeded 300 req/60s window", ...}}` ([`security.py:322-332`](/Users/openclaw/dev/cyclone/backend/src/cyclone/security.py)). Affected test groups: `test_prodfiles_smoke.py::test_fromhpe_*_prodfiles_parse` (4), `test_api_835.py` (9), `test_api_parse_persists_ack.py` (2), `test_api_parse_persists.py` (7), `test_api_277ca.py` (8), `test_api_batch_export_837.py` (8), `test_api_gets.py` (12), `test_api_eligibility.py` (5), `test_inbox_endpoints.py` (8), `test_clearhouse_api.py` (12), `test_batch_diff.py` (3), and others — the failure is uniform, not a specific test regression. The same tests pass when run in isolation (e.g., `uv run pytest tests/test_api_gets.py` → 2/2 pass). |
| Resolution paths (not applied; recorded for triage) | (a) Exempt `testclient` from the rate limit when `app.state.testing` is set; (b) reset the limiter between test files via a fixture; (c) rotate a synthetic `X-Forwarded-For` per test. Any of these is a small, contained change. |
### 3.4 Privileged surfaces
| Field | Value |
|---|---|
| Outcome | **Proved** |
| Severity | Low |
| Evidence | SQLCipher key: macOS Keychain, service `cyclone`, account `cyclone.db.key`, with grace-period account `cyclone.db.key.previous` for rotation rollback ([`db_crypto.py:62-67`](/Users/openclaw/dev/cyclone/backend/src/cyclone/db_crypto.py)). Rotation via `PRAGMA rekey` + table-count sanity check ([`db_crypto.py:11-24`](/Users/openclaw/dev/cyclone/backend/src/cyclone/db_crypto.py)). Backup passphrase + salt: Keychain accounts `backup.passphrase` and `backup.salt` ([`backup_service.py:71-77`](/Users/openclaw/dev/cyclone/backend/src/cyclone/backup_service.py)). Two-step restore with 32-byte random token + 5-min TTL ([`backup_service.py:80`](/Users/openclaw/dev/cyclone/backend/src/cyclone/backup_service.py)). SFTP password: account `sftp.gainwell.password` ([`secrets.py:13-16`](/Users/openclaw/dev/cyclone/backend/src/cyclone/secrets.py)). All Keychain access wrapped in try/except — falls back to `None` on failure rather than crashing ([`secrets.py:50-72`](/Users/openclaw/dev/cyclone/backend/src/cyclone/secrets.py)). `keyring` is an optional import ([`secrets.py:32-36`](/Users/openclaw/dev/cyclone/backend/src/cyclone/secrets.py)). |
| Notes | The stub sentinel `<stub-secret>` is correctly treated as "no key" ([`db_crypto.py:114-115`](/Users/openclaw/dev/cyclone/backend/src/cyclone/db_crypto.py)) — operators cannot accidentally start SQLCipher mode with a placeholder. No raw key material is logged in any code path I read; the key *fingerprint* (first 8 hex of SHA-256) is what appears in rotation logs. Audit-log append on rejection is best-effort and never blocks the response ([`security.py:344-369`](/Users/openclaw/dev/cyclone/backend/src/cyclone/security.py)). |
### 3.5 Performance
| Field | Value |
|---|---|
| Outcome | **Weak** |
| Severity | Medium |
| Evidence | `time uv run pytest -q --no-header``111 failed, 853 passed, 1 warning in 152.85s (0:02:32)`. Test framework: pytest 8.4.2 + pytest-asyncio (Mode.AUTO) + pytest-randomly + pytest-cov. Frontend: vitest 4.1.9 + happy-dom 20.10.6 + Puppeteer Core 25.2.0 (per [`package.json`](/Users/openclaw/dev/cyclone/package.json) devDependencies). CSS-reduction tooling at [`tools/css-*.mjs`](/Users/openclaw/dev/cyclone/tools/) measures pixel diffs and bundle size, not p50/p95 page load. |
| Notes | 964 backend tests in 152 s ≈ 158 ms/test. Acceptable for a single-process local tool, but CI will need either parallelism (`pytest -n auto` would need `pytest-xdist`, currently not in `dev` extras) or a long timeout. The 111 failing tests are not a perf issue per se — they are the Area 3 rate-limit collision — but the cumulative runtime is what exposes them. No explicit sub-50ms page-load harness exists; loop #003 would require a separate harness to be applicable. |
### 3.6 Deployment
| Field | Value |
|---|---|
| Outcome | **Proved** |
| Severity | Low (README install is slightly out of sync with current `uv` practice) |
| Evidence | [`backend/src/cyclone/__main__.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/__main__.py) lines 1835 (binds `127.0.0.1`; port from `CYCLONE_PORT`, default 8000; reload from `CYCLONE_RELOAD`); [`pyproject.toml:9`](/Users/openclaw/dev/cyclone/backend/pyproject.toml) `requires-python = ">=3.11"`; [`pyproject.toml:34-43`](/Users/openclaw/dev/cyclone/backend/pyproject.toml) declares `sqlcipher` and `sftp` extras; [`uv.lock`](/Users/openclaw/dev/cyclone/backend/uv.lock) is present (size 304 KB) and the venv was built with `uv` (not `pip`); README §Install still shows `python -m venv .venv` + `pip install -e '.[dev]'`. No `Dockerfile`, no `docker-compose.yml`, no `Makefile`, no `pre-commit` config, no `ruff` config. |
| Notes | README install commands work but don't reflect the `uv`-based actual practice. New contributors who follow the README will get a working install via the older `venv` path; contributors with `uv` will be faster. Not a blocker. |
### 3.7 Scheduled jobs
| Field | Value |
|---|---|
| Outcome | **Proved** |
| Severity | Low |
| Evidence | MFT scheduler ([`scheduler.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/scheduler.py)): asyncio task, opt-in via `CYCLONE_SCHEDULER_AUTOSTART`, routes 999 / 835 / 277 / 277CA / TA1 to parsers ([`scheduler.py:76`](/Users/openclaw/dev/cyclone/backend/src/cyclone/scheduler.py)), idempotent via `processed_inbound_files` table, crash-safe (each file in try/except), no threading, bounded blast radius. Backup scheduler ([`backup_scheduler.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/backup_scheduler.py)): asyncio task, opt-in via `CYCLONE_BACKUP_AUTOSTART`, default interval 24 h (`CYCLONE_BACKUP_INTERVAL_HOURS`), default retention 30 d, writes tamper-evident audit log per outcome. PubSub ([`pubsub.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/pubsub.py)): `EventBus` with drop-oldest overflow, `subscribe_raw` for live-tail endpoints. Health snapshot ([`api_routers/health.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/api_routers/health.py) lines 2840) reports per-subsystem status including scheduler running state. |
| Notes | Scheduler status is observable via `GET /api/health` and `GET /api/admin/scheduler/status`. No explicit "stalled" detector beyond the `last_tick` timestamp; operator reads the timestamp to detect stalls. Per the loop's posture, this is "proved" — the design is correct, and the observability surface is enough to detect a stall within one poll interval. |
### 3.8 Business logic (data path)
| Field | Value |
|---|---|
| Outcome | **Proved** |
| Severity | Low |
| Evidence | Parsers for 837P ([`parse_837.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/parsers/parse_837.py) 417 LOC + [`serialize_837.py`](/Users/openclaw/dev/cyclone/parsers/serialize_837.py) 627 LOC), 835 ([`parse_835.py`](/Users/openclaw/dev/cyclone/parsers/parse_835.py) 553 LOC; no outbound 835 serializer, intentional), 999 ([`parse_999.py`](/Users/openclaw/dev/cyclone/parsers/parse_999.py) 298 LOC + [`serialize_999.py`](/Users/openclaw/dev/cyclone/parsers/serialize_999.py) 279 LOC), TA1 ([`parse_ta1.py`](/Users/openclaw/dev/cyclone/parsers/parse_ta1.py) 186 LOC), 270 ([`parse_270.py`](/Users/openclaw/dev/cyclone/parsers/parse_270.py) 416 LOC + [`serialize_270.py`](/Users/openclaw/dev/cyclone/parsers/serialize_270.py) 324 LOC), 271 ([`parse_271.py`](/Users/openclaw/dev/cyclone/parsers/parse_271.py) 426 LOC), 277CA ([`parse_277ca.py`](/Users/openclaw/dev/cyclone/parsers/parse_277ca.py) 355 LOC + [`models_277ca.py`](/Users/openclaw/dev/cyclone/parsers/models_277ca.py) 161 LOC). CAS reason codes ([`cas_codes.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/parsers/cas_codes.py) 206 LOC). 7-state claim lifecycle. 5-lane inbox (Rejected / Payer-rejected / Candidates / Unmatched / Done today). Per-line 837 SV1 ↔ 835 SVC audit. Pure-function reconciliation ([`reconcile.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/reconcile.py) `match` + `apply_payment` + `apply_reversal` with 7-day default window). 4-field scoring ([`scoring.py:88`](/Users/openclaw/dev/cyclone/backend/src/cyclone/scoring.py) `score_pair`). |
| Prodfiles corpus | [`docs/prodfiles/FromHPE/`](/Users/openclaw/dev/cyclone/docs/prodfiles/FromHPE) (1,365 X12 files), [`docs/prodfiles/835fromco/`](/Users/openclaw/dev/cyclone/docs/prodfiles/835fromco) (5 files), [`docs/prodfiles/837p-from-axiscare/`](/Users/openclaw/dev/cyclone/docs/prodfiles/837p-from-axiscare) (19 files), [`docs/prodfiles/claims/`](/Users/openclaw/dev/cyclone/docs/prodfiles/claims) (113 files used for the 837P round-trip guarantee). |
| Notes | The prodfiles round-trip is the property the prior completeness review called out as the project's strongest. `test_prodfiles_smoke.py` (4 tests) directly exercises `FromHPE/` and `claims/` prodfiles. Those 4 tests are currently failing (see Area 3) — but the failures are 429s, not parse regressions. Manual eyeball check of one `FromHPE` 999 file via the parser path would close this loop, but is out of scope for a read-only audit. |
### 3.9 Code quality
| Field | Value |
|---|---|
| Outcome | **Weak** |
| Severity | Medium |
| Evidence | 964 backend tests (vs 574 in the 2026-06-20 review; +67.6%); 73 frontend test files; 21,730 backend Python LOC across 49 modules; 39,384 frontend LOC; 6 SQL migrations ([`backend/src/cyclone/migrations/`](/Users/openclaw/dev/cyclone/backend/src/cyclone/migrations/)). God-modules: [`store.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/store.py) **2,423 LOC** (was 2,086 in the prior review; +337) and [`api.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/api.py) **3,548 LOC** (was "1,000+" in the prior review; **3.5×** growth). The `api_routers/` package exists with 5 small routers ([acks.py, admin.py, health.py, ta1_acks.py, __init__.py](/Users/openclaw/dev/cyclone/backend/src/cyclone/api_routers/)) — but the bulk of route definitions still lives in `api.py`. SP21 store split is in flight on `refactor/store-split` per REQUIREMENTS.md §2.1; not on `css-reduction`. No `.editorconfig`, no `.pre-commit-config.yaml`, no `Makefile`, no `ruff.toml` / `.ruff.toml`; `eslint` script exists in `package.json` but no `.eslintrc` config file visible. |
| Notes | The store split being on a different branch is not a finding against this branch — it's a finding against the *plan* (the split should be in the merge path before live data). The `api.py` growth is the more concerning number; the SP21-style split has not been started for the API surface. 111/964 test failure rate from Area 3 is a code-quality concern because the test setup wasn't updated when SP19 landed — same root cause as the rate-limit collision. |
---
## 4. Cross-cutting findings
### 4.1 The one blocking finding
**Rate-limit / pytest collision (§3.3) is the only thing standing between this branch and "ready for live data."** The fix is contained (a few lines in `conftest.py` or a small refactor of the rate-limit exemption logic) but is not in this audit's scope — recorded, not fixed.
### 4.2 What the prior review got right vs. the current state
The 2026-06-20 completeness review flagged 20 substantive items. Status on this branch:
| Prior finding (2026-06-20) | Status today (2026-06-23) | Evidence |
|---|---|---|
| #1 No encryption at rest | **Resolved** by SP12 + SP15 | [`db_crypto.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/db_crypto.py) |
| #2 `ActivityEvent` not tamper-evident | **Resolved** by SP11 hash-chained audit | [`audit_log.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/audit_log.py) |
| #3 No backup automation | **Resolved** by SP17 | [`backup_service.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/backup_service.py), [`backup_scheduler.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/backup_scheduler.py) |
| #4 No request size / rate limits | **Resolved** by SP19 | [`security.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/security.py) |
| #5 No structured logging | **Resolved** by SP18 | [`logging_config.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/logging_config.py) |
| #6 No `pubs_timeout` exposed | Partial — `EventBus.max_queue_size` is configurable but no API knob | [`pubsub.py:23`](/Users/openclaw/dev/cyclone/backend/src/cyclone/pubsub.py) |
| #7 No 277CA | **Resolved** by SP10 | [`parse_277ca.py`](/Users/openclaw/dev/cyclone/parsers/parse_277ca.py), [`models_277ca.py`](/Users/openclaw/dev/cyclone/parsers/models_277ca.py), [`inbox_state_277ca.py`](/Users/openclaw/dev/cyclone/inbox_state_277ca.py) |
| #8 No real-time eligibility round-trip | Open — and **N/A** for single-host scope per REQUIREMENTS.md §2.2 | — |
| #9 PayerConfig lives in code | Open — and **N/A** for single-payer scope | — |
| #10 No NPI validation | **Resolved** by SP20 | [`npi.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/npi.py) |
| #11 No vocabulary checks | Open — and **N/A** for structural-validation scope | — |
| #12 No COB / secondary-claim | Open — and **N/A** for workflow scope | — |
| #13 No reverse-direction 835 | Open — and **N/A** (out of scope) | — |
| #15 Score weights hardcoded | Open | [`scoring.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/scoring.py) — same code, no change |
| #16 No config file persistence | Open | [`providers.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/providers.py), [`payers.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/payers.py) |
| #17 `store.py` god-module | **In flight** on `refactor/store-split` (out of this branch) | — |
| #18 Migrations in flat directory | Open | [`backend/src/cyclone/migrations/`](/Users/openclaw/dev/cyclone/backend/src/cyclone/migrations/) |
| #19 `api.py` monolithic | Open and **growing** (3,548 LOC, 3.5× the prior review) | [`api.py`](/Users/openclaw/dev/cyclone/backend/src/cyclone/api.py) |
| #20 README "what's next" missing | Open | [`README.md`](/Users/openclaw/dev/cyclone/README.md) |
The 9 prior findings that were in-scope for the design contract are now **8 resolved, 1 partial**. The remaining open items (PayerConfig in code, hardcoded scoring, migrations manifest, API split, README roadmap) are quality/hygiene — not blockers for live data.
### 4.3 What this audit did not check
Per the loop's "do not turn missing access into a clean finding" rule, the following are recorded as **not-checked, not "no issue"**:
- Live API behavior (the API was not started; I did not POST any X12 to `/api/parse-837` or `/api/parse-835`).
- Keychain contents (no `security find-generic-password` calls).
- SQLCipher open / `PRAGMA rekey` round-trip (no DB writes).
- Backup encrypt / decrypt / verify (no backups created).
- SFTP wire-up (no outbound connection).
- Visual UI rendering (no browser launched).
- TypeScript `tsc -b --noEmit` output.
- ESLint output.
- Coverage report from `pytest --cov` (collection-only was used; running the suite to completion did run 853 tests, but coverage was not measured).
These would each be a separate audit pass if you want them. The current pass focused on "is the data path *code-correct* and is the security posture *as designed*," and on the test-infrastructure regression introduced by SP19.
---
## 5. Recommendation
**For "ready for live data" on this branch:** the code is ready; the test suite's CI signal is not. Two-step gate:
1. **Fix the rate-limit / pytest collision (§3.3).** Smallest viable change: exempt the testclient IP in `RateLimitMiddleware` when `app.state.testing` is set, or reset the limiter between test files via a `conftest.py` autouse fixture. This is one branch of work; estimated diff is a few lines.
2. **Run the full suite to a clean pass.** Re-run `cd backend && uv run pytest -q` and confirm `0 failed`. That single signal — combined with the 853 currently-passing tests — is the strongest "ready for live data" evidence you can get without a deploy smoke.
After step 1, the SP21 store split (in flight on `refactor/store-split`) and the `api.py` split (not started) are the next-hygiene items. Neither blocks live data on a single-host local tool.
**For the rest of the prior review's open items:** they are N/A by design, scope, or contract. They should not be re-litigated as blockers for live data on this branch.
---
## 6. Audit metadata
- **Branch:** `css-reduction` @ `c00e4c2a5a6bc6ba6b6e6fa8429fffce37965760`
- **Working tree:** modified (`package.json`, `package-lock.json`), untracked (`audit-uiux-extended.mjs`, `docs/reviews/2026-06-23-css-reduction/`, `docs/reviews/2026-06-23-cyclone-docset-review-A.md`, `docs/reviews/2026-06-23-cyclone-docset-review-B.md`, `tools/`). No uncommitted changes to `backend/` were observed.
- **Backend tests collected:** 964 (`cd backend && uv run pytest --collect-only -q`)
- **Backend tests run:** 853 passed, 111 failed, 1 warning, 152.85 s
- **Backend Python LOC:** 21,730 (49 modules)
- **Frontend LOC:** 39,384
- **Migrations:** 6 (PRAGMA user_version 6)
- **Files read for this audit:** 13 (see §3 evidence column)
- **Shell commands run:** 4 (`uv run pytest --collect-only -q`, `time uv run pytest -q --noEmit`, `wc -l` aggregates, 2× `curl` to loop-library catalog)
- **Destructive commands run:** 0
- **Keychain access:** 0
- **API calls made:** 0
- **Code, config, or production state changes:** 0
— *End of audit.*
@@ -0,0 +1,70 @@
# Auth Posture Alignment Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use
> superpowers:subagent-driven-development (recommended) or
> superpowers:executing-plans to implement this plan task-by-task. Steps
> use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Reconcile `CLAUDE.md`, `docs/REQUIREMENTS.md`, and `docs/ARCHITECTURE.md` with the auth work that landed in `main` on 2026-06-23, and add a loud `AUTH_DISABLED` startup warning so a misconfigured production deploy fails loudly.
**Architecture:** Docs-only + one 6-line `__main__.py` edit + three skills addenda. No code paths change; the auth code already in `main` is the source of truth.
**Tech Stack:** Markdown, Python `logging`, existing `cyclone.auth.deps.AUTH_DISABLED` flag.
**Spec:** [`docs/superpowers/specs/2026-06-23-cyclone-auth-posture-alignment-design.md`](../specs/2026-06-23-cyclone-auth-posture-alignment-design.md)
---
## File structure
Modified files:
- `CLAUDE.md` (3 lines: 7, 97, 182)
- `docs/REQUIREMENTS.md` (3 NFR / scope lines + §11 R-1 row + §6.1 SP24 row)
- `docs/ARCHITECTURE.md` (2 lines: 16, 703 + 1 new "Auth" subsection + migrations table note)
- `backend/src/cyclone/__main__.py` (startup warning when `AUTH_DISABLED`)
- `.superpowers/skills/cyclone-tests/SKILL.md` (addendum)
- `.superpowers/skills/cyclone-api-router/SKILL.md` (addendum)
- `.superpowers/skills/cyclone-spec/SKILL.md` (addendum)
## Task 0: Mark spec in implementation
- [ ] Spec header `Status: Draft, awaiting user sign-off``Status: Approved (in implementation on sp24-doc-posture-alignment)`.
## Task 1: `CLAUDE.md`
- [ ] Line 7 — replace "Local-only by design: binds to `127.0.0.1`, no auth, no internet exposure." with the v1 posture: "Local-only by design: binds to `127.0.0.1`, requires login (auth boundary is HTTP; file-system protection unchanged), no internet exposure."
- [ ] Line 97 — update SP numbering to reflect "SP numbers are used through **SP22**; **SP23** is the Ubuntu+Docker fork (awaiting user decision); this increment is **SP24**."
- [ ] Line 182 — replace the "Local-only by design. The backend binds to `127.0.0.1`, has no auth…" bullet with the new posture (login required; auth boundary is HTTP; SQLCipher + Keychain unchanged; don't add internet exposure).
## Task 2: `docs/REQUIREMENTS.md`
- [ ] Line 36 — replace "Local-only on purpose: binds `127.0.0.1`, no auth, no internet exposure, single operator, single machine, one trading partner (Colorado Medicaid, currently)." with the v1 posture.
- [ ] Line 39 — replace "Threat model: a process on the same host. No second party to authenticate; no second host to harden against." with the new threat model (process on same host + HTTP-layer login; SQLCipher + Keychain handle file-system threats; SP23 changes the model to LAN).
- [ ] Line 154 (NFR-1) — replace "no auth, no API key" with "login required (bcrypt + HttpOnly session cookie; first admin bootstrapped from env vars `CYCLONE_ADMIN_USERNAME` + `CYCLONE_ADMIN_PASSWORD`); dev/test escape hatch via `CYCLONE_AUTH_DISABLED=1`."
- [ ] §11 R-1 row — change "**Open** — addressed only if/when SP23 ships." to "**Closed by SP24** — auth shipped via the merge of `origin/main` on 2026-06-23 (commits `a25504b`..`39ae988`); SP24 reconciled the docs to match. SP23 still covers the LAN-bind / Docker / RBAC product fork."
- [ ] §6.1 — add an SP24 row pointing at this plan + the spec.
## Task 3: `docs/ARCHITECTURE.md`
- [ ] Line 16 — replace "has no authentication because the threat model is a stolen or imaged drive, not a remote attacker." with the new posture.
- [ ] Line 703 — replace "Multi-user / multi-host — no auth, no LAN-bind, no Docker, no reverse proxy. The operator is one person, the host is one machine. (SP23 fork if this changes.)" with the new posture (login required; SP23 covers LAN-bind / Docker / RBAC fork).
- [ ] Add a new "### Auth" subsection under §5.1 listing the `cyclone.auth/` package contents and the `matrix_gate` dependency contract.
- [ ] Migrations table — add a note that 0013 + 0014 are auth migrations and explain the renumbering on `claims-unique-fix` (0013/0014 → 0015/0016) to keep the auth migrations at the front.
## Task 4: `backend/src/cyclone/__main__.py`
- [ ] After `bootstrap.run()`, check `cyclone.auth.deps.AUTH_DISABLED` and emit a `WARNING` via `logging.getLogger("cyclone")` if True. The warning text must include the words "AUTH_DISABLED" and "dev only" so a misconfigured production deploy is greppable from logs.
## Task 5: Skills addenda
- [ ] `cyclone-tests` — add a paragraph noting the conftest's `AUTH_DISABLED` flip is mandatory context for any new test.
- [ ] `cyclone-api-router` — add a paragraph noting every router needs `Depends(matrix_gate)` and the role matrix is in `cyclone.auth.permissions`.
- [ ] `cyclone-spec` — add a paragraph noting the spec template's "threat model" example needs to be auth-aware (don't say "no second party to authenticate" any more; reference this SP as the reference pattern).
## Task 6: Verification
- [ ] `grep -nE 'no auth|no authentication|no second party' CLAUDE.md docs/REQUIREMENTS.md docs/ARCHITECTURE.md` returns no false-positive matches.
- [ ] `cd backend && .venv/bin/python -c "import cyclone.__main__"` doesn't crash.
- [ ] `cd backend && .venv/bin/python -c "import cyclone; from cyclone.auth import deps; print(deps.AUTH_DISABLED)"` prints `False` (default).
- [ ] `cd backend && CYCLONE_AUTH_DISABLED=1 .venv/bin/python -c "from cyclone.auth.bootstrap import run; run(); from cyclone.auth.deps import AUTH_DISABLED; print(AUTH_DISABLED)"` prints `True` (env var flips the flag).
@@ -0,0 +1,88 @@
# Cyclone Auth Posture Alignment — Design
**Date:** 2026-06-23
**Status:** Approved (in implementation on `sp24-doc-posture-alignment`, 2026-06-23)
**Branch:** `sp24-doc-posture-alignment` (off `css-reduction``docs/REQUIREMENTS.md` and `docs/ARCHITECTURE.md` were added on `css-reduction` and do not yet exist on `main`)
**Depends on:** The auth work that landed in main via the merge of `origin/main` on 2026-06-23 (commits `a25504b`..`39ae988`, 14 commits, the `feat(auth):`/`fix(auth):`/etc. series on `auth-rebased`).
**Replaces:** The "no auth, no LAN-bind, single operator" claim in `CLAUDE.md`, `docs/REQUIREMENTS.md`, and `docs/ARCHITECTURE.md` — the codebase no longer matches the doc and the divergence needs to be resolved one way or the other.
---
## 1. Overview
The auth work that landed in main is materially more than a stub. The codebase now has:
- A `users` and `sessions` SQLAlchemy model (migrations 0013 + 0014)
- A `User.password_hash` field using bcrypt
- An `auth_router` exposing `/api/auth/login`, `/api/auth/logout`, `/api/auth/me`
- A `matrix_gate` FastAPI dependency and a permissions matrix that gates every existing endpoint by role (admin / user / viewer)
- An `AUTH_DISABLED` flag (module-level in `cyclone.auth.deps`, also settable via `CYCLONE_AUTH_DISABLED=1` at boot) that the conftest autouse fixture flips to `True` so the test suite can run without a login round-trip per request
- A `RateLimitMiddleware` (SP19) that the conftest bypasses via `app.state.testing`
- A `RequireAuth` route guard and an `AuthProvider` React context on the frontend
- A sidebar user indicator + logout button on the shell
- A `cyclone admin` CLI for creating users and rotating passwords
But `CLAUDE.md`, `docs/REQUIREMENTS.md`, and `docs/ARCHITECTURE.md` (all three added or updated on the `css-reduction` branch in commit `12311bf` / `a39bfb2`) still say:
- `CLAUDE.md:7` — "Local-only by design: binds to `127.0.0.1`, **no auth**, no internet exposure."
- `CLAUDE.md:182` — "**Local-only by design.** The backend binds to `127.0.0.1`, has no auth, and the threat model is a stolen/imaged drive, not a remote attacker. **Don't add internet exposure or auth without an explicit spec.**"
- `docs/REQUIREMENTS.md:36` — "**Local-only on purpose:** binds `127.0.0.1`, **no auth**, no internet exposure, single operator, single machine, one trading partner"
- `docs/REQUIREMENTS.md:39` — "**Threat model:** a process on the same host. No second party to authenticate; no second host to harden against."
- `docs/REQUIREMENTS.md:154` — NFR-1: "no auth, no API key"
- `docs/ARCHITECTURE.md:16` — "has no authentication because the threat model is a stolen or imaged drive, not a remote attacker"
- `docs/ARCHITECTURE.md:703` — "Multi-user / multi-host — **no auth**, no LAN-bind, no Docker, no reverse proxy. The operator is one person, the host is one machine. (SP23 fork if this changes.)"
The pre-auth claims in the docs are now false. The threat model is no longer "a process on the same host" — there is at minimum a password boundary that requires a deliberate authentication step before any data is returned.
## 2. Goals
1. **Decide the canonical auth posture.** Is this v1 with a single local operator who has to log in, or is it the first step toward SP23 (Ubuntu + Docker + RBAC + LAN-bind)? Pick one and write it down; the docs and the code must agree.
2. **Update the three stale top-level docs** (`CLAUDE.md`, `docs/REQUIREMENTS.md`, `docs/ARCHITECTURE.md`) to reflect the chosen posture. Every "no auth" claim is replaced with the truth; every "single operator, single host" claim is qualified by the new auth boundary.
3. **Update the relevant Cyclone superpowers skills** that still describe the pre-auth system: at minimum `cyclone-tests` (conftest's `AUTH_DISABLED` flag is now mandatory context for any new test file), `cyclone-api-router` (the `matrix_gate` dependency is now part of every router), and `cyclone-spec` (the SP-N spec template's "threat model" section needs an auth-aware example).
4. **Make `AUTH_DISABLED` discoverable in the conftest.** The conftest autouse fixture flips `cyclone.auth.deps.AUTH_DISABLED = True` for every test, and the test suite relies on this. A new test file that imports `cyclone.auth.deps` and reads the flag directly will see it as `True` and may make wrong assumptions. A `cyclone.auth.testing` helper that documents "this is what the test suite does to the auth flag, and how to opt out per-test" would make the dependency explicit.
5. **Tighten the migration sequence.** Migrations 0013 and 0014 (auth_users_and_sessions, audit_log_user_id) are auth-related. They currently have no docstring beyond the filename. The migrations table in `docs/ARCHITECTURE.md` should list them and explain the dependency (the `audit_log.user_id` FK in 0014 is a forward reference to `users.id` from 0013, so the renumbering on the `claims-unique-fix` branch — 0013/0014 → 0015/0016 — was necessary to keep the auth migrations at the front of the chain).
## 3. Non-goals
- **Reverting the auth work.** It ships in main, it's tested, and the operator can no longer use Cyclone without logging in. Going back is a separate decision the user would have to ask for explicitly; this SP assumes the auth work stays.
- **Shipping SP23 (Ubuntu + Docker + LAN-bind).** SP23 is its own design (`docs/superpowers/specs/2026-06-22-cyclone-ubuntu-docker-deployment-design.md`) and is still "awaiting user decision." This SP only reconciles the doc/code divergence that the auth-merge created; it does not advance the LAN-bind / Docker conversation.
- **Adding new auth features.** No SSO, no MFA, no per-claim ACL, no audit log viewer UI. The auth in main is what's documented; this SP just describes it.
- **Changing the data model.** The `users` / `sessions` / `audit_log.user_id` schema stays. The bcrypt-hashed password and HttpOnly session cookie stay. The `admin` / `user` / `viewer` role enum stays.
## 4. Decisions to make (questions for the user)
These are the points that the spec can't answer on its own. They each have a default that matches the auth work in main, but the user may want to override.
1. **What is the v1 posture?** The auth work in main binds to `127.0.0.1` (still) and gates every endpoint behind `matrix_gate` (now). The default reading is "single-operator local-only, but with a login screen." Alternatives: revert the auth (separate decision), or treat this as a stepping stone to SP23.
- **Default:** v1 = single-operator local-only with auth. SP23 is a future decision.
2. **How is the first admin created?** `cyclone.auth.bootstrap` reads `CYCLONE_ADMIN_USERNAME` + `CYCLONE_ADMIN_PASSWORD` from the env and creates the row on first boot (no users exist) — see `backend/src/cyclone/auth/bootstrap.py:45-65`. If the env vars are unset and no users exist, `cyclone serve` errors out with a message telling the operator to set them. The `cyclone admin create-user` CLI is a follow-up convenience for adding more users after the first one.
- **Default:** the env-var bootstrap stays. Document the env vars in `CLAUDE.md` under the existing `Install` / `Dev` sections.
3. **Does the `AUTH_DISABLED` escape hatch ship as a real production knob?** It's a `cyclone.auth.deps.AUTH_DISABLED` module-level boolean that the conftest flips to `True` for the test suite, AND `CYCLONE_AUTH_DISABLED=1` sets it at boot via `cyclone.auth.bootstrap:37-43`. The current behavior is "synthetic admin, no role check" when the flag is set.
- **Default:** keep the env-var escape hatch (it makes local dev + tests possible), but add a startup log line in `cyclone serve` that screams `WARNING: CYCLONE_AUTH_DISABLED=1 — all requests treated as admin, dev only` so a misconfigured production deploy fails loudly. Make the conftest path explicit in `cyclone-tests`.
4. **Should the docs be explicit about what the auth boundary is and isn't?** The default reading is "the auth boundary is the HTTP layer; the file-system and the SQLite file are still bound by the local-only threat model (stolen/imaged drive, SQLCipher at rest, etc.)."
- **Default:** the auth boundary is HTTP-layer only. SQLCipher, Keychain, and the 127.0.0.1 bind are unchanged.
## 5. Plan
The plan lives in `docs/superpowers/plans/2026-06-23-cyclone-auth-posture-alignment.md` once the spec is approved. The shape of the plan is:
1. `CLAUDE.md` — replace lines 7 and 182 with the v1 posture ("local-only with auth; auth boundary is HTTP; default bootstrap on first run"). Update the `Frontend at a glance` / `Backend at a glance` sections to mention `cyclone.auth` and `matrix_gate`. Note the `AUTH_DISABLED` test flag in `cyclone-tests`.
2. `docs/REQUIREMENTS.md` — replace the "Local-only on purpose" line 36 and the "Threat model" line 39 with the v1 posture. Update NFR-1 (line 154) to reflect that auth IS now part of the contract. Update §6 (FRs) to add an "Auth boundary" subsection. Update §11 (Roadmap) to note that SP24 lands the auth posture and SP23 is a separate future decision.
3. `docs/ARCHITECTURE.md` — replace line 16 and line 703. Add an "Auth" section to the module map (`cyclone.auth` package, the `matrix_gate` dependency, the conftest bypass). Update the migrations table to list 0013 and 0014 and explain why the renumbering on the SP22 branch was necessary.
4. The three Cyclone superpowers skills under `.superpowers/skills/` that describe tests, routing, and spec shape: each gets a one-paragraph addendum.
5. `cyclone serve` startup log: emit a `WARNING: AUTH_DISABLED` line if `cyclone.auth.deps.AUTH_DISABLED` is `True` at boot. The flag is off by default; only the conftest flips it.
## 6. Verification
- The three top-level docs no longer contain "no auth" / "no authentication" / "no second party to authenticate" claims that are false.
- The Cyclone skills addenda are present and self-consistent.
- The startup warning fires when `AUTH_DISABLED = True` and is silent otherwise.
- The existing test suite still passes (the auth changes are in main; this SP only touches docs + the startup warning).
## 7. Out of scope
- Any new feature beyond docs + skills addenda + startup warning.
- Any change to the `users` / `sessions` / `audit_log` schema.
- Any change to the role matrix or the per-endpoint gate.
- Any change to SP23 (separate spec, separate decision).
- The CLAUDE.md contradiction is the canary; the rest of the doc set may have other places where the pre-auth claim leaked in. The implementation step sweeps `docs/` and `*.md` files under `.superpowers/skills/` for the strings "no auth", "no authentication", "single operator, single host" and either fixes them or explicitly marks them as historical context.