Repository navigation
refactor(migration-tools): refs carry invariants, per-file layout - #372
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:
📝 WalkthroughWalkthroughMigration ref storage moved from a single Changes
Sequence Diagram(s)sequenceDiagram
participant CLI as CLI
participant API as MigrationAPI
participant FS as FileSystem
CLI->>API: resolveMigrationPaths() -> refsDir
CLI->>API: readRefs(refsDir) / readRef(refsDir, name)
API->>FS: read `${refsDir}/${name}.json` or enumerate `*.json`
FS-->>API: file contents (JSON)
API->>API: parse & validate -> RefEntry { hash, invariants }
API-->>CLI: return RefEntry / Refs map
CLI->>API: writeRef(refsDir, name, RefEntry)
API->>FS: write `${refsDir}/${name}.json` (temp + rename)
FS-->>API: write success
CLI->>API: deleteRef(refsDir, name)
API->>FS: unlink `${refsDir}/${name}.json` (cleanup empty dirs)
FS-->>API: delete success
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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 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/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/runtime-executor
@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: |
e4ef9dd to
6abbe53
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (6)
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts (1)
376-397: Redundant ref-lookup fallback.The
if (refEntry) { … } else { resolveRef(...) }split is equivalent to just callingresolveRef(allRefs, activeRefName).hash.resolveRefperforms the same map lookup and raisesMIGRATION.UNKNOWN_REFwhen missing, plus validates the ref-name shape — which the directallRefs[activeRefName]path skips. Collapsing to a single call removes a branch and ensures invalid ref names are reported consistently.♻️ Simplification
if (options.ref) { activeRefName = options.ref; - const refEntry = allRefs[activeRefName]; - if (refEntry) { - activeRefHash = refEntry.hash; - } else { - try { - activeRefHash = resolveRef(allRefs, activeRefName).hash; - } catch (error) { - if (MigrationToolsError.is(error)) { - return notOk( - errorRuntime(error.message, { - why: error.why, - fix: error.fix, - meta: { code: error.code }, - }), - ); - } - throw error; - } - } + try { + activeRefHash = resolveRef(allRefs, activeRefName).hash; + } catch (error) { + if (MigrationToolsError.is(error)) { + return notOk( + errorRuntime(error.message, { + why: error.why, + fix: error.fix, + meta: { code: error.code }, + }), + ); + } + throw error; + } }🤖 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 376 - 397, The branch that directly reads allRefs[activeRefName] is redundant and skips validate logic; replace the if/else with a single call to resolveRef(allRefs, activeRefName).hash to obtain activeRefHash so invalid ref names are handled uniformly by resolveRef. Keep the existing try/catch around resolveRef and preserve the MigrationToolsError handling that returns notOk(errorRuntime(...)), referencing the symbols activeRefName, activeRefHash, allRefs, resolveRef, MigrationToolsError, notOk, and errorRuntime.packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts (2)
47-50: Duplication withresolveMigrationPaths.
resolveRefsDirreimplements logic already present inresolveMigrationPathsfrom../utils/command-helpers.ts, which returnsrefsDiras part of its result. Reusing it keeps refs-dir resolution in one place and ensures all commands compute the same path.♻️ Proposed refactor
-import { addGlobalOptions, setCommandDescriptions } from '../utils/command-helpers'; +import { + addGlobalOptions, + resolveMigrationPaths, + setCommandDescriptions, +} from '../utils/command-helpers'; @@ -function resolveRefsDir(configPath?: string, config?: { migrations?: { dir?: string } }): string { - const base = configPath ? resolve(configPath, '..') : process.cwd(); - return resolve(base, config?.migrations?.dir ?? 'migrations', 'refs'); -}Then replace
resolveRefsDir(options.config, config)call sites withresolveMigrationPaths(options.config, config).refsDir.🤖 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-ref.ts` around lines 47 - 50, resolveRefsDir duplicates logic already implemented by resolveMigrationPaths; remove the local resolveRefsDir function and replace its call sites (e.g., resolveRefsDir(options.config, config)) with resolveMigrationPaths(options.config, config).refsDir, ensuring you import resolveMigrationPaths from ../utils/command-helpers.ts if not already imported and update any references to use the refsDir property returned by resolveMigrationPaths.
196-202:ref get(non-JSON) drops invariants from human-readable output.Given refs now carry
invariants, consider mirroring thelistcommand by appending an[invariants: …]suffix when present. Otherwise users can only discover invariants via--jsonorref list. Minor UX polish.🤖 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-ref.ts` around lines 196 - 202, The non-JSON (human) output in the ref get flow currently only prints value.hash and drops value.invariants; update the callback passed to handleResult so that when flags.json is false it prints value.hash and, if value.invariants exists and is non-empty, appends a human-readable suffix like " [invariants: …]" (e.g., join the invariants array with commas or format similarly to the ref list command). Locate the callback around handleResult(result, flags, ui, (value) => { ... }) and change the ui.output branch that currently does ui.output(value.hash) to build and output the combined string including invariants.packages/1-framework/3-tooling/migration/src/refs.ts (2)
141-146: Temp-file suffix can collide under concurrent writes.
Date.now()has millisecond granularity; twowriteRefcalls for the same name within the same tick (e.g., concurrent CLI invocations or tests) would both write to the same.name.json.<ms>.tmpand the subsequentrenameon one of them could lose the other's data mid-flight. A random suffix (e.g.,crypto.randomUUID()orrandomBytes(8).toString('hex')) makes the temp path unique regardless of timing.♻️ Proposed fix
- const tmpPath = join(dir, `.${name.split('/').pop()}.json.${Date.now()}.tmp`); + const tmpPath = join( + dir, + `.${name.split('/').pop()}.json.${Date.now()}.${randomBytes(6).toString('hex')}.tmp`, + );Plus
import { randomBytes } from 'node:crypto';.🤖 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/refs.ts` around lines 141 - 146, The temp-file suffix using Date.now() (in the tmpPath definition used before writeFile/rename) can collide under concurrent writes; replace the timestamp suffix with a cryptographically-unique suffix (e.g., crypto.randomUUID() or randomBytes(8).toString('hex')) and add the corresponding import from 'node:crypto' so each tmpPath for the same name is unique, leaving the rest of the logic (tmpPath variable, writeFile call, and rename to filePath) unchanged.
168-177:startsWith(refsDir)lacks a separator boundary.If
refsDiris/tmp/refsand a sibling dir/tmp/refs-backupexists,dir.startsWith(refsDir)returns true for that sibling. In practicediris always derived fromjoin(refsDir, name.json)so this won't trigger today, but the cleanup loop is robust only by accident. Consider guarding with a separator-aware check (e.g.,dir === refsDir || dir.startsWith(refsDir + '/')) to make the invariant explicit.🤖 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/refs.ts` around lines 168 - 177, The cleanup loop using dir, refsDir, dirname and rmdir should guard against false positives from startsWith by checking a path-separator boundary; replace the condition that uses dir.startsWith(refsDir) with a separator-aware check (e.g., require dir === refsDir or dir starts with refsDir + path.sep using path.sep) so sibling paths like /tmp/refs-backup are not treated as children of refsDir; update the while condition accordingly and keep the remainder of the rmdir/try/catch logic unchanged.packages/1-framework/3-tooling/migration/test/refs.test.ts (1)
273-348: Consider a test for files deeper than.jsonwith non-.jsonsiblings being pruned.The
ignores non-json filestest only checks at the top level. SincereadRefswalks recursively (readdir(..., { recursive: true })) and filters by.endsWith('.json'), a non-JSON file nested under a subdirectory (e.g.,envs/README.md) would also be ignored — a quick nested variant would lock that behavior in.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/migration/test/refs.test.ts` around lines 273 - 348, Add a test to readRefs that confirms non-.json files are ignored in nested directories: create a subdirectory (e.g., 'envs'), write a valid JSON ref file (e.g., 'envs/staging.json') and a non-JSON sibling (e.g., 'envs/README.md'), call readRefs(refsDir) and assert the result only contains the 'envs/staging' entry; reference the readRefs helper used in refs.test.ts and mirror the style of the existing "ignores non-json files" test to ensure recursive filtering by .endsWith('.json') is validated.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@examples/prisma-next-demo/migration-fixtures/linear/refs/prod.json`:
- Around line 2-6: The fixture's "hash" field is an object but must be a string
per the RefEntry schema and the nested "invariants" inside that object is
misplaced; update the "hash" property to the inner string value (e.g., replace
the object at "hash" with "contract-1" or the proper sha256 string) and move or
merge the array currently at "hash.invariants" into the top-level "invariants"
array (replacing or concatenating with the existing top-level "invariants" as
appropriate) so the file has a string "hash" and a single top-level "invariants"
array.
In `@packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts`:
- Around line 442-448: The test currently contains a tautological assertion
`expect(markerAtB === refEntry.hash).toBe(true)`—replace it with an assertion
that verifies actual behavior: call findPath(graph, markerAtB, refEntry.hash)
and assert the expected result (e.g., an empty path or same-node result) such as
expect(findPath(graph, markerAtB, refEntry.hash)).toHaveLength(0) or
expect(...).toEqual([]); remove the original tautology and keep the check that
the path behavior for markerAtB matches the intended semantics.
- Around line 221-235: The test description "'apply does not mutate ref files'"
is inaccurate because the test never calls the migration apply path; either
change the test to invoke the actual apply flow (run the CLI command or function
that implements "migration apply" and then assert the ref files are
byte-identical before/after) referencing the migration apply entrypoint, or
rename the test to accurately describe what it does (e.g., "writeRef round-trips
through readRef/readRefs") and keep the existing assertions that
readRef/readRefs return the same objects written by writeRef; locate the current
test by the existing test name string and update it accordingly while keeping
the usage of writeRef, readRef, and readRefs intact.
In `@packages/1-framework/3-tooling/migration/src/refs.ts`:
- Around line 180-195: resolveRef currently looks up refs[name] which can return
inherited Object.prototype members (e.g., "constructor"); change resolveRef to
first check ownership with Object.hasOwn(refs, name) and throw the
MIGRATION.UNKNOWN_REF error if the property is not an own property, then read
refs[name]; alternatively ensure refs is created with no prototype
(Object.create(null)) in readRefs, but follow the repo guideline to prefer
Object.hasOwn in resolveRef (function resolveRef) to safely gate the lookup.
---
Nitpick comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts`:
- Around line 47-50: resolveRefsDir duplicates logic already implemented by
resolveMigrationPaths; remove the local resolveRefsDir function and replace its
call sites (e.g., resolveRefsDir(options.config, config)) with
resolveMigrationPaths(options.config, config).refsDir, ensuring you import
resolveMigrationPaths from ../utils/command-helpers.ts if not already imported
and update any references to use the refsDir property returned by
resolveMigrationPaths.
- Around line 196-202: The non-JSON (human) output in the ref get flow currently
only prints value.hash and drops value.invariants; update the callback passed to
handleResult so that when flags.json is false it prints value.hash and, if
value.invariants exists and is non-empty, appends a human-readable suffix like "
[invariants: …]" (e.g., join the invariants array with commas or format
similarly to the ref list command). Locate the callback around
handleResult(result, flags, ui, (value) => { ... }) and change the ui.output
branch that currently does ui.output(value.hash) to build and output the
combined string including invariants.
In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 376-397: The branch that directly reads allRefs[activeRefName] is
redundant and skips validate logic; replace the if/else with a single call to
resolveRef(allRefs, activeRefName).hash to obtain activeRefHash so invalid ref
names are handled uniformly by resolveRef. Keep the existing try/catch around
resolveRef and preserve the MigrationToolsError handling that returns
notOk(errorRuntime(...)), referencing the symbols activeRefName, activeRefHash,
allRefs, resolveRef, MigrationToolsError, notOk, and errorRuntime.
In `@packages/1-framework/3-tooling/migration/src/refs.ts`:
- Around line 141-146: The temp-file suffix using Date.now() (in the tmpPath
definition used before writeFile/rename) can collide under concurrent writes;
replace the timestamp suffix with a cryptographically-unique suffix (e.g.,
crypto.randomUUID() or randomBytes(8).toString('hex')) and add the corresponding
import from 'node:crypto' so each tmpPath for the same name is unique, leaving
the rest of the logic (tmpPath variable, writeFile call, and rename to filePath)
unchanged.
- Around line 168-177: The cleanup loop using dir, refsDir, dirname and rmdir
should guard against false positives from startsWith by checking a
path-separator boundary; replace the condition that uses dir.startsWith(refsDir)
with a separator-aware check (e.g., require dir === refsDir or dir starts with
refsDir + path.sep using path.sep) so sibling paths like /tmp/refs-backup are
not treated as children of refsDir; update the while condition accordingly and
keep the remainder of the rmdir/try/catch logic unchanged.
In `@packages/1-framework/3-tooling/migration/test/refs.test.ts`:
- Around line 273-348: Add a test to readRefs that confirms non-.json files are
ignored in nested directories: create a subdirectory (e.g., 'envs'), write a
valid JSON ref file (e.g., 'envs/staging.json') and a non-JSON sibling (e.g.,
'envs/README.md'), call readRefs(refsDir) and assert the result only contains
the 'envs/staging' entry; reference the readRefs helper used in refs.test.ts and
mirror the style of the existing "ignores non-json files" test to ensure
recursive filtering by .endsWith('.json') is validated.
🪄 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: 900e4d47-62eb-4d9d-a988-40de89a98353
⛔ Files ignored due to path filters (2)
projects/graph-based-migrations/plans/invariant-aware-routing-plan.mdis excluded by!projects/**projects/graph-based-migrations/specs/invariant-aware-routing.spec.mdis excluded by!projects/**
📒 Files selected for processing (44)
examples/prisma-next-demo/migration-fixtures/complex/refs.jsonexamples/prisma-next-demo/migration-fixtures/complex/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/complex/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/converging-branches/refs.jsonexamples/prisma-next-demo/migration-fixtures/converging-branches/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/experiment.jsonexamples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/diamond/refs.jsonexamples/prisma-next-demo/migration-fixtures/diamond/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/kitchen-sink/refs.jsonexamples/prisma-next-demo/migration-fixtures/kitchen-sink/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/linear/refs.jsonexamples/prisma-next-demo/migration-fixtures/linear/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/long-spine/refs.jsonexamples/prisma-next-demo/migration-fixtures/long-spine/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/long-spine/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs/feature.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/rollback-continue/refs.jsonexamples/prisma-next-demo/migration-fixtures/rollback-continue/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs.jsonexamples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/single-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/single-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/single-branch/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs/experiment.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs/feature.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs/prod.jsonpackages/1-framework/3-tooling/cli/src/commands/migration-apply.tspackages/1-framework/3-tooling/cli/src/commands/migration-ref.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/test/commands/migration-ref.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-status.test.tspackages/1-framework/3-tooling/migration/src/exports/refs.tspackages/1-framework/3-tooling/migration/src/refs.tspackages/1-framework/3-tooling/migration/test/refs.test.ts
💤 Files with no reviewable changes (14)
- examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs.json
- examples/prisma-next-demo/migration-fixtures/linear/refs.json
- examples/prisma-next-demo/migration-fixtures/converging-branches/refs.json
- examples/prisma-next-demo/migration-fixtures/rollback-continue/refs.json
- examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/diamond/refs.json
- examples/prisma-next-demo/migration-fixtures/long-spine/refs.json
- examples/prisma-next-demo/migration-fixtures/single-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/complex/refs.json
- examples/prisma-next-demo/migration-fixtures/multi-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/sub-branches/refs.json
- examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs.json
- packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts
- examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs.json
- resolveRef: guard with Object.hasOwn so ref names like 'constructor'
don't walk the Object.prototype chain and bypass UNKNOWN_REF. Added a
regression test covering the 'constructor' lookup.
- migration-ref.test.ts: dropped a misnamed test ('apply does not
mutate ref files') that never invoked apply — duplicative of the
CRUD coverage in refs.test.ts.
- migration-ref.test.ts: replaced a tautological `markerAtB === refEntry.hash`
assertion with an actual findPath check (path from B to B is empty).
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/1-framework/3-tooling/migration/src/refs.ts (1)
104-109: Silently swallowing non-ENOENTreadFileerrors inreadRefs.The empty
catch { continue }treats every read failure as a missing-file case. That's fine for a benign race (file deleted betweenreaddirandreadFile), but it also silently dropsEACCES,EPERM,EISDIR, etc., producing aRefsthat silently omits entries — callers will then see a misleadingUNKNOWN_REFdownstream. Consider narrowing the swallow to ENOENT only:♻️ Proposed change
let raw: string; try { raw = await readFile(filePath, 'utf-8'); - } catch { - continue; + } catch (error) { + if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') { + continue; + } + throw error; }🤖 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/refs.ts` around lines 104 - 109, In readRefs, the catch block around readFile(filePath, 'utf-8') currently swallows all errors (declared via raw variable), which hides real failures; change the catch to inspect the thrown error (e.g., err.code) and only continue when err.code === 'ENOENT' (or err?.code === 'ENOENT'), otherwise rethrow the error so EACCES/EPERM/EISDIR/etc. bubble up; keep references to readRefs, readFile, filePath and the raw variable when making this change.
🤖 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/commands/migration-ref.test.ts`:
- Around line 419-424: The assertion using atTarget (const atTarget = markerHash
=== refEntry.hash; expect(atTarget).toBe(false);) is tautological because
markerHash and refEntry.hash are test constants; remove these two lines and
either (a) drop the redundant check entirely since findPath(graph, markerHash,
refEntry.hash) already asserts behavior, or (b) replace them with a meaningful
assertion such as verifying the path contents or distance (e.g., assert the
nodes/length returned by findPath or check resolver/distance logic related to
markerHash and refEntry.hash) so the test actually validates runtime behavior;
update the assertions around findPath, markerHash, and refEntry to reflect the
chosen approach.
---
Nitpick comments:
In `@packages/1-framework/3-tooling/migration/src/refs.ts`:
- Around line 104-109: In readRefs, the catch block around readFile(filePath,
'utf-8') currently swallows all errors (declared via raw variable), which hides
real failures; change the catch to inspect the thrown error (e.g., err.code) and
only continue when err.code === 'ENOENT' (or err?.code === 'ENOENT'), otherwise
rethrow the error so EACCES/EPERM/EISDIR/etc. bubble up; keep references to
readRefs, readFile, filePath and the raw variable when making this change.
🪄 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: a3feccd0-cb6a-45f5-b6c6-1304628d5c81
📒 Files selected for processing (5)
examples/prisma-next-demo/migration-fixtures/linear/refs/prod.jsonpackages/1-framework/3-tooling/cli/src/commands/migration-ref.tspackages/1-framework/3-tooling/cli/test/commands/migration-ref.test.tspackages/1-framework/3-tooling/migration/src/refs.tspackages/1-framework/3-tooling/migration/test/refs.test.ts
✅ Files skipped from review due to trivial changes (1)
- examples/prisma-next-demo/migration-fixtures/linear/refs/prod.json
98f7bdc to
19b136a
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/1-framework/3-tooling/migration/src/refs.ts (1)
168-177:⚠️ Potential issue | 🟡 MinorBare
catchsilently swallows non-ENOTEMPTYerrors during cleanup.The cleanup loop intends to stop when a parent directory is non-empty (
ENOTEMPTY), but the barecatch { break; }also masks real problems — e.g.,EACCES/EPERM(permissions),EBUSY(Windows handle lock), orEIO(I/O failure) — leaving the caller with no signal that deletion partially failed. At minimum, break only onENOTEMPTY(and arguablyENOENT, harmless) and rethrow anything else so that real filesystem errors surface.🛡️ Proposed fix
// Clean empty parent directories up to refsDir let dir = dirname(filePath); while (dir !== refsDir && dir.startsWith(refsDir)) { try { await rmdir(dir); dir = dirname(dir); - } catch { - break; + } catch (error) { + const code = error instanceof Error ? (error as { code?: string }).code : undefined; + if (code === 'ENOTEMPTY' || code === 'ENOENT') { + break; + } + throw error; } }🤖 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/refs.ts` around lines 168 - 177, The cleanup loop currently swallows all errors in the try/catch around rmdir(dirname) — update the catch in the loop that references dirname, refsDir, filePath and rmdir so it only breaks silently for benign filesystem errors (at minimum 'ENOTEMPTY' and optionally 'ENOENT') and rethrows any other errors (e.g., 'EACCES', 'EPERM', 'EBUSY', 'EIO') so real failures surface to the caller; implement an error check on err.code inside the catch and only break for the allowed codes, otherwise rethrow the error.
🧹 Nitpick comments (2)
packages/1-framework/3-tooling/migration/src/refs.ts (1)
141-146: Optional: tmp-file name collision window under concurrent writers.
${Date.now()}is millisecond-precision; two concurrentwriteRefcalls targeting the same ref name (or different refs that collapse to the same tmp basename in the same directory) can produce identicaltmpPath, causing interleavedwriteFilecontent beforerename. Append a small random component (e.g.,randomBytes(6).toString('hex')orrandomUUID()) to make the temp path collision-free.♻️ Proposed refactor
+import { randomBytes } from 'node:crypto'; ... - const tmpPath = join(dir, `.${name.split('/').pop()}.json.${Date.now()}.tmp`); + const tmpSuffix = `${Date.now()}.${randomBytes(6).toString('hex')}`; + const tmpPath = join(dir, `.${name.split('/').pop()}.json.${tmpSuffix}.tmp`);🤖 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/refs.ts` around lines 141 - 146, The tmpPath generation in writeRef using `${Date.now()}` can collide under concurrent writes causing writeFile races before rename; modify the tmpPath creation (tmpPath variable) to include a cryptographically safe random suffix (e.g., randomBytes(6).toString('hex') or randomUUID()) so each temporary filename is unique, then continue to use writeFile(tmpPath, ...) and rename(tmpPath, filePath) as before.packages/1-framework/3-tooling/migration/test/refs.test.ts (1)
1-501: Optional: the file is at the 500-line split threshold.File length is right at the coding-guideline threshold ("Keep test files under 500 lines"). No action needed now, but as more coverage lands (e.g., in M1+), consider splitting along natural
describeboundaries intorefs.validate.test.ts(validateRefName/validateRefValue),refs.storage.test.ts(writeRef/readRef/readRefs/deleteRef), andrefs.resolve.test.ts(resolveRef + round-trip).As per coding guidelines: "Keep test files under 500 lines to maintain readability and navigability. If a test file exceeds this limit, it should be split into multiple files."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/migration/test/refs.test.ts` around lines 1 - 501, The test file is right at the 500-line guideline threshold; split it into smaller test files by grouping related describes: move validateRefName and validateRefValue tests into refs.validate.test.ts (tests referencing validateRefName and validateRefValue), move writeRef/readRef/readRefs/deleteRef tests into refs.storage.test.ts (tests referencing writeRef, readRef, readRefs, deleteRef), and move resolveRef plus the round-trip suite into refs.resolve.test.ts (tests referencing resolveRef and the round-trip describe); ensure imports (MigrationToolsError, RefEntry, Refs) and constant fixtures (HASH_A, HASH_B, ENTRY_A, ENTRY_B) are preserved or duplicated as needed and update any test setup/teardown (beforeEach/afterEach) to work per-file.
🤖 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/migration/src/refs.ts`:
- Around line 86-127: The readRefs function currently swallows all readFile
errors when loading each JSON file; change the readFile catch in readRefs so it
only skips the file for benign errors (file not found race ENOENT or EISDIR) and
rethrows for other errors (permission, I/O, etc.). Locate the readFile try/catch
inside readRefs (the block that sets raw and currently does "catch { continue;
}"), inspect the caught error (ensure it's an Error and read its code property),
continue only when code === 'ENOENT' or code === 'EISDIR', otherwise rethrow the
error so the CLI surfaces real failures. Ensure you reference readFile,
jsonFiles, and readRefs when making the change.
---
Duplicate comments:
In `@packages/1-framework/3-tooling/migration/src/refs.ts`:
- Around line 168-177: The cleanup loop currently swallows all errors in the
try/catch around rmdir(dirname) — update the catch in the loop that references
dirname, refsDir, filePath and rmdir so it only breaks silently for benign
filesystem errors (at minimum 'ENOTEMPTY' and optionally 'ENOENT') and rethrows
any other errors (e.g., 'EACCES', 'EPERM', 'EBUSY', 'EIO') so real failures
surface to the caller; implement an error check on err.code inside the catch and
only break for the allowed codes, otherwise rethrow the error.
---
Nitpick comments:
In `@packages/1-framework/3-tooling/migration/src/refs.ts`:
- Around line 141-146: The tmpPath generation in writeRef using `${Date.now()}`
can collide under concurrent writes causing writeFile races before rename;
modify the tmpPath creation (tmpPath variable) to include a cryptographically
safe random suffix (e.g., randomBytes(6).toString('hex') or randomUUID()) so
each temporary filename is unique, then continue to use writeFile(tmpPath, ...)
and rename(tmpPath, filePath) as before.
In `@packages/1-framework/3-tooling/migration/test/refs.test.ts`:
- Around line 1-501: The test file is right at the 500-line guideline threshold;
split it into smaller test files by grouping related describes: move
validateRefName and validateRefValue tests into refs.validate.test.ts (tests
referencing validateRefName and validateRefValue), move
writeRef/readRef/readRefs/deleteRef tests into refs.storage.test.ts (tests
referencing writeRef, readRef, readRefs, deleteRef), and move resolveRef plus
the round-trip suite into refs.resolve.test.ts (tests referencing resolveRef and
the round-trip describe); ensure imports (MigrationToolsError, RefEntry, Refs)
and constant fixtures (HASH_A, HASH_B, ENTRY_A, ENTRY_B) are preserved or
duplicated as needed and update any test setup/teardown (beforeEach/afterEach)
to work per-file.
🪄 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: f8b1f7bc-9f33-4f80-a670-777db0b43de7
⛔ 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 (44)
examples/prisma-next-demo/migration-fixtures/complex/refs.jsonexamples/prisma-next-demo/migration-fixtures/complex/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/complex/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/converging-branches/refs.jsonexamples/prisma-next-demo/migration-fixtures/converging-branches/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/experiment.jsonexamples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/diamond/refs.jsonexamples/prisma-next-demo/migration-fixtures/diamond/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/kitchen-sink/refs.jsonexamples/prisma-next-demo/migration-fixtures/kitchen-sink/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/linear/refs.jsonexamples/prisma-next-demo/migration-fixtures/linear/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/long-spine/refs.jsonexamples/prisma-next-demo/migration-fixtures/long-spine/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/long-spine/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs/feature.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/rollback-continue/refs.jsonexamples/prisma-next-demo/migration-fixtures/rollback-continue/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs.jsonexamples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/single-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/single-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/single-branch/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs/experiment.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs/feature.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs/prod.jsonpackages/1-framework/3-tooling/cli/src/commands/migration-apply.tspackages/1-framework/3-tooling/cli/src/commands/migration-ref.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/test/commands/migration-ref.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-status.test.tspackages/1-framework/3-tooling/migration/src/exports/refs.tspackages/1-framework/3-tooling/migration/src/refs.tspackages/1-framework/3-tooling/migration/test/refs.test.ts
💤 Files with no reviewable changes (14)
- examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs.json
- examples/prisma-next-demo/migration-fixtures/linear/refs.json
- examples/prisma-next-demo/migration-fixtures/single-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs.json
- examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/diamond/refs.json
- examples/prisma-next-demo/migration-fixtures/sub-branches/refs.json
- examples/prisma-next-demo/migration-fixtures/multi-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/rollback-continue/refs.json
- examples/prisma-next-demo/migration-fixtures/complex/refs.json
- examples/prisma-next-demo/migration-fixtures/long-spine/refs.json
- packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts
- examples/prisma-next-demo/migration-fixtures/converging-branches/refs.json
✅ Files skipped from review due to trivial changes (18)
- examples/prisma-next-demo/migration-fixtures/sub-branches/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/multi-branch/refs/feature.json
- examples/prisma-next-demo/migration-fixtures/rollback-continue/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/experiment.json
- examples/prisma-next-demo/migration-fixtures/complex/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/converging-branches/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/long-spine/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/multi-branch/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/diamond/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/long-spine/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/complex/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/sub-branches/refs/feature.json
- examples/prisma-next-demo/migration-fixtures/single-branch/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/multi-branch/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/sub-branches/refs/experiment.json
🚧 Files skipped from review as they are similar to previous changes (8)
- examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/linear/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/single-branch/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/prod.json
- 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-ref.ts
- packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts
e6389f1 to
52e6917
Compare
There was a problem hiding this comment.
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)
374-395:⚠️ Potential issue | 🟠 MajorDirect
allRefs[activeRefName]lookup bypasses the prototype-chain guard added inresolveRef.
allRefsis a plain object, soallRefs["constructor"]returnsObject(the constructor function, truthy), makingrefEntrynon-null and settingactiveRefHash = refEntry.hash→undefined. TheresolveReffallback is never reached, so instead of surfacingMIGRATION.UNKNOWN_REF(as intended by theObject.hasOwnguard inresolveRef), the command silently ignores--ref constructor(or any name matching anObject.prototypemember) and falls through to contract-hash targeting.The direct lookup is also redundant —
resolveRefdoes the same map lookup, just with correct own-property semantics. Simplest fix is to drop the branch:🛡️ Proposed fix
if (options.ref) { activeRefName = options.ref; - const refEntry = allRefs[activeRefName]; - if (refEntry) { - activeRefHash = refEntry.hash; - } else { - try { - activeRefHash = resolveRef(allRefs, activeRefName).hash; - } catch (error) { - if (MigrationToolsError.is(error)) { - return notOk( - errorRuntime(error.message, { - why: error.why, - fix: error.fix, - meta: { code: error.code }, - }), - ); - } - throw error; - } - } + try { + activeRefHash = resolveRef(allRefs, activeRefName).hash; + } catch (error) { + if (MigrationToolsError.is(error)) { + return notOk( + errorRuntime(error.message, { + why: error.why, + fix: error.fix, + meta: { code: error.code }, + }), + ); + } + throw error; + } }🤖 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 374 - 395, The branch that directly reads allRefs[activeRefName] bypasses the prototype-safe check in resolveRef and can misinterpret prototype keys (e.g., "constructor"); remove the direct lookup and always call resolveRef(allRefs, activeRefName) when options.ref is provided, then assign activeRefHash from its .hash, keeping the existing MigrationToolsError handling (the try/catch and notOk(errorRuntime(...))) unchanged; update references in the block around options.ref so only resolveRef is used to obtain the ref entry and hash.
♻️ Duplicate comments (1)
packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts (1)
422-423:⚠️ Potential issue | 🟡 MinorTautological
atTargetassertion still present.
markerHash === refEntry.hashcomparesEMPTY_CONTRACT_HASHtoHASH_B, both fixture constants set up earlier in the same test — the assertion can never fail regardless of production behavior. The immediately precedingfindPath(graph, markerHash, refEntry.hash)check already covers the meaningful behavior.♻️ Proposed fix
const markerHash = EMPTY_CONTRACT_HASH; const pathToRef = findPath(graph, markerHash, refEntry.hash); expect(pathToRef).toHaveLength(2); - - const atTarget = markerHash === refEntry.hash; - expect(atTarget).toBe(false);🤖 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/commands/migration-ref.test.ts` around lines 422 - 423, Remove the tautological assertion that compares markerHash to refEntry.hash (the atTarget check) since markerHash and refEntry.hash are fixture constants (EMPTY_CONTRACT_HASH and HASH_B) and the meaningful behavior is already asserted by the preceding findPath(graph, markerHash, refEntry.hash) check; specifically, delete the atTarget variable and the expect(atTarget).toBe(false) assertion so the test relies only on the findPath assertion.
🧹 Nitpick comments (1)
packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts (1)
3-3: Usepathefor path operations.The sibling test file
packages/1-framework/3-tooling/migration/test/refs.test.ts(line 3) already importsjoinfrompathe; keeping this file onnode:pathis an inconsistency within the PR.♻️ Proposed fix
-import { join } from 'node:path'; +import { join } from 'pathe';As per coding guidelines: "Use
patheinstead ofnode:pathfor path manipulation in TypeScript files."🤖 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/commands/migration-ref.test.ts` at line 3, Replace the import of join from 'node:path' with the pathe equivalent: update the module import so the file uses join from 'pathe' (i.e., change the import that currently brings in join from 'node:path' to import join from 'pathe') so it matches the sibling test (refs.test.ts) and the project's path-handling guideline.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 374-395: The branch that directly reads allRefs[activeRefName]
bypasses the prototype-safe check in resolveRef and can misinterpret prototype
keys (e.g., "constructor"); remove the direct lookup and always call
resolveRef(allRefs, activeRefName) when options.ref is provided, then assign
activeRefHash from its .hash, keeping the existing MigrationToolsError handling
(the try/catch and notOk(errorRuntime(...))) unchanged; update references in the
block around options.ref so only resolveRef is used to obtain the ref entry and
hash.
---
Duplicate comments:
In `@packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts`:
- Around line 422-423: Remove the tautological assertion that compares
markerHash to refEntry.hash (the atTarget check) since markerHash and
refEntry.hash are fixture constants (EMPTY_CONTRACT_HASH and HASH_B) and the
meaningful behavior is already asserted by the preceding findPath(graph,
markerHash, refEntry.hash) check; specifically, delete the atTarget variable and
the expect(atTarget).toBe(false) assertion so the test relies only on the
findPath assertion.
---
Nitpick comments:
In `@packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts`:
- Line 3: Replace the import of join from 'node:path' with the pathe equivalent:
update the module import so the file uses join from 'pathe' (i.e., change the
import that currently brings in join from 'node:path' to import join from
'pathe') so it matches the sibling test (refs.test.ts) and the project's
path-handling guideline.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: a1e63a72-5acf-40f4-88a2-1c92d0916996
⛔ 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 (44)
examples/prisma-next-demo/migration-fixtures/complex/refs.jsonexamples/prisma-next-demo/migration-fixtures/complex/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/complex/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/converging-branches/refs.jsonexamples/prisma-next-demo/migration-fixtures/converging-branches/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/experiment.jsonexamples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/diamond/refs.jsonexamples/prisma-next-demo/migration-fixtures/diamond/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/kitchen-sink/refs.jsonexamples/prisma-next-demo/migration-fixtures/kitchen-sink/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/linear/refs.jsonexamples/prisma-next-demo/migration-fixtures/linear/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/long-spine/refs.jsonexamples/prisma-next-demo/migration-fixtures/long-spine/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/long-spine/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs/feature.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/multi-branch/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/rollback-continue/refs.jsonexamples/prisma-next-demo/migration-fixtures/rollback-continue/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs.jsonexamples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/single-branch/refs.jsonexamples/prisma-next-demo/migration-fixtures/single-branch/refs/prod.jsonexamples/prisma-next-demo/migration-fixtures/single-branch/refs/staging.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs/experiment.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs/feature.jsonexamples/prisma-next-demo/migration-fixtures/sub-branches/refs/prod.jsonpackages/1-framework/3-tooling/cli/src/commands/migration-apply.tspackages/1-framework/3-tooling/cli/src/commands/migration-ref.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/test/commands/migration-ref.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-status.test.tspackages/1-framework/3-tooling/migration/src/exports/refs.tspackages/1-framework/3-tooling/migration/src/refs.tspackages/1-framework/3-tooling/migration/test/refs.test.ts
💤 Files with no reviewable changes (14)
- examples/prisma-next-demo/migration-fixtures/single-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs.json
- examples/prisma-next-demo/migration-fixtures/multi-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/converging-branches/refs.json
- examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/sub-branches/refs.json
- examples/prisma-next-demo/migration-fixtures/long-spine/refs.json
- examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs.json
- examples/prisma-next-demo/migration-fixtures/diamond/refs.json
- examples/prisma-next-demo/migration-fixtures/complex/refs.json
- examples/prisma-next-demo/migration-fixtures/rollback-continue/refs.json
- examples/prisma-next-demo/migration-fixtures/linear/refs.json
- packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts
- examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs.json
✅ Files skipped from review due to trivial changes (18)
- examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/experiment.json
- examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/rollback-continue/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/sub-branches/refs/feature.json
- examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/sub-branches/refs/experiment.json
- examples/prisma-next-demo/migration-fixtures/single-branch/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/converging-branches/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/multi-branch/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/complex/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/sub-branches/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/single-branch/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/multi-branch/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/complex/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/long-spine/refs/prod.json
- packages/1-framework/3-tooling/migration/src/exports/refs.ts
- examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/prod.json
🚧 Files skipped from review as they are similar to previous changes (5)
- examples/prisma-next-demo/migration-fixtures/diamond/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/long-spine/refs/staging.json
- examples/prisma-next-demo/migration-fixtures/linear/refs/prod.json
- examples/prisma-next-demo/migration-fixtures/multi-branch/refs/feature.json
The empty-parent walk after deleteRef wrapped `rmdir` in a bare
`catch {}`, which swallowed every error — not just the intended
"directory has siblings" signal that means "stop walking up." A real
failure like EACCES or EIO would silently leave the working tree in a
half-cleaned state.
Narrow the catch to the expected codes (ENOTEMPTY on Linux, EEXIST on
some BSDs, ENOENT for concurrent removal) and rethrow anything else.
Matches the pattern used elsewhere in this file.
Addresses review feedback from @SevInf on PR #372.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
packages/1-framework/3-tooling/migration/src/refs.ts (2)
97-123:readRefsaccepts files with invalid ref names.
refNameFromPathonly strips the.jsonsuffix; the resultingnameis never run throughvalidateRefName. A stray file such asFoo.json,.hidden.json, orweird name.json(e.g., committed by hand) ends up keyed intorefsand visible viaObject.keys(refs)(CLI listing, error hints, etc.), even thoughresolveRefwill refuse to look it up later. Filtering invalid names here keeps the in-memory map consistent with what callers can actually resolve.♻️ Proposed change
for (const jsonFile of jsonFiles) { const filePath = join(refsDir, jsonFile); const name = refNameFromPath(refsDir, filePath); + if (!validateRefName(name)) { + continue; + }🤖 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/refs.ts` around lines 97 - 123, readRefs currently accepts JSON files whose names (derived by refNameFromPath) may be invalid and are never validated, causing refs to contain keys that resolveRef will reject; update readRefs to call validateRefName(name) after computing name and skip the file (continue) when validation fails so only valid ref names are added to the refs map, referencing the functions refNameFromPath, validateRefName, and readRefs (and leaving existing JSON parse/RefEntrySchema checks intact).
141-146: Temp filename only usesDate.now()— concurrent writers to the same ref can collide.Two
writeRefcalls for the samenamewithin the same millisecond compute identicaltmpPaths; bothwriteFiles open/truncate the same file, the writes interleave, and the surviving content (after one finishes and the other renames) can be a partial/corrupted JSON. Adding a process- or randomness-derived component avoids this.♻️ Proposed change
- const tmpPath = join(dir, `.${name.split('/').pop()}.json.${Date.now()}.tmp`); + const tmpPath = join( + dir, + `.${name.split('/').pop()}.json.${process.pid}.${Date.now()}.${randomUUID()}.tmp`, + );with
import { randomUUID } from 'node:crypto';(orMath.random().toString(36).slice(2)if you prefer to avoid the import).🤖 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/refs.ts` around lines 141 - 146, The temporary filename generation for tmpPath uses only Date.now() which can collide for concurrent writes; update the tmp filename in the write logic (where tmpPath is built) to append a unique randomness or process-derived token (e.g., use randomUUID() from node:crypto or Math.random().toString(36).slice(2) alongside Date.now()), and add the corresponding import if using randomUUID; keep the rest of the writeFile/rename flow unchanged so each writeRef/tmpPath is globally unique and avoids interleaved/truncated JSON.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/1-framework/3-tooling/migration/src/refs.ts`:
- Around line 97-123: readRefs currently accepts JSON files whose names (derived
by refNameFromPath) may be invalid and are never validated, causing refs to
contain keys that resolveRef will reject; update readRefs to call
validateRefName(name) after computing name and skip the file (continue) when
validation fails so only valid ref names are added to the refs map, referencing
the functions refNameFromPath, validateRefName, and readRefs (and leaving
existing JSON parse/RefEntrySchema checks intact).
- Around line 141-146: The temporary filename generation for tmpPath uses only
Date.now() which can collide for concurrent writes; update the tmp filename in
the write logic (where tmpPath is built) to append a unique randomness or
process-derived token (e.g., use randomUUID() from node:crypto or
Math.random().toString(36).slice(2) alongside Date.now()), and add the
corresponding import if using randomUUID; keep the rest of the writeFile/rename
flow unchanged so each writeRef/tmpPath is globally unique and avoids
interleaved/truncated JSON.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 213a688f-c49a-4152-bcee-2c2e5c1aa93c
📒 Files selected for processing (1)
packages/1-framework/3-tooling/migration/src/refs.ts
Spec for invariant-aware migration routing end-to-end. Refs can declare required invariants (per-file `migrations/refs/<name>.json`); the CLI picks the shortest graph path whose edges collectively provide them, or fails with a structured `NO_INVARIANT_PATH` error naming what's missing and showing the structural fallback path. Key design decisions: - `invariantId?: string` on `DataTransformOperation` is the opt-in routing key; `name` keeps its retry/ledger identity. Rename of `name` never breaks a ref. - `providedInvariants` on `migration.json` is the attestation-covered aggregate; `MigrationChainEntry.invariants` propagates from the manifest at graph-reconstruction time. - `prisma_contract.marker` grows an `invariants text[]` column (Mongo: equivalent field on the marker doc); runner unions applied invariants on each successful apply; `readMarker` returns the set with graceful fallback for deployments pre-ALTER. No new SPI. - `findPathWithInvariants(graph, from, to, required)` returns the shortest path whose edges collectively cover `required`, or `null`. BFS over `(node, covered-set)` states with state-level dedup. - CLI computes `effectiveRequired = ref.invariants − marker.invariants` and routes through the primitive; `status` surfaces required / applied / missing sets. Plan structures five slices (M0–M4) with an explicit dependency graph: M0 ref-file refactor (landed), M1 marker-side storage, M2 edges declare invariants, M3 pathfinder primitive, M4 CLI integration. M1 and M2 are orthogonal; M3 waits for M2; M4 integrates everything. Also amends `data-migrations-spec.md` to point at the routing spec for §Graph integration, adds a refinement pointer to §D2 (identity-by-name split via `invariantId`), and prunes stale acceptance criteria / non-goals that now live in the routing spec.
Refs move from a monolithic `migrations/refs.json` to a per-ref
directory layout at `migrations/refs/<name>.json`. Each ref file is a
typed `RefEntry = { hash, invariants: string[] }` — laying the
groundwork for invariant-aware routing (see
`projects/graph-based-migrations/specs/invariant-aware-routing.spec.md`).
- `readRef`, `readRefs`, `writeRef`, `deleteRef`, `resolveRef` on the
new per-file API in `packages/1-framework/3-tooling/migration/src/refs.ts`.
Validation is Arktype-backed; write path is atomic-rename; delete
walks empty parent directories.
- `validateRefName` / `validateRefValue` surface at the public API;
format rules mirror `REF_NAME_PATTERN`.
- CLI commands (`migration ref set/list/rm`, `migration apply --ref`,
`migration status --ref`) switch from `refsPath` to `refsDir`.
- `migration-ref` uses the shared `resolveMigrationPaths` helper
rather than duplicating path-resolution logic.
- All fixture refs.json files in `examples/prisma-next-demo/migration-fixtures/`
converted to per-directory layout.
No runtime consumer of `ref.invariants` yet — that's M1–M4 of the
routing plan. This commit is M0.
The empty-parent walk after deleteRef wrapped `rmdir` in a bare
`catch {}`, which swallowed every error — not just the intended
"directory has siblings" signal that means "stop walking up." A real
failure like EACCES or EIO would silently leave the working tree in a
half-cleaned state.
Narrow the catch to the expected codes (ENOTEMPTY on Linux, EEXIST on
some BSDs, ENOENT for concurrent removal) and rethrow anything else.
Matches the pattern used elsewhere in this file.
Addresses review feedback from @SevInf on PR #372.
The `--ref` branch in `migration status` was doing a direct `allRefs[activeRefName]` lookup before falling back to `resolveRef`. Refs is a plain `Record<string, RefEntry>`, so an attacker- or typo- supplied name like `"constructor"` returned `Object.prototype.constructor` truthy, dereferenced `.hash` as undefined, and assigned `undefined` to `activeRefHash` — bypassing `resolveRef`'s `Object.hasOwn` gate (which exists for exactly this reason; see `refs.ts:181`). Collapse to a single `resolveRef` call inside the existing MigrationToolsError try/catch. The fast-path was a misoptimisation: `resolveRef` is already O(1) and is the intended public entry point.
`readRefs` looped over `jsonFiles` (output of `readdir { recursive: true }`)
and wrapped each `readFile` in `catch { continue; }`. The intent was to
tolerate the TOCTOU race where a file is removed between `readdir` and
`readFile`, but the bare catch swallowed every error — permissions
failures, I/O errors, EMFILE, etc. — silently dropping the ref from the
result with no diagnostic.
Narrow the catch to ENOENT (the actual race) and EISDIR (defensive
against a directory whose name ends in `.json`). Anything else
propagates so the CLI surfaces real failures.
Same pattern as the rmdir cleanup fix (f5776a4).
c52addd to
5d680bc
Compare
closes [TML-2305](https://linear.app/prisma-company/issue/TML-2305/ref-file-refactor-per-file-layout-with-invariants-m0-of-tml-2297) part of [TML-2297](https://linear.app/prisma-company/issue/TML-2297/pn-invariant-aware-routing) ## Intent Lay the storage groundwork for invariant-aware migration routing. Environment refs need to carry *required invariants* alongside their target hash so that a future pathfinder (specced in the accompanying doc) can route through paths that satisfy those invariants. The ref format also moves from a single `refs.json` blob to a per-file directory layout — one file per ref — so refs are independently versionable, diffable, and editable. This PR lands the M0 slice of the invariant-aware-routing spec. The spec + plan ship alongside it for context; subsequent PRs implement M1–M5. ## Change map - **Implementation**: - [packages/1-framework/3-tooling/migration/src/refs.ts](packages/1-framework/3-tooling/migration/src/refs.ts) — `RefEntry`, Arktype schema, per-file `readRef`/`writeRef`/`deleteRef`, directory walk for `readRefs`, validation helpers, atomic-rename write, empty-parent cleanup on delete. - [packages/1-framework/3-tooling/migration/src/exports/refs.ts](packages/1-framework/3-tooling/migration/src/exports/refs.ts) — widened the public surface. - [packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts](packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts) — switched `refsPath` to `refsDir` in the shared path resolver. - [packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts](packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts) — resolves refs via the per-file API, unwraps `.hash` at the call site. - [packages/1-framework/3-tooling/cli/src/commands/migration-status.ts](packages/1-framework/3-tooling/cli/src/commands/migration-status.ts) — same adjustment for the status command. - [packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts](packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts) — `ref set/list/rm` rewritten against the per-file API. - **Tests (evidence)**: - [packages/1-framework/3-tooling/migration/test/refs.test.ts](packages/1-framework/3-tooling/migration/test/refs.test.ts) — 52 tests covering the storage primitives, validation, atomicity, parent-directory cleanup, invariants on `RefEntry`. - [packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts](packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts) — CLI flows (`ref set`, `ref list`, `ref rm`) against the per-file layout. - 17 migration fixture directories under [test/integration/test/migration-fixtures/](test/integration/test/migration-fixtures/) migrated to the new layout (one `refs/<name>.json` per ref). - Stale CLI test for the flat-`refs.json` API removed. - **Docs (context)**: - [projects/graph-based-migrations/specs/invariant-aware-routing.spec.md](projects/graph-based-migrations/specs/invariant-aware-routing.spec.md) — full spec: pathfinder, decision surface, errors, marker-side applied-invariants storage, CLI. Prerequisites section marks this PR's work as P1. - [projects/graph-based-migrations/plans/invariant-aware-routing-plan.md](projects/graph-based-migrations/plans/invariant-aware-routing-plan.md) — milestones, one PR each; this PR ships M0. ## The story 1. **Refs gain invariants as a first-class field.** Before this PR, a ref was `{ name: hash }` inside a monolithic `migrations/refs.json`. That format has nowhere to declare "to reach this target state, the database must have invariants X and Y satisfied" — which the invariant-aware routing spec needs. `RefEntry = { hash, invariants: readonly string[] }` replaces the bare-string value; the hash is still validated as `sha256:empty | sha256:<64-hex>`, invariants are free-form names validated by Arktype. 2. **One file per ref, not one blob.** `migrations/refs/<name>.json` replaces the old `migrations/refs.json`. Ref names are validated against a conservative pattern (`^[a-z0-9](...)?(/[a-z0-9]...)*$`) — lowercase, hyphen-allowed, slash-namespaced, no dots or trailing slashes. The layout supports nested refs (`feature/my-branch`) without schema pain; each ref is an independently editable file in the working tree, which plays better with git review. 3. **Storage primitives + helpers.** `readRef(refsDir, name)`, `readRefs(refsDir)`, `writeRef(refsDir, name, entry)`, `deleteRef(refsDir, name)`, `resolveRef(refs, name)`, `validateRefName`, `validateRefValue`. Writes are atomic (tmp file + `rename`); deletes walk empty parent directories back up to `refsDir`; reads swallow `ENOENT` and return empty to keep callers simple. Arktype schema narrows on parse to reject invalid hashes at the storage boundary. 4. **CLI call sites threaded through.** `migration apply --ref`, `migration status --ref`, and `migration ref set/list/rm` all switch from `refsPath` to `refsDir`. `resolveRef` now returns `RefEntry`, so the three callers that previously consumed a bare string (`migration apply`, `migration status`) unwrap `.hash` explicitly. No behavior change for users who never pass `--ref`. 5. **Spec + plan land alongside.** The docs commit establishes the end-to-end roadmap so future reviewers can see where M0 fits. M1–M5 decompose the remaining work into independently shippable PRs, with the test-coverage matrix mapping every acceptance criterion to a verification. ## Behavior changes & evidence - **Refs are structured records, not strings.** `RefEntry = { hash, invariants: readonly string[] }`. The CLI continues to accept a plain hash on `migration ref set <name> <hash>` and implicitly uses `invariants: []`; richer payloads are edited by hand in the per-file JSON for v1. - **Why**: invariant-aware routing needs a place to declare required invariants per ref. - **Implementation**: [packages/1-framework/3-tooling/migration/src/refs.ts](packages/1-framework/3-tooling/migration/src/refs.ts) - **Tests**: [packages/1-framework/3-tooling/migration/test/refs.test.ts](packages/1-framework/3-tooling/migration/test/refs.test.ts) - **On-disk layout: per-file, not monolithic.** `migrations/refs/<name>.json` replaces `migrations/refs.json`. - **Why**: monolithic blob conflates unrelated refs, worsens review diffs, and requires coordinated edits. Per-file refs are independently versioned; nested ref names work naturally as subdirectories. - **Implementation**: [packages/1-framework/3-tooling/migration/src/refs.ts](packages/1-framework/3-tooling/migration/src/refs.ts) — `readdir` with `recursive: true`, atomic-rename write, empty-parent cleanup on delete. - **Tests**: [packages/1-framework/3-tooling/migration/test/refs.test.ts](packages/1-framework/3-tooling/migration/test/refs.test.ts) — nested ref names, delete-parent-cleanup, atomicity. - **`resolveRef` return type changed from `string` to `RefEntry`.** Callers unwrap `.hash` explicitly. - **Why**: the structured record is what routing downstream will want; returning the hash alone would throw away invariants. - **Implementation**: [migration-apply.ts](packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts), [migration-status.ts](packages/1-framework/3-tooling/cli/src/commands/migration-status.ts) - **Tests**: CLI integration covers `apply --ref` and `status --ref` end-to-end. - **`migration ref set/list/rm` rewritten against the per-file API.** - **Why**: the old commands wrote the monolithic blob; they now produce/consume one file per ref. - **Implementation**: [migration-ref.ts](packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts) - **Tests**: [migration-ref.test.ts](packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts) - **17 migration fixture directories migrated to the new layout.** No behavior change — this is test data reflecting the new storage shape. ## Compatibility / migration / risk - **Breaking change to on-disk ref format.** Any repo with an existing `migrations/refs.json` won't be found by the new reader — refs live in `migrations/refs/*.json` now. The system is pre-1.0, but downstream users with an older ref file need to migrate manually (one JSON file per entry). Error surface is clean: `readRefs` swallows ENOENT and returns `{}`, so a missing directory looks like "no refs" rather than a hard failure. - **Internal API break**: `resolveRef` now returns `RefEntry`, not `string`. All call sites in this PR are updated; any consumer outside the workspace (there aren't any yet, since the package isn't published) would need to unwrap `.hash`. - **No runtime cost.** Reading a directory of small JSON files is trivially fast at CLI scale. ## Follow-ups / open questions This PR is M0 of the invariant-aware-routing workstream ([TML-2297](https://linear.app/prisma-company/issue/TML-2297/pn-invariant-aware-routing)). The remaining milestones land as separate PRs: - **Prerequisites P2, P3 — renames.** `dag.ts → graph.ts` (P2) and `MigrationChainEntry → MigrationEdge` (P3). Each a standalone, logic-free commit/PR that lands before M2 so subsequent routing diffs target the new names. - **M1 — Marker-side applied-invariants storage.** `prisma_contract.marker` grows an `invariants text[]` column (Mongo: equivalent field on the marker doc) in the `CREATE TABLE IF NOT EXISTS` DDL. Runner unions `manifest.providedInvariants` on apply; `readMarker` returns the set. No compat shim — consistent with the breaking `edgeId` change, consumers re-apply against a fresh database. No new SPI. (Design pivoted away from ledger-side storage during spec review — marker-side is narrower and doesn't depend on [TML-2130](https://linear.app/prisma-company/issue/TML-2130), which stays an independent follow-up.) - **M2 — Authoring + edge-level invariants.** `invariantId?: string` on `DataTransformOperation` (opt-in routing identity; `name` keeps retry/ledger identity). Verify-time checks: `INVALID_INVARIANT_ID`, `DUPLICATE_INVARIANT_IN_EDGE`, `PROVIDED_INVARIANTS_MISMATCH`. `migration.json` carries `providedInvariants` — emit writes, verify re-derives. `MigrationChainEntry.invariants` propagates from the manifest at graph-reconstruction time. Assumes P2/P3 have landed. - **M3 — Pathfinder primitive.** `findPathWithInvariants` with state-level dedup and invariant-preferring neighbour ordering when `required ≠ ∅`. - **M4 — Decision surface + CLI integration with marker subtraction.** `migration apply --ref` and `status --ref` compute `effectiveRequired = ref.invariants − readMarker().invariants` and route through the pathfinder. `UNKNOWN_INVARIANT` pre-check fires fatally in both commands. `NO_INVARIANT_PATH` surfaces when a satisfying path doesn't exist. Status displays required / applied / missing. - **M5 — Close-out.** Doc migration; spec/plan deletion; prune `data-migrations-spec.md`. No open questions block this PR. ## Non-goals / intentionally out of scope - **Invariant-aware routing.** Spec describes it; the pathfinder + decision surface + CLI integration arrive in M3–M4. - **Applied-invariants storage.** Marker-side storage lands in M1. (The spec's rejected alternatives — ledger-side columns, graph-derived snapshot — are documented for context; they aren't part of this PR.) - **CLI UX for editing `ref.invariants`.** For v1, users edit the JSON files directly. - **Migration of existing `refs.json` blobs.** Pre-existing internal consumers need to manually split their blob into per-file entries; no automated migration tool. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Refactor** * Migration refs now stored as individual per-ref files in a refs directory instead of one refs file. * Ref entries include metadata (invariants) alongside content hashes. * CLI migration commands updated to use the new refs/ layout and updated help text. * Per-ref create/read/update/delete support with improved error messaging. * **Tests** * Test suites updated to validate per-ref file storage, CRUD behavior, error scenarios, and resolve semantics. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
closes TML-2305
part of TML-2297
Intent
Lay the storage groundwork for invariant-aware migration routing. Environment refs need to carry required invariants alongside their target hash so that a future pathfinder (specced in the accompanying doc) can route through paths that satisfy those invariants. The ref format also moves from a single
refs.jsonblob to a per-file directory layout — one file per ref — so refs are independently versionable, diffable, and editable.This PR lands the M0 slice of the invariant-aware-routing spec. The spec + plan ship alongside it for context; subsequent PRs implement M1–M5.
Change map
RefEntry, Arktype schema, per-filereadRef/writeRef/deleteRef, directory walk forreadRefs, validation helpers, atomic-rename write, empty-parent cleanup on delete.refsPathtorefsDirin the shared path resolver..hashat the call site.ref set/list/rmrewritten against the per-file API.RefEntry.ref set,ref list,ref rm) against the per-file layout.refs/<name>.jsonper ref).refs.jsonAPI removed.The story
Refs gain invariants as a first-class field. Before this PR, a ref was
{ name: hash }inside a monolithicmigrations/refs.json. That format has nowhere to declare "to reach this target state, the database must have invariants X and Y satisfied" — which the invariant-aware routing spec needs.RefEntry = { hash, invariants: readonly string[] }replaces the bare-string value; the hash is still validated assha256:empty | sha256:<64-hex>, invariants are free-form names validated by Arktype.One file per ref, not one blob.
migrations/refs/<name>.jsonreplaces the oldmigrations/refs.json. Ref names are validated against a conservative pattern (^[a-z0-9](...)?(/[a-z0-9]...)*$) — lowercase, hyphen-allowed, slash-namespaced, no dots or trailing slashes. The layout supports nested refs (feature/my-branch) without schema pain; each ref is an independently editable file in the working tree, which plays better with git review.Storage primitives + helpers.
readRef(refsDir, name),readRefs(refsDir),writeRef(refsDir, name, entry),deleteRef(refsDir, name),resolveRef(refs, name),validateRefName,validateRefValue. Writes are atomic (tmp file +rename); deletes walk empty parent directories back up torefsDir; reads swallowENOENTand return empty to keep callers simple. Arktype schema narrows on parse to reject invalid hashes at the storage boundary.CLI call sites threaded through.
migration apply --ref,migration status --ref, andmigration ref set/list/rmall switch fromrefsPathtorefsDir.resolveRefnow returnsRefEntry, so the three callers that previously consumed a bare string (migration apply,migration status) unwrap.hashexplicitly. No behavior change for users who never pass--ref.Spec + plan land alongside. The docs commit establishes the end-to-end roadmap so future reviewers can see where M0 fits. M1–M5 decompose the remaining work into independently shippable PRs, with the test-coverage matrix mapping every acceptance criterion to a verification.
Behavior changes & evidence
Refs are structured records, not strings.
RefEntry = { hash, invariants: readonly string[] }. The CLI continues to accept a plain hash onmigration ref set <name> <hash>and implicitly usesinvariants: []; richer payloads are edited by hand in the per-file JSON for v1.On-disk layout: per-file, not monolithic.
migrations/refs/<name>.jsonreplacesmigrations/refs.json.readdirwithrecursive: true, atomic-rename write, empty-parent cleanup on delete.resolveRefreturn type changed fromstringtoRefEntry. Callers unwrap.hashexplicitly.apply --refandstatus --refend-to-end.migration ref set/list/rmrewritten against the per-file API.17 migration fixture directories migrated to the new layout. No behavior change — this is test data reflecting the new storage shape.
Compatibility / migration / risk
migrations/refs.jsonwon't be found by the new reader — refs live inmigrations/refs/*.jsonnow. The system is pre-1.0, but downstream users with an older ref file need to migrate manually (one JSON file per entry). Error surface is clean:readRefsswallows ENOENT and returns{}, so a missing directory looks like "no refs" rather than a hard failure.resolveRefnow returnsRefEntry, notstring. All call sites in this PR are updated; any consumer outside the workspace (there aren't any yet, since the package isn't published) would need to unwrap.hash.Follow-ups / open questions
This PR is M0 of the invariant-aware-routing workstream (TML-2297). The remaining milestones land as separate PRs:
dag.ts → graph.ts(P2) andMigrationChainEntry → MigrationEdge(P3). Each a standalone, logic-free commit/PR that lands before M2 so subsequent routing diffs target the new names.prisma_contract.markergrows aninvariants text[]column (Mongo: equivalent field on the marker doc) in theCREATE TABLE IF NOT EXISTSDDL. Runner unionsmanifest.providedInvariantson apply;readMarkerreturns the set. No compat shim — consistent with the breakingedgeIdchange, consumers re-apply against a fresh database. No new SPI. (Design pivoted away from ledger-side storage during spec review — marker-side is narrower and doesn't depend on TML-2130, which stays an independent follow-up.)invariantId?: stringonDataTransformOperation(opt-in routing identity;namekeeps retry/ledger identity). Verify-time checks:INVALID_INVARIANT_ID,DUPLICATE_INVARIANT_IN_EDGE,PROVIDED_INVARIANTS_MISMATCH.migration.jsoncarriesprovidedInvariants— emit writes, verify re-derives.MigrationChainEntry.invariantspropagates from the manifest at graph-reconstruction time. Assumes P2/P3 have landed.findPathWithInvariantswith state-level dedup and invariant-preferring neighbour ordering whenrequired ≠ ∅.migration apply --refandstatus --refcomputeeffectiveRequired = ref.invariants − readMarker().invariantsand route through the pathfinder.UNKNOWN_INVARIANTpre-check fires fatally in both commands.NO_INVARIANT_PATHsurfaces when a satisfying path doesn't exist. Status displays required / applied / missing.data-migrations-spec.md.No open questions block this PR.
Non-goals / intentionally out of scope
ref.invariants. For v1, users edit the JSON files directly.refs.jsonblobs. Pre-existing internal consumers need to manually split their blob into per-file entries; no automated migration tool.Summary by CodeRabbit
Refactor
Tests