Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

refactor(migration-tools): refs carry invariants, per-file layout - #372

Merged
saevarb merged 5 commits into
mainfrom
feat/ref-invariants
Apr 27, 2026
Merged

saevarb merged 5 commits into
mainfrom
feat/ref-invariants

Conversation

@saevarb

@saevarb saevarb commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

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.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

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.

  • On-disk layout: per-file, not monolithic. migrations/refs/<name>.json replaces migrations/refs.json.

  • 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, 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.

  • 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). 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, 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.

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.

@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Migration ref storage moved from a single migrations/refs.json map to a directory-based migrations/refs/ layout with per-ref JSON files containing RefEntry objects (hash + invariants). CLI, migration APIs, and tests updated to read/write/delete per-ref files and to surface invariants.

Changes

Cohort / File(s) Summary
Fixture refs → per-file
examples/prisma-next-demo/migration-fixtures/*/refs.json, examples/prisma-next-demo/migration-fixtures/*/refs/*.json
Removed monolithic refs.json fixture files and added per-ref files (prod.json, staging.json, feature.json, experiment.json) each containing { "hash": "...", "invariants": [] }.
Core ref storage API
packages/1-framework/3-tooling/migration/src/refs.ts, packages/1-framework/3-tooling/migration/src/exports/refs.ts
Replaced map-of-hashes model with Record<string, RefEntry>; removed writeRefs; added readRef/writeRef/deleteRef; readRefs enumerates *.json files; resolveRef returns RefEntry. Validation and migration error codes/messages updated.
CLI: commands & helpers
packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts, .../migration-apply.ts, .../migration-status.ts, .../utils/command-helpers.ts
Switched from refsPath (single file) to refsDir (directory). migration-ref now uses per-ref APIs and returns invariants; migration-apply/migration-status extract .hash from RefEntry; resolveMigrationPaths exposes refsDir. Removed errorRefNotFound helper.
Tests: update and rework
packages/1-framework/3-tooling/migration/test/refs.test.ts, packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts, packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts (deleted)
Rewrote tests to validate per-file read/write/delete behavior, nested ref names, file validation errors, and updated error codes. Deleted old status test covering refs.json error surfaces; CLI tests updated extensively.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through folders, one by one,
Each ref now sleeps in its own little sun,
Hash tucked with invariants, cozy and neat,
The CLI nudges files with a rhythmic beat,
Tiny JSON burrows — tidy and sweet! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.35% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and accurately describes the main change: migrating refs from a monolithic JSON file to a per-file layout, with each ref now carrying invariants metadata.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/ref-invariants

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-runtime@372

@prisma-next/family-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-mongo@372

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@372

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@372

@prisma-next/middleware-telemetry

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/middleware-telemetry@372

@prisma-next/mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo@372

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-paradedb@372

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@372

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@372

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@372

@prisma-next/sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sqlite@372

@prisma-next/target-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-mongo@372

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-mongo@372

@prisma-next/driver-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-mongo@372

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@372

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@372

@prisma-next/config

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/config@372

@prisma-next/errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/errors@372

@prisma-next/framework-components

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/framework-components@372

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@372

@prisma-next/ts-render

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ts-render@372

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@372

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@372

@prisma-next/psl-parser

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-parser@372

@prisma-next/psl-printer

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-printer@372

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@372

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@372

@prisma-next/migration-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/migration-tools@372

prisma-next

npm i https://pkg.pr.new/prisma/prisma-next@372

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@372

@prisma-next/runtime-executor

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/runtime-executor@372

@prisma-next/mongo-codec

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-codec@372

@prisma-next/mongo-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract@372

@prisma-next/mongo-value

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-value@372

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-psl@372

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-ts@372

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-emitter@372

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-schema-ir@372

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-ast@372

@prisma-next/mongo-orm

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-orm@372

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-builder@372

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-lowering@372

@prisma-next/mongo-wire

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-wire@372

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@372

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@372

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@372

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@372

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-psl@372

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@372

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@372

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@372

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@372

@prisma-next/sql-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-builder@372

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@372

@prisma-next/target-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-sqlite@372

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@372

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-sqlite@372

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@372

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-sqlite@372

commit: 5d680bc

@saevarb
saevarb force-pushed the feat/ref-invariants branch 2 times, most recently from e4ef9dd to 6abbe53 Compare April 23, 2026 09:21
@saevarb saevarb changed the title feat(migrations): Invariant-aware routing refactor(migration-tools): refs carry invariants, per-file layout Apr 23, 2026
@saevarb
saevarb marked this pull request as ready for review April 23, 2026 09:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 calling resolveRef(allRefs, activeRefName).hash. resolveRef performs the same map lookup and raises MIGRATION.UNKNOWN_REF when missing, plus validates the ref-name shape — which the direct allRefs[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 with resolveMigrationPaths.

resolveRefsDir reimplements logic already present in resolveMigrationPaths from ../utils/command-helpers.ts, which returns refsDir as 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 with resolveMigrationPaths(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 the list command by appending an [invariants: …] suffix when present. Otherwise users can only discover invariants via --json or ref 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; two writeRef calls for the same name within the same tick (e.g., concurrent CLI invocations or tests) would both write to the same .name.json.<ms>.tmp and the subsequent rename on one of them could lose the other's data mid-flight. A random suffix (e.g., crypto.randomUUID() or randomBytes(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 refsDir is /tmp/refs and a sibling dir /tmp/refs-backup exists, dir.startsWith(refsDir) returns true for that sibling. In practice dir is always derived from join(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 .json with non-.json siblings being pruned.

The ignores non-json files test only checks at the top level. Since readRefs walks 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3134f51 and 6abbe53.

⛔ Files ignored due to path filters (2)
  • projects/graph-based-migrations/plans/invariant-aware-routing-plan.md is excluded by !projects/**
  • projects/graph-based-migrations/specs/invariant-aware-routing.spec.md is excluded by !projects/**
📒 Files selected for processing (44)
  • examples/prisma-next-demo/migration-fixtures/complex/refs.json
  • examples/prisma-next-demo/migration-fixtures/complex/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/complex/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/converging-branches/refs.json
  • examples/prisma-next-demo/migration-fixtures/converging-branches/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/experiment.json
  • examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/diamond/refs.json
  • examples/prisma-next-demo/migration-fixtures/diamond/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs.json
  • examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/linear/refs.json
  • examples/prisma-next-demo/migration-fixtures/linear/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/long-spine/refs.json
  • examples/prisma-next-demo/migration-fixtures/long-spine/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/long-spine/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs/feature.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/rollback-continue/refs.json
  • examples/prisma-next-demo/migration-fixtures/rollback-continue/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs.json
  • examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/single-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/single-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/single-branch/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs/experiment.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs/feature.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs/prod.json
  • packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts
  • packages/1-framework/3-tooling/migration/src/exports/refs.ts
  • packages/1-framework/3-tooling/migration/src/refs.ts
  • packages/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

saevarb pushed a commit that referenced this pull request Apr 23, 2026
- 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).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/1-framework/3-tooling/migration/src/refs.ts (1)

104-109: Silently swallowing non-ENOENT readFile errors in readRefs.

The empty catch { continue } treats every read failure as a missing-file case. That's fine for a benign race (file deleted between readdir and readFile), but it also silently drops EACCES, EPERM, EISDIR, etc., producing a Refs that silently omits entries — callers will then see a misleading UNKNOWN_REF downstream. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6abbe53 and 98f7bdc.

📒 Files selected for processing (5)
  • examples/prisma-next-demo/migration-fixtures/linear/refs/prod.json
  • packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts
  • packages/1-framework/3-tooling/migration/src/refs.ts
  • packages/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

@saevarb
saevarb force-pushed the feat/ref-invariants branch from 98f7bdc to 19b136a Compare April 24, 2026 14:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/1-framework/3-tooling/migration/src/refs.ts (1)

168-177: ⚠️ Potential issue | 🟡 Minor

Bare catch silently swallows non-ENOTEMPTY errors during cleanup.

The cleanup loop intends to stop when a parent directory is non-empty (ENOTEMPTY), but the bare catch { break; } also masks real problems — e.g., EACCES/EPERM (permissions), EBUSY (Windows handle lock), or EIO (I/O failure) — leaving the caller with no signal that deletion partially failed. At minimum, break only on ENOTEMPTY (and arguably ENOENT, 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 concurrent writeRef calls targeting the same ref name (or different refs that collapse to the same tmp basename in the same directory) can produce identical tmpPath, causing interleaved writeFile content before rename. Append a small random component (e.g., randomBytes(6).toString('hex') or randomUUID()) 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 describe boundaries into refs.validate.test.ts (validateRefName/validateRefValue), refs.storage.test.ts (writeRef/readRef/readRefs/deleteRef), and refs.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

📥 Commits

Reviewing files that changed from the base of the PR and between 98f7bdc and 19b136a.

⛔ Files ignored due to path filters (3)
  • projects/graph-based-migrations/plans/invariant-aware-routing-plan.md is excluded by !projects/**
  • projects/graph-based-migrations/specs/data-migrations-spec.md is excluded by !projects/**
  • projects/graph-based-migrations/specs/invariant-aware-routing.spec.md is excluded by !projects/**
📒 Files selected for processing (44)
  • examples/prisma-next-demo/migration-fixtures/complex/refs.json
  • examples/prisma-next-demo/migration-fixtures/complex/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/complex/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/converging-branches/refs.json
  • examples/prisma-next-demo/migration-fixtures/converging-branches/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/experiment.json
  • examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/diamond/refs.json
  • examples/prisma-next-demo/migration-fixtures/diamond/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs.json
  • examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/linear/refs.json
  • examples/prisma-next-demo/migration-fixtures/linear/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/long-spine/refs.json
  • examples/prisma-next-demo/migration-fixtures/long-spine/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/long-spine/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs/feature.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/rollback-continue/refs.json
  • examples/prisma-next-demo/migration-fixtures/rollback-continue/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs.json
  • examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/single-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/single-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/single-branch/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs/experiment.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs/feature.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs/prod.json
  • packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts
  • packages/1-framework/3-tooling/migration/src/exports/refs.ts
  • packages/1-framework/3-tooling/migration/src/refs.ts
  • packages/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

@saevarb
saevarb force-pushed the feat/ref-invariants branch 4 times, most recently from e6389f1 to 52e6917 Compare April 24, 2026 15:37

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🟠 Major

Direct allRefs[activeRefName] lookup bypasses the prototype-chain guard added in resolveRef.

allRefs is a plain object, so allRefs["constructor"] returns Object (the constructor function, truthy), making refEntry non-null and setting activeRefHash = refEntry.hash → undefined. The resolveRef fallback is never reached, so instead of surfacing MIGRATION.UNKNOWN_REF (as intended by the Object.hasOwn guard in resolveRef), the command silently ignores --ref constructor (or any name matching an Object.prototype member) and falls through to contract-hash targeting.

The direct lookup is also redundant — resolveRef does 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 | 🟡 Minor

Tautological atTarget assertion still present.

markerHash === refEntry.hash compares EMPTY_CONTRACT_HASH to HASH_B, both fixture constants set up earlier in the same test — the assertion can never fail regardless of production behavior. The immediately preceding findPath(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: Use pathe for path operations.

The sibling test file packages/1-framework/3-tooling/migration/test/refs.test.ts (line 3) already imports join from pathe; keeping this file on node:path is an inconsistency within the PR.

♻️ Proposed fix
-import { join } from 'node:path';
+import { join } from 'pathe';

As per coding guidelines: "Use pathe instead of node:path for 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

📥 Commits

Reviewing files that changed from the base of the PR and between 19b136a and 52e6917.

⛔ Files ignored due to path filters (3)
  • projects/graph-based-migrations/plans/invariant-aware-routing-plan.md is excluded by !projects/**
  • projects/graph-based-migrations/specs/data-migrations-spec.md is excluded by !projects/**
  • projects/graph-based-migrations/specs/invariant-aware-routing.spec.md is excluded by !projects/**
📒 Files selected for processing (44)
  • examples/prisma-next-demo/migration-fixtures/complex/refs.json
  • examples/prisma-next-demo/migration-fixtures/complex/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/complex/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/converging-branches/refs.json
  • examples/prisma-next-demo/migration-fixtures/converging-branches/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/experiment.json
  • examples/prisma-next-demo/migration-fixtures/diamond-sub-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/diamond/refs.json
  • examples/prisma-next-demo/migration-fixtures/diamond/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs.json
  • examples/prisma-next-demo/migration-fixtures/kitchen-sink/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/linear/refs.json
  • examples/prisma-next-demo/migration-fixtures/linear/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/long-spine/refs.json
  • examples/prisma-next-demo/migration-fixtures/long-spine/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/long-spine/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs/feature.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/multi-branch/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/multi-rollback-branch/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/rollback-continue/refs.json
  • examples/prisma-next-demo/migration-fixtures/rollback-continue/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs.json
  • examples/prisma-next-demo/migration-fixtures/sequential-diamonds/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/single-branch/refs.json
  • examples/prisma-next-demo/migration-fixtures/single-branch/refs/prod.json
  • examples/prisma-next-demo/migration-fixtures/single-branch/refs/staging.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs/experiment.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs/feature.json
  • examples/prisma-next-demo/migration-fixtures/sub-branches/refs/prod.json
  • packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-ref.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts
  • packages/1-framework/3-tooling/migration/src/exports/refs.ts
  • packages/1-framework/3-tooling/migration/src/refs.ts
  • packages/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

saevarb pushed a commit that referenced this pull request Apr 27, 2026
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
packages/1-framework/3-tooling/migration/src/refs.ts (2)

97-123: readRefs accepts files with invalid ref names.

refNameFromPath only strips the .json suffix; the resulting name is never run through validateRefName. A stray file such as Foo.json, .hidden.json, or weird name.json (e.g., committed by hand) ends up keyed into refs and visible via Object.keys(refs) (CLI listing, error hints, etc.), even though resolveRef will 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 uses Date.now() — concurrent writers to the same ref can collide.

Two writeRef calls for the same name within the same millisecond compute identical tmpPaths; both writeFiles 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'; (or Math.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

📥 Commits

Reviewing files that changed from the base of the PR and between 52e6917 and f5776a4.

📒 Files selected for processing (1)
  • packages/1-framework/3-tooling/migration/src/refs.ts

Sævar Berg added 5 commits April 27, 2026 10:41
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).
@saevarb
saevarb force-pushed the feat/ref-invariants branch from c52addd to 5d680bc Compare April 27, 2026 08:51
@saevarb
saevarb merged commit 37fa4c6 into main Apr 27, 2026
15 checks passed
@saevarb
saevarb deleted the feat/ref-invariants branch April 27, 2026 09:44
wmadden pushed a commit that referenced this pull request May 4, 2026
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 -->
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants