Skip to content

CODEX TASK 9

You are Cedric on gpt-6-astra (high reasoning), worker #1, pass 9 v2: MIGRATION proof of concept. Revised after the plan reviews. Astra (Cedric/OpenAI) and Carbon (Gemini) both returned PROCEED-WITH-FIXES; Fable's findings are appended below if present. Run AFTER passes 8 and 10 are committed. Follow docs/ANDREW-STYLE-GUIDE.md. Fallback tag: demo-safe-3. Synthetic data only.

Story (Innovare's roadmap): Allscripts → Ottehr/Oystehr → their own EMR. We prove ONE path rigorously, and describe the rest honestly.

SCOPE (narrowed: do ONLY this, and make it bulletproof)

Core path: fixtures → in-house clinical store (SQLite, EF Core) → independent read-back → reconcile → identical risk flags. It must be idempotent, resumable and fail-closed.

Secondary, only after the core passes: - fixtures → localehr (HAPI, FHIR transaction sink, loopback only) - an OystehrFhirSink exercised ONLY through mocked-HTTP guard/dry-run tests

CUT: - --from operational - live Oystehr writes - a new SQL Server container - API Sink:Mode hot-swapping - new cdktn resources (describe the target IaC in docs instead) - a live migration endpoint in the UI

Data model: the "illustrative in-house clinical store" (never call it a full EMR)

  • InHouseStoreDbContext (SQLite file inhouse-store.db) with its own migrations.
  • Use an emr_ table prefix on SQLite. Apply HasDefaultSchema("emr") only when the provider is SQL Server, and document this. Don't imply SQL Server validation from SQLite tests.
  • Entities: Patient, Encounter, AllergyIntolerance, Immunization, Observation (with an explicit ObservationComponent child for BP systolic/diastolic), Condition, MedicationRequest (named honestly; don't call it Medication), IntakeAnswer.
  • Normalized columns carry the clinically relevant fields: (system, code, display), value + unit + precision, effective vs recorded dates as DateTimeOffset or DateOnly per FHIR precision, status/verificationStatus, and Patient/Encounter FKs.
  • Also keep OriginalFhirJson + ContentSha256 (the preserved source) in a separate emr_source_payload table.
  • ID crosswalk emr_id_map: UNIQUE (SourceEndpoint, ResourceType, SourceId) → TargetId, plus SourceVersion, ContentSha256, MapperVersion, RunId.
  • Never auto-merge patients. Flag identifier collisions / possible duplicates for review.
  • migration_run and migration_checkpoint tables.

Migration mechanics

  1. Manifest first: export an IMMUTABLE manifest of the source: resource type, id, versionId, ContentSha256 and dependency refs. A resume is bound to the manifest hash + target + mapper version; a mismatched resume FAILS.
  2. Topological order: Patient → Encounter → everything else.
  3. Resolve relative, absolute and fullUrl references. Preserve #contained.
  4. Unresolved or unsupported references → REJECT (counted and listed), never silently dropped.
  5. Skip-if-unchanged: if the crosswalk has the same SourceVersion + ContentSha256, write NOTHING. Run #2 must report created=0, updated=0, unchanged=N, and must not bump any target version (HAPI: no PUT for unchanged).
  6. Report created / updated / unchanged / rejected / conflicted.
  7. HAPI updates use If-Match/ETag and fail on conflict.
  8. Transactional chunks (in-house): the target rows + crosswalk + checkpoint commit in ONE transaction per chunk. ChangeTracker.Clear() per chunk, AutoDetectChanges off.
  9. Remote sinks: persist intent, and resolve uncertain outcomes by read-back before any replay.
  10. CLI: migrate --from fixtures --to <inhouse|localehr|oystehr> [--dry-run] [--apply] [--resume]
  11. --dry-run ALWAYS means zero target mutations, including schema and checkpoint writes; only local reports are written.
  12. Local SQLite and loopback HAPI (host must be localhost/127.0.0.1/::1, else refuse) are written without --apply.
  13. Any non-loopback endpoint (Oystehr) requires --apply AND OYSTEHR_SEED_CONFIRM=I_OWN_THIS_PROJECT AND a disposable project flag. Otherwise dry-run.
  14. Contradictory flags → error. NEVER run Oystehr apply yourself.

Reconciliation (independent, fail-closed)

  • Read back from the COMMITTED target via InHouseStoreSource (normalized emr_* columns only, NOT OriginalFhirJson) and, for HAPI, a FHIR read.
  • Compare against independently specified expectations from the source:
  • counts by type
  • per-record field checks: (system, code, version), value/unit/precision, effective vs recorded date and offset/precision, status/verification, null vs absent
  • referential integrity (zero orphan FKs, Patient/Encounter linkage)
  • an unmapped_elements list (extensions/modifierExtensions/fields not modeled)
  • duplicate-patient warnings
  • Risk-flag parity with a frozen evaluation date and rule version (never-impute preserved): RiskEngine over source vs over the read-back store → identical, per patient.
  • NEGATIVE tests are REQUIRED. A dropped field, an altered unit and a broken reference must each make the report FAIL with a nonzero exit code.
  • Reports (docs/migration-report-*.md/json) are REDACTED: counts, synthetic resource ids, hashes and flag codes/counts only. No names, DOBs, free text, URLs or headers. No secrets in logs.

Tests (required)

  • fixtures→inhouse→reconcile: PASS, flags identical
  • run #2: 0 writes
  • crash BEFORE commit and crash AFTER commit / before checkpoint: both resume correctly with no dupes and no loss
  • a mismatched manifest resume fails
  • the three negative tests fail closed
  • dry-run makes zero mutations
  • loopback guard
  • Oystehr guard tests (mocked HTTP)
  • crosswalk uniqueness
  • unresolved reference rejected

Docs: docs/MIGRATION.md (Andrew reads this; plain + technical)

  • The 3-hop story, with an honest boundary: "the PoC proves fixtures → illustrative in-house store with verified fidelity; Allscripts export and the Oystehr hop are not executed tonight".
  • Field coverage/loss matrix.
  • Tools in their lanes:
  • EF migrations = deterministic target DDL + constraints (not ETL)
  • CLI + manifest + checkpoints = repeatable ETL + reconciliation
  • Aspire = a reproducible local rehearsal stack with telemetry
  • cdktn = repeatable Azure target provisioning (synth-only here, not deployment or cutover)
  • OLTP vs OLAP: the in-house store = the system of record replacing Oystehr (hop 3); the DuckDB lakehouse stays the analytics plane across all hops.
  • "Outside this FHIR demonstration; requires separate migration or reimplementation":
  • auth/users (reprovision)
  • consent directives + enforcement
  • documents/attachments + access controls (a separate blob pipeline)
  • scheduling
  • billing/claims/coverage/AR run-out
  • open orders/ePrescribing
  • terminology catalogs and local Allscripts codes
  • provenance/history
  • immutable audit (AuditEvent archival)
  • operational config
  • Zambdas (port + retest)

For each: export access, destination and validation. - Cutover runbook, labeled UNEXECUTED: 1. write freeze or change capture 2. final delta 3. reconciliation gate 4. clinical acceptance 5. writer ownership 6. rollback limits for post-cutover writes - At scale: staging tables + SqlBulkCopy + MERGE at 10M+ rows. - What I'd say if asked.

UI

A READ-ONLY "Migration" page over the generated migration-report.json snapshot: the 3-hop diagram, the verified-core numbers, and the PLANNED labels on unexecuted hops. Plus an e2e assert.

DONE

  • dotnet build (0 warnings)
  • dotnet test
  • npm test
  • npm run build:snapshot
  • npm run e2e
  • REAL runs: migrate --from fixtures --to inhouse (twice; the second run 0 writes), a resume-after-crash demo, and migrate --from fixtures --to localehr (if HAPI available)

Paste the outputs and redacted reports into VERIFY.md "Pass 9 (migration v2)". Commit per item with git -c user.name="Andrew Jones" -c user.email="andrewjonesdev1@gmail.com" commit and the Co-Authored-By trailers for Cedric (Codex) and Claude Opus 5.5. Push.

ADDED (Andrew, 2026-11-12, 9:25 PM): "And the migration pattern for them, don't forget." Same bar as pass 11

The migration is Innovare's roadmap, so it is held to EXACTLY the pass-11 quality bar. It becomes column D in docs/QUALITY-MATRIX.md, and the CI check fails if any D cell is empty. - Tests: NUnit + Moq. - Use AutoFixture/Bogus only for non-clinical rows: manifest entries, crosswalk rows, checkpoints. - Use the Synthea + Ottehr fixtures for clinical content. - Stryker.NET mutate scope: - the FHIR→emr_* mapper - crosswalk lookup/upsert - skip-if-unchanged - manifest hash/resume binding - the reconciliation comparers

Set break > 0 and assert mutants > 0. The three required negative tests (dropped field, altered unit, broken reference) must be among the tests that kill the mutants. - Contract tests: - the manifest JSON and the migration-report JSON are pinned to a captured real run, with an origin comment - the HAPI transaction-bundle response is pinned to a captured response from the local HAPI - Semgrep + gitleaks cover the migration code. The redaction tests prove that reports never contain names, DOBs, free text, URLs or headers. - CI: a migration job runs fixtures→inhouse twice, asserts that the second run makes 0 writes, and asserts reconcile = PASS with identical flags. - Both styles, one pattern (this is the point Andrew wants made): - Innovare style (OLTP): the in-house EF Core store is the system of record. It is EF migrations + cdktn + Aspire. - SSM style (OLAP): after the migration, re-run the DuckDB lakehouse (bronze→silver→gold) READING FROM the in-house store as its source. Assert that the gold risk flags are identical to before the migration. This proves the analytics plane survives every hop: Allscripts → Oystehr → in-house, the same way SSM moved Epic data into the lake. - MIGRATION.md gets a "same pattern, both planes" section with a diagram. - Commit and push each item yourself as its check passes. Never stop to ask for a review chair; the council gates the merge.

ADDED: Fable plan review (claude-fable-5-1, PROCEED-WITH-FIXES). Items not already covered above, all MANDATORY

  1. Reverse-map reconciliation (Fable Critical #10). A checksum of mapper output vs mapper output proves determinism, not correctness.
  2. Add an in-house → FHIR reverse mapper.
  3. Canonicalize both sides: strip meta/text, sort keys, UTC instant + precision, parse→serialize, never string equality.
  4. Compare against the source.
  5. Feed the reverse-mapped FHIR into the SAME Way 1 RiskEngine path for flag parity. One engine, no third adapter.
  6. Negative control in the report (Critical #11). Flip one A1c value and null one field in the target. The report must list exactly those diffs, and flag parity must break. Show this as "negative control: PASS (caught 2/2)" in the redacted report.
  7. HAPI chunking (Critical #2). Chunk by PATIENT SUBGRAPH: Patient + all dependents in one transaction Bundle. Use deterministic order (patient id, type, id). Checkpoint = last completed patient. Chunking by type breaks referential integrity on write.
  8. HAPI ids (High #3). HAPI rejects purely numeric client ids on PUT by default. Prefix them src-<id> (or assert they are alphanumeric) and record the mapping in emr_id_map.
  9. Partial-failure policy (High #6).
  10. Stop on the first failure by default; --continue-on-error opts out.
  11. Failed ids + error class go in migration_run, with a nonzero exit.
  12. The report lists the failed ids.
  13. Crash tests use an injected IFailureInjector through DI.
  14. Unresolved external refs (Medium #9). Practitioner, Organization and Location are not modeled: keep them as SourceRef text with a nullable FK, and count them in the report. Never silently drop them.
  15. Reports (Low #14). Each run writes to artifacts/migration/. Commit ONE canonical redacted copy under docs/. Every report has a "SYNTHETIC DATA" banner.
  16. Not-migrated list (High #15). Add to MIGRATION.md, each with owner + plan:
  17. Task/Communication
  18. Questionnaire DEFINITIONS + versioning (answers migrate, the questionnaire does not)
  19. Practitioner/Organization/Location reference data
  20. Oystehr RBAC roles/policies + app configs
  21. Subscriptions/webhooks
  22. lab, eRx and HL7v2 interfaces
  23. telehealth
  24. AuditEvent + resource history (retention obligation; archived read-only, not migrated)
  25. DocumentReference/Binary + Z3 buckets: "none in the synthetic set; the real set will have them"
  26. Honesty (High #16). The Allscripts hop is NOT demonstrated; the fixtures stand in. The real source is the Allscripts Unity API or a C-CDA export behind the same IFhirSource contract. Say so in MIGRATION.md and the UI.
  27. "What I'd say if asked" additions (Medium #19):
    • delta/CDC after the initial load (--since _lastUpdated, documented, not built)
    • why not FHIR Bulk $export (the right tool at scale; NDJSON into the same manifest)
    • batch size vs transaction limits
    • Sqlite ignores the emr schema
  28. Oystehr guard (High #23).
    • The confirm must be OYSTEHR_SEED_CONFIRM=I_OWN_THIS_PROJECT:<projectId> matching the configured project id.
    • Test: --apply without a matching confirm exits nonzero, and the fake HTTP handler saw 0 requests.
    • Oystehr READS are env-gated too.
  29. Hygiene (Medium #24).
    • Redact the Authorization header in HttpClient logging.
    • The idmap/checkpoint store ids + hashes only, never payloads.
    • Test that no OYSTEHR_* values appear in committed appsettings.