Repository navigation
feat(migration,cli): invariant-aware ref routing (M4) + self-edge support - #404
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughRef-declared invariants are now validated and treated as routing requirements: commands resolve ref invariants, compute effectiveRequired = ref.invariants − marker.invariants, call an invariant-aware pathfinder that returns ok|unreachable|unsatisfiable, and surface new errors/result fields carrying required/satisfied/missing invariants and per-edge invariant metadata. Changes
Sequence DiagramsequenceDiagram
actor User
participant CLI
participant MigrationGraph
participant PathFinder
participant Database
participant Marker
User->>CLI: migration apply --ref <name>
CLI->>MigrationGraph: load ref entry (target hash, declared invariants)
CLI->>MigrationGraph: collectDeclaredInvariants + validate declared exist
alt unknown invariant
MigrationGraph-->>CLI: errorUnknownInvariant
CLI-->>User: fail (MIGRATION.UNKNOWN_INVARIANT)
else known invariants
CLI->>Database: read marker (storageHash, marker.invariants)
Database-->>CLI: marker state
Note over CLI: effectiveRequired = declared − marker.invariants
CLI->>PathFinder: findPathWithDecision(from, to, { required: effectiveRequired })
alt unsatisfiable
PathFinder-->>CLI: unsatisfiable (missing + structuralPath)
CLI-->>User: fail (MIGRATION.NO_INVARIANT_PATH)
else unreachable
PathFinder-->>CLI: unreachable
CLI-->>User: fail (structural unreachable)
else ok
PathFinder-->>CLI: ok (selectedPath with satisfiedInvariants)
CLI->>Database: apply migrations (plan.providedInvariants forwarded)
Database-->>CLI: operations complete
CLI->>Marker: upsert marker unioning satisfied invariants (unless true no-op)
Marker-->>CLI: marker updated / unchanged
CLI-->>User: success (includes invariant metadata)
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-telemetry
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts (1)
656-697:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon’t declare the ref “up to date” before invariant routing runs.
This block derives
summaryandMIGRATION.UP_TO_DATEfrom structural pending edges only. If the marker is already at the ref hash buteffectiveRequiredis still non-empty, the laterfindPathWithDecision()call can legitimately select a self-edge/data path while Lines 661 and 690-696 still reportAt ref ... target/UP_TO_DATE.Also applies to: 699-740
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts` around lines 656 - 697, The summary and diagnostics currently mark the DB/ref as "up to date" based only on pendingCount and marker/contract equality; update the conditions that set summary (in the mode === 'online' branch where markerHash, contractHash, pendingCount, summarizeRefDistance are used) and the diagnostics push for 'MIGRATION.UP_TO_DATE' so they also require that effectiveRequired is empty (or that findPathWithDecision() would not require any non-self/data edges) before declaring up-to-date; specifically, when computing summary and when pushing 'MIGRATION.UP_TO_DATE', check effectiveRequired (or the result of findPathWithDecision()) and avoid the up-to-date messages if effectiveRequired has entries (even if markerHash === contractHash or pendingCount === 0).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 713-720: The call to findPathWithDecision in migration-status.ts
uses the old parameter order; update the invocation to pass effectiveRequired
(required) before activeRefName (refName) and ensure when markerHash is
undefined you route from EMPTY_CONTRACT_HASH (i.e., call
findPathWithDecision(graph, EMPTY_CONTRACT_HASH, targetHash, effectiveRequired,
activeRefName) or the equivalent new-ordered signature) so online DB runs with
no marker still follow invariant routing; adjust the conditional that determines
the source hash to use EMPTY_CONTRACT_HASH when markerHash is undefined before
calling findPathWithDecision.
In `@packages/1-framework/3-tooling/migration/test/migration-graph.test.ts`:
- Around line 479-485: The tests call findPathWithDecision(graph, 'H1', 'H2',
'production') using the old fourth-parameter position for refName; update calls
to the new signature findPathWithDecision(graph, from, to, required, refName) by
inserting the required argument (e.g., true/false or the intended value) as the
fourth parameter and move 'production' to the fifth position; apply this change
for the invocation at the shown block and the other listed call sites (lines
referenced in the review) so that all calls to findPathWithDecision use the new
parameter order.
---
Outside diff comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 656-697: The summary and diagnostics currently mark the DB/ref as
"up to date" based only on pendingCount and marker/contract equality; update the
conditions that set summary (in the mode === 'online' branch where markerHash,
contractHash, pendingCount, summarizeRefDistance are used) and the diagnostics
push for 'MIGRATION.UP_TO_DATE' so they also require that effectiveRequired is
empty (or that findPathWithDecision() would not require any non-self/data edges)
before declaring up-to-date; specifically, when computing summary and when
pushing 'MIGRATION.UP_TO_DATE', check effectiveRequired (or the result of
findPathWithDecision()) and avoid the up-to-date messages if effectiveRequired
has entries (even if markerHash === contractHash or pendingCount === 0).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 85d90825-cd75-4119-bcee-873dae4d5c10
⛔ Files ignored due to path filters (1)
projects/graph-based-migrations/specs/invariant-aware-routing.spec.mdis excluded by!projects/**
📒 Files selected for processing (23)
packages/1-framework/3-tooling/cli/src/commands/migration-apply.tspackages/1-framework/3-tooling/cli/src/commands/migration-new.tspackages/1-framework/3-tooling/cli/src/commands/migration-status.tspackages/1-framework/3-tooling/cli/src/utils/command-helpers.tspackages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.tspackages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.tspackages/1-framework/3-tooling/cli/test/output.json-shapes.test.tspackages/1-framework/3-tooling/cli/test/utils/command-helpers.test.tspackages/1-framework/3-tooling/migration/src/errors.tspackages/1-framework/3-tooling/migration/src/exports/errors.tspackages/1-framework/3-tooling/migration/src/migration-graph.tspackages/1-framework/3-tooling/migration/test/errors.test.tspackages/1-framework/3-tooling/migration/test/migration-graph.test.tspackages/2-sql/9-family/src/core/migrations/types.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-runner.tspackages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.tspackages/3-targets/3-targets/postgres/src/core/migrations/runner.tspackages/3-targets/3-targets/sqlite/src/core/migrations/runner.tspackages/3-targets/6-adapters/postgres/test/migrations/runner.basic.integration.test.tspackages/3-targets/6-adapters/postgres/test/migrations/runner.idempotency.integration.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/runner.idempotency.test.tstest/integration/test/cli-journeys/invariant-routing.e2e.test.tstest/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts
💤 Files with no reviewable changes (3)
- packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
- packages/3-targets/6-adapters/postgres/test/migrations/runner.basic.integration.test.ts
- packages/2-sql/9-family/src/core/migrations/types.ts
Addresses three findings from the PR #404 code review: - Route from EMPTY_CONTRACT_HASH when no marker is present (parity with migration-apply). Previously online-mode status with no marker yet silently skipped invariant routing — UNSATISFIABLE refs against a fresh DB couldn't be previewed. - F06: in offline mode, leave appliedInvariants and missingInvariants undefined instead of presenting the empty intersection as the authoritative answer. The renderer surfaces "(unknown — connect a database to evaluate)" so users aren't misled into thinking the marker has nothing. - F07: requiredInvariants is now always present on MigrationStatusResult (default []), matching the D9 convention that PathDecision already follows. Knowable from the ref alone, computable offline. JSON-shape snapshots updated. appliedInvariants and missingInvariants remain optional — absent in offline mode is the signal that they are genuinely unknown, not zero.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
packages/1-framework/3-tooling/cli/test/output.json-shapes.test.ts (1)
166-188: ⚡ Quick winPin
appliedInvariantsandmissingInvariantsin the status shape test too.This updated fixture only exercises
requiredInvariants, so a regression that drops either of the new marker-derived arrays frommigration status --jsonwould still pass. Since this file is here to lock the wire contract, it’s worth adding one online sample that includes both keys.Suggested fix
const result: MigrationStatusResult = { ok: true, mode: 'online', migrations: [], markerHash: 'sha256:marker', @@ summary: 'At ref "production" target', diagnostics: [], requiredInvariants: [], + appliedInvariants: [], + missingInvariants: [], };[ + "appliedInvariants", "contractHash", "diagnostics", "markerHash", + "missingInvariants", "migrations", "mode", "ok", "pathDecision", "refs",🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/test/output.json-shapes.test.ts` around lines 166 - 188, The test fixture for MigrationStatusResult ('matches expected keys in online mode with refs') omits the marker-derived arrays appliedInvariants and missingInvariants, allowing regressions to drop those keys; update the result object used in that test (the MigrationStatusResult literal) to include both appliedInvariants and missingInvariants (populate as appropriate, e.g. empty arrays or representative values) so the JSON shape asserts both keys are present when running migration status --json.test/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts (1)
450-455: ⚡ Quick winUse
aggregate()here instead offind().This adds a new Mongo read via
find()even though the repo rule is to standardize onaggregate()for Mongo query execution. Keeping the journey on the same command surface avoids baking a forbidden pattern into new tests.Suggested fix
const users = await client .db(dbName) .collection('users') - .find({}, { projection: { _id: 0, email: 1, name: 1 } }) - .sort({ email: 1 }) + .aggregate([ + { $project: { _id: 0, email: 1, name: 1 } }, + { $sort: { email: 1 } }, + ]) .toArray();As per coding guidelines, "MongoDB: Use
aggregateinstead of obsoletefind/findOnecommands".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts` around lines 450 - 455, Replace the .find(...) call with an equivalent .aggregate(...) pipeline to follow the repo rule; specifically, where you call client.db(dbName).collection('users').find({}, { projection: { _id: 0, email: 1, name: 1 } }).sort({ email: 1 }).toArray(), change it to client.db(dbName).collection('users').aggregate([...]) using a pipeline with a $project stage that selects _id:0, email:1, name:1 and a $sort stage on email, then call .toArray() on the aggregation cursor so the resulting users variable remains the same.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 683-690: The current logic can fall through to
MIGRATION.UP_TO_DATE when a requested ref is unreachable; call out and handle
the unreachable result from findPathWithDecision/summarizeRefDistance before
treating pendingCount === 0 as "up to date." Specifically, when activeRefHash is
provided, detect the unreachable outcome (check the decision.kind from
findPathWithDecision or detect the "No path between..." case returned by
summarizeRefDistance) and set summary to that unreachable message (or the
summarizeRefDistance result) instead of allowing the code path that sets
MIGRATION.UP_TO_DATE; ensure the branches that use summarizeRefDistance (and
variables activeRefHash, markerHash, pendingCount, hasInvariantWork) do not fall
through to the up-to-date branch when the ref is unreachable.
In `@packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts`:
- Around line 178-190: The no-op detection is broken because
applyValue.operationsExecuted is incremented for every data transform that
returns ok—even when it was self-skipped—so isSelfEdgeNoOp incorrectly sees
nonzero operationsExecuted; update the logic so operationsExecuted only counts
transforms that actually ran (not the skip paths). Concretely: change
applyPlan()/executeDataTransform() so executeDataTransform returns or propagates
an explicit "executed" boolean (or an enum like executed/skipped) for each
transform, and increment applyValue.operationsExecuted only when executed ===
true; then isSelfEdgeNoOp (which uses applyValue.operationsExecuted,
deriveProvidedInvariants, incomingInvariants, existingMarker, and isSelfEdge)
will correctly detect true no-op re-applies and skip marker/ledger writes.
---
Nitpick comments:
In `@packages/1-framework/3-tooling/cli/test/output.json-shapes.test.ts`:
- Around line 166-188: The test fixture for MigrationStatusResult ('matches
expected keys in online mode with refs') omits the marker-derived arrays
appliedInvariants and missingInvariants, allowing regressions to drop those
keys; update the result object used in that test (the MigrationStatusResult
literal) to include both appliedInvariants and missingInvariants (populate as
appropriate, e.g. empty arrays or representative values) so the JSON shape
asserts both keys are present when running migration status --json.
In `@test/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts`:
- Around line 450-455: Replace the .find(...) call with an equivalent
.aggregate(...) pipeline to follow the repo rule; specifically, where you call
client.db(dbName).collection('users').find({}, { projection: { _id: 0, email: 1,
name: 1 } }).sort({ email: 1 }).toArray(), change it to
client.db(dbName).collection('users').aggregate([...]) using a pipeline with a
$project stage that selects _id:0, email:1, name:1 and a $sort stage on email,
then call .toArray() on the aggregation cursor so the resulting users variable
remains the same.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: ea3747f0-8ebf-4048-8baf-defecfe470ed
⛔ Files ignored due to path filters (1)
projects/graph-based-migrations/specs/invariant-aware-routing.spec.mdis excluded by!projects/**
📒 Files selected for processing (6)
packages/1-framework/3-tooling/cli/src/commands/migration-status.tspackages/1-framework/3-tooling/cli/test/output.json-shapes.test.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-runner.tspackages/3-targets/3-targets/postgres/src/core/migrations/runner.tstest/integration/test/cli-journeys/invariant-routing.e2e.test.tstest/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
wmadden
left a comment
There was a problem hiding this comment.
Local code review (comment-only)
Generated review artifacts on the branch under projects/graph-based-migrations/specs/reviews/pr-404/ — three files: walkthrough.md, system-design-review.md, code-review.md. Per-line comments below summarize each finding; the full code-review doc has full context, code samples, and acceptance-criteria verification.
Material items
- F23 (correctness) —
UNKNOWN_INVARIANTpre-check rejects ids the marker has already satisfied. Spec's marker-monotonicity guarantee implies markers can carry ids whose defining migrations have been pruned; current code fails loudly in that case. Local fix; needs a test for the retired-but-applied case. Comments onmigration-apply.tsL206–220 andmigration-status.tsL461–475. - F24 (architecture) — Runners re-derive
providedInvariantsfromplan.operationsin three places. Canonical, signed, verified value already lives onpkg.metadata.providedInvariants. Surface it onMigrationApplyStep, drop the three derivations. Comments on each runner; full discussion onpostgres/runner.tsL184.
Findings posted as line comments
F01 (mapping helper), F03 (Mongo no-op divergence comment), F07 (invariant quoting + tree-view test gap, F22), F09 (positional args), F10 (misleading comment), F12 (stateKey separator), F13 (status data flow), F17 (test cast), F19 (partial-coverage error message test), F23, F24.
Findings in this body (no clean diff anchor)
- F02 —
migration-apply.tsL142–169 reads contract envelope only when--refis absent; the asymmetry could collapse toconst destinationHash = refEntry?.hash ?? (await readContractEnvelope(config)).storageHash;. Cosmetic. - F04 —
MigrationStatusResult.appliedInvariants/missingInvariantsare conditional onmode === 'online'but the type doesn't enforce co-presence (only JSDoc says so). Tighten to a discriminated union or document explicitly. - F05 —
MigrationStatusResult.appliedInvariantsis intersected withrequiredInvariantsfor display. Per spec. JSON consumers have no field for "all marker invariants" — worth a JSDoc note. - F06 —
marker?.invariants ?? []is fine butmarker ? marker.invariants : []is one less type-narrow chain. Minor. - F08 —
NoInvariantPathStructuralEdgeis exported fromexports/errors.tsAND surfaces in JSON envelopes viameta.structuralPath. Worth a stability note in the type's JSDoc and a shape-pinning test. - F11 —
migration-status.tsimportsMigrationPlanOperationbut the file may not use it directly (it usespkg.opssummaries). Verify and drop if unused. - F14 —
migration-apply.tspendingMigrationsarray build (L361–373) can use.map(...)oncebundleByDir.get(...)lookup is factored. Minor. - F15 —
findPathWithDecisiontieBreakReasonsonly fires when the chosen edge is the first sorted candidate. Worth a unit test asserting the tieBreakReasons populate for the non-first case. - F16 — Mongo runner:
incomingInvariants = deriveProvidedInvariants(options.plan.operations)runs beforedeserializeMongoOps. Fine today (derivation readsinvariantIdfrom a structural property), but worth confirming the ordering is intentional. Subsumed by F24 fix. - F18 —
migration-status.tsJSON output destructures with underscore-prefixed names (_g,_b,_es,_arh,_arn,_d) at L819–824. Cryptic. Either expand to readable names or add a one-line comment. - F20 — Mongo journey doesn't cover self-edge end-to-end. Postgres Journey S exists; Mongo parity would close the gap. Not blocking; routing logic is target-agnostic.
- F21 — F8 (no behavior change without
--ref) is structurally enforced byfindPathWithInvariants(graph, f, t, new Set()) === findPath(graph, f, t), but the plan asks for a snapshot regression guard against fixtures from before this work. Not found in the diff.
AC verification highlights
- 10 PASS, 0 FAIL, 1 NOT VERIFIED (F21), 3 WEAK (F22 tree view, F23 unknown-invariant pre-check, F23 re-apply for retired ids).
- Full table in
code-review.md§Acceptance-criteria verification.
Architecture / docs (system-design-review)
- ADR work intentionally absent per spec §"Close-out (M5)" — expected.
- S1–S6 are documentation/follow-up; S7 = F23, S8 = F24. See
system-design-review.md.
| if (activeRefEntry && activeRefEntry.invariants.length > 0) { | ||
| const declared = collectDeclaredInvariants(graph); | ||
| const unknown = activeRefEntry.invariants.filter((id) => !declared.has(id)); | ||
| if (unknown.length > 0) { | ||
| return notOk( | ||
| mapMigrationToolsError( | ||
| errorUnknownInvariant({ | ||
| ...ifDefined('refName', activeRefName), | ||
| unknown, | ||
| declared: [...declared].sort(), | ||
| }), | ||
| ), | ||
| ); | ||
| } | ||
| } |
There was a problem hiding this comment.
F23 (status) — same UNKNOWN_INVARIANT issue as apply
This pre-check runs at line 461–475, before client.readMarker() at line 537. After the fix, the marker invariants need to factor into "known". Status --offline has no marker — the simplest rule is: skip the pre-check offline (or document that offline is graph-strict and may produce false UNKNOWN_INVARIANT for retired-but-applied ids).
See full discussion on migration-apply.ts L206–220.
| // writes so an idempotent re-apply of a self-edge data transform | ||
| // doesn't churn updatedAt or pile up empty ledger entries. db update | ||
| // no-ops still write a ledger entry as audit trail. | ||
| const incomingInvariants = deriveProvidedInvariants(options.plan.operations); |
There was a problem hiding this comment.
F24 — sqlite copy of the re-derivation. After surfacing providedInvariants on MigrationApplyStep, this becomes const incomingInvariants = options.plan.providedInvariants; and the deriveProvidedInvariants import goes away. See full discussion on postgres/runner.ts L184.
| // Sort + dedupe so the initMarker path writes a stable initial value. | ||
| // updateMarker merges server-side, so no client-side union is needed. | ||
| const incomingInvariants = Array.from(new Set(options.invariants ?? [])).sort(); | ||
| const incomingInvariants = deriveProvidedInvariants(options.plan.operations); |
There was a problem hiding this comment.
F24 — mongo copy of the re-derivation. After surfacing providedInvariants on MigrationApplyStep, this becomes const incomingInvariants = options.plan.providedInvariants; and the deriveProvidedInvariants import goes away. See full discussion on postgres/runner.ts L184.
| export interface NoInvariantPathStructuralEdge { | ||
| readonly dirName: string; | ||
| readonly migrationHash: string; | ||
| readonly from: string; | ||
| readonly to: string; | ||
| readonly invariants: readonly string[]; | ||
| } | ||
|
|
||
| export function errorNoInvariantPath(args: { | ||
| readonly refName?: string; | ||
| readonly required: readonly string[]; | ||
| readonly missing: readonly string[]; | ||
| readonly structuralPath: readonly NoInvariantPathStructuralEdge[]; | ||
| }): MigrationToolsError { | ||
| const { refName, required, missing, structuralPath } = args; | ||
| const refClause = refName ? `Ref "${refName}"` : 'Target'; | ||
| const missingList = missing.map((id) => JSON.stringify(id)).join(', '); | ||
| const requiredList = required.map((id) => JSON.stringify(id)).join(', '); | ||
| return new MigrationToolsError( | ||
| 'MIGRATION.NO_INVARIANT_PATH', | ||
| 'No path covers the required invariants', | ||
| { | ||
| why: `${refClause} requires invariants the reachable path doesn't cover. required=[${requiredList}], missing=[${missingList}].`, | ||
| fix: 'Add a migration on the path that runs `dataTransform({ invariantId: "<id>", … })` for each missing invariant, or retarget the ref to a hash whose path already provides them.', | ||
| details: { | ||
| required, | ||
| missing, | ||
| structuralPath, | ||
| ...ifDefined('refName', refName), | ||
| }, | ||
| }, | ||
| ); | ||
| } |
There was a problem hiding this comment.
F19 — errorNoInvariantPath's why message format is not tested for partial coverage
errors.test.ts covers: all four required ids missing, none missing. The interesting case — some required satisfied, others missing — isn't pinned. The why message includes both required and missing lists; a future change that swaps phrasing might silently regress the partial-coverage rendering.
Add a test where required = ["a", "b", "c"] and missing = ["c"], asserting the why mentions both lists distinctly.
Addresses three findings from the PR #404 code review: - Route from EMPTY_CONTRACT_HASH when no marker is present (parity with migration-apply). Previously online-mode status with no marker yet silently skipped invariant routing — UNSATISFIABLE refs against a fresh DB couldn't be previewed. - F06: in offline mode, leave appliedInvariants and missingInvariants undefined instead of presenting the empty intersection as the authoritative answer. The renderer surfaces "(unknown — connect a database to evaluate)" so users aren't misled into thinking the marker has nothing. - F07: requiredInvariants is now always present on MigrationStatusResult (default []), matching the D9 convention that PathDecision already follows. Knowable from the ref alone, computable offline. JSON-shape snapshots updated. appliedInvariants and missingInvariants remain optional — absent in offline mode is the signal that they are genuinely unknown, not zero.
14b877d to
2cb4fe7
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts (1)
715-731:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon’t emit
MIGRATION.UP_TO_DATEwhen the ref target is unreachable.The summary path already reports
No path between database marker and ref ..., but this code still ignoresoutcome.kind === 'unreachable'. In that casependingCount === 0andhasInvariantWork === false, sostatus --jsoncan still carry aMIGRATION.UP_TO_DATEdiagnostic even though the selected ref is unreachable from the current marker.Suggested fix
+ let refTargetUnreachable = false; let pathDecision: MigrationStatusResult['pathDecision']; if (mode === 'online') { const originHash = markerHash ?? EMPTY_CONTRACT_HASH; const outcome = findPathWithDecision( graph, @@ if (outcome.kind === 'ok') { pathDecision = toPathDecisionResult(outcome.decision); + } else if (outcome.kind === 'unreachable') { + refTargetUnreachable = true; } else if (outcome.kind === 'unsatisfiable') { return notOk( mapMigrationToolsError( errorNoInvariantPath({ @@ - } else { + } else if (!refTargetUnreachable) { diagnostics.push({ code: 'MIGRATION.UP_TO_DATE', severity: 'info', message: 'Database is up to date', hints: [], }); }Also applies to: 734-763
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts` around lines 715 - 731, The code currently emits a 'MIGRATION.UP_TO_DATE' diagnostic when pendingCount === 0 and hasInvariantWork === false even if the migration outcome is unreachable; update the condition that pushes the 'MIGRATION.UP_TO_DATE' diagnostic (and the analogous block around lines 734-763) to also require outcome.kind !== 'unreachable' (or check outcome.kind === 'reachable') before pushing that diagnostic, i.e., locate the branch that uses pendingCount and hasInvariantWork and add an additional guard against outcome.kind === 'unreachable' so unreachable refs never yield an UP_TO_DATE diagnostic.packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts (1)
109-110:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winQuote invariant ids in the
provides [...]suffix.Joining raw ids here makes the label ambiguous as soon as an invariant id contains a comma, bracket, or quote, and it no longer matches the JSON-quoted formatting used by the invariant error envelopes. Rendering each id with
JSON.stringify()keeps the human graph unambiguous.Suggested fix
- const invariantsSuffix = - entry.invariants.length > 0 ? ` provides [${entry.invariants.join(', ')}]` : ''; + const invariantsSuffix = + entry.invariants.length > 0 + ? ` provides [${entry.invariants.map((id) => JSON.stringify(id)).join(', ')}]` + : '';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts` around lines 109 - 110, The current invariantsSuffix construction uses entry.invariants.join(', ') which can produce ambiguous labels when ids contain commas, brackets, or quotes; change the logic that builds invariantsSuffix (the variable invariantsSuffix in graph-migration-mapper.ts) to map each id through JSON.stringify before joining (e.g. entry.invariants.map(id => JSON.stringify(id)).join(', ')) so each invariant id is quoted/escaped consistently with the JSON-quoted invariant error envelopes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 734-763: The display/render logic still uses the structural path
from findPath/resolveDisplayChain/deriveEdgeStatuses/migrationGraphToRenderInput
instead of the invariant-aware route computed by findPathWithDecision; update
the code that computes the visible chain and edge statuses to prefer
outcome.decision.selectedPath (from findPathWithDecision) when present (i.e.
when pathDecision/outcome.kind === 'ok'), by passing that selectedPath into
resolveDisplayChain (or replacing the earlier findPath result) and then into
deriveEdgeStatuses/migrationGraphToRenderInput so the JSON, tree/✓/⧗ markers,
and rendered subgraph reflect the exact route that migration apply will execute.
---
Duplicate comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 715-731: The code currently emits a 'MIGRATION.UP_TO_DATE'
diagnostic when pendingCount === 0 and hasInvariantWork === false even if the
migration outcome is unreachable; update the condition that pushes the
'MIGRATION.UP_TO_DATE' diagnostic (and the analogous block around lines 734-763)
to also require outcome.kind !== 'unreachable' (or check outcome.kind ===
'reachable') before pushing that diagnostic, i.e., locate the branch that uses
pendingCount and hasInvariantWork and add an additional guard against
outcome.kind === 'unreachable' so unreachable refs never yield an UP_TO_DATE
diagnostic.
In
`@packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts`:
- Around line 109-110: The current invariantsSuffix construction uses
entry.invariants.join(', ') which can produce ambiguous labels when ids contain
commas, brackets, or quotes; change the logic that builds invariantsSuffix (the
variable invariantsSuffix in graph-migration-mapper.ts) to map each id through
JSON.stringify before joining (e.g. entry.invariants.map(id =>
JSON.stringify(id)).join(', ')) so each invariant id is quoted/escaped
consistently with the JSON-quoted invariant error envelopes.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: f4b5c0c6-0c91-49ed-813e-d4af32418c0a
📒 Files selected for processing (7)
packages/1-framework/3-tooling/cli/src/commands/migration-apply.tspackages/1-framework/3-tooling/cli/src/commands/migration-new.tspackages/1-framework/3-tooling/cli/src/commands/migration-status.tspackages/1-framework/3-tooling/cli/src/utils/command-helpers.tspackages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.tspackages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.tspackages/1-framework/3-tooling/cli/test/control-api/contract-emit.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/1-framework/3-tooling/cli/src/commands/migration-new.ts
- packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts
- packages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.ts
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/1-framework/3-tooling/cli/test/control-api/client.test.ts (1)
903-918:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAssert that
providedInvariantsactually reaches the runner plan.Adding the field to the fixture is good, but this test still doesn't verify the new contract: the runner mock ignores its input, so dropping
packageToStep(...).providedInvariantsorplan.providedInvariantswould still pass.🧪 Suggested assertion
+ let executedPlan: + | { readonly providedInvariants?: readonly string[] } + | undefined; + const mockTargetWithMigrations = { ...mockTarget, migrations: { @@ createRunner: () => ({ - execute: async () => ({ - ok: true, - value: { operationsPlanned: 1, operationsExecuted: 1 }, - }), + execute: async ({ plan }) => { + executedPlan = plan; + return { + ok: true, + value: { operationsPlanned: 1, operationsExecuted: 1 }, + }; + }, }), contractToSchema: () => ({}), }, } as unknown as typeof mockTarget; @@ expect(result.ok).toBe(true); + expect(executedPlan?.providedInvariants).toEqual([]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/test/control-api/client.test.ts` around lines 903 - 918, The test calls client.migrationApply with a migration fixture that includes providedInvariants, but the runner mock ignores its input so the test doesn't assert the new field actually reaches the runner plan; modify the test to assert that the runner is invoked with a plan containing providedInvariants (e.g. inspect the argument passed into the mocked runner function or packageToStep/plan object) and add an assertion that the plan.providedInvariants or packageToStep(...).providedInvariants equals the expected array from the fixture; ensure you reference the call site used by the mock (the mocked runner function invoked by migrationApply) and verify providedInvariants is forwarded unchanged.packages/1-framework/3-tooling/migration/src/migration-graph.ts (1)
382-395:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDon't report a tie-break when the invariant requirement already forced the branch.
This loop only filters alternatives by structural reachability. With
requirednon-empty, the selected edge can be the only branch that still covers a needed invariant and also happen to sort first bycompareTieBreak; in that casetieBreakReasonswill incorrectly claim "selected by tie-break" even though the invariant constraint already decided it. That makespathDecisionmisleading for CLI JSON consumers.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/migration/src/migration-graph.ts` around lines 382 - 395, The loop is currently flagging a "selected by tie-break" even when the chosen edge was the only one that satisfies the required invariants; change the logic in the for (const edge of path) block so that before pushing the tie-break message you check whether multiple reachable candidates actually satisfy the invariant requirement. Concretely, when computing reachable (from graph.forwardChain.get(edge.from) filtered by reachesTarget), also filter by the required-invariant predicate you use elsewhere (the same check that determines whether an edge covers items in required) and only treat it as a tie-break if more than one reachable candidate remains after applying that required filter; otherwise do not push the tieBreakReasons entry even if sorted[0] matched edge.migrationHash. This uses the existing variables reachable, sorted (sortedNeighbors), edge.migrationHash, reachesTarget and tieBreakReasons so you can locate and update the condition in that block.
🧹 Nitpick comments (1)
docs/architecture docs/adrs/ADR 001 - Migrations as Edges.md (1)
22-23: ⚡ Quick winKeep runner skip mechanics out of ADR 001.
These bullets pin implementation details like
operationsExecuted === 0and the exact marker/ledger skip sequence, which makes the ADR age with runner internals instead of the architectural decision itself. I’d keep the ADR at the contract-level rule and move the execution mechanics to the Migration System subsystem doc.Based on learnings: "ADRs in prisma/prisma-next should document architectural design decisions and the key constraints/assumptions only. Do not include implementation algorithms, emitter derivation logic, or step-by-step derivation/migration rules."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/architecture` docs/adrs/ADR 001 - Migrations as Edges.md around lines 22 - 23, Remove the two implementation-detail bullets ("Runner upfront skip narrowed." and "Post-hoc no-op skip (self-edge only).") from ADR 001 and replace them with a single contract-level statement summarizing the intended skip behavior at a high level (e.g., "Runners may avoid work when origin equals destination or when execution would not change system invariants; exact skip mechanics are runner-specific"). Move the detailed algorithmic mechanics that reference operationsExecuted, self-edge no-op conditions, marker/ledger write sequencing, and any runner-specific postchecks into the Migration System subsystem documentation so ADR 001 only contains the architectural decision and constraints.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/1-framework/3-tooling/cli/test/utils/command-helpers.test.ts`:
- Around line 114-142: The test never verifies the fallback because the helper
decision() always supplies requiredInvariants and satisfiedInvariants; update
the "defaults to empty arrays" test to invoke toPathDecisionResult(decision({
requiredInvariants: undefined, satisfiedInvariants: undefined })) so the helper
returns those fields as undefined and you exercise toPathDecisionResult's
defaulting logic for requiredInvariants and satisfiedInvariants; reference the
decision() helper and toPathDecisionResult() when making the change.
In `@packages/1-framework/3-tooling/migration/src/errors.ts`:
- Around line 155-160: The diagnostic message emitted by reconstructGraph() for
migrations where from === to incorrectly states "with no operations" and "the
migration is a no-op"; update the wording in the reemitHint call (the message
constructed around dirName, dir, and hash) to clarify that the error occurs when
there are no data-transform (data-class) ops rather than no operations at all,
and instruct users to add a dataTransform op, change the contract so from ≠ to,
or delete the directory; keep the existing reemitHint usage and context but
replace the misleading phrases so the hint accurately reflects the absence of
data-class ops rather than a complete lack of operations.
---
Outside diff comments:
In `@packages/1-framework/3-tooling/cli/test/control-api/client.test.ts`:
- Around line 903-918: The test calls client.migrationApply with a migration
fixture that includes providedInvariants, but the runner mock ignores its input
so the test doesn't assert the new field actually reaches the runner plan;
modify the test to assert that the runner is invoked with a plan containing
providedInvariants (e.g. inspect the argument passed into the mocked runner
function or packageToStep/plan object) and add an assertion that the
plan.providedInvariants or packageToStep(...).providedInvariants equals the
expected array from the fixture; ensure you reference the call site used by the
mock (the mocked runner function invoked by migrationApply) and verify
providedInvariants is forwarded unchanged.
In `@packages/1-framework/3-tooling/migration/src/migration-graph.ts`:
- Around line 382-395: The loop is currently flagging a "selected by tie-break"
even when the chosen edge was the only one that satisfies the required
invariants; change the logic in the for (const edge of path) block so that
before pushing the tie-break message you check whether multiple reachable
candidates actually satisfy the invariant requirement. Concretely, when
computing reachable (from graph.forwardChain.get(edge.from) filtered by
reachesTarget), also filter by the required-invariant predicate you use
elsewhere (the same check that determines whether an edge covers items in
required) and only treat it as a tie-break if more than one reachable candidate
remains after applying that required filter; otherwise do not push the
tieBreakReasons entry even if sorted[0] matched edge.migrationHash. This uses
the existing variables reachable, sorted (sortedNeighbors), edge.migrationHash,
reachesTarget and tieBreakReasons so you can locate and update the condition in
that block.
---
Nitpick comments:
In `@docs/architecture` docs/adrs/ADR 001 - Migrations as Edges.md:
- Around line 22-23: Remove the two implementation-detail bullets ("Runner
upfront skip narrowed." and "Post-hoc no-op skip (self-edge only).") from ADR
001 and replace them with a single contract-level statement summarizing the
intended skip behavior at a high level (e.g., "Runners may avoid work when
origin equals destination or when execution would not change system invariants;
exact skip mechanics are runner-specific"). Move the detailed algorithmic
mechanics that reference operationsExecuted, self-edge no-op conditions,
marker/ledger write sequencing, and any runner-specific postchecks into the
Migration System subsystem documentation so ADR 001 only contains the
architectural decision and constraints.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 681a602b-c08b-4d46-b315-6ff78e27220a
⛔ Files ignored due to path filters (3)
projects/graph-based-migrations/plans/invariant-aware-routing-plan.mdis excluded by!projects/**projects/graph-based-migrations/specs/data-migrations-spec.mdis excluded by!projects/**projects/graph-based-migrations/specs/invariant-aware-routing.spec.mdis excluded by!projects/**
📒 Files selected for processing (23)
docs/architecture docs/adrs/ADR 001 - Migrations as Edges.mddocs/architecture docs/adrs/ADR 208 - Invariant-aware migration routing.mdpackages/1-framework/1-core/framework-components/src/control/control-migration-types.tspackages/1-framework/3-tooling/cli/src/commands/migration-apply.tspackages/1-framework/3-tooling/cli/src/commands/migration-status.tspackages/1-framework/3-tooling/cli/src/control-api/operations/migration-apply.tspackages/1-framework/3-tooling/cli/src/control-api/types.tspackages/1-framework/3-tooling/cli/src/utils/command-helpers.tspackages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.tspackages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.tspackages/1-framework/3-tooling/cli/test/control-api/client.test.tspackages/1-framework/3-tooling/cli/test/output.json-shapes.test.tspackages/1-framework/3-tooling/cli/test/utils/command-helpers.test.tspackages/1-framework/3-tooling/cli/test/utils/formatters/graph-migration-mapper.test.tspackages/1-framework/3-tooling/migration/src/errors.tspackages/1-framework/3-tooling/migration/src/migration-graph.tspackages/1-framework/3-tooling/migration/test/errors.test.tspackages/1-framework/3-tooling/migration/test/migration-graph.test.tspackages/2-sql/9-family/src/core/migrations/types.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-runner.tspackages/3-targets/3-targets/postgres/src/core/migrations/runner.tspackages/3-targets/3-targets/sqlite/src/core/migrations/runner.tstest/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts
✅ Files skipped from review due to trivial changes (2)
- packages/1-framework/3-tooling/cli/test/utils/formatters/graph-migration-mapper.test.ts
- docs/architecture docs/adrs/ADR 208 - Invariant-aware migration routing.md
🚧 Files skipped from review as they are similar to previous changes (6)
- packages/3-targets/3-targets/sqlite/src/core/migrations/runner.ts
- packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
- packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts
- packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts
- packages/1-framework/3-tooling/cli/test/output.json-shapes.test.ts
- packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
…lock Project 1 scope
Promotes cipherstash-extension and middleware-param-transform from standalone
projects into the cipherstash-integration umbrella, and adds two new task
specs covering the PSL constructor surface and migration factories.
Project 1 scope is locked end-to-end-tested: EncryptedString only (3 argument
shapes, nullable + non-nullable), eq + ilike operators, EQL bundle install via
databaseDependencies.init, hand-authored migration.ts using rawSql({...}) for
EQL search-config installation. Other column types (Number/Date/Boolean/Json),
other operator families (orderAndRange, searchableJson), and planner-driven
per-column DDL are deferred to Project 2.
Key design corrections vs the prior drafts:
- Codec descriptor uses post-#402 RuntimeParameterizedCodecDescriptor<P> with
arktype-validated params (mirrors pgvector's length plumbing).
- PSL surface is namespaced constructors (cipherstash.EncryptedString(...)),
not attribute form (@cipherstash.encrypted(...)) — attributes can't couple
legal arguments to the field's scalar type at the grammar level.
- Migration factories ride on the pre-existing Postgres rawSql({...}) escape
hatch with operationClass: 'additive', not DataTransformOperation. PR #404
is therefore an indirect (Project-2-only) dependency, not Project 1.
…herstash, narrow sql-raw-factory to public surface Add raw-sql-ast-node task spec under cipherstash-integration: defines RawSqlExpr as a new AnyQueryAst arm, the Postgres lowerer arm, and a planFromAst envelope helper. Cipherstash owns the AST node so the migration-factories spec can build DataTransformOperations without depending on the parallel sql-raw-factory project's user-facing template-literal factory. Rewrite migration-factories spec accordingly: factories now produce DataTransformOperation entries carrying invariantIds (per PR #404) rather than rawSql({...}) additive ops. Each entry's run() builds a SqlQueryPlan with a RawSqlExpr ast via the package-internal API, parameterizing all four arguments to eql_v2.add_search_config so user table/column inputs flow through ParamRefs rather than text-inlined. Narrow sql-raw-factory spec to its actual scope: the public raw\`...\` template-literal factory layered on top of the AST node (RawArg type union, identifier(...) escape hatch, type-level rejection of bare values, param() ergonomic re-export). Hard upstream dependency on the AST node existing — which it will, because cipherstash-integration ships it. sql-raw-factory now consumes that work rather than owning it. Update umbrella status table and References to reflect: raw-sql-ast-node joins as a Project 1 task; sql-raw-factory moves from "Direct, upstream sequencing" dependency to "Downstream consumer (not a dependency)".
… with high-level plan Restructure the cipherstash-integration project from a single-spec layout into a three-component umbrella: - project-1/: searchable-encryption MVP (the previous umbrella spec rescoped as Project 1, plus its 5 task specs moved under specs/) - project-2/: planner-driven DDL + expanded surface (new stub) - sql-raw-factory/: public raw\`...\` template-literal factory (moved from projects/sql-raw-factory/) New artifacts at the umbrella level: - spec.md: scope of the umbrella, why three components, cross-component design decisions (RawSqlExpr ownership, DataTransformOperation choice, end-to-end-tested-only scope), in-flight framework dependency status (PRs #400/#402 merged 2026-05-01; #404/#409 still open). - plan.md: component-level sequencing. Phase A is Project 1 (critical path, gated externally on #404 + #409); phase B is sql-raw-factory and Project 2 in parallel afterwards, each with its own gating story (sql-raw-factory blocks on Project 1's RawSqlExpr AST node landing; Project 2 blocks on Project 1 + TML-2338 + TML-2339). Project 1's spec is reframed: drop "this is the umbrella" language, add a header pointing to the new umbrella, repath all relative references for the new directory depth (3-up from project-1/, 4-up from project-1/specs/, 3-up from sql-raw-factory/). Resolve the previously- open question about Project 2's on-disk slug. No content changes to the per-task specs beyond reference repaths.
…e-slice milestones project-1/plan.md sequences Project 1 as five end-to-end-demoable milestones rather than one-milestone-per-task-spec: - M1: framework SPI (raw-sql-ast-node + middleware-param-transform; no user-facing surface yet, but the seams unblock other extensions) - M2: store-only round-trip (psl + envelope-codec storage path; encrypted column type works for storage; no operators yet) - M3: eq operator + manual addSearchConfig migration (first searchable round-trip end-to-end against live EQL) - M4: ilike + activatePendingSearches + decryptAll (completes Project 1's user-facing surface; all UMB ACs green) - M5: close-out per projects/README.md lifecycle Records that Project 1 is independent of both open framework PRs: - #404 (invariant-aware ref routing): migration factories carry invariantId fields regardless; the routing benefit is retroactive when #404 lands. - #409 (middleware intercept + contentHash): edits the same RuntimeMiddleware types but adds non-overlapping fields; whichever lands first, the other rebases mechanically. Updates the umbrella plan and spec to reflect the new posture: PRs #404 and #409 demoted from "hard gating" to "coordinate-only" / "not a dependency"; status table marks Project 1's plan as drafted.
…lock Project 1 scope
Promotes cipherstash-extension and middleware-param-transform from standalone
projects into the cipherstash-integration umbrella, and adds two new task
specs covering the PSL constructor surface and migration factories.
Project 1 scope is locked end-to-end-tested: EncryptedString only (3 argument
shapes, nullable + non-nullable), eq + ilike operators, EQL bundle install via
databaseDependencies.init, hand-authored migration.ts using rawSql({...}) for
EQL search-config installation. Other column types (Number/Date/Boolean/Json),
other operator families (orderAndRange, searchableJson), and planner-driven
per-column DDL are deferred to Project 2.
Key design corrections vs the prior drafts:
- Codec descriptor uses post-#402 RuntimeParameterizedCodecDescriptor<P> with
arktype-validated params (mirrors pgvector's length plumbing).
- PSL surface is namespaced constructors (cipherstash.EncryptedString(...)),
not attribute form (@cipherstash.encrypted(...)) — attributes can't couple
legal arguments to the field's scalar type at the grammar level.
- Migration factories ride on the pre-existing Postgres rawSql({...}) escape
hatch with operationClass: 'additive', not DataTransformOperation. PR #404
is therefore an indirect (Project-2-only) dependency, not Project 1.
…herstash, narrow sql-raw-factory to public surface Add raw-sql-ast-node task spec under cipherstash-integration: defines RawSqlExpr as a new AnyQueryAst arm, the Postgres lowerer arm, and a planFromAst envelope helper. Cipherstash owns the AST node so the migration-factories spec can build DataTransformOperations without depending on the parallel sql-raw-factory project's user-facing template-literal factory. Rewrite migration-factories spec accordingly: factories now produce DataTransformOperation entries carrying invariantIds (per PR #404) rather than rawSql({...}) additive ops. Each entry's run() builds a SqlQueryPlan with a RawSqlExpr ast via the package-internal API, parameterizing all four arguments to eql_v2.add_search_config so user table/column inputs flow through ParamRefs rather than text-inlined. Narrow sql-raw-factory spec to its actual scope: the public raw\`...\` template-literal factory layered on top of the AST node (RawArg type union, identifier(...) escape hatch, type-level rejection of bare values, param() ergonomic re-export). Hard upstream dependency on the AST node existing — which it will, because cipherstash-integration ships it. sql-raw-factory now consumes that work rather than owning it. Update umbrella status table and References to reflect: raw-sql-ast-node joins as a Project 1 task; sql-raw-factory moves from "Direct, upstream sequencing" dependency to "Downstream consumer (not a dependency)".
… with high-level plan Restructure the cipherstash-integration project from a single-spec layout into a three-component umbrella: - project-1/: searchable-encryption MVP (the previous umbrella spec rescoped as Project 1, plus its 5 task specs moved under specs/) - project-2/: planner-driven DDL + expanded surface (new stub) - sql-raw-factory/: public raw\`...\` template-literal factory (moved from projects/sql-raw-factory/) New artifacts at the umbrella level: - spec.md: scope of the umbrella, why three components, cross-component design decisions (RawSqlExpr ownership, DataTransformOperation choice, end-to-end-tested-only scope), in-flight framework dependency status (PRs #400/#402 merged 2026-05-01; #404/#409 still open). - plan.md: component-level sequencing. Phase A is Project 1 (critical path, gated externally on #404 + #409); phase B is sql-raw-factory and Project 2 in parallel afterwards, each with its own gating story (sql-raw-factory blocks on Project 1's RawSqlExpr AST node landing; Project 2 blocks on Project 1 + TML-2338 + TML-2339). Project 1's spec is reframed: drop "this is the umbrella" language, add a header pointing to the new umbrella, repath all relative references for the new directory depth (3-up from project-1/, 4-up from project-1/specs/, 3-up from sql-raw-factory/). Resolve the previously- open question about Project 2's on-disk slug. No content changes to the per-task specs beyond reference repaths.
…e-slice milestones project-1/plan.md sequences Project 1 as five end-to-end-demoable milestones rather than one-milestone-per-task-spec: - M1: framework SPI (raw-sql-ast-node + middleware-param-transform; no user-facing surface yet, but the seams unblock other extensions) - M2: store-only round-trip (psl + envelope-codec storage path; encrypted column type works for storage; no operators yet) - M3: eq operator + manual addSearchConfig migration (first searchable round-trip end-to-end against live EQL) - M4: ilike + activatePendingSearches + decryptAll (completes Project 1's user-facing surface; all UMB ACs green) - M5: close-out per projects/README.md lifecycle Records that Project 1 is independent of both open framework PRs: - #404 (invariant-aware ref routing): migration factories carry invariantId fields regardless; the routing benefit is retroactive when #404 lands. - #409 (middleware intercept + contentHash): edits the same RuntimeMiddleware types but adds non-overlapping fields; whichever lands first, the other rebases mechanically. Updates the umbrella plan and spec to reflect the new posture: PRs #404 and #409 demoted from "hard gating" to "coordinate-only" / "not a dependency"; status table marks Project 1's plan as drafted.
… test (F01–F03) ADR 208: document plan-envelope threading of providedInvariants; refresh AC-A06 evidence and AC-M05 verification note; align decision record and problem framing. ADR 001: scope post-hoc self-edge noop predicate vs data-op execution counting (matches postgres runner TODO). CLI test: pin apply --ref success JSON (exit 0, Already up to date, migrationsApplied 0) for marker-only retired invariant case. Refs: PR #404 reviewer findings F01–F03.
…lock Project 1 scope
Promotes cipherstash-extension and middleware-param-transform from standalone
projects into the cipherstash-integration umbrella, and adds two new task
specs covering the PSL constructor surface and migration factories.
Project 1 scope is locked end-to-end-tested: EncryptedString only (3 argument
shapes, nullable + non-nullable), eq + ilike operators, EQL bundle install via
databaseDependencies.init, hand-authored migration.ts using rawSql({...}) for
EQL search-config installation. Other column types (Number/Date/Boolean/Json),
other operator families (orderAndRange, searchableJson), and planner-driven
per-column DDL are deferred to Project 2.
Key design corrections vs the prior drafts:
- Codec descriptor uses post-#402 RuntimeParameterizedCodecDescriptor<P> with
arktype-validated params (mirrors pgvector's length plumbing).
- PSL surface is namespaced constructors (cipherstash.EncryptedString(...)),
not attribute form (@cipherstash.encrypted(...)) — attributes can't couple
legal arguments to the field's scalar type at the grammar level.
- Migration factories ride on the pre-existing Postgres rawSql({...}) escape
hatch with operationClass: 'additive', not DataTransformOperation. PR #404
is therefore an indirect (Project-2-only) dependency, not Project 1.
…herstash, narrow sql-raw-factory to public surface Add raw-sql-ast-node task spec under cipherstash-integration: defines RawSqlExpr as a new AnyQueryAst arm, the Postgres lowerer arm, and a planFromAst envelope helper. Cipherstash owns the AST node so the migration-factories spec can build DataTransformOperations without depending on the parallel sql-raw-factory project's user-facing template-literal factory. Rewrite migration-factories spec accordingly: factories now produce DataTransformOperation entries carrying invariantIds (per PR #404) rather than rawSql({...}) additive ops. Each entry's run() builds a SqlQueryPlan with a RawSqlExpr ast via the package-internal API, parameterizing all four arguments to eql_v2.add_search_config so user table/column inputs flow through ParamRefs rather than text-inlined. Narrow sql-raw-factory spec to its actual scope: the public raw\`...\` template-literal factory layered on top of the AST node (RawArg type union, identifier(...) escape hatch, type-level rejection of bare values, param() ergonomic re-export). Hard upstream dependency on the AST node existing — which it will, because cipherstash-integration ships it. sql-raw-factory now consumes that work rather than owning it. Update umbrella status table and References to reflect: raw-sql-ast-node joins as a Project 1 task; sql-raw-factory moves from "Direct, upstream sequencing" dependency to "Downstream consumer (not a dependency)".
… with high-level plan Restructure the cipherstash-integration project from a single-spec layout into a three-component umbrella: - project-1/: searchable-encryption MVP (the previous umbrella spec rescoped as Project 1, plus its 5 task specs moved under specs/) - project-2/: planner-driven DDL + expanded surface (new stub) - sql-raw-factory/: public raw\`...\` template-literal factory (moved from projects/sql-raw-factory/) New artifacts at the umbrella level: - spec.md: scope of the umbrella, why three components, cross-component design decisions (RawSqlExpr ownership, DataTransformOperation choice, end-to-end-tested-only scope), in-flight framework dependency status (PRs #400/#402 merged 2026-05-01; #404/#409 still open). - plan.md: component-level sequencing. Phase A is Project 1 (critical path, gated externally on #404 + #409); phase B is sql-raw-factory and Project 2 in parallel afterwards, each with its own gating story (sql-raw-factory blocks on Project 1's RawSqlExpr AST node landing; Project 2 blocks on Project 1 + TML-2338 + TML-2339). Project 1's spec is reframed: drop "this is the umbrella" language, add a header pointing to the new umbrella, repath all relative references for the new directory depth (3-up from project-1/, 4-up from project-1/specs/, 3-up from sql-raw-factory/). Resolve the previously- open question about Project 2's on-disk slug. No content changes to the per-task specs beyond reference repaths.
…e-slice milestones project-1/plan.md sequences Project 1 as five end-to-end-demoable milestones rather than one-milestone-per-task-spec: - M1: framework SPI (raw-sql-ast-node + middleware-param-transform; no user-facing surface yet, but the seams unblock other extensions) - M2: store-only round-trip (psl + envelope-codec storage path; encrypted column type works for storage; no operators yet) - M3: eq operator + manual addSearchConfig migration (first searchable round-trip end-to-end against live EQL) - M4: ilike + activatePendingSearches + decryptAll (completes Project 1's user-facing surface; all UMB ACs green) - M5: close-out per projects/README.md lifecycle Records that Project 1 is independent of both open framework PRs: - #404 (invariant-aware ref routing): migration factories carry invariantId fields regardless; the routing benefit is retroactive when #404 lands. - #409 (middleware intercept + contentHash): edits the same RuntimeMiddleware types but adds non-overlapping fields; whichever lands first, the other rebases mechanically. Updates the umbrella plan and spec to reflect the new posture: PRs #404 and #409 demoted from "hard gating" to "coordinate-only" / "not a dependency"; status table marks Project 1's plan as drafted.
…lock Project 1 scope
Promotes cipherstash-extension and middleware-param-transform from standalone
projects into the cipherstash-integration umbrella, and adds two new task
specs covering the PSL constructor surface and migration factories.
Project 1 scope is locked end-to-end-tested: EncryptedString only (3 argument
shapes, nullable + non-nullable), eq + ilike operators, EQL bundle install via
databaseDependencies.init, hand-authored migration.ts using rawSql({...}) for
EQL search-config installation. Other column types (Number/Date/Boolean/Json),
other operator families (orderAndRange, searchableJson), and planner-driven
per-column DDL are deferred to Project 2.
Key design corrections vs the prior drafts:
- Codec descriptor uses post-#402 RuntimeParameterizedCodecDescriptor<P> with
arktype-validated params (mirrors pgvector's length plumbing).
- PSL surface is namespaced constructors (cipherstash.EncryptedString(...)),
not attribute form (@cipherstash.encrypted(...)) — attributes can't couple
legal arguments to the field's scalar type at the grammar level.
- Migration factories ride on the pre-existing Postgres rawSql({...}) escape
hatch with operationClass: 'additive', not DataTransformOperation. PR #404
is therefore an indirect (Project-2-only) dependency, not Project 1.
…herstash, narrow sql-raw-factory to public surface Add raw-sql-ast-node task spec under cipherstash-integration: defines RawSqlExpr as a new AnyQueryAst arm, the Postgres lowerer arm, and a planFromAst envelope helper. Cipherstash owns the AST node so the migration-factories spec can build DataTransformOperations without depending on the parallel sql-raw-factory project's user-facing template-literal factory. Rewrite migration-factories spec accordingly: factories now produce DataTransformOperation entries carrying invariantIds (per PR #404) rather than rawSql({...}) additive ops. Each entry's run() builds a SqlQueryPlan with a RawSqlExpr ast via the package-internal API, parameterizing all four arguments to eql_v2.add_search_config so user table/column inputs flow through ParamRefs rather than text-inlined. Narrow sql-raw-factory spec to its actual scope: the public raw\`...\` template-literal factory layered on top of the AST node (RawArg type union, identifier(...) escape hatch, type-level rejection of bare values, param() ergonomic re-export). Hard upstream dependency on the AST node existing — which it will, because cipherstash-integration ships it. sql-raw-factory now consumes that work rather than owning it. Update umbrella status table and References to reflect: raw-sql-ast-node joins as a Project 1 task; sql-raw-factory moves from "Direct, upstream sequencing" dependency to "Downstream consumer (not a dependency)".
… with high-level plan Restructure the cipherstash-integration project from a single-spec layout into a three-component umbrella: - project-1/: searchable-encryption MVP (the previous umbrella spec rescoped as Project 1, plus its 5 task specs moved under specs/) - project-2/: planner-driven DDL + expanded surface (new stub) - sql-raw-factory/: public raw\`...\` template-literal factory (moved from projects/sql-raw-factory/) New artifacts at the umbrella level: - spec.md: scope of the umbrella, why three components, cross-component design decisions (RawSqlExpr ownership, DataTransformOperation choice, end-to-end-tested-only scope), in-flight framework dependency status (PRs #400/#402 merged 2026-05-01; #404/#409 still open). - plan.md: component-level sequencing. Phase A is Project 1 (critical path, gated externally on #404 + #409); phase B is sql-raw-factory and Project 2 in parallel afterwards, each with its own gating story (sql-raw-factory blocks on Project 1's RawSqlExpr AST node landing; Project 2 blocks on Project 1 + TML-2338 + TML-2339). Project 1's spec is reframed: drop "this is the umbrella" language, add a header pointing to the new umbrella, repath all relative references for the new directory depth (3-up from project-1/, 4-up from project-1/specs/, 3-up from sql-raw-factory/). Resolve the previously- open question about Project 2's on-disk slug. No content changes to the per-task specs beyond reference repaths.
…e-slice milestones project-1/plan.md sequences Project 1 as five end-to-end-demoable milestones rather than one-milestone-per-task-spec: - M1: framework SPI (raw-sql-ast-node + middleware-param-transform; no user-facing surface yet, but the seams unblock other extensions) - M2: store-only round-trip (psl + envelope-codec storage path; encrypted column type works for storage; no operators yet) - M3: eq operator + manual addSearchConfig migration (first searchable round-trip end-to-end against live EQL) - M4: ilike + activatePendingSearches + decryptAll (completes Project 1's user-facing surface; all UMB ACs green) - M5: close-out per projects/README.md lifecycle Records that Project 1 is independent of both open framework PRs: - #404 (invariant-aware ref routing): migration factories carry invariantId fields regardless; the routing benefit is retroactive when #404 lands. - #409 (middleware intercept + contentHash): edits the same RuntimeMiddleware types but adds non-overlapping fields; whichever lands first, the other rebases mechanically. Updates the umbrella plan and spec to reflect the new posture: PRs #404 and #409 demoted from "hard gating" to "coordinate-only" / "not a dependency"; status table marks Project 1's plan as drafted.
Wires `migration apply --ref` and `migration status --ref` through
the M3 invariant-aware pathfinder. The CLI now subtracts already-applied
invariants from `ref.invariants` before routing, so re-applying a ref
after the marker has accumulated some invariants doesn't spuriously fail.
Unknown invariant ids in a ref fail loudly before any DB activity, and
reachable-but-unsatisfiable targets emit a structured `NO_INVARIANT_PATH`
error with the structural fallback path attached for diagnosis.
Pathfinder surface: `findPathWithDecision` now returns a discriminated
`FindPathOutcome` (`ok` / `unreachable` / `unsatisfiable`) so callers
don't re-derive structural reachability. `PathDecision` always carries
`requiredInvariants` and `satisfiedInvariants`. The `unsatisfiable` arm
also carries the per-edge structural path and the `missing` set —
correctly accounting for partial coverage when the structural path
provides some required invariants.
Runner threading: `MigrationApplyStep.invariants` and the framework-level
`MigrationRunner.execute({ invariants })` field flow `manifest.providedInvariants`
through to the runner so the marker write unions atomically per applied edge.
Status surface: required / applied / missing rows render alongside the
existing `ref` header (D12 mode annotation), edge labels in the dagre
graph view gain `provides [X, Y]` for invariant-bearing migrations,
and the JSON envelope ships all four invariant sets plus per-edge
`invariants` on `selectedPath` entries.
Closes the M4 milestone of the invariant-aware-routing project.
Three journey tests against a real PGlite database that exercise the M4 routing surface end-to-end: - Happy path: plans a planner-emitted NOT-NULL backfill dataTransform, patches the scaffold to inject `invariantId`, sets a ref requiring the same id, runs `migration apply --ref` and verifies the data was backfilled, the marker accumulated the invariant, and a re-apply is a noop (marker subtraction empties `effectiveRequired`). - UNKNOWN_INVARIANT: a ref declares an id no migration provides. Both `apply --ref` and `status --ref` exit 1 with the structured error before any DB activity; verified by reading the marker through `status` (without --ref so the pre-check doesn't fire) and confirming it didn't advance. - NO_INVARIANT_PATH: a divergent graph where INVARIANT_ID is declared on branch A but the ref points at branch B. Apply fails with MIGRATION.NO_INVARIANT_PATH, the error envelope carries the structural path, and the off-branch edge correctly reports `invariants: []`. Lives alongside the existing journey tests under `test/cli-journeys/` and runs through the journey vitest config.
Three journeys against MongoMemoryReplSet that mirror the Postgres
invariant-routing journey, smoke-testing that the family-neutral
routing surface (CLI commands, pathfinder, error wiring) works
identically against a Mongo runner with the aggregation-pipeline
marker merge:
- Happy path: hand-author a migration with `dataTransform({ invariantId,
check, run })` that lowercases user names. Ref requires the invariant.
Apply succeeds, the actual data is lowercased, marker.invariants
accumulates server-side via $setUnion, and re-apply is a noop.
- UNKNOWN_INVARIANT: ref names a typo id; apply and status both exit 1
before any DB write (verified by reading the marker through status
without --ref).
- NO_INVARIANT_PATH: divergent graph (branch A declares the invariant,
branch B doesn't); ref points at branch B, apply fails with the
structured error and structuralPath populated.
Demonstrates the routing layer is genuinely target-agnostic — the test
file is a near-mechanical translation of the SQL version, with only
target-specific bits (MongoMemoryReplSet harness, hand-authored
migration template using mongo-query-ast Raw* commands) differing.
…n tie-break loop The R6 fix that gated `tieBreakReasons` on the invariant-viable pool left three `noNonNullAssertion` lint warnings (`path[i]!`, `coveragePrefixes[i]!`, `sortedViable[0]!`) that failed the migration-tools lint job in CI. Refactor the loop to use `path.entries()` for the edge (eliminates `path[i]!`), add an explicit `prefixSet === undefined` continue for `coveragePrefixes[i]` (provably unreachable since `coveragePrefixes` is built one-per-edge from `path`, but the guard keeps the type narrowed without an assertion), and switch `sortedViable[0]!.migrationHash` to `?.migrationHash` (provably equivalent because the surrounding `sortedViable.length > 1` precondition makes the optional chain resolve identically). Behavior preserved: the same edges produce the same `tieBreakReasons` and `alternativeCount`. The control flow is flattened with `continue` guards, which is the cleaner shape for this kind of multi-stage filter.
…t ids
Wmadden's existing test for the F07 quoting fix covers the common case
(ASCII-clean ids like 'users.email-unique'), where the format change
from `provides [a, b]` to `provides ["a", "b"]` is purely cosmetic.
The case the quoting actually defends against — ids that contain
punctuation — is unpinned: an id like 'weird,id' would render as
`provides [weird,id]` (ambiguous) without `JSON.stringify`, and
`["weird,id"]` (unambiguous) with it. validateInvariantId rejects
whitespace + ASCII control chars but does not forbid commas, brackets,
or quotes, so this is reachable from authored migrations.
Adds a focused test for two such ids ('weird,id', 'has"quote') asserting
the exact escaped output, alongside wmadden's common-case test. Ported
from the local backup branch on `b1b04d3c8`.
The data-migrations parent spec and its plan were the last remaining files in projects/graph-based-migrations/. With TML-2283 closing on PR #404 merge, neither has an open workstream consuming them: the routing slice is owned by ADR 208, the conceptual model lives in ADR 176, and the data-transform authoring + planner-positioning theory text has no live consumer. The umbrella folder retires entirely.
…lock Project 1 scope
Promotes cipherstash-extension and middleware-param-transform from standalone
projects into the cipherstash-integration umbrella, and adds two new task
specs covering the PSL constructor surface and migration factories.
Project 1 scope is locked end-to-end-tested: EncryptedString only (3 argument
shapes, nullable + non-nullable), eq + ilike operators, EQL bundle install via
databaseDependencies.init, hand-authored migration.ts using rawSql({...}) for
EQL search-config installation. Other column types (Number/Date/Boolean/Json),
other operator families (orderAndRange, searchableJson), and planner-driven
per-column DDL are deferred to Project 2.
Key design corrections vs the prior drafts:
- Codec descriptor uses post-#402 RuntimeParameterizedCodecDescriptor<P> with
arktype-validated params (mirrors pgvector's length plumbing).
- PSL surface is namespaced constructors (cipherstash.EncryptedString(...)),
not attribute form (@cipherstash.encrypted(...)) — attributes can't couple
legal arguments to the field's scalar type at the grammar level.
- Migration factories ride on the pre-existing Postgres rawSql({...}) escape
hatch with operationClass: 'additive', not DataTransformOperation. PR #404
is therefore an indirect (Project-2-only) dependency, not Project 1.
…herstash, narrow sql-raw-factory to public surface Add raw-sql-ast-node task spec under cipherstash-integration: defines RawSqlExpr as a new AnyQueryAst arm, the Postgres lowerer arm, and a planFromAst envelope helper. Cipherstash owns the AST node so the migration-factories spec can build DataTransformOperations without depending on the parallel sql-raw-factory project's user-facing template-literal factory. Rewrite migration-factories spec accordingly: factories now produce DataTransformOperation entries carrying invariantIds (per PR #404) rather than rawSql({...}) additive ops. Each entry's run() builds a SqlQueryPlan with a RawSqlExpr ast via the package-internal API, parameterizing all four arguments to eql_v2.add_search_config so user table/column inputs flow through ParamRefs rather than text-inlined. Narrow sql-raw-factory spec to its actual scope: the public raw\`...\` template-literal factory layered on top of the AST node (RawArg type union, identifier(...) escape hatch, type-level rejection of bare values, param() ergonomic re-export). Hard upstream dependency on the AST node existing — which it will, because cipherstash-integration ships it. sql-raw-factory now consumes that work rather than owning it. Update umbrella status table and References to reflect: raw-sql-ast-node joins as a Project 1 task; sql-raw-factory moves from "Direct, upstream sequencing" dependency to "Downstream consumer (not a dependency)".
… with high-level plan Restructure the cipherstash-integration project from a single-spec layout into a three-component umbrella: - project-1/: searchable-encryption MVP (the previous umbrella spec rescoped as Project 1, plus its 5 task specs moved under specs/) - project-2/: planner-driven DDL + expanded surface (new stub) - sql-raw-factory/: public raw\`...\` template-literal factory (moved from projects/sql-raw-factory/) New artifacts at the umbrella level: - spec.md: scope of the umbrella, why three components, cross-component design decisions (RawSqlExpr ownership, DataTransformOperation choice, end-to-end-tested-only scope), in-flight framework dependency status (PRs #400/#402 merged 2026-05-01; #404/#409 still open). - plan.md: component-level sequencing. Phase A is Project 1 (critical path, gated externally on #404 + #409); phase B is sql-raw-factory and Project 2 in parallel afterwards, each with its own gating story (sql-raw-factory blocks on Project 1's RawSqlExpr AST node landing; Project 2 blocks on Project 1 + TML-2338 + TML-2339). Project 1's spec is reframed: drop "this is the umbrella" language, add a header pointing to the new umbrella, repath all relative references for the new directory depth (3-up from project-1/, 4-up from project-1/specs/, 3-up from sql-raw-factory/). Resolve the previously- open question about Project 2's on-disk slug. No content changes to the per-task specs beyond reference repaths.
…e-slice milestones project-1/plan.md sequences Project 1 as five end-to-end-demoable milestones rather than one-milestone-per-task-spec: - M1: framework SPI (raw-sql-ast-node + middleware-param-transform; no user-facing surface yet, but the seams unblock other extensions) - M2: store-only round-trip (psl + envelope-codec storage path; encrypted column type works for storage; no operators yet) - M3: eq operator + manual addSearchConfig migration (first searchable round-trip end-to-end against live EQL) - M4: ilike + activatePendingSearches + decryptAll (completes Project 1's user-facing surface; all UMB ACs green) - M5: close-out per projects/README.md lifecycle Records that Project 1 is independent of both open framework PRs: - #404 (invariant-aware ref routing): migration factories carry invariantId fields regardless; the routing benefit is retroactive when #404 lands. - #409 (middleware intercept + contentHash): edits the same RuntimeMiddleware types but adds non-overlapping fields; whichever lands first, the other rebases mechanically. Updates the umbrella plan and spec to reflect the new posture: PRs #404 and #409 demoted from "hard gating" to "coordinate-only" / "not a dependency"; status table marks Project 1's plan as drafted.
…port (#404) # Walkthrough — invariant-routing-cli (M4) closes [TML-2363](https://linear.app/prisma-company/issue/TML-2363/cli-integration-of-invariant-aware-routing-m4-of-tml-2297) part of [TML-2297](https://linear.app/prisma-company/issue/TML-2297/pn-invariant-aware-routing) ## Intent M4 of [TML-2297](https://linear.app/prisma-company/issue/TML-2297) — the CLI integration that makes invariant-aware routing user-visible. `migration apply --ref` and `migration status --ref` subtract `marker.invariants` (M1) from `ref.invariants` (M0) and route the effective set through M3's `findPathWithInvariants`. Refs that name an invariant id no migration *and* no marker has ever applied fail with `MIGRATION.UNKNOWN_INVARIANT` after `readMarker()` but before any state mutation; refs whose target is reachable but uncovered fail with `MIGRATION.NO_INVARIANT_PATH` carrying the structural fallback path. The decision surface gains `requiredInvariants` / `satisfiedInvariants`; `--json` output gains the four invariant sets and per-edge `invariants` on `selectedPath`. Status's dagre graph render annotates each edge label with `provides ["X", "Y"]` (JSON-quoted, matching the error envelope format) when relevant; a new `MIGRATION.INVARIANTS_PENDING` info diagnostic surfaces when the marker matches the structural target but is missing required ids, so status doesn't claim "up to date" while the apply path still has work to do. The design lives in two ADRs: [ADR 001 (Migrations as Edges)](../../../docs/architecture%20docs/adrs/ADR%20001%20-%20Migrations%20as%20Edges.md) — amended for the self-edge relaxation — and [ADR 208 (Invariant-aware migration routing)](../../../docs/architecture%20docs/adrs/ADR%20208%20-%20Invariant-aware%20migration%20routing.md) — new — together replacing the standalone `projects/graph-based-migrations/` spec + plan, which retire in this PR. This PR also lifts a related restriction surfaced during implementation: **self-edge migrations** (`from === to`) are now allowed when they declare at least one data op. The motivating use case is "normalise emails to lowercase" — a pure data migration with no schema diff. Without self-edge support there's no way to author one, and as soon as we tried we hit two latent bugs in the SQL runners. Both fixed; the routing surface now has end-to-end coverage for self-edges across SQL and Mongo. ## Change map - **Errors (migration-tools)**: - [packages/1-framework/3-tooling/migration/src/errors.ts (L266–L320)](../../../../../packages/1-framework/3-tooling/migration/src/errors.ts:266-320) — `errorNoInvariantPath`, `errorUnknownInvariant`, and `NoInvariantPathStructuralEdge` payload type - [packages/1-framework/3-tooling/migration/src/exports/errors.ts](../../../../../packages/1-framework/3-tooling/migration/src/exports/errors.ts) — re-export of the new constructors - **Pathfinder decision surface (migration-tools)**: - [packages/1-framework/3-tooling/migration/src/migration-graph.ts](../../../../../packages/1-framework/3-tooling/migration/src/migration-graph.ts) — `PathDecision` gains always-present `requiredInvariants` / `satisfiedInvariants`; `findPathWithDecision(graph, from, to, { refName?, required? })` (options object) returns a discriminated `FindPathOutcome` (`ok` / `unreachable` / `unsatisfiable`); the `unsatisfiable` arm carries `structuralPath` and `missing` so callers don't recompute either; `tieBreakReasons` only populates when there are multiple invariant-viable alternatives at a step - **Self-edge support (migration-tools + cli)**: - [packages/1-framework/3-tooling/migration/src/migration-graph.ts (L48–L52)](../../../../../packages/1-framework/3-tooling/migration/src/migration-graph.ts:48-52) — `reconstructGraph` narrows the `from === to` rejection to "self-edge with no data ops" - [packages/1-framework/3-tooling/migration/src/migration-graph.ts (`findPathWithInvariants`, `findPathWithDecision`)](../../../../../packages/1-framework/3-tooling/migration/src/migration-graph.ts) — drop the `from === to ⇒ unsatisfiable` early returns when `required ≠ ∅`; BFS handles self-edges naturally - [packages/1-framework/3-tooling/migration/src/errors.ts (`errorSameSourceAndTarget`)](../../../../../packages/1-framework/3-tooling/migration/src/errors.ts) — message reflects the narrowed semantic - [packages/1-framework/3-tooling/cli/src/commands/migration-new.ts](../../../../../packages/1-framework/3-tooling/cli/src/commands/migration-new.ts) — lifts the "No changes detected" rejection only when `--from` is explicit - **CLI wiring (cli)**: - [packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts](../../../../../packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts) — captures the full `RefEntry`, computes `effectiveRequired = ref.invariants − marker.invariants` after `readMarker`, runs the marker-aware `UNKNOWN_INVARIANT` pre-check (known set is `(declared) ∪ (marker.invariants)`), threads through `findPathWithDecision`, maps `unsatisfiable` to `errorNoInvariantPath`, surfaces `requiredInvariants` / `satisfiedInvariants` / per-edge `invariants` in `pathDecision` - [packages/1-framework/3-tooling/cli/src/commands/migration-status.ts](../../../../../packages/1-framework/3-tooling/cli/src/commands/migration-status.ts) — same pre-check + same effective-required computation; `MigrationStatusResult` gains `requiredInvariants` / `appliedInvariants` / `missingInvariants` (top-level, populated only when `--ref` is in play); header gains a `required` row alongside `ref`; summary block gains `applied` / `missing` rows; new `MIGRATION.INVARIANTS_PENDING` info diagnostic when marker is at target but missing required ids; suppresses `MIGRATION.UP_TO_DATE` when the marker can't reach the contract target - [packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts](../../../../../packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts) — `PathDecisionResult` shape gains `requiredInvariants` / `satisfiedInvariants` and per-edge `invariants`; new `collectDeclaredInvariants(graph)` and `toStructuralEdge(edge)` helpers used by both commands - [packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts](../../../../../packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts) — edge label gains `provides ["X", "Y"]` suffix (JSON-quoted) when invariants present - **Runner threading (framework + cli + targets)**: - [packages/1-framework/1-core/framework-components/src/control/control-migration-types.ts](../../../../../packages/1-framework/1-core/framework-components/src/control/control-migration-types.ts) — `MigrationPlan` gains `providedInvariants?: readonly string[]` so callers can carry the manifest's canonical set down to the runner - [packages/1-framework/3-tooling/cli/src/control-api/types.ts (`MigrationApplyStep`)](../../../../../packages/1-framework/3-tooling/cli/src/control-api/types.ts) — gains `providedInvariants: readonly string[]` (required at the CLI/runner boundary) - [packages/1-framework/3-tooling/cli/src/control-api/operations/migration-apply.ts](../../../../../packages/1-framework/3-tooling/cli/src/control-api/operations/migration-apply.ts) — populates `plan.providedInvariants` from `manifest.providedInvariants` before calling `runner.execute({ plan })` - [packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts](../../../../../packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts) — reads `options.plan.providedInvariants` directly; narrows the upfront skip to exclude self-edges; adds post-hoc no-op skip scoped to self-edges - [packages/3-targets/3-targets/sqlite/src/core/migrations/runner.ts](../../../../../packages/3-targets/3-targets/sqlite/src/core/migrations/runner.ts) — same three changes, mirrored - [packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts](../../../../../packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts) — same: reads from `options.plan.providedInvariants` - **Tests (evidence)**: - [packages/1-framework/3-tooling/migration/test/errors.test.ts](../../../../../packages/1-framework/3-tooling/migration/test/errors.test.ts) — new file, covers both error constructors' code/category/details/why/fix shapes, including the `errorNoInvariantPath` `why` rendering for all-missing, none-missing, and partial-coverage cases (`required = [a,b,c]`, `missing = [c]`) - [packages/1-framework/3-tooling/migration/test/migration-graph.test.ts](../../../../../packages/1-framework/3-tooling/migration/test/migration-graph.test.ts) — `findPathWithDecision` outcome cases (ok / unreachable / unsatisfiable); satisfied-invariants intersection semantics; partial-coverage `missing` correctness; self-edge graph reconstruction + pathfinder cases - [packages/1-framework/3-tooling/cli/test/utils/command-helpers.test.ts](../../../../../packages/1-framework/3-tooling/cli/test/utils/command-helpers.test.ts) — `toPathDecisionResult` slim view propagates per-edge `invariants` and the two new top-level fields - [packages/1-framework/3-tooling/cli/test/control-api/client.test.ts](../../../../../packages/1-framework/3-tooling/cli/test/control-api/client.test.ts) — runner-options threading covered indirectly (data ops carry `invariantId`, runner derives the set) - [packages/1-framework/3-tooling/cli/test/output.json-shapes.test.ts](../../../../../packages/1-framework/3-tooling/cli/test/output.json-shapes.test.ts) — JSON envelope shape pinned with the new fields and per-edge `invariants` - [packages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.ts](../../../../../packages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.ts) — new file, in-process integration tests for the `UNKNOWN_INVARIANT` pre-check: apply + status fail with the structured error on truly unknown ids; empty-required ref does not trip the check; the **retired-but-applied case** (id is on the marker but not declared in the graph) passes the pre-check and the apply is a no-op via marker subtraction - [test/integration/test/cli-journeys/invariant-routing.e2e.test.ts](../../../../../test/integration/test/cli-journeys/invariant-routing.e2e.test.ts) — new file, 6 Postgres journeys: O (happy path with marker accumulation), P (UNKNOWN_INVARIANT), Q (NO_INVARIANT_PATH on a divergent graph), R (A→B→A→B re-apply, marker.invariants monotonic across rollback), S (self-edge data migration end-to-end), T (`INVARIANTS_PENDING` surfaces when marker is at target but missing required ids) - [test/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts](../../../../../test/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts) — new file, 3 Mongo journeys mirroring the Postgres happy/UNKNOWN/NO_PATH cases against `MongoMemoryReplSet` - [packages/1-framework/3-tooling/cli/test/utils/formatters/graph-migration-mapper.test.ts](../../../../../packages/1-framework/3-tooling/cli/test/utils/formatters/graph-migration-mapper.test.ts) — pins the `provides ["X", "Y"]` JSON-quoted suffix on the dagre edge label, including the punctuation case (ids containing commas / quotes) the format defends against - [packages/3-targets/6-adapters/postgres/test/migrations/runner.idempotency.integration.test.ts](../../../../../packages/3-targets/6-adapters/postgres/test/migrations/runner.idempotency.integration.test.ts) — runner-level self-edge: ops actually execute (sentinel-table side effect); true no-op self-edge skips marker + ledger writes (`updated_at` byte-identical, ledger row count unchanged) - [packages/3-targets/6-adapters/sqlite/test/migrations/runner.idempotency.test.ts](../../../../../packages/3-targets/6-adapters/sqlite/test/migrations/runner.idempotency.test.ts) — same two SQLite tests ## The story 1. **Decision surface threads `required` end-to-end.** `findPathWithDecision(graph, from, to, { refName?, required? })` is the single integration point: every `--ref` invocation flows through it. Both options default — passing nothing yields byte-identical behaviour to today's structural routing. When `required ≠ ∅` the function delegates to M3's `findPathWithInvariants` and packages the result into a discriminated `FindPathOutcome`. `PathDecision` always carries `requiredInvariants` / `satisfiedInvariants` (default `[]`) so the JSON wire shape is stable regardless of regime. 2. **Discriminated `FindPathOutcome`.** `findPathWithDecision` returns `{ kind: 'ok', decision } | { kind: 'unreachable' } | { kind: 'unsatisfiable', structuralPath, missing }`. The pathfinder already knows which case it is, so it tells callers directly — three-way switch at the call site, no redundant structural BFS, no risk of forgetting to disambiguate. The `unsatisfiable` arm computes `missing` against the structural fallback path's edge invariants, so partial coverage (some required satisfied along the structural path, others not) is reported correctly rather than echoing the full required set. 3. **Marker subtraction is the load-bearing CLI primitive.** `effectiveRequired = ref.invariants − marker.invariants`. This single line is what makes ref-driven re-applies idempotent: once the marker has accumulated `X`, a subsequent `apply --ref` whose `ref.invariants` includes `X` doesn't insist on re-providing it. Combined with M3's empty-required equivalence, marker subtraction turns the second apply into a structural shortest-path BFS — pre-M4 routing, free. 4. **`UNKNOWN_INVARIANT` is a pre-check, not a runtime failure — and the marker contributes to the "known" set.** After `client.readMarker()` returns, both commands compute `(declared by graph) ∪ (marker.invariants)` and reject any ref id outside that union. Typos and not-yet-attested migrations still fail with a structured error and a non-zero exit, but state-mutating runner calls haven't started. The marker contribution honours the spec's "applied-at-least-once" semantic: markers can legitimately carry ids whose defining migration has been pruned/squashed, and treating those as `UNKNOWN_INVARIANT` would block re-applies the database has already fulfilled. Status applies the same check at the same severity — a misconfigured ref surfaces consistently across both commands. 5. **`NO_INVARIANT_PATH` is constructed on the pathfinder side.** When required is non-empty and `findPathWithInvariants` returns null, the pathfinder runs the structural fallback `findPath` once, computes `missing` against the structural path's edge invariants, and returns `unsatisfiable` with both pieces. Callers consume `outcome.missing` and `outcome.structuralPath` directly. The error envelope carries each structural-path edge's per-edge `invariants` so consumers can see what *is* provided, not just what isn't. 6. **Status surfaces required / applied / missing as structural rows.** `ref` and `required` go in the styled header (computable pre-DB); `applied` and `missing` follow the summary block (require the marker read). JSON output gets all four sets at the result root — `requiredInvariants`, `appliedInvariants`, `missingInvariants`, plus `pathDecision.satisfiedInvariants`. Edge labels in the dagre graph render gain a `provides ["X", "Y"]` suffix (JSON-quoted, matching the format used by `MIGRATION.NO_INVARIANT_PATH` envelopes). The "applied" vocabulary is intentional — the marker is "applied at least once", not "currently true of data". A new `MIGRATION.INVARIANTS_PENDING` info diagnostic fires when the marker matches the structural target but is missing required invariants, so status doesn't read "up to date" while the apply path still has work to do. 7. **Runners read `providedInvariants` from the plan envelope.** `MigrationPlan.providedInvariants` carries the manifest's canonical invariant set down to the runner; `MigrationApplyStep.providedInvariants` is the CLI/runner-boundary equivalent. The CLI populates both fields from `manifest.providedInvariants` before calling `runner.execute({ plan })`. The manifest is the single source of truth — `migrationHash` includes it, and the loader verifies it equal to `deriveProvidedInvariants(ops)` at read time — so runners can consume it directly without re-deriving. All three runners (postgres, sqlite, mongo) read the same field, so a fourth runner family doesn't need to import `migration-tools/invariants` to participate. 8. **Self-edges (from === to) are first-class when they declare a data op.** Not in the spec — surfaced during M4 implementation. Use case: a migration that does only `dataTransform({ invariantId, check, run })` against the current schema. `reconstructGraph` accepts the package iff at least one operation is `operationClass === 'data'`; `findPathWithInvariants` and `findPathWithDecision` lost their `from === to ⇒ unsatisfiable` early returns when `required ≠ ∅` (BFS handles self-edges naturally); `migration new` lifts its "No changes detected" rejection when `--from` is explicit (default no-flag still rejects). `findPath` keeps its `from === to ⇒ []` short-circuit because the empty path is structurally shortest. 9. **SQL runner skip semantics are self-edge-aware.** The upfront skip in `applyPlan` (`markerAtDestination && origin != null ⇒ skip ALL ops`) excludes self-edges — for `from === to` plans the marker matches destination by construction, and the data transform must still fire. A separate post-hoc skip scoped to self-edges (`isSelfEdge && operationsExecuted === 0 && incomingIsSubsetOfExisting ⇒ skip marker + ledger writes`) keeps an apply-with-nothing-to-execute from churning `marker.updatedAt` or piling up empty ledger entries. The post-hoc predicate keys on `operationsExecuted === 0`, which counts ops the runner ran through the loop — a data transform whose `check` finds no work still increments the counter, so the predicate covers "structurally empty self-edge plan" rather than "data transform self-skipped at runtime". Today that distinction is unreachable from the CLI because marker subtraction empties `effectiveRequired` on re-apply and short-circuits before the runner; tightening the predicate to per-op "actually ran" needs a per-op `executed` flag from `executeDataTransform` and is filed as a follow-up. `db update` no-ops still write a ledger entry as audit trail. ## Behavior changes & evidence - **`migration apply --ref <name>` and `migration status --ref <name>` route through invariants.** Both compute `effectiveRequired = ref.invariants − marker.invariants` and thread the result into `findPathWithDecision`. Empty effective set is structurally identical to today's no-ref routing (F8). - **Why**: the user-visible primitive of the spec. Refs declare "reach hash H with X applied"; the CLI picks the path that delivers X. - **Implementation**: - [packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts](../../../../../packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts) - [packages/1-framework/3-tooling/cli/src/commands/migration-status.ts](../../../../../packages/1-framework/3-tooling/cli/src/commands/migration-status.ts) - **Tests**: - [test/integration/test/cli-journeys/invariant-routing.e2e.test.ts](../../../../../test/integration/test/cli-journeys/invariant-routing.e2e.test.ts) — Journey O: full happy path against PGlite (data backfilled, marker.invariants accumulates, re-apply is no-op via subtraction) - [test/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts](../../../../../test/integration/test/cli-journeys/invariant-routing.mongo.e2e.test.ts) — Mongo O: same shape against `MongoMemoryReplSet`, proving the CLI layer is family-agnostic - **`MIGRATION.UNKNOWN_INVARIANT` pre-check fires after `readMarker()` but before any state mutation.** Both commands compute `(declared by graph) ∪ (marker.invariants)` and reject any ref id outside that union; exit 1 with a structured envelope listing `unknown` and `declared`. The marker contribution honours the spec's "applied-at-least-once" semantic — retired-but-applied ids stay valid and the apply is a no-op via marker subtraction. - **Why**: misconfigured refs (typos, not-yet-attested migrations) surface loudly and consistently. The marker-aware variant prevents valid ids from spuriously failing after a migration is pruned. - **Implementation**: - [packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts (`collectDeclaredInvariants`)](../../../../../packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts) - Pre-check inlined in apply / status, run after `client.readMarker()` so the marker contribution is in scope - **Tests**: - [packages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.ts](../../../../../packages/1-framework/3-tooling/cli/test/commands/migration-invariants.test.ts) — apply + status fail with the structured error on truly unknown ids; the retired-but-applied case (id is on marker but not declared in graph) passes the pre-check - Journey P (both Postgres and Mongo files) — end-to-end via real CLI - **`MIGRATION.NO_INVARIANT_PATH` carries the structural fallback path and `missing`.** When `from`→`to` is reachable but every reachable path leaves at least one required invariant uncovered, the pathfinder returns `unsatisfiable` with the structural shortest path attached; the CLI consumes both directly. - **Why**: F6. Authors need to see *what's reachable* and *what's missing*. The structural path tells them where they'd land structurally; the `missing` set names the work the path doesn't do. - **Implementation**: - [packages/1-framework/3-tooling/migration/src/migration-graph.ts (`FindPathOutcome.unsatisfiable`)](../../../../../packages/1-framework/3-tooling/migration/src/migration-graph.ts) — pathfinder computes `missing` against the structural path's edge invariants - [packages/1-framework/3-tooling/migration/src/errors.ts (`errorNoInvariantPath`)](../../../../../packages/1-framework/3-tooling/migration/src/errors.ts) — structured error - **Tests**: - Journey Q (both Postgres and Mongo files) — divergent graph where required invariant is on branch A but ref points at branch B; asserts `meta.code`, `meta.required`, `meta.missing`, and that the structural path's last edge has empty `invariants` - [packages/1-framework/3-tooling/migration/test/migration-graph.test.ts](../../../../../packages/1-framework/3-tooling/migration/test/migration-graph.test.ts) — partial-coverage `missing`: required `{X, Y}`, structural path covers `X`, `missing` is `[Y]` not `[X, Y]` - **`PathDecision.requiredInvariants` and `satisfiedInvariants` always present.** Default to `[]`; populated when `required` is supplied. `satisfiedInvariants` is derived from `selectedPath` — never independently computed. - **Why**: stable JSON wire shape regardless of regime; consumers don't have to branch on presence/absence. - **Implementation**: - [packages/1-framework/3-tooling/migration/src/migration-graph.ts](../../../../../packages/1-framework/3-tooling/migration/src/migration-graph.ts) - [packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts (`PathDecisionResult`)](../../../../../packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts) — slim view propagates both fields and per-edge `invariants` - **Tests**: - [packages/1-framework/3-tooling/cli/test/utils/command-helpers.test.ts](../../../../../packages/1-framework/3-tooling/cli/test/utils/command-helpers.test.ts) — defaults, propagation, intersection semantics, slim-view shape - [packages/1-framework/3-tooling/cli/test/output.json-shapes.test.ts](../../../../../packages/1-framework/3-tooling/cli/test/output.json-shapes.test.ts) — JSON envelope stability - **Status `--ref` surfaces required / applied / missing in human + JSON output.** Header gets a `required` row; summary gets `applied` / `missing` rows; JSON gets all four sets (required, applied, missing, satisfied) at the result root plus per-edge `invariants` on `pathDecision.selectedPath`. Edge labels in the dagre graph render gain `provides ["X", "Y"]` (JSON-quoted, matching the format used by error envelopes — defends against ids containing punctuation). - **Why**: the user-visible read on whether the data the ref names is reachable, applied, or pending. The "applied" vocabulary is intentional — the marker tracks "applied at least once", not "currently true of data". - **Implementation**: - [packages/1-framework/3-tooling/cli/src/commands/migration-status.ts](../../../../../packages/1-framework/3-tooling/cli/src/commands/migration-status.ts) - [packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts](../../../../../packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts) — edge labels gain `provides ["X", "Y"]` - **Tests**: Journey O asserts the four-set shape end-to-end; offline status shape is unchanged when `--ref` is not used; `graph-migration-mapper.test.ts` pins the JSON-quoted format with both clean ids and ids containing punctuation. - **`MIGRATION.INVARIANTS_PENDING` info diagnostic in status.** Fires when the marker matches the structural target (`pendingCount === 0`) but is missing required invariants — the apply path has work to do via a path that provides the missing ids (typically a self-edge), so status doesn't claim "up to date". - **Why**: under the marker-monotonic semantic, `pendingCount === 0` doesn't imply the ref's required set is satisfied; the human view needs to surface that gap rather than mislead. - **Implementation**: [migration-status.ts](../../../../../packages/1-framework/3-tooling/cli/src/commands/migration-status.ts). - **Tests**: Journey T (Postgres) — applies a self-edge providing X, manually clears `marker.invariants` via SQL, asserts status surfaces `INVARIANTS_PENDING` with the missing id and does not surface `UP_TO_DATE`. - **Self-edge migrations land as a first-class shape.** `from === to` with at least one data op is accepted. Routing handles them natively (BFS sees the self-edge as a covering edge for the required invariant). `migration new --from <hash>` is the explicit author opt-in. - **Why**: the data-only-migration use case has no other expression. Users hitting the rejection had to fake a no-op schema diff to get a different hash, which is gross. With self-edges, normalise-emails reads naturally as a one-edge migration on the current contract. - **Implementation**: - [packages/1-framework/3-tooling/migration/src/migration-graph.ts (`reconstructGraph`)](../../../../../packages/1-framework/3-tooling/migration/src/migration-graph.ts) — narrowed rejection - [packages/1-framework/3-tooling/cli/src/commands/migration-new.ts](../../../../../packages/1-framework/3-tooling/cli/src/commands/migration-new.ts) — `--from` opt-in - SQL runners — narrowed upfront skip; post-hoc no-op skip - **Tests**: - [packages/1-framework/3-tooling/migration/test/migration-graph.test.ts](../../../../../packages/1-framework/3-tooling/migration/test/migration-graph.test.ts) — graph + pathfinder accept/route self-edges - [packages/3-targets/6-adapters/postgres/test/migrations/runner.idempotency.integration.test.ts](../../../../../packages/3-targets/6-adapters/postgres/test/migrations/runner.idempotency.integration.test.ts) — runner-level: ops actually execute (sentinel-table side effect); no-op self-edge skips marker + ledger writes - [packages/3-targets/6-adapters/sqlite/test/migrations/runner.idempotency.test.ts](../../../../../packages/3-targets/6-adapters/sqlite/test/migrations/runner.idempotency.test.ts) — same SQLite - Journey S (Postgres) — full e2e: `migration new --from <c1>`, hand-author dataTransform with invariantId, apply via `--ref`, both seed rows normalised, marker stays at C1, marker.invariants accumulates the id - **A→B→A→B marker monotonicity pinned.** Direct UPDATE on the marker row resets `core_hash` back to A while leaving `invariants` alone (drift / aborted rollback simulation). Re-apply via `--ref` selects M1 (only A→B edge) and advances the marker back to B. `marker.invariants` stays `['X']` — set-union with an already-present id is a no-op. - **Why**: the spec's "applied-at-least-once" semantic. Set never shrinks. Whether the data transform's *body* re-runs depends on its `check` (out of scope of this PR; the journey documents the caveat in a comment). - **Implementation**: emergent — the existing CLI flow already does the right thing; the test pins the behavior. - **Tests**: Journey R (Postgres). ## Compatibility / migration / risk - **Pathfinder API additions.** `findPathWithDecision(graph, from, to, { refName?, required? })` accepts an options object; both fields default and a no-options call yields byte-identical behaviour to today's structural routing. `PathDecision` and `PathDecisionResult` gain always-present `requiredInvariants` / `satisfiedInvariants` (default `[]`). - **`FindPathOutcome` is a discriminated return shape.** `findPathWithDecision` returns `ok` / `unreachable` / `unsatisfiable` (with `structuralPath` and `missing`) — breaking for in-package callers, but the only callers are the two CLI commands updated in this PR; not re-exported. - **`MigrationPlan` and `MigrationApplyStep` carry `providedInvariants`.** `MigrationPlan.providedInvariants?: readonly string[]` at the framework-components level; `MigrationApplyStep.providedInvariants: readonly string[]` (required) at the CLI/runner boundary. The CLI populates both from `manifest.providedInvariants`. The framework-level field is optional so non-manifest planners (`db init`, `db update`) can omit it. - **`UNKNOWN_INVARIANT` widened to honour marker monotonicity.** An id that's gone from the graph but still present on the marker (retired-but-applied) passes the pre-check; the apply is a no-op via marker subtraction. True typos still fail loudly. - **Self-edge support narrows existing rejections.** `reconstructGraph` accepts `from === to` packages that declare at least one data op; `migration new` accepts `--from <currentHash>` to scaffold a self-edge package. Pre-self-edge migrations are unchanged — the relaxation is purely additive. - **SQL runner skip semantics for self-edges are observable.** `apply --ref` against a self-edge target now executes the data transforms (was previously silently skipped). The path was unreachable from the CLI before self-edges were authorable, so no regression for existing migrations. - **No on-disk format changes.** M2's manifest fields and M1's marker columns are unchanged. No new migration files. No breaking schema work. - **`migration ref set` does not write `invariants`.** Refs that need invariants are edited as JSON for v1; e2e tests use a small `writeRefFile` helper. Adding a Commander option is a small follow-up. ## Follow-ups / open questions - **`migration ref set --invariants`**. Spec deferred; v1 edits JSON manually. One Commander argument when product asks. - **CLI surface for self-edge authoring**. `migration new --from <hash>` works but is rough — the user has to know to pass `--from`. Could add `migration new --self-edge` as a friendlier alias if the use case is common. - **General no-op skip on SQL runners**. The post-hoc skip is currently scoped to self-edges to preserve the audit-trail behavior of `db update` against a matching marker (existing SQLite test). If product wants `db update` no-ops to also skip the ledger write (matching Mongo), drop `isSelfEdge && ` from the predicate and update one SQLite test assertion. - **Vocabulary review**. "invariant" leaks across `invariantId`, four error codes, status output, and ref JSON. Spec deferred; not blocking. Cleanup once the term is either accepted or replaced. - **Per-target test matrix**. Postgres + Mongo journeys are near-mechanical translations of each other. A shared matrix harness would deduplicate, but that's separate scaffolding work. ## Non-goals / intentionally out of scope - **Ledger per-invariant provenance**. Marker stores the union; the ledger doesn't record which migration first contributed which invariant. Spec deferred. - **TML-2130** (`deriveEdgeStatuses` consulting the ledger). Independent fix; marker-side applied-invariants storage doesn't depend on it. - **Draft / unattested edge invariants**. Drafts aren't in the routing graph; status renders them via a separate channel that doesn't carry invariants. - **Mongo journey for self-edges**. Postgres journey covers the e2e flow; Mongo runner already had the right shape (no skip-operations gate). Could mirror later for full target parity. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * CLI is invariant-aware: status/apply show required/satisfied/missing invariants, per-path invariant annotations, and structured NO_INVARIANT_PATH / UNKNOWN_INVARIANT diagnostics; applies forward provided invariants to runners. * `migration new` requires explicit --from for data-only no-change emits. * **Bug Fixes** * Self-edge semantics refined: true no-ops skip marker/ledger writes; self-edge data transforms still execute. * **Tests** * Extensive unit, integration and e2e suites added for invariant routing and marker behaviors. * **Documentation** * ADRs added/updated describing invariant-aware routing and self-edge policy. * **Chores** * Runners derive invariants from plans (caller option removed); test timeout defaults adjusted. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor Agent <[email protected]>
The data-migrations parent spec and its plan were the last remaining files in projects/graph-based-migrations/. With TML-2283 closing on PR #404 merge, neither has an open workstream consuming them: the routing slice is owned by ADR 208, the conceptual model lives in ADR 176, and the data-transform authoring + planner-positioning theory text has no live consumer. The umbrella folder retires entirely.
Will flagged three places in his review where I claimed `migration verify`
was the integrity gate. The command doesn't exist — manifest integrity
runs at load time in readMigrationPackage (re-derive providedInvariants
from ops.json + recompute migrationHash). Self-review of all our edits
turned up additional issues, mostly clustered in ADR 208's §"At a glance"
example.
ADR 208 §"At a glance" example:
- this.dataTransform(endContract, name, options) — was 2-arg
dataTransform(name, options), which doesn't exist on Postgres.
- check / run closures take no parameters and return SqlQueryPlan |
Buildable. Was check: db => ... / run: db => ..., neither shape exists.
- addColumn requires defaultSql in ColumnSpec — was missing.
- Made the example explicitly schematic ("query bodies elided") since the
full SQL DSL surface isn't relevant to the routing story.
- Migration class needs describe() and the bottom MigrationCLI.run(...)
to be a complete authored migration; both added.
ADR 208 §"At a glance" prose:
- "MIGRATION.UNKNOWN_INVARIANT before any database activity" was wrong;
the check now runs after client.connect + readMarker (per the post-#404
fix that defers the check until marker.invariants is available).
- "no migration provides" was incomplete; the actual rule checks
declared ∪ marker.invariants, so an id from a retired migration that
the marker still has does not fail UNKNOWN_INVARIANT.
- Replaced the fictitious "→ prod / required / applied / missing /
route" output box with prose; the box doesn't match real apply output.
ADR 208 §"Manifest aggregate" / §"Plan envelope" / §"Alternatives":
- All three referenced `migration verify`. Replaced with "load-time
integrity check" or equivalent.
ADR 169 §3 (Will's #1): "The migration `verify` step ..." → "When a
migration is loaded from disk, the loader ..."
ADR 192 (Will's #2): "at verify time" → "at load time"
# docs(adrs): extend M5 close-out across the related ADR set **Base:** `invariant-routing-cli` (stacked on top of #404) **Branch:** `invarant-routing-closeout` ## Summary Stacks on #404. Extends the M5 close-out — which today touches **ADR 001** (self-edge relaxation) and the new **ADR 208** (invariant-aware migration routing) — across the rest of the ADR set the work materially affected: 021, 039, 042, 169, 176, 192. The goal: a reader landing on any of those ADRs sees the v1 decisions inline rather than having to chase ADR 208 to find out what changed underneath them. Most of the amendments are short cross-reference updates; the substantive additions to ADR 208 are: - **`#### Why marker, not ledger or graph-derived`** — promotes the marker-vs-ledger distinction from a pragmatic trade-off to a principle: marker = framework-issued guarantee record, ledger = audit artifact, structural framework behaviour must never depend on the audit log. The framing was inline in the spec and would have been lost when the spec was retired. - **`### Performance and the absence of a hard guard`** — lifts the conclusions from the now-retired `invariant-aware-routing-bench.md`: production-typical inputs stay sub-millisecond, the `2^k` curve only materialises on synthetic worst case, no hard guard warranted for v1, optional `--verbose` heads-up at large `k` if we want it later. Plus a final cleanup pass: `projects/graph-based-migrations/` is retired in full (its remaining transient artefacts had no live consumers — the routing slice is in ADR 208, the conceptual model is in ADR 176, and TML-2283 closes on #404 merge), as are the orphaned April migration-perf baselines under `docs/planning/benchmarks/`. ## What's deliberately not in this PR Two sections from an earlier draft of this work were dropped after rebasing onto the current `invariant-routing-cli`, because the post-#404 polish trail made them obsolete: - **A "Known soundness gap: pre-check vs. squash" subsection in ADR 208** flagging the case where `UNKNOWN_INVARIANT` could fire even when `marker.invariants` already had the id. Closed by `52ab770c8 fix(cli): defer UNKNOWN_INVARIANT pre-check until marker.invariants` — the CLI now subtracts before the pre-check. - **A "runner derives invariants from `plan.operations`" framing in ADR 208 §D7.** Replaced by `ec06cc550 feat(migrations): thread providedInvariants through plan envelope` — runners now read `options.plan.providedInvariants`, and ADR 208's existing §"Plan envelope carries `providedInvariants`" already documents the new shape correctly. No code, tests, or behavioural changes — this is documentation + transient-artefact cleanup only. ## Test plan - [ ] Walk each amendment side-by-side with the relevant code (DDL builders for ADR 021, `findPathWithInvariants` for ADR 039, `MigrationOpSchema` for ADR 192, runners for ADR 208) and confirm the prose matches what's actually in `main + #404`. - [ ] Verify cross-references resolve. The mongo-migration-authoring spec has one inbound link to the now-retired `data-migrations-spec.md` that's been left dangling on purpose (different workstream's content). - [ ] Note: there's a pre-existing number collision at ADR 208 — `ADR 208 - Higher-order codecs for parameterized types.md` (codec work) and `ADR 208 - Invariant-aware migration routing.md` (this work) coexist. Out of scope here; the team will need to renumber one. ## Related - Parent PR: #404 (`feat(migration,cli): invariant-aware ref routing (M4) + self-edge support`) - Linear umbrella: TML-2297 - Retires the `projects/graph-based-migrations/` umbrella folder in full following #404's spec/plan retirement (`2f5c24869`) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Updated architecture documentation to clarify migration routing, contract marker storage semantics, and invariant-aware path resolution. * Removed obsolete migration graph and planner baseline benchmark files. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…e; reframe as type/operator catalog expansion
Option A from the design discussion: keep the Project 1 / Project 2
split, but drop Project 2's planner-integration mandate now that
TML-2397 (contract spaces) ships the codec lifecycle hook
framework-wide. Project 2 becomes purely surface expansion (more types,
more operators); each new type instantiates Project 1's pattern.
Umbrella spec.md:
- Add new section: Foundation (TML-2397 contract spaces). Covers the
three concerns dissolved by TML-2397: EQL bundle install, per-column
search-config DDL, strict dbInit preserved per-space.
- Update component overview table: Project 2 description rewritten
('Expanded type/operator surface') without planner-integration claim.
- Update Components section descriptions for both Project 1 and
Project 2.
- Update Cross-component design decisions: replace 'Migration factories
produce DataTransformOperations' (now obsolete; codec hook owns the
surface) with 'Per-column search-config DDL is emitted by the codec
lifecycle hook'. Affects both Project 1 and Project 2.
- Update In-flight framework dependencies table: TML-2397 listed as
satisfied foundation; PRs #404 / #409 promoted to merged status (they
landed on the contract-spaces base before our rebase). Drop the
obsolete framework-prerequisites paragraph for Project 2.
- Update 'Why an umbrella' wording: Project 1's RawSqlExpr AST node
still motivates sql-raw-factory, just no longer for migration-factory
reasons.
Umbrella plan.md:
- Update component diagram: replace 'in-flight framework PRs' arrows
with TML-2397 + PR-bundle as foundation arrows; drop separate
'framework prerequisites' arrow into Project 2.
- Update dependency-edges table: TML-2397 row added; PRs row
consolidated to satisfied; framework-prerequisites row removed.
- Update Sequencing section text: drop 'Project 2 blocked on framework
prereqs' note; Project 2 now gates on Project 1 only.
- Update Phase A — Project 1: reflect M0 + M1 done, M2 next; remove
'hand-authored migration factories' from goal.
- Update Phase B — Project 2: drop framework-prereqs gating; add
per-type sequencing within Project 2.
- Update Status table: TML-2397 row noted; remove obsolete framework-
prereqs gating from Project 2 row.
Project 2 spec.md:
- Retitle: 'Expanded type/operator surface' (was 'Planner-driven DDL +
expanded type/operator surface').
- Rewrite Summary + Description to drop the planner-integration half
entirely; reframe as instantiating Project 1's pattern per type.
- Replace Dependencies table: drop framework prerequisites; add TML-2397
as satisfied foundation; clarify Project 1 hard dependency.
- Update Open Questions: keep type-specific ones (mode-flag downgrade,
re-encryption migration, column-key-id, searchableJson semantics);
add 'order of type rollout' note (customer-demand-driven).
Project 1 spec.md:
- Update header summary line: 'expanded type/operator surface' (drop
'planner-driven DDL' from Project 2's description).
- Update Non-goals: replace 'planner-driven per-column DDL beyond the
lifecycle hook' with 'edge cases of the codec hook deferred to
Project 2' (cross-type transitions, mode-flag downgrade policy).
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
Project 1 is now rebased onto tml-2397-cipherstash-contract-space, which shipped the cipherstash control plane (descriptor, codec lifecycle hook, contract-space artefacts, EQL bundle install via the contract-space migration runner). Project 1 now delivers only the runtime layer on top: envelope, SDK interface, codec encode/decode, bulk-encrypt middleware, PSL constructor, TS factory, operator lowering, end-to-end tests. spec.md changes: - New § Foundation section pinning TML-2397 as the architectural base. - Replace § EQL bundle installation as an extension dependency (databaseDependencies.init) with § EQL bundle installation as a contract-space migration (the runner applies the bundle byte-for-byte inside the cipherstash space). - Replace § Migration factories with § Per-column search config: emitted automatically by the codec lifecycle hook. The user no longer writes addSearchConfig / activatePendingSearches calls; the codec hook on TML-2397 emits add_search_config / remove_search_config / rotate ops per field-delta. - Add AC-UMB8 (strict dbInit preserved) and AC-UMB9 (tree-shakable control vs runtime planes). - Drop the migration-factories row from the task-spec status table. - Update § In-flight dependencies: TML-2397 listed as foundation; PR #404 routing benefit realized via TML-2397; PR #409 already on the contract-spaces base. plan.md changes: - Restructured milestones: M0 (rebase) and M1 (framework SPI cherry- picks) marked DONE; M2 (cipherstash runtime layer) is the bulk of remaining work; M3 (operators + decryptAll + full e2e); M4 (close- out). Original M2.a/M2.b/M2.c/M3/M4 collapse into the new M2/M3. - New § What survives, what dies, what's already done section gives a per-commit traceability matrix from PR #416 / part-2 → this branch. - M2 task list replaces the old M2.c task list; T2.9 (codec hook flag- name alignment) is the only Project-1-side adjustment to TML-2397's cipherstash codec hook. - M3 collapses the old M3+M4 (operator lowering + migration factories + decryptAll). Migration-factory tasks are removed; codec hook on TML-2397 owns that surface. specs/migration-factories.spec.md: - Replaced with a redirect noting it is obsolete and pointing at the TML-2397 codec lifecycle hook. The original spec is preserved in git history on origin/tml-2373-project-1-part-2 for archaeology. The redirect file is deleted in M4 close-out.
…e; reframe as type/operator catalog expansion
Option A from the design discussion: keep the Project 1 / Project 2
split, but drop Project 2's planner-integration mandate now that
TML-2397 (contract spaces) ships the codec lifecycle hook
framework-wide. Project 2 becomes purely surface expansion (more types,
more operators); each new type instantiates Project 1's pattern.
Umbrella spec.md:
- Add new section: Foundation (TML-2397 contract spaces). Covers the
three concerns dissolved by TML-2397: EQL bundle install, per-column
search-config DDL, strict dbInit preserved per-space.
- Update component overview table: Project 2 description rewritten
('Expanded type/operator surface') without planner-integration claim.
- Update Components section descriptions for both Project 1 and
Project 2.
- Update Cross-component design decisions: replace 'Migration factories
produce DataTransformOperations' (now obsolete; codec hook owns the
surface) with 'Per-column search-config DDL is emitted by the codec
lifecycle hook'. Affects both Project 1 and Project 2.
- Update In-flight framework dependencies table: TML-2397 listed as
satisfied foundation; PRs #404 / #409 promoted to merged status (they
landed on the contract-spaces base before our rebase). Drop the
obsolete framework-prerequisites paragraph for Project 2.
- Update 'Why an umbrella' wording: Project 1's RawSqlExpr AST node
still motivates sql-raw-factory, just no longer for migration-factory
reasons.
Umbrella plan.md:
- Update component diagram: replace 'in-flight framework PRs' arrows
with TML-2397 + PR-bundle as foundation arrows; drop separate
'framework prerequisites' arrow into Project 2.
- Update dependency-edges table: TML-2397 row added; PRs row
consolidated to satisfied; framework-prerequisites row removed.
- Update Sequencing section text: drop 'Project 2 blocked on framework
prereqs' note; Project 2 now gates on Project 1 only.
- Update Phase A — Project 1: reflect M0 + M1 done, M2 next; remove
'hand-authored migration factories' from goal.
- Update Phase B — Project 2: drop framework-prereqs gating; add
per-type sequencing within Project 2.
- Update Status table: TML-2397 row noted; remove obsolete framework-
prereqs gating from Project 2 row.
Project 2 spec.md:
- Retitle: 'Expanded type/operator surface' (was 'Planner-driven DDL +
expanded type/operator surface').
- Rewrite Summary + Description to drop the planner-integration half
entirely; reframe as instantiating Project 1's pattern per type.
- Replace Dependencies table: drop framework prerequisites; add TML-2397
as satisfied foundation; clarify Project 1 hard dependency.
- Update Open Questions: keep type-specific ones (mode-flag downgrade,
re-encryption migration, column-key-id, searchableJson semantics);
add 'order of type rollout' note (customer-demand-driven).
Project 1 spec.md:
- Update header summary line: 'expanded type/operator surface' (drop
'planner-driven DDL' from Project 2's description).
- Update Non-goals: replace 'planner-driven per-column DDL beyond the
lifecycle hook' with 'edge cases of the codec hook deferred to
Project 2' (cross-type transitions, mode-flag downgrade policy).
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
Walkthrough — invariant-routing-cli (M4)
closes TML-2363
part of TML-2297
Intent
M4 of TML-2297 — the CLI integration that makes invariant-aware routing user-visible.
migration apply --refandmigration status --refsubtractmarker.invariants(M1) fromref.invariants(M0) and route the effective set through M3'sfindPathWithInvariants. Refs that name an invariant id no migration and no marker has ever applied fail withMIGRATION.UNKNOWN_INVARIANTafterreadMarker()but before any state mutation; refs whose target is reachable but uncovered fail withMIGRATION.NO_INVARIANT_PATHcarrying the structural fallback path. The decision surface gainsrequiredInvariants/satisfiedInvariants;--jsonoutput gains the four invariant sets and per-edgeinvariantsonselectedPath. Status's dagre graph render annotates each edge label withprovides ["X", "Y"](JSON-quoted, matching the error envelope format) when relevant; a newMIGRATION.INVARIANTS_PENDINGinfo diagnostic surfaces when the marker matches the structural target but is missing required ids, so status doesn't claim "up to date" while the apply path still has work to do.The design lives in two ADRs: ADR 001 (Migrations as Edges) — amended for the self-edge relaxation — and ADR 208 (Invariant-aware migration routing) — new — together replacing the standalone
projects/graph-based-migrations/spec + plan, which retire in this PR.This PR also lifts a related restriction surfaced during implementation: self-edge migrations (
from === to) are now allowed when they declare at least one data op. The motivating use case is "normalise emails to lowercase" — a pure data migration with no schema diff. Without self-edge support there's no way to author one, and as soon as we tried we hit two latent bugs in the SQL runners. Both fixed; the routing surface now has end-to-end coverage for self-edges across SQL and Mongo.Change map
errorNoInvariantPath,errorUnknownInvariant, andNoInvariantPathStructuralEdgepayload typePathDecisiongains always-presentrequiredInvariants/satisfiedInvariants;findPathWithDecision(graph, from, to, { refName?, required? })(options object) returns a discriminatedFindPathOutcome(ok/unreachable/unsatisfiable); theunsatisfiablearm carriesstructuralPathandmissingso callers don't recompute either;tieBreakReasonsonly populates when there are multiple invariant-viable alternatives at a stepreconstructGraphnarrows thefrom === torejection to "self-edge with no data ops"findPathWithInvariants,findPathWithDecision) — drop thefrom === to ⇒ unsatisfiableearly returns whenrequired ≠ ∅; BFS handles self-edges naturallyerrorSameSourceAndTarget) — message reflects the narrowed semantic--fromis explicitRefEntry, computeseffectiveRequired = ref.invariants − marker.invariantsafterreadMarker, runs the marker-awareUNKNOWN_INVARIANTpre-check (known set is(declared) ∪ (marker.invariants)), threads throughfindPathWithDecision, mapsunsatisfiabletoerrorNoInvariantPath, surfacesrequiredInvariants/satisfiedInvariants/ per-edgeinvariantsinpathDecisionMigrationStatusResultgainsrequiredInvariants/appliedInvariants/missingInvariants(top-level, populated only when--refis in play); header gains arequiredrow alongsideref; summary block gainsapplied/missingrows; newMIGRATION.INVARIANTS_PENDINGinfo diagnostic when marker is at target but missing required ids; suppressesMIGRATION.UP_TO_DATEwhen the marker can't reach the contract targetPathDecisionResultshape gainsrequiredInvariants/satisfiedInvariantsand per-edgeinvariants; newcollectDeclaredInvariants(graph)andtoStructuralEdge(edge)helpers used by both commandsprovides ["X", "Y"]suffix (JSON-quoted) when invariants presentMigrationPlangainsprovidedInvariants?: readonly string[]so callers can carry the manifest's canonical set down to the runnerMigrationApplyStep) — gainsprovidedInvariants: readonly string[](required at the CLI/runner boundary)plan.providedInvariantsfrommanifest.providedInvariantsbefore callingrunner.execute({ plan })options.plan.providedInvariantsdirectly; narrows the upfront skip to exclude self-edges; adds post-hoc no-op skip scoped to self-edgesoptions.plan.providedInvariantserrorNoInvariantPathwhyrendering for all-missing, none-missing, and partial-coverage cases (required = [a,b,c],missing = [c])findPathWithDecisionoutcome cases (ok / unreachable / unsatisfiable); satisfied-invariants intersection semantics; partial-coveragemissingcorrectness; self-edge graph reconstruction + pathfinder casestoPathDecisionResultslim view propagates per-edgeinvariantsand the two new top-level fieldsinvariantId, runner derives the set)invariantsUNKNOWN_INVARIANTpre-check: apply + status fail with the structured error on truly unknown ids; empty-required ref does not trip the check; the retired-but-applied case (id is on the marker but not declared in the graph) passes the pre-check and the apply is a no-op via marker subtractionINVARIANTS_PENDINGsurfaces when marker is at target but missing required ids)MongoMemoryReplSetprovides ["X", "Y"]JSON-quoted suffix on the dagre edge label, including the punctuation case (ids containing commas / quotes) the format defends againstupdated_atbyte-identical, ledger row count unchanged)The story
Decision surface threads
requiredend-to-end.findPathWithDecision(graph, from, to, { refName?, required? })is the single integration point: every--refinvocation flows through it. Both options default — passing nothing yields byte-identical behaviour to today's structural routing. Whenrequired ≠ ∅the function delegates to M3'sfindPathWithInvariantsand packages the result into a discriminatedFindPathOutcome.PathDecisionalways carriesrequiredInvariants/satisfiedInvariants(default[]) so the JSON wire shape is stable regardless of regime.Discriminated
FindPathOutcome.findPathWithDecisionreturns{ kind: 'ok', decision } | { kind: 'unreachable' } | { kind: 'unsatisfiable', structuralPath, missing }. The pathfinder already knows which case it is, so it tells callers directly — three-way switch at the call site, no redundant structural BFS, no risk of forgetting to disambiguate. Theunsatisfiablearm computesmissingagainst the structural fallback path's edge invariants, so partial coverage (some required satisfied along the structural path, others not) is reported correctly rather than echoing the full required set.Marker subtraction is the load-bearing CLI primitive.
effectiveRequired = ref.invariants − marker.invariants. This single line is what makes ref-driven re-applies idempotent: once the marker has accumulatedX, a subsequentapply --refwhoseref.invariantsincludesXdoesn't insist on re-providing it. Combined with M3's empty-required equivalence, marker subtraction turns the second apply into a structural shortest-path BFS — pre-M4 routing, free.UNKNOWN_INVARIANTis a pre-check, not a runtime failure — and the marker contributes to the "known" set. Afterclient.readMarker()returns, both commands compute(declared by graph) ∪ (marker.invariants)and reject any ref id outside that union. Typos and not-yet-attested migrations still fail with a structured error and a non-zero exit, but state-mutating runner calls haven't started. The marker contribution honours the spec's "applied-at-least-once" semantic: markers can legitimately carry ids whose defining migration has been pruned/squashed, and treating those asUNKNOWN_INVARIANTwould block re-applies the database has already fulfilled. Status applies the same check at the same severity — a misconfigured ref surfaces consistently across both commands.NO_INVARIANT_PATHis constructed on the pathfinder side. When required is non-empty andfindPathWithInvariantsreturns null, the pathfinder runs the structural fallbackfindPathonce, computesmissingagainst the structural path's edge invariants, and returnsunsatisfiablewith both pieces. Callers consumeoutcome.missingandoutcome.structuralPathdirectly. The error envelope carries each structural-path edge's per-edgeinvariantsso consumers can see what is provided, not just what isn't.Status surfaces required / applied / missing as structural rows.
refandrequiredgo in the styled header (computable pre-DB);appliedandmissingfollow the summary block (require the marker read). JSON output gets all four sets at the result root —requiredInvariants,appliedInvariants,missingInvariants, pluspathDecision.satisfiedInvariants. Edge labels in the dagre graph render gain aprovides ["X", "Y"]suffix (JSON-quoted, matching the format used byMIGRATION.NO_INVARIANT_PATHenvelopes). The "applied" vocabulary is intentional — the marker is "applied at least once", not "currently true of data". A newMIGRATION.INVARIANTS_PENDINGinfo diagnostic fires when the marker matches the structural target but is missing required invariants, so status doesn't read "up to date" while the apply path still has work to do.Runners read
providedInvariantsfrom the plan envelope.MigrationPlan.providedInvariantscarries the manifest's canonical invariant set down to the runner;MigrationApplyStep.providedInvariantsis the CLI/runner-boundary equivalent. The CLI populates both fields frommanifest.providedInvariantsbefore callingrunner.execute({ plan }). The manifest is the single source of truth —migrationHashincludes it, and the loader verifies it equal toderiveProvidedInvariants(ops)at read time — so runners can consume it directly without re-deriving. All three runners (postgres, sqlite, mongo) read the same field, so a fourth runner family doesn't need to importmigration-tools/invariantsto participate.Self-edges (from === to) are first-class when they declare a data op. Not in the spec — surfaced during M4 implementation. Use case: a migration that does only
dataTransform({ invariantId, check, run })against the current schema.reconstructGraphaccepts the package iff at least one operation isoperationClass === 'data';findPathWithInvariantsandfindPathWithDecisionlost theirfrom === to ⇒ unsatisfiableearly returns whenrequired ≠ ∅(BFS handles self-edges naturally);migration newlifts its "No changes detected" rejection when--fromis explicit (default no-flag still rejects).findPathkeeps itsfrom === to ⇒ []short-circuit because the empty path is structurally shortest.SQL runner skip semantics are self-edge-aware. The upfront skip in
applyPlan(markerAtDestination && origin != null ⇒ skip ALL ops) excludes self-edges — forfrom === toplans the marker matches destination by construction, and the data transform must still fire. A separate post-hoc skip scoped to self-edges (isSelfEdge && operationsExecuted === 0 && incomingIsSubsetOfExisting ⇒ skip marker + ledger writes) keeps an apply-with-nothing-to-execute from churningmarker.updatedAtor piling up empty ledger entries. The post-hoc predicate keys onoperationsExecuted === 0, which counts ops the runner ran through the loop — a data transform whosecheckfinds no work still increments the counter, so the predicate covers "structurally empty self-edge plan" rather than "data transform self-skipped at runtime". Today that distinction is unreachable from the CLI because marker subtraction emptieseffectiveRequiredon re-apply and short-circuits before the runner; tightening the predicate to per-op "actually ran" needs a per-opexecutedflag fromexecuteDataTransformand is filed as a follow-up.db updateno-ops still write a ledger entry as audit trail.Behavior changes & evidence
migration apply --ref <name>andmigration status --ref <name>route through invariants. Both computeeffectiveRequired = ref.invariants − marker.invariantsand thread the result intofindPathWithDecision. Empty effective set is structurally identical to today's no-ref routing (F8).MongoMemoryReplSet, proving the CLI layer is family-agnosticMIGRATION.UNKNOWN_INVARIANTpre-check fires afterreadMarker()but before any state mutation. Both commands compute(declared by graph) ∪ (marker.invariants)and reject any ref id outside that union; exit 1 with a structured envelope listingunknownanddeclared. The marker contribution honours the spec's "applied-at-least-once" semantic — retired-but-applied ids stay valid and the apply is a no-op via marker subtraction.collectDeclaredInvariants)client.readMarker()so the marker contribution is in scopeMIGRATION.NO_INVARIANT_PATHcarries the structural fallback path andmissing. Whenfrom→tois reachable but every reachable path leaves at least one required invariant uncovered, the pathfinder returnsunsatisfiablewith the structural shortest path attached; the CLI consumes both directly.missingset names the work the path doesn't do.FindPathOutcome.unsatisfiable) — pathfinder computesmissingagainst the structural path's edge invariantserrorNoInvariantPath) — structured errormeta.code,meta.required,meta.missing, and that the structural path's last edge has emptyinvariantsmissing: required{X, Y}, structural path coversX,missingis[Y]not[X, Y]PathDecision.requiredInvariantsandsatisfiedInvariantsalways present. Default to[]; populated whenrequiredis supplied.satisfiedInvariantsis derived fromselectedPath— never independently computed.PathDecisionResult) — slim view propagates both fields and per-edgeinvariantsStatus
--refsurfaces required / applied / missing in human + JSON output. Header gets arequiredrow; summary getsapplied/missingrows; JSON gets all four sets (required, applied, missing, satisfied) at the result root plus per-edgeinvariantsonpathDecision.selectedPath. Edge labels in the dagre graph render gainprovides ["X", "Y"](JSON-quoted, matching the format used by error envelopes — defends against ids containing punctuation).provides ["X", "Y"]--refis not used;graph-migration-mapper.test.tspins the JSON-quoted format with both clean ids and ids containing punctuation.MIGRATION.INVARIANTS_PENDINGinfo diagnostic in status. Fires when the marker matches the structural target (pendingCount === 0) but is missing required invariants — the apply path has work to do via a path that provides the missing ids (typically a self-edge), so status doesn't claim "up to date".pendingCount === 0doesn't imply the ref's required set is satisfied; the human view needs to surface that gap rather than mislead.marker.invariantsvia SQL, asserts status surfacesINVARIANTS_PENDINGwith the missing id and does not surfaceUP_TO_DATE.Self-edge migrations land as a first-class shape.
from === towith at least one data op is accepted. Routing handles them natively (BFS sees the self-edge as a covering edge for the required invariant).migration new --from <hash>is the explicit author opt-in.reconstructGraph) — narrowed rejection--fromopt-inmigration new --from <c1>, hand-author dataTransform with invariantId, apply via--ref, both seed rows normalised, marker stays at C1, marker.invariants accumulates the idA→B→A→B marker monotonicity pinned. Direct UPDATE on the marker row resets
core_hashback to A while leavinginvariantsalone (drift / aborted rollback simulation). Re-apply via--refselects M1 (only A→B edge) and advances the marker back to B.marker.invariantsstays['X']— set-union with an already-present id is a no-op.check(out of scope of this PR; the journey documents the caveat in a comment).Compatibility / migration / risk
findPathWithDecision(graph, from, to, { refName?, required? })accepts an options object; both fields default and a no-options call yields byte-identical behaviour to today's structural routing.PathDecisionandPathDecisionResultgain always-presentrequiredInvariants/satisfiedInvariants(default[]).FindPathOutcomeis a discriminated return shape.findPathWithDecisionreturnsok/unreachable/unsatisfiable(withstructuralPathandmissing) — breaking for in-package callers, but the only callers are the two CLI commands updated in this PR; not re-exported.MigrationPlanandMigrationApplyStepcarryprovidedInvariants.MigrationPlan.providedInvariants?: readonly string[]at the framework-components level;MigrationApplyStep.providedInvariants: readonly string[](required) at the CLI/runner boundary. The CLI populates both frommanifest.providedInvariants. The framework-level field is optional so non-manifest planners (db init,db update) can omit it.UNKNOWN_INVARIANTwidened to honour marker monotonicity. An id that's gone from the graph but still present on the marker (retired-but-applied) passes the pre-check; the apply is a no-op via marker subtraction. True typos still fail loudly.reconstructGraphacceptsfrom === topackages that declare at least one data op;migration newaccepts--from <currentHash>to scaffold a self-edge package. Pre-self-edge migrations are unchanged — the relaxation is purely additive.apply --refagainst a self-edge target now executes the data transforms (was previously silently skipped). The path was unreachable from the CLI before self-edges were authorable, so no regression for existing migrations.migration ref setdoes not writeinvariants. Refs that need invariants are edited as JSON for v1; e2e tests use a smallwriteRefFilehelper. Adding a Commander option is a small follow-up.Follow-ups / open questions
migration ref set --invariants. Spec deferred; v1 edits JSON manually. One Commander argument when product asks.migration new --from <hash>works but is rough — the user has to know to pass--from. Could addmigration new --self-edgeas a friendlier alias if the use case is common.db updateagainst a matching marker (existing SQLite test). If product wantsdb updateno-ops to also skip the ledger write (matching Mongo), dropisSelfEdge &&from the predicate and update one SQLite test assertion.invariantId, four error codes, status output, and ref JSON. Spec deferred; not blocking. Cleanup once the term is either accepted or replaced.Non-goals / intentionally out of scope
deriveEdgeStatusesconsulting the ledger). Independent fix; marker-side applied-invariants storage doesn't depend on it.Summary by CodeRabbit
New Features
migration newrequires explicit --from for data-only no-change emits.Bug Fixes
Tests
Documentation
Chores