Commit Graph

132 Commits

Author SHA1 Message Date
Tyler f003c1f73a feat(sp17): encrypted DB backup automation
Adds automated encrypted backups of the live SQLite file. Closes the
'no backup automation' gap called out in the completeness review
(docs/reviews/2026-06-20-cyclone-completeness-review.md §3.1 #3) and
gives the SP16 MFT scheduler a recovery path when the MFT pipeline
loses days of inbound 999/277CA work in a single crash.

Architecture
------------
- AES-256-GCM with PBKDF2-HMAC-SHA256 (200,000 iters, 16-byte salt)
- Online backups via SQLite's .backup() API — no app downtime
- Salt + passphrase persisted to macOS Keychain (separate accounts
  backup.passphrase + backup.salt) so the key is reproducible across
  processes
- Two-step restore (initiate → confirm) with a one-shot 64-char hex
  token; the second call disposes + rebuilds the engine only if the
  token matches within a 5-minute TTL
- Tamper-evident audit chain (SP11) — db.backup_created,
  db.backup_failed, db.backup_pruned, db.backup_restored,
  db.backup_passphrase_set
- BackupService + BackupScheduler + module-level singletons
- 8 admin endpoints + 6 CLI subcommands
- Auto-start opt-in via CYCLONE_BACKUP_AUTOSTART=true; default
  interval 24h, default retention 30 days
- Fallback posture: if no separate passphrase is set and SQLCipher
  is enabled, the key is derived from the SQLCipher DB key with a
  fixed salt + WARNING log (degraded but never plaintext)

New modules
-----------
- cyclone.backup          — PBKDF2, AES-GCM, sidecar format
- cyclone.backup_service  — create_now / list / verify / restore / prune / status
- cyclone.backup_scheduler — async tick loop with audit hooks

New surface
-----------
- 8 admin endpoints under /api/admin/backup/*
- 6 CLI subcommands under cyclone backup (init-passphrase, create,
  list, verify, restore, prune, status)
- Migration 0012_backups.sql + DbBackup ORM
- store.add_backup_pending()

Tests
-----
- 14 unit tests in test_backup_crypto.py (key derivation, encrypt/
  decrypt round-trip, tampered ciphertext, wrong passphrase, sidecar
  round-trip, filename format)
- 19 tests in test_backup_service.py (create/list/verify/restore/
  prune/status, error handling, fallback key, module singleton)
- 14 API tests in test_api_backup.py (all 8 endpoints + scheduler
  endpoints, two-step restore, error responses)
- 10 tests in test_backup_scheduler.py (tick / start / stop /
  audit / coalescing / module singleton)
- 5 CLI tests in test_cli_backup.py (create / list / verify /
  restore confirm prompt / prune confirm prompt /
  init-passphrase minimum-length check)

Total new tests: 62. All pass. Full backend suite: 833 passed,
9 skipped (gitignored prodfiles), 1 warning.

Design doc: docs/superpowers/specs/2026-06-21-cyclone-encrypted-backup-design.md
README: new 'Encrypted Backups (SP17)' section, SP17 entry in
Roadmap, retention default documented in §Project layout.
2026-06-21 09:43:51 -06:00
Tyler d54c44f04a feat(sp12): SQLCipher encryption at rest (optional)
- New cyclone.db_crypto module:
  * is_sqlcipher_available() — capability check
  * is_encryption_enabled() — Keychain key + sqlcipher3 present
  * get_db_key() — reads 'cyclone.db.key' from Keychain
  * make_sqlcipher_connect_creator(url, key) — SQLAlchemy creator
- db._make_engine() now switches to SQLCipher when key is present
- pyproject.toml: optional 'sqlcipher' extra (sqlcipher3>=0.6,<1)
- Fallback: without Keychain key, DB stays plain SQLite (no surprise
  behavior for operators who haven't set up encryption yet)
- Verified: encrypted file is unreadable as plain SQLite, wrong key
  raises on first query, migrations + ORM work transparently
- HIPAA §164.312(a)(2)(iv) compliance note in docs

Tests: 705 -> 717 (12 new for SQLCipher). All 717 backend tests pass.
2026-06-20 23:52:41 -06:00
Tyler 62bb09f183 feat(sp11): tamper-evident hash-chained audit_log
- New audit_log table (migration 0009, user_version=9):
  * id, event_type, entity_type, entity_id, actor, payload_json,
    created_at, prev_hash, hash
  * Indexes on (entity_type, entity_id), event_type, created_at
- New cyclone.audit_log module:
  * append_event(session, AuditEvent) — appends one chained row
  * verify_chain(session) — walks the chain, returns first bad id
  * SHA-256 hash over canonical row form (unit-separator delimited)
  * Genesis prev_hash = 64 zeros (Bitcoin-style sentinel)
- New AuditLog ORM model
- New admin API endpoints:
  * GET /api/admin/audit-log (paginated, filterable)
  * GET /api/admin/audit-log/verify (returns ok/first_bad_id/reason)
- Hooked into existing endpoints to append events:
  * /api/parse-999 → 'claim.rejected' per matched claim
  * /api/parse-277ca → 'claim.payer_rejected' per matched claim
  * /api/clearhouse/submit → 'clearhouse.submitted' per claim
- HIPAA §164.316(b)(2) compliance note in docs

Tests: 688 -> 705 (9 audit + 8 audit-API). All 705 backend tests pass.
2026-06-20 23:45:43 -06:00
Tyler 2c0afbe9c5 feat(sp10): 277CA parser + Payer-Rejected Inbox lane
- Add cyclone.parsers.models_277ca + parse_277ca (X12 005010X214)
  - Per-Patient HL ClaimStatus with REF*1K (PCN), REF*EJ (tax ID),
    STC category code, amount, service date
  - STC classifier: A1-A3 accepted, A4/A6/A7 rejected, A8/A9 pended,
    P1-P5 paid, anything else unknown
  - Multiple STCs per Patient HL: last wins (canonical pattern for
    'first pended, then paid' acknowledgments)
  - Subscriber-level STCs surface in unscoped_statuses
- Add apply_277ca_rejections — stamps Claim.payer_rejected_* fields on
  matching rows (lookup by patient_control_number, mirrors 999 path)
- New /api/parse-277ca, /api/277ca-acks, /api/277ca-acks/{id} endpoints
- New two77ca_acks table + Two77caAck ORM model
- New Claim columns: payer_rejected_at, _reason, _status_code, _by_277ca_id
- New payer_rejected lane in /api/inbox/lanes (distinct from 999
  envelope rejected lane)
- New PayerConfig277CA block in config/payers.yaml + Pydantic model
- Migration 0008 bumps user_version to 8

Tests: 654 -> 688 (parser 22 + apply 6 + API 8 + config 6 + adjustments).
All 688 backend tests pass; 1 pre-existing skipped test class unaffected.
2026-06-20 23:41:01 -06:00
Tyler c62826daea feat(sp9): multi-payer, multi-NPI, SFTP stub for dzinesco/TOC
- providers table seeded with 3 NPIs (Montrose, Delta, Salida)
- payers + payer_configs (per-tx config) join table
- clearhouse singleton (dzinesco identity, SFTP block, filename block)
- config/payers.yaml loader with Pydantic schema validation
- cyclone/edi/filenames.py: HCPF X12 File Naming Standards helpers
- cyclone/clearhouse/sftp.py: stub that copies to ./var/sftp/staging/...
- cyclone/secrets.py: macOS Keychain wrapper via keyring
- 11 new validation rules R200-R210 (CO MAP + HCPF naming)
- 6 new API endpoints (/api/clearhouse/*, /api/config/*, /api/admin/reload-config)
- migration 0007
- 72 new tests (646 total passing, was 574)

See spec: docs/superpowers/specs/2026-06-20-cyclone-multi-payer-npi-sftp-design.md
2026-06-20 23:07:31 -06:00
Tyler fbe9940a3f feat(ui): cohesive frontend polish — design system + per-screen refinement
Distill the UI into a single, recognizable voice: a precision
instrument for one operator on one machine. Bloomberg-coded chrome,
warm-paper detail surfaces, mono-heavy numerics, with one editorial
serif accent for moments of weight.

Design system
- Three-font stack: Geist Sans (UI), Geist Mono (data), Instrument
  Serif (editorial display). No Inter, no system fonts.
- Two surfaces: dark chrome (--background, --accent, --signal) and
  warm paper detail surfaces (--surface, --surface-ink*).
- Inbox has its own Ticker Tape terminal palette (--tt-*).
- Shared component classes: .eyebrow, .mono, .display, .surface,
  .surface-2, .row-hover, .nav-active, .kbd, .editorial, .hairline.
- --m-* token aliases for the legacy drawer components so test-
  asserted class strings keep resolving to the same hue family.

Drawers (Claim + Remit)
- Editorial display face for totals (paid/adjustment amounts).
- Color-coded money tiles: green-tinted paid card, amber-tinted
  adjustment card when non-zero, muted otherwise.
- Tabs get accent-blue underline + CSS-driven active state.
- Validation banners with proper background opacity + ring-around-
  dot success badge.
- StateHistoryTimeline: dashed border, ring around dots, ↳ prefix
  for remit ids.
- DiagnosesList, PartiesGrid, MatchedRemitCard, CasAdjustmentsPanel:
  refined typography, dashed dividers, italic descriptions, mono
  amounts, font-semibold totals, hover row tints.

Inbox Ticker Tape
- Custom RowCheckbox with sr-only input + amber accent.
- Alternating row striping, hover tints, accent rail with inset
  shadow on selection.
- Refined sparkline with glow at high values.
- BulkBar: bottom-floating bar with amber count chip, larger shadow.
- CandidateBreakdown: animated progress bars with amber gradient.
- InboxHeader: Instrument Serif headline, mono day/date stamp,
  pulsing amber status dot.

Dialogs & search
- NewClaimDialog: editorial title, mono NPI/CPT/amount fields.
- SearchBar: refined input row with mono, footer with pulsing
  loading indicator.
- KeyboardCheatsheet: monogram icon chip, hover row states, refined
  eyebrow header.

Primitives
- StatusBadge / ClaimStateBadge: per-state dot indicators.
- SelectItem: data-[highlighted]:outline tokens for keyboard a11y.
- Table primitives: refined header treatment, hover/focus states.

Tests + build
- 354/354 tests passing across 59 files.
- Vite build clean (53.84 kB CSS / 560.86 kB JS).
- Eyebrow assertions updated to match the consolidated .eyebrow
  class (intact visual contract, abstracted class string).
- Badge variant tokens updated to the polished bg-muted/80 /
  /0.14 opacity scale.
2026-06-20 22:27:01 -06:00
Tyler 561018c690 feat(sp8): outbound 837P serializer — full rebuild + round-trip tests
- backend/src/cyclone/parsers/serialize_837.py — full-rebuild 837P serializer.
  Emits envelope (ISA/GS/ST/SE/GE/IEA + BHT) + submitter/receiver/billing
  provider/subscriber/payer hierarchy + editable segments (CLM/REF*G1/HI)
  + per-service-line LX/SV1/DTP*472/REF*6R — all from canonical
  ClaimOutput fields.

  Pivoted from spec §3.1 hybrid to full rebuild because ClaimOutput.raw_segments
  only captures post-CLM segments (CLM, REF*G1, HI, LX, SV1 pairs) — not the
  envelope or hierarchies. A pass-through approach cannot regenerate those
  without expanding raw_segments in parse_837.py (out of scope for this SP).

- backend/tests/test_serialize_837.py — 36 tests covering envelope shape,
  hierarchy segments, claim-level builders, service-line builders, edited-field
  propagation, round-trip, custom sender/receiver IDs, and resubmit helper.

- backend/tests/test_prodfiles_smoke.py::test_claims_prodfile_round_trip —
  every file in docs/prodfiles/claims/ (113 files) round-trips through
  serialize_837 → parse_837_text with deep-equal ClaimOutput (modulo
  validation, which is recomputed by the parser).

- docs/superpowers/plans/2026-06-20-cyclone-serialize-837.md — full plan
  with amendment note documenting the Approach A pivot.

Per session convention, plan note about unrelated modifications to
parse_835.py / fixtures stashed separately.
2026-06-20 20:27:48 -06:00
Tyler 27c1680830 docs: refresh README roadmap (SP4/6/7 shipped, add Next up) + commit SP6 plan
- Mark SP4 as fully shipped (batch diff, search, CSV, a11y all landed)
- Add SP6 (Inbox) and SP7 (Per-line reconciliation) sections
- Add SP6 + SP7 endpoint inventories
- Note next up: outbound 837P serializer

The workflow-automation plan was authored but never committed; the
features it specified have shipped, so commit it for the historical
record alongside this README refresh.
2026-06-20 19:58:26 -06:00
Tyler e35c59bd6e docs(sp7): SP7 implementation plan — 21 tasks across 6 phases 2026-06-20 19:19:26 -06:00
Tyler c43160927b docs(sp7): SP7 design spec — per-service-line adjustment audit 2026-06-20 19:15:55 -06:00
Tyler a58f613bcd docs(sp7): outbound 837P serializer design spec
Sub-project 7 adds serialize_837.py so a parsed ClaimOutput can be
regenerated as a complete X12 837P file (the shape of
docs/prodfiles/claims/). Unblocks the SP6 resubmit lane end-to-end
and adds a 'Download 837' affordance on the claim drawer.

Approach: hybrid (fresh envelope + selective body rebuild). Stable
segments (provider/subscriber/payer hierarchies) pass through from
claim.raw_segments; editable segments (CLM, REF*G1, HI, SV1, DTP*472)
are rebuilt from canonical ClaimOutput fields so post-parse edits
propagate to the output.

Out of scope: 997 ACK, claim <-> TA1/999 linking, in-app claim
editing UI, multi-CLM envelope batching, Inbox/drawer redesign.
2026-06-20 19:12:34 -06:00
Tyler 1359b0753a merge: SP5 live-tail — pub/sub + 3 stream endpoints + frontend tail integration
Brings the SP5 live-tail implementation into main:

Backend
  * EventBus (cyclone.pubsub): per-kind fan-out with drop-oldest overflow
  * FastAPI lifespan initializes the bus + db once per process
  * store.add() publishes claim_written / remittance_written /
    activity_recorded events on every batch write
  * GET /api/{claims,remittances,activity}/stream: NDJSON snapshot +
    live subscription + 15s idle heartbeat
  * EventBus.unsubscribe() lets the tail loop release its queue on
    client disconnect (no queue leak per open stream)

Frontend
  * src/lib/tail-stream.ts: streamTail() async-generator over fetch
  * src/store/tail-store.ts: zustand with FIFO cap 10k per slice
  * src/hooks/useTailStream.ts: connecting/live/reconnecting/stalled/error/closed
    state machine with 1→2→4→8→16→30s backoff
  * src/hooks/useMergedTail.ts: base + tail merge with filter
  * src/components/TailStatusPill.tsx: badge + Reconnect button
  * Claims, Remittances, ActivityLog pages wired to the tail

Tests
  * 437 backend tests pass (was 418 before SP5)
  * 154 frontend tests pass (was 124)
  * npm run typecheck clean
  * end-to-end smoke: open /api/claims/stream, POST 837, see new claims
    arrive in real time without refresh

# Conflicts:
#	src/pages/ActivityLog.tsx
#	src/pages/Remittances.test.tsx
#	src/pages/Remittances.tsx
2026-06-20 17:28:58 -06:00
Tyler b980e77cf2 docs(sp5): live-tail design spec — pub/sub + long-poll NDJSON for claims/remits/activity 2026-06-20 13:47:54 -06:00
Tyler 972cc99200 docs: mark SP4 partial shipped (claim drawer); tick all plan checkboxes 2026-06-20 12:37:31 -06:00
Tyler bdc851f0f0 docs(sp4): per-claim detail drawer implementation plan (24 tasks, 5 phases) 2026-06-20 08:55:49 -06:00
Tyler 25cd785e62 docs(sp4): per-claim detail drawer design spec + gitignore superpowers dir 2026-06-20 08:44:20 -06:00
Tyler 446a02d0a2 docs: mark SP3 shipped; tick all plan checkboxes 2026-06-20 08:25:15 -06:00
Tyler 763ca3d758 docs(sp3): put transaction_type_code on ClaimOutput (mirrors envelope convention) 2026-06-20 07:18:16 -06:00
Tyler 467087d683 docs(sp3): fix rule IDs (R034/R035) and BHT06 naming in plan+spec 2026-06-20 07:18:03 -06:00
Tyler b47818883a docs: add EDI features spec + implementation plan (sub-project 3, 30 tasks) 2026-06-20 07:14:14 -06:00
Tyler b7f831e170 docs: tick off completed boxes in sub-project 1 plan (housekeeping) 2026-06-20 00:11:01 -06:00
Tyler 53010b89dd docs: add DB + reconciliation implementation plan (30 tasks, 7 phases)
Implements the spec at docs/superpowers/specs/2026-06-19-cyclone-db-reconciliation-design.md.

Phase 1 — Backend foundation (T1-T3): SQLAlchemy dep, db.py skeleton,
PRAGMA user_version migration runner, 0001_initial.sql with 6 tables.
Phase 2 — ORM models (T4-T6): Batch, Claim, Remittance, CasAdjustment,
Match, ActivityEvent + ClaimState enum.
Phase 3 — Reconciliation pure functions (T7-T8): match() with date
window + multi-claim fallback, apply_payment/apply_reversal,
split_unmatched.
Phase 4 — Store facade refactor (T9-T12): CycloneStore replaces
InMemoryStore with same public API + list_unmatched / manual_match /
manual_unmatch; reconcile.run orchestrator wired into store.add().
Phase 5 — API additions (T13-T17): db.init() in startup,
GET /api/reconciliation/unmatched, POST /match, POST /unmatch,
parse-835 response includes reconciliation summary; TODO marker
removal verification.
Phase 6 — Frontend (T18-T26): ClaimState types, api.listUnmatched/
matchRemit/unmatchClaim, useReconciliation hook, ClaimStateBadge
primitive (7 states, same palette), Reconciliation page, sidebar
nav entry, vitest worktree exclude.
Phase 7 — Docs + smoke (T27-T30): README persistence section + DB
URL docs, tick off sub-project 1 plan boxes, full end-to-end smoke
procedure, merge to main.

Total: 30 tasks across 7 phases. TDD discipline per task with
~32 new backend tests + ~4 new frontend tests. Target after
completion: 210 backend + 7 frontend tests passing.
2026-06-19 20:51:31 -06:00
Tyler cf9af8e1d9 docs: add DB + reconciliation design spec (sub-project 2 of 4)
Replaces the in-memory store with SQLite via SQLAlchemy 2.0; adds
automatic 837P ↔ 835 reconciliation on every 835 parse; ships a
manual /reconciliation page; extends the claim lifecycle to a
7-state model with reversal handling.

Key decisions (locked from brainstorming):
- SQLite at ~/.local/share/cyclone/cyclone.db, overridable via
  CYCLONE_DB_URL (Postgres escape hatch)
- SQLAlchemy 2.0 sync ORM; PRAGMA user_version migration runner
- Strict auto-match on patient_control_number (CLM01 == CLP01)
  within +/-7 days of service_date
- 7-state claim model with reversal that sets Claim.state=REVERSED
  and preserves prior state on Match.prior_claim_state
- Reconciliation triggered inside store.add() after ERA persist;
  fail-soft (logged + activity event, never blocks parse)
- 3 new API endpoints; new /reconciliation page; same palette
  and aesthetic voice as sub-project 1

Spec is approved-section-by-section and self-reviewed.
2026-06-19 20:42:44 -06:00
Tyler 307a8d3b69 docs: add co-medicaid reference note 2026-06-19 19:49:34 -06:00
Tyler 8c12e3c81a docs: add x12 naming reference note 2026-06-19 19:49:26 -06:00
Tyler 5927636b7b docs: add 835 reference note 2026-06-19 19:49:15 -06:00
Tyler 9fe41b7269 docs: add 837p reference note 2026-06-19 19:49:02 -06:00
Tyler d7ef35dd9a docs: add production-readiness implementation plan (33 tasks, 4 phases)
Phases:
1. Backend (T1-T10): cyclone.store module, 6 GET routes, NDJSON streaming,
   parse persistence, uvicorn 127.0.0.1 bind, full test suite run
2. Frontend (T11-T27): react-query wiring, 5 new UI primitives (Skeleton,
   EmptyState, ErrorState, FilterChips, Pagination), Layout-level refetch
   indicator, 5 page refactors (Claims, Remittances, Providers, ActivityLog,
   Upload), 6 hooks, 3 keyframes, api.test.ts
3. Docs (T28-T32): 4 reference notes (837p, 835, x12naming, co-medicaid),
   root README rewrite
4. Smoke (T33): end-to-end manual test with full acceptance checklist

Self-review included at end of plan (spec coverage table + placeholder
scan + type consistency check).

For agentic workers: superpowers:subagent-driven-development (recommended)
or superpowers:executing-plans.
2026-06-19 18:43:17 -06:00
Tyler 078de28cc4 docs: add live-data UX section + aesthetic acceptance checks
- Replace 7.6 (skeleton) with hairline + scanline-shimmer design that
  matches the existing precision-instrument voice (Cabinet Grotesk + Geist
  Mono, true-black + electric-blue, hairline chrome, radial light + grain)
- Add 7.7 Live-data UX patterns: skeleton variants, EmptyState primitive,
  ErrorState primitive, Layout-level refetch indicator, Active filter chips,
  newly-streamed row highlight, status color alignment, pagination footer
- Add 13.1 visual / aesthetic acceptance checks
- Voice decision: stay the course — additive only, no new accent / typeface /
  layout primitive / light theme
2026-06-19 18:36:39 -06:00
Tyler 9e34f22cb3 docs: add production-readiness design spec (local-only, sub-project 1 of 4) 2026-06-19 18:31:40 -06:00
Cyclone 5ed59ef01a Add 837P parser implementation plan
- 12 tasks: project skeleton, exceptions, segments, models, payer config,
  fixtures, validator, parser orchestrator, CO fixture, writer, CLI, README
- TDD throughout; each task has 4-6 bite-sized steps with full code
- Optional prodfile smoke test (skipped if docs/prodfiles absent)
- Self-review checklist confirms full spec coverage
2026-06-19 15:12:04 -06:00
Cyclone d9dc8a86bd Add 837P parser design spec
- Approved design for the Python 837P parser module under backend/
- Pydantic v2, click CLI, structural + CO Medicaid validation
- One JSON file per claim, summary.json, continue-on-failure
- Includes .gitignore for the Python + Node stack
2026-06-19 15:07:52 -06:00