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

feat(migrations): on-disk migration planning, serialization, and apply - #184

Merged
saevarb merged 90 commits into
mainfrom
feat/on-disk-migrations-v2
Mar 4, 2026
Merged

saevarb merged 90 commits into
mainfrom
feat/on-disk-migrations-v2

Conversation

@saevarb

@saevarb saevarb commented Feb 26, 2026 •

Copy link
Copy Markdown
Contributor

Supersedes #179

closes TML-1936
refs TML-1937
refs TML-1938

Summary

End-to-end on-disk migration support: plan migrations offline, serialize them to disk, and apply them against a live database.

  • Offline migration planning (migration plan): Diffs two contracts without a DB connection. Uses contractToSchemaIR() to synthesize a SqlSchemaIR from the previous contract, then feeds it into the existing PostgresMigrationPlanner — no new planner needed. Supports additive, widening, and destructive operations.
  • On-disk migration format: migration.json + ops.json serialization, edge attestation (computeEdgeId, attestMigration, verifyMigration), DAG reconstruction with cycle/orphan detection.
  • CLI commands:
    • migration plan — offline diff → attested package
    • migration apply — read pending migrations from DAG, execute sequentially against a live DB via ControlClient
    • migration verify — re-attest / validate integrity
  • Destructive change detection: Hash-diff heuristic catches removals; the planner catches type changes and nullability tightening as conflicts.
  • Migration apply: Reads on-disk packages, determines pending migrations via DAG path from DB marker to leaf, executes each in its own transaction with full execution checks (prechecks, postchecks, idempotency). Resume-safe — re-run after failure picks up from the last successful migration. Warns when contract.json is stale (storageHash differs from DAG leaf).

Architecture

contract.ts → emit → contract.json
                           ↓
                 migration plan (offline):
                   contractToSchemaIR(from) + planner.plan(to)
                           ↓
                 migrations/<timestamp>_<name>/
                   ├── migration.json  (manifest + edge attestation)
                   └── ops.json        (SQL operations)
                           ↓
                 migration apply (online):
                   read marker → find pending path → ControlClient.migrationApply() per edge
                           ↓
                 DB updated, marker at new hash

Key implementation details (migration apply)

  • Routes through ControlClient, consistent with db init and db update
  • origin: null for first migration (runner expects no marker on fresh DB, not EMPTY_CONTRACT_HASH)
  • Destination contract validated via familyInstance.validateContractIR() before passing to runner
  • Framework components built from config for schema verification
  • One transaction per migration with all execution checks enabled
  • Policy-agnostic: passes all operation classes to the runner (policy gate is at plan time)
  • Stale-plan detection: warns when contract.json storageHash differs from DAG leaf

Test plan

  • Unit tests for contractToSchemaIR conversion (15 tests)
  • Unit tests for detectDestructiveChanges (7 tests)
  • Planner integration tests (9 tests)
  • CLI command unit tests for migration-plan, migration-verify
  • Migration apply unit tests — DAG path resolution (6 tests)
  • Migration plan CLI e2e tests (7 tests)
  • Migration apply CLI e2e tests against real Postgres (5 tests: single apply, idempotency, multi-migration, destructive, resume)
  • Migration tools tests (attestation, DAG, I/O round-trips)
  • NativeTypeExpander tests (with and without expander)
  • pnpm test:all passes
  • pnpm lint:deps clean
  • pnpm typecheck clean

Summary by CodeRabbit

  • New Features

    • CLI: add migration commands — plan, show, status, verify, and apply for offline on-disk migrations
    • On-disk migrations: persistent migration packages with content-attested edge IDs and DAG-based chaining
    • Runtime API: read marker and apply migrations programmatically
  • Documentation

    • Comprehensive migration docs, ADRs, and user stories for on-disk workflow
  • Tests

    • Extensive unit and end-to-end tests covering planning, attestation, DAGs, verification, and apply flows
  • Chores

    • Added migrations config option and minor ignore-file updates

@linear

linear Bot commented Feb 26, 2026

Copy link
Copy Markdown
TML-1936 [PN] M1: Planner + abstract ops IR

Contract-to-contract diff planner that produces abstract operation IR. No DB connection needed — pure, offline diffing of two SqlStorage states.\n\nDelivered:\n- Abstract ops IR types (8 op types, 14 ADR 044 check types) in @prisma-next/core-control-plane/abstract-ops\n- planContractDiff() planner in @prisma-next/family-sql/control\n- 20 unit tests covering all additive op types, conflict detection, determinism\n- pnpm lint:deps clean\n\nSee projects/on-disk-migrations/plans/plan.md Milestone 1.

TML-1937 [PN] M2: On-disk persistence + DAG

Build the on-disk migration format, file management, edge attestation, and DAG reconstruction.\n\nScope:\n- migration.json + ops.json types and I/O (read/write migration packages)\n- Edge attestation: computeEdgeId, attestMigration, verifyMigration\n- DAG reconstruction: reconstructGraph, findLeaf, findPath, cycle/orphan detection\n- Directory naming, collision handling\n- Unit tests (round-trip, validation, attestation, DAG)\n\nSee projects/on-disk-migrations/plans/plan.md Milestone 2.

TML-1938 [PN] M3: CLI commands + E2E flows

Build CLI commands (migration plan, migration new, migration verify, db update) and validate full user flows end-to-end.\n\nScope:\n- Config: migrations.dir in PrismaNextConfig\n- migration new (scaffold empty Draft)\n- migration plan (emit → diff → write attested migration package)\n- migration verify (re-attest / validate)\n- db update (connect → introspect → plan → apply → update marker)\n- E2E tests for new project flow, incremental changes, no-op, existing DB adoption\n\nSee projects/on-disk-migrations/plans/plan.md Milestone 3.

@coderabbitai

coderabbitai Bot commented Feb 26, 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

Adds an on-disk migrations system: new @prisma-next/migration-tools package (I/O, DAG, attestation), five CLI migration commands (plan/show/status/apply/verify), control-client migration APIs, SQL contract→schema IR and destructive-change detection, plus extensive types, docs, and tests.

Changes

Cohort / File(s) Summary
New migration tools package
packages/1-framework/3-tooling/migration/*, packages/1-framework/3-tooling/migration/src/*, packages/1-framework/3-tooling/migration/src/exports/*, packages/1-framework/3-tooling/migration/test/*, packages/1-framework/3-tooling/migration/package.json, packages/1-framework/3-tooling/migration/tsconfig*
New @prisma-next/migration-tools with IO (read/write/format), attestation (compute/verify edgeId), canonicalize-json, DAG utilities, errors, types, re-export barrels, and comprehensive tests and build/test configs.
CLI: migration commands & wiring
packages/1-framework/3-tooling/cli/src/commands/migration-*.ts, packages/1-framework/3-tooling/cli/src/cli.ts, packages/1-framework/3-tooling/cli/tsdown.config.ts, packages/1-framework/3-tooling/cli/package.json, packages/1-framework/3-tooling/cli/src/utils/*, packages/1-framework/3-tooling/cli/src/control-api/*
Adds migration-plan/show/status/verify/apply commands, registers them in CLI, extends output formatters, adds resolveContractPath helper, and pushes control-client APIs (readMarker, migrationApply) and executeMigrationApply orchestration.
Control-plane & client exports
packages/1-framework/1-core/migration/control-plane/src/constants.ts, .../exports/constants.ts, .../migrations.ts, .../package.json, .../tsdown.config.ts
Adds EMPTY_CONTRACT_HASH constant, MigrationPlan display types, and contractToSchema signature on TargetMigrationsCapability; exposes constants via package exports.
SQL family: contract→schema IR
packages/2-sql/3-tooling/family/src/core/migrations/contract-to-schema-ir.ts, .../exports/control.ts, packages/2-sql/.../test/contract-to-schema-ir.test.ts
Adds contractToSchemaIR, NativeTypeExpander, and detectDestructiveChanges; exports these from family control and adds tests.
Postgres target wiring
packages/3-targets/3-targets/postgres/src/exports/control.ts, packages/3-targets/.../test/migrations/planner.contract-to-schema-ir.test.ts
Exposes migrations.contractToSchema that maps ContractIR → schema IR using expandParameterizedNativeType; adds planner round-trip tests.
CLI control API & operations
packages/1-framework/3-tooling/cli/src/control-api/types.ts, .../client.ts, .../operations/migration-apply.ts
Adds MigrationApply types, readMarker and migrationApply methods on ControlClientImpl, and executeMigrationApply implementation coordinating runner execution per edge.
IO, attestation, DAG, errors, types
packages/1-framework/3-tooling/migration/src/{io,attestation,dag,errors,types,canonicalize-json}.ts
Implementations for migration package format, read/write, validation schemas, edge hashing (new array-of-hashes method), attestation/verification, graph reconstruction, cycle/orphan detection, and tooling errors with MIGRATION codes.
Output, formatting, and helpers
packages/1-framework/3-tooling/cli/src/utils/output.ts, .../command-helpers.ts, .../migration-command-scaffold.ts
Adds migration-specific formatters (apply/verify/show/status), destructive-operation warnings, and resolveContractPath helper; updates path resolution usage across commands.
Config & public types
packages/1-framework/1-core/shared/config/src/config-types.ts, .gitignore
Adds optional migrations.dir to PrismaNextConfig and ignores .cursor entries in .gitignore.
Documentation & plans
docs/architecture/..., projects/on-disk-migrations/*, docs/adrs/ADR 028 - Migration Structure & Operations.md
ADRs and subsystem docs updated for edgeId computation; full on-disk migrations spec, plans, notes, user stories, and task specs added.
Integration & unit tests / fixtures
packages/1-framework/3-tooling/cli/test/**/*, packages/1-framework/3-tooling/migration/test/**/*, test/integration/test/**/*, test/integration/test/fixtures/**
Extensive unit, integration, and e2e tests for planning, verification, apply flow, attestation, DAG operations, IO validation, contract→schema IR, and multiple CLI scenarios, plus fixtures.

Sequence Diagram(s)

sequenceDiagram
    rect rgba(220,240,255,0.5)
    actor CLI as CLI User
    participant PlanCmd as migration-plan<br/>Command
    participant Config as Config<br/>Loader
    participant IO as Migration<br/>I/O
    participant DAG as DAG<br/>Utilities
    participant Planner as Migration<br/>Planner
    participant Attest as Attestation<br/>Engine
    end

    CLI->>PlanCmd: run migration plan [--from]
    PlanCmd->>Config: load config, resolve paths
    PlanCmd->>IO: read existing migrations → DAG
    IO->>DAG: reconstructGraph()
    DAG-->>PlanCmd: leaf/fromHash
    PlanCmd->>Planner: plan operations (from→to)
    Planner-->>PlanCmd: MigrationPlan
    PlanCmd->>IO: writeMigrationPackage(dir, manifest, ops)
    PlanCmd->>Attest: attestMigration(dir) → computeEdgeId
    Attest-->>IO: update migration.json with edgeId
    Attest-->>PlanCmd: edgeId
    PlanCmd-->>CLI: output MigrationPlanResult (edgeId, dir, ops)
Loading
sequenceDiagram
    rect rgba(235,255,235,0.5)
    actor CLI as CLI User
    participant ApplyCmd as migration-apply<br/>Command
    participant Config as Config<br/>Loader
    participant IO as Migration<br/>I/O
    participant DAG as DAG<br/>Utilities
    participant Client as Control<br/>Client
    participant Runner as Migration<br/>Runner
    participant DB as Database
    end

    CLI->>ApplyCmd: run migration apply
    ApplyCmd->>Config: load config, resolve paths
    ApplyCmd->>IO: readMigrationsDir()
    IO->>DAG: reconstructGraph()
    DAG-->>ApplyCmd: leaf, chain
    ApplyCmd->>Client: readMarker()
    Client->>DB: query marker
    DB-->>Client: markerHash
    Client-->>ApplyCmd: markerHash
    ApplyCmd->>DAG: findPath(markerHash → leaf)
    ApplyCmd->>IO: readMigrationPackage(dir) for each edge
    ApplyCmd->>Client: migrationApply(pendingEdges)
    Client->>Runner: for each edge: build plan & execute
    Runner->>DB: begin → execute DDL → update marker → commit
    Runner-->>Client: per-edge result
    Client-->>ApplyCmd: MigrationApplyResult
    ApplyCmd-->>CLI: report applied migrations and marker
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐰 I nibble hashes, hop through DAG and plan,

Attest each edge with a careful paw and scan.
Packages written, verifications in flight,
CLI commands hum through the moonlit night.
On-disk migrations — stitched by rabbit delight.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/on-disk-migrations-v2

@saevarb
saevarb marked this pull request as draft February 26, 2026 12:52
@pkg-pr-new

pkg-pr-new Bot commented Feb 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/runtime-executor

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

@prisma-next/sql-runtime

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

@prisma-next/extension-pgvector

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/contract-authoring

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

@prisma-next/contract-ts

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/cli

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

@prisma-next/emitter

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

@prisma-next/eslint-plugin

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/eslint-plugin@184

@prisma-next/migration-tools

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

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

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

@prisma-next/family-sql

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

@prisma-next/sql-kysely-lane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-kysely-lane@184

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-lane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane@184

@prisma-next/target-postgres

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

@prisma-next/adapter-postgres

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

@prisma-next/driver-postgres

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

@prisma-next/core-control-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-control-plane@184

@prisma-next/core-execution-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-execution-plane@184

@prisma-next/config

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

@prisma-next/contract

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

@prisma-next/operations

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

@prisma-next/plan

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

@prisma-next/utils

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

commit: 87dd28c

@saevarb saevarb changed the title feat(migrations): offline migration planning, on-disk serialization, and CLI commands feat(migrations): on-disk migration planning, serialization, and apply Feb 27, 2026
@saevarb
saevarb force-pushed the feat/on-disk-migrations-v2 branch from 5e0a8a4 to 271d5c2 Compare February 27, 2026 10:05
@saevarb
saevarb marked this pull request as ready for review February 27, 2026 15:19
@saevarb
saevarb changed the base branch from main to feat/db-update March 2, 2026 10:06
@saevarb
saevarb force-pushed the feat/on-disk-migrations-v2 branch from 37d5b77 to 8aa25ae Compare March 2, 2026 11:16

@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: 16

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

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

17-39: ⚠️ Potential issue | 🔴 Critical

Attestation input is still forgeable via unframed concat and excludes parentEdgeId.

Two integrity problems remain: graph linkage (parentEdgeId) is not covered by the hash, and join(':') is not a robust framing scheme for multi-part canonical payloads.

Suggested fix
 export function computeEdgeId(manifest: MigrationManifest, ops: MigrationOps): string {
   const {
     edgeId: _edgeId,
-    parentEdgeId: _parentEdgeId,
     signature: _signature,
     fromContract: _fromContract,
     toContract: _toContract,
     ...strippedMeta
   } = manifest;
@@
-  const combined = [
-    canonicalManifest,
-    canonicalOps,
-    canonicalFromContract,
-    canonicalToContract,
-  ].join(':');
-  const hash = createHash('sha256').update(combined).digest('hex');
+  const parts = [canonicalManifest, canonicalOps, canonicalFromContract, canonicalToContract];
+  const framed = parts
+    .map((part) => `${Buffer.byteLength(part, 'utf8')}:${part}`)
+    .join('|');
+  const hash = createHash('sha256').update(framed, 'utf8').digest('hex');
🤖 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/attestation.ts` around lines 17
- 39, The hashing currently omits parentEdgeId and uses a fragile join(':')
framing; update the attestation input construction to include
manifest.parentEdgeId (use the manifest symbol names like
parentEdgeId/_parentEdgeId) and replace the string join framing with a robust
framing (e.g., build a deterministic array or length-prefixed concatenation) so
canonicalManifest, canonicalOps, canonicalFromContract, canonicalToContract and
parentEdgeId are serialized together in a non-ambiguous way before feeding into
createHash('sha256') — use the existing canonicalizeJson/canonicalizeContract
helpers to produce each element and then serialize them as a single framed
payload (not simple join(':')) assigned to combined and hashed.
🟡 Minor comments (15)
packages/1-framework/3-tooling/migration/README.md-39-39 (1)

39-39: ⚠️ Potential issue | 🟡 Minor

Remove milestone notation from durable README docs.

Line 39 includes (M3), which is transition/milestone context rather than current-state documentation. Keep this line timeless (e.g., just @prisma-next/cli — CLI commands consume these functions).

Based on learnings: “Do not reference transient project artifacts … from durable system documentation,” and as per coding guidelines: “Update design docs to reflect the current state only, not the transition history.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/3-tooling/migration/README.md` at line 39, Edit the
README line referencing `@prisma-next/cli` to remove the milestone notation
"(M3)"; specifically update the text that currently reads "`@prisma-next/cli`
(M3) — CLI commands consume these functions" to a timeless form such as
"`@prisma-next/cli` — CLI commands consume these functions" so the durable
documentation no longer references transition/milestone context.
test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-apply/prisma-next.config.with-db.ts-14-18 (1)

14-18: ⚠️ Potential issue | 🟡 Minor

Same unknown types property issue.

As noted in the migration-plan config, the types field on line 17 is not part of the ContractConfig interface.

🐛 Proposed fix
   contract: {
     source: async () => ({ ok: true as const, value: contract }),
     output: 'output/contract.json',
-    types: 'output/contract.d.ts',
   },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-apply/prisma-next.config.with-db.ts`
around lines 14 - 18, The config object named contract includes an unknown
property types which is not part of the ContractConfig interface; remove the
line "types: 'output/contract.d.ts'," from the contract object (or if you
intended to support emitting types, add the correct property name to the
ContractConfig interface instead of adding an unsupported key). Locate the
contract object in the config (the async source, output, and types entries) and
either delete the types entry or update the ContractConfig type to include the
intended field so the config matches the interface.
test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-plan/prisma-next.config.ts-12-16 (1)

12-16: ⚠️ Potential issue | 🟡 Minor

Remove unknown types property from contract config.

The ContractConfig interface only defines source and output properties. Per the interface documentation, the .d.ts types file is automatically colocated with the output path (e.g., contract.json → contract.d.ts). The types field on line 15 is not valid and should be removed.

🐛 Fix
  contract: {
    source: async () => ({ ok: true as const, value: contract }),
    output: 'output/contract.json',
-   types: 'output/contract.d.ts',
  },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-plan/prisma-next.config.ts`
around lines 12 - 16, The contract config object (named contract in
prisma-next.config.ts) contains an invalid/unknown property types; remove the
types: 'output/contract.d.ts' entry from the contract config so it only has the
supported source and output properties per ContractConfig, relying on the
automatic colocated .d.ts generation for the output path (e.g., contract.json →
contract.d.ts).
packages/1-framework/3-tooling/migration/src/io.ts-127-131 (1)

127-131: ⚠️ Potential issue | 🟡 Minor

Use an ops-specific error instead of manifest error for ops.json validation failures.

Invalid operations currently throw MIGRATION.INVALID_MANIFEST, which is misleading for callers and users.

Suggested fix
 function validateOps(ops: unknown, filePath: string): asserts ops is MigrationOps {
   const result = MigrationOpsSchema(ops);
   if (result instanceof type.errors) {
-    throw errorInvalidManifest(filePath, result.summary);
+    throw errorInvalidOps(filePath, result.summary);
   }
 }
🤖 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/io.ts` around lines 127 - 131,
The validateOps function currently throws errorInvalidManifest when
MigrationOpsSchema validation fails, which is misleading for ops.json; change it
to throw an ops-specific error (e.g., errorInvalidOps) instead of
errorInvalidManifest and pass the same filePath and validation summary; update
or add the error helper (errorInvalidOps) to produce a MIGRATION.INVALID_OPS
code/message and use it in validateOps where MigrationOpsSchema(ops) yields an
instance of type.errors.
packages/1-framework/3-tooling/cli/test/commands/migration-verify.test.ts-26-33 (1)

26-33: ⚠️ Potential issue | 🟡 Minor

Add cleanup for created temp directories.

createTempDir() creates real directories under OS temp, but this file never removes them. Add afterEach cleanup to avoid test artifact buildup.

🧹 Suggested cleanup pattern
-import { mkdir, writeFile } from 'node:fs/promises';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
 import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { join } from 'pathe';
@@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it } from 'vitest';
@@
-async function createTempDir(prefix: string): Promise<string> {
-  const dir = join(
-    tmpdir(),
-    `test-migration-verify-${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`,
-  );
-  await mkdir(dir, { recursive: true });
-  return dir;
-}
+const tempDirs: string[] = [];
+async function createTempDir(prefix: string): Promise<string> {
+  const dir = await mkdtemp(join(tmpdir(), `test-migration-verify-${prefix}-`));
+  tempDirs.push(dir);
+  return dir;
+}
@@
 describe('migration verify', () => {
+  afterEach(async () => {
+    await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
+  });
+
   it('verifies attested package', async () => {

Also applies to: 35-134

🤖 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-verify.test.ts`
around lines 26 - 33, The tests call createTempDir which creates real OS temp
directories but never removes them; modify the test file to track created temp
dirs (e.g., push each returned path from createTempDir into an array) and add an
afterEach hook that iterates the array and removes each directory using
fs.promises.rm (or fs.promises.rmdir for older Node) with recursive: true and
force: true, then clear the array; reference the createTempDir helper and the
test suite's afterEach to perform this cleanup so no temp artifacts remain after
each test.
packages/1-framework/3-tooling/cli/test/commands/migration-verify.test.ts-3-3 (1)

3-3: ⚠️ Potential issue | 🟡 Minor

Replace node:path with pathe import on line 3.

This TypeScript test file imports from node:path but should use pathe for cross-platform path manipulation consistency. Update line 3 from:

import { join } from 'node:path';

to:

import { join } from 'pathe';

The pathe package is already available as a dependency in this package.

🤖 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-verify.test.ts` at
line 3, Replace the Node built-in import with the pathe package: change the
import declaration that currently reads "import { join } from 'node:path';" to
use "pathe" instead (i.e., import { join } from 'pathe';) so the test uses the
cross-platform path utility; update the import statement that references join
accordingly.
packages/1-framework/1-core/migration/control-plane/src/migrations.ts-53-56 (1)

53-56: ⚠️ Potential issue | 🟡 Minor

Duplicate section header.

Lines 53-56 repeat the "Plan Types (Display-Oriented)" header that already appears at lines 36-38. This appears to be a copy-paste artifact.

Proposed fix
-// ============================================================================
-// Plan Types (Display-Oriented)
-// ============================================================================
-
 /**
  * A migration plan for display purposes.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/1-core/migration/control-plane/src/migrations.ts` around
lines 53 - 56, Remove the duplicate section header "Plan Types
(Display-Oriented)" (the repeated comment block with the same separator lines)
that was accidentally copy-pasted; keep the original header near the first
occurrence and delete the repeated block so only one "Plan Types
(Display-Oriented)" section heading and its separators remain in migrations.ts.
packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts-511-535 (1)

511-535: ⚠️ Potential issue | 🟡 Minor

The destructive-color test is not validating color behavior.

This test currently only checks plain text presence, so it can pass even if yellow styling is removed. Please assert ANSI styling (or a color/no-color output delta) explicitly.

As per coding guidelines: "**/{*.test.ts,*.test-d.ts,test/**,**/test/**}: Avoid tautological tests that only restate fixture input."

🤖 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-status.test.ts`
around lines 511 - 535, The test currently only verifies the plain text "1 op (1
destructive)" and doesn't assert color styling; update the test around
parseGlobalFlags and formatMigrationStatusOutput to explicitly assert ANSI
yellow escape sequences are present when color is enabled (e.g. check for
"\u001b[33m" or "\x1b[33m" wrapping the destructive summary and the
corresponding reset like "\u001b[39m" or "\x1b[0m"), and add a complementary
assertion that when parseGlobalFlags({ color: false }) the output does NOT
contain those ANSI codes; target the existing test block that builds the
migrations fixture and the expect() asserting output toContain so it validates
color/no-color differences for the destructive summary text.
packages/1-framework/3-tooling/cli/test/commands/migration-apply.test.ts-41-48 (1)

41-48: ⚠️ Potential issue | 🟡 Minor

Temporary directories are created but not cleaned up.

createTempDir() creates persistent directories under system temp and this file never removes them, which can leave residue across runs.

As per coding guidelines: "{test/e2e/**,test/integration/**,packages/1-framework/3-tooling/cli/**}: Tests must clean up their own ephemeral directories."

🤖 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-apply.test.ts`
around lines 41 - 48, createTempDir creates ephemeral dirs but never cleans them
up; modify it to record each created path (e.g., push into a module-level array
like createdTempDirs) and add a test teardown (afterEach or afterAll in
migration-apply.test.ts) that iterates createdTempDirs and removes each with
fs.promises.rm(path, { recursive: true, force: true }) or fs.promises.rmdir for
compatibility, and ensure createTempDir still returns the path; alternatively
return a cleanup callback from createTempDir and call it in the test teardown.
packages/1-framework/3-tooling/cli/src/commands/migration-show.ts-49-50 (1)

49-50: ⚠️ Potential issue | 🟡 Minor

looksLikePath() misclassifies bare directory names.

Lines 49-50 only treat strings containing / or \ as paths. A valid local directory like 20260301_init is routed as a hash prefix and can fail unexpectedly.

🤖 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-show.ts` around
lines 49 - 50, The looksLikePath(target: string) function currently only checks
for '/' or '\\' and misclassifies bare local directory names (e.g.,
"20260301_init"); update it to detect real filesystem paths by importing fs (and
optionally path) and returning true when fs.existsSync(target) (or when
path.isAbsolute(target) or it begins with './' or '../'), otherwise fall back to
the existing separator checks; modify the looksLikePath implementation
accordingly so callers that expect a real local path (function looksLikePath)
will treat existing directories/files as paths.
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts-2-2 (1)

2-2: ⚠️ Potential issue | 🟡 Minor

Replace node:path with pathe in this TypeScript file.

Line 2 imports from node:path, which violates the repository standard for TypeScript path manipulation. Use pathe instead for consistent cross-platform behavior.

♻️ Proposed fix
-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';
🤖 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` at line
2, Replace the Node builtin import with pathe: in migration-status.ts update the
import that currently reads import { relative, resolve } from 'node:path' to
import { relative, resolve } from 'pathe' so the file uses the
repository-standard cross-platform path utilities (ensure any usages of relative
or resolve in this module continue to work after swapping the import).
packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts-2-2 (1)

2-2: ⚠️ Potential issue | 🟡 Minor

Use pathe instead of node:path for path operations in this TypeScript CLI command.

Line 2 imports from node:path, but the project standard is to use pathe for all TypeScript path manipulation. This is already established in other CLI command files like contract-emit.ts and migration-plan.ts.

♻️ Proposed fix
-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';
🤖 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-apply.ts` at line
2, Replace the node:path import with pathe: change the import that currently
pulls "relative" and "resolve" from "node:path" to import those symbols from
"pathe" instead; update any local uses of relative and resolve in
migration-apply.ts as needed (follow the same pattern used in contract-emit.ts
and migration-plan.ts) so all path operations use pathe.
packages/1-framework/3-tooling/cli/src/commands/migration-show.ts-184-184 (1)

184-184: ⚠️ Potential issue | 🟡 Minor

Remove redundant cast—pkg.ops is already correctly typed as MigrationPlanOperation[].

The MigrationPackage type defines ops: MigrationOps, and MigrationOps is a type alias for readonly MigrationPlanOperation[]. The cast on line 184 is unnecessary since the type is already correct through proper interface typing. Remove the cast and access pkg.ops directly.

🤖 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-show.ts` at line
184, Remove the redundant type cast on the ops property: pkg.ops is already
typed via MigrationPackage → MigrationOps as readonly MigrationPlanOperation[],
so replace usages that do const ops = pkg.ops as readonly
MigrationPlanOperation[]; with direct access (const ops = pkg.ops) and ensure
any downstream code expects readonly MigrationPlanOperation[]; update references
to ops if needed but do not add any explicit casts for MigrationPlanOperation.
packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts-90-90 (1)

90-90: ⚠️ Potential issue | 🟡 Minor

Fix the type mismatch in MigrationApplyEdge to eliminate the blind cast on line 90.

The cast as MigrationApplyEdge['operations'] on line 90 is unnecessary because pkg.ops (typed as MigrationPlanOperation[]) should be directly assignable to the expected type. The root cause is that MigrationApplyEdge.operations defines operationClass as string, while MigrationPlanOperation.operationClass is the more specific type MigrationOperationClass ('additive' | 'widening' | 'destructive'). Update the MigrationApplyEdge interface to declare operationClass: MigrationOperationClass instead of string, making the assignment type-safe without a cast.

🤖 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-apply.ts` at line
90, Change the type on MigrationApplyEdge so its operations property matches
MigrationPlanOperation: update the operationClass field in the
MigrationApplyEdge definition from string to MigrationOperationClass (the union
'additive'|'widening'|'destructive') so that pkg.ops (typed as
MigrationPlanOperation[]) can be assigned directly to
MigrationApplyEdge['operations'] without the blind cast; locate the
MigrationApplyEdge interface and replace operationClass: string with
operationClass: MigrationOperationClass and then remove the "as
MigrationApplyEdge['operations']" cast where operations: pkg.ops is assigned.
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts-121-121 (1)

121-121: ⚠️ Potential issue | 🟡 Minor

Remove the unnecessary blind cast when reading package operations.

Line 121 casts pkg?.ops ?? [] to readonly MigrationPlanOperation[], but this cast is redundant. The pkg?.ops property is already typed as MigrationOps (which expands to readonly MigrationPlanOperation[]), and the fallback [] is assignable to that type. The cast can be safely removed:

Suggested fix
-    const ops = (pkg?.ops ?? []) as readonly MigrationPlanOperation[];
+    const ops = pkg?.ops ?? [];
🤖 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` at line
121, Remove the redundant type cast on the ops assignment: the expression
pkg?.ops ?? [] is already compatible with MigrationOps / readonly
MigrationPlanOperation[], so delete the explicit cast to readonly
MigrationPlanOperation[] on the const ops declaration (the reference to pkg?.ops
and the variable ops should remain unchanged).
🧹 Nitpick comments (30)
.gitignore (1)

16-18: Redundant ignore entries under .cursor

Line 18 (.cursor) already covers Line 16 and Line 17, so those two lines are redundant. Consider keeping only .cursor for clarity.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.gitignore around lines 16 - 18, The .gitignore currently lists ".cursor",
".cursor/rules", and ".cursor/commands"; remove the redundant specific entries
".cursor/rules" and ".cursor/commands" and keep only the top-level ".cursor"
entry so the whole directory is ignored (update the file to contain a single
".cursor" line and delete the two subpath lines).
packages/1-framework/3-tooling/cli/vitest.config.ts (1)

43-48: Remove duplicate coverage exclusion entries

Lines 43–48 contain duplicated glob entries for the same three migration command files. This is harmless at runtime but adds config noise and maintenance risk.

Proposed cleanup
         'src/commands/db-verify.ts',
         'src/commands/migration-apply.ts',
         'src/commands/migration-plan.ts',
         'src/commands/migration-verify.ts',
-        'src/commands/migration-apply.ts',
-        'src/commands/migration-plan.ts',
-        'src/commands/migration-verify.ts',
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/3-tooling/cli/vitest.config.ts` around lines 43 - 48,
The coverage.exclude array in vitest.config.ts contains duplicate glob entries
for the same files; remove the repeated entries so each of
'src/commands/migration-apply.ts', 'src/commands/migration-plan.ts', and
'src/commands/migration-verify.ts' appears only once in the coverage.exclude
list (edit the coverage.exclude property in the vitest config to deduplicate
those three filenames).
packages/1-framework/3-tooling/cli/src/commands/db-sign.ts (1)

2-2: Use pathe instead of node:path for path operations.

Per coding guidelines and learnings from PR #191, prefer pathe over node:path.

♻️ Suggested fix
-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';

Based on learnings: "In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase (including CLI commands and tooling 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/src/commands/db-sign.ts` at line 2,
Replace the node:path import with pathe: update the import statement that
currently imports relative and resolve from 'node:path' to import them from
'pathe' instead (the rest of the code using relative and resolve in db-sign.ts
should work unchanged because pathe provides the same functions); ensure there
are no other node:path usages in the file and run a quick build/test to verify
no import errors remain.
packages/1-framework/3-tooling/cli/test/utils/command-helpers.test.ts (1)

1-1: Use pathe instead of node:path for path operations in tests.

Per coding guidelines, prefer pathe over node:path across the codebase including test files.

♻️ Suggested fix
-import { resolve } from 'node:path';
+import { resolve } from 'pathe';

Based on learnings: "In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase (including CLI commands and tooling 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/utils/command-helpers.test.ts` at
line 1, Replace the Node built-in path import with pathe: change the import of
resolve from 'node:path' to import { resolve } from 'pathe' and update any path
usage tied to the resolve symbol in the test (e.g., calls to resolve(...)) to
ensure they continue to work with pathe; keep the same symbol name so no further
call-site changes are needed.
packages/1-framework/3-tooling/cli/src/commands/db-verify.ts (1)

2-2: Use pathe instead of node:path for path operations.

Per coding guidelines and learnings from PR #191, prefer pathe over node:path.

♻️ Suggested fix
-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';

Based on learnings: "In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase (including CLI commands and tooling 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/src/commands/db-verify.ts` at line 2,
Replace the node:path import with pathe: update the import statement that
currently brings in relative and resolve from "node:path" to import the same
named functions from "pathe", and ensure any uses of relative(...) and
resolve(...) in this file (e.g., in db-verify command logic) continue to call
those functions unchanged so path operations now use pathe instead of node:path.
packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts (1)

1-1: Use pathe instead of node:path for path operations.

Per coding guidelines and learnings from PR #191, prefer pathe over node:path for consistent cross-platform behavior.

♻️ Suggested fix
-import { resolve } from 'node:path';
+import { resolve } from 'pathe';

Based on learnings: "In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase (including CLI commands and tooling 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/src/utils/command-helpers.ts` at line 1,
Replace the node:path import with pathe: change the import of resolve from
'node:path' to import { resolve } from 'pathe' so all path operations in this
module use the pathe library; update any usages of resolve in this file (e.g.,
functions referencing resolve) to continue functioning unchanged but now sourced
from pathe for consistent cross-platform behavior.
packages/1-framework/3-tooling/cli/src/utils/migration-command-scaffold.ts (1)

2-2: Use pathe instead of node:path for path operations.

Per coding guidelines and learnings from PR #191, prefer pathe over node:path.

♻️ Suggested fix
-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';

Based on learnings: "In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase (including CLI commands and tooling 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/src/utils/migration-command-scaffold.ts`
at line 2, Replace the node:path import with pathe: update the import statement
that currently imports relative and resolve from 'node:path' to import them from
'pathe' instead so all path operations in migration-command-scaffold.ts use
pathe (keep the imported symbols relative and resolve unchanged and ensure any
usages of those functions in this file continue to work).
packages/1-framework/3-tooling/cli/src/commands/db-schema-verify.ts (1)

2-2: Use pathe instead of node:path for path operations.

Per coding guidelines and learnings from PR #191, prefer pathe over node:path.

♻️ Suggested fix
-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';

Based on learnings: "In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase (including CLI commands and tooling 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/src/commands/db-schema-verify.ts` at line
2, Replace the node:path import with pathe and use pathe's implementations of
resolve and relative; specifically change the import of "relative" and "resolve"
from 'node:path' to 'pathe' and ensure any uses of resolve(...) and
relative(...) in db-schema-verify.ts call the pathe versions (update import and
any references to those symbols accordingly).
packages/1-framework/3-tooling/migration/README.md (1)

16-24: Shorten Mermaid node labels and move detail into surrounding text.

Lines 16-24 pack too much detail into labels, which hurts readability and conflicts with the Mermaid-label brevity guideline. Keep nodes short (e.g., CLI, I/O, Attestation, DAG) and explain details in bullets below the diagram.

Proposed simplification
 graph TD
-    CLI["CLI commands<br/>(migration plan, apply, verify)"] --> IO["io.ts<br/>File I/O"]
-    CLI --> ATT["attestation.ts<br/>Edge attestation"]
-    CLI --> DAG["dag.ts<br/>DAG operations"]
-    IO --> TYPES["types.ts<br/>MigrationManifest, etc."]
-    ATT --> IO
-    ATT --> CAN["canonicalize-json.ts"]
-    ATT --> CP["@prisma-next/core-control-plane<br/>canonicalizeContract"]
-    DAG --> TYPES
-    DAG --> ABS["@prisma-next/core-control-plane<br/>EMPTY_CONTRACT_HASH"]
+    CLI["CLI"] --> IO["I/O"]
+    CLI --> ATT["Attestation"]
+    CLI --> DAG["DAG"]
+    IO --> TYPES["Types"]
+    ATT --> IO
+    ATT --> CAN["Canonicalize JSON"]
+    ATT --> CP["Core Control Plane"]
+    DAG --> TYPES
+    DAG --> ABS["Empty Contract Hash"]

As per coding guidelines: “Keep Mermaid diagram labels short and move detail to surrounding Markdown.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/3-tooling/migration/README.md` around lines 16 - 24, The
Mermaid nodes in the diagram use verbose labels (e.g., CLI["CLI
commands<br/>(migration plan, apply, verify)"], IO["io.ts<br/>File I/O"],
ATT["attestation.ts<br/>Edge attestation"], DAG["dag.ts<br/>DAG operations"],
TYPES["types.ts<br/>MigrationManifest, etc."], CAN["canonicalize-json.ts"],
CP["@prisma-next/core-control-plane<br/>canonicalizeContract"],
ABS["@prisma-next/core-control-plane<br/>EMPTY_CONTRACT_HASH"]) — shorten each
node to a concise identifier (CLI, I/O, Attestation, DAG, Types, Canonicalize,
ControlPlane, EmptyHash) and move the file/function details into a short bullet
list in the surrounding Markdown under the diagram that documents file names and
exported symbols (e.g., list io.ts → File I/O, attestation.ts → Edge
attestation, canonicalize-json.ts, `@prisma-next/core-control-plane` →
canonicalizeContract, EMPTY_CONTRACT_HASH, types.ts → MigrationManifest).
packages/1-framework/3-tooling/cli/test/commands/migration-e2e.test.ts (3)

99-110: Group related manifest assertions with an object matcher.

These checks validate one related structure (pkg.manifest) and are clearer/shorter as a single toMatchObject() assertion.

Suggested diff
-    expect(pkg.manifest.from).toBe(EMPTY_CONTRACT_HASH);
-    expect(pkg.manifest.to).toBe('sha256:initial-hash');
-    expect(pkg.manifest.edgeId).toBe(edgeId);
-    expect(pkg.manifest.fromContract).toBeNull();
-    expect(pkg.manifest.toContract).toEqual(toContract);
+    expect(pkg.manifest).toMatchObject({
+      from: EMPTY_CONTRACT_HASH,
+      to: 'sha256:initial-hash',
+      edgeId,
+      fromContract: null,
+      toContract,
+    });

As per coding guidelines: "**/*.test.ts: Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests."

🤖 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-e2e.test.ts`
around lines 99 - 110, Replace the multiple individual assertions against
pkg.manifest with a single object matcher: after calling
verifyMigration(packageDir) and readMigrationPackage(packageDir) (symbols:
verifyMigration, readMigrationPackage, verifyResult), assert pkg.manifest using
toMatchObject({ from: EMPTY_CONTRACT_HASH, to: 'sha256:initial-hash', edgeId,
fromContract: null, toContract: toContract }) and keep the separate assertions
for verifyResult.ok and verifyResult.storedEdgeId as-is; this consolidates the
related manifest checks into one concise assertion while still validating ops
length with expect(pkg.ops).toHaveLength(1).

18-41: Use the shared createContractIR() factory instead of manual ContractIR literals.

Manual assembly here duplicates contract shape and is brittle as ContractIR evolves.

As per coding guidelines: "**/*.test.ts: Use factory functions like createContractIR() instead of manual object creation for ContractIR objects in tests."

🤖 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-e2e.test.ts`
around lines 18 - 41, Replace the manual ContractIR assembly in the
createContract function with the shared test factory createContractIR: build the
minimal storage object (tables -> columns) as you already do, then call
createContractIR({ storage, schemaVersion: '1', targetFamily: 'sql', target:
'postgres', /* other defaults if factory requires */ }) instead of returning the
literal; update the createContract function to import and delegate to
createContractIR and remove the explicit ContractIR literal so tests use the
canonical factory and stay resilient to ContractIR shape changes.

3-3: Use pathe instead of node:path in this TypeScript test.

This file imports join from node:path; repo rules require pathe for TS path handling consistency.

Suggested diff
-import { join } from 'node:path';
+import { join } from 'pathe';

As per coding guidelines: "**/*.{ts,tsx,mts,cts}: 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-e2e.test.ts` at
line 3, The test imports join from node:path which violates the repo TS rule;
change the import to use pathe by replacing "import { join } from 'node:path'"
with "import { join } from 'pathe'" so all calls to join in
migration-e2e.test.ts continue to work with the repository's TypeScript path
handling conventions.
packages/1-framework/3-tooling/migration/src/canonicalize-json.ts (1)

1-17: Consider using an established library for deterministic JSON serialization.

The implementation is functionally correct for basic cases, but for attestation/hashing where determinism is critical, consider using a battle-tested library like fast-json-stable-stringify or json-stringify-deterministic. These handle edge cases such as toJSON methods, special object types, and have been extensively tested.

That said, if the scope is intentionally limited to plain objects/arrays for manifest serialization and you want to avoid the dependency, the current implementation is acceptable.

📦 Alternative using established library
+import stableStringify from 'fast-json-stable-stringify';
+
-function sortKeys(value: unknown): unknown {
-  if (value === null || typeof value !== 'object') {
-    return value;
-  }
-  if (Array.isArray(value)) {
-    return value.map(sortKeys);
-  }
-  const sorted: Record<string, unknown> = {};
-  for (const key of Object.keys(value).sort()) {
-    sorted[key] = sortKeys((value as Record<string, unknown>)[key]);
-  }
-  return sorted;
-}
-
 export function canonicalizeJson(value: unknown): string {
-  return JSON.stringify(sortKeys(value));
+  return stableStringify(value);
 }

Based on learnings: "In Prisma-next's TypeScript codebase, prefer using well-established utility libraries (e.g., Lodash) rather than building custom utilities for complex object operations."

🤖 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/canonicalize-json.ts` around
lines 1 - 17, The custom deterministic serializer (functions sortKeys and
canonicalizeJson) can miss edge-cases (toJSON, special object types); replace it
with a battle-tested deterministic stringify library (e.g.,
fast-json-stable-stringify or json-stringify-deterministic) by importing that
library and returning its output from canonicalizeJson, removing or deprecating
sortKeys; ensure canonicalizeJson delegates all serialization to the library so
hashing/attestation uses the library's proven behavior and update any callers to
rely on canonicalizeJson as before.
packages/1-framework/1-core/migration/control-plane/src/config-types.ts (1)

80-86: Consider normalizing migrations.dir default in defineConfig().

The JSDoc states "Defaults to 'migrations'" but defineConfig() doesn't apply this default, unlike contract.output which is normalized on line 148. This could lead to inconsistent behavior where callers expect the default but receive undefined.

♻️ Proposed fix to add migrations normalization

Add normalization logic in defineConfig() after the contract normalization block (around line 160):

   // Return config as-is if no contract (preserve literal types)
-  return config;
+  // Normalize migrations config if present
+  const normalizedMigrations = config.migrations
+    ? { dir: config.migrations.dir ?? 'migrations' }
+    : undefined;
+
+  return {
+    ...config,
+    ...(normalizedMigrations && { migrations: normalizedMigrations }),
+  };
 }

Note: You may want to apply this normalization alongside the contract normalization to avoid multiple spread operations.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/1-core/migration/control-plane/src/config-types.ts`
around lines 80 - 86, The JSDoc promises migrations.dir defaults to "migrations"
but defineConfig() doesn't set it; update defineConfig() (near the existing
contract.output normalization block) to normalize the migrations field by
ensuring migrations exists and setting migrations.dir to "migrations" when
undefined (mirror how contract.output is normalized) — adjust the same
spread/merge that handles contract normalization to also apply migrations
normalization so callers always receive a concrete migrations.dir value.
packages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.ts (1)

67-559: Split this test file; it exceeds the 500-line limit.

This module bundles round-trip, additive, destructive, and conflict behavior in one file (~559 lines). Please split by concern into multiple {base}.{category}.test.ts files.

As per coding guidelines: "**/*.test.ts: Keep test files under 500 lines ... split by functionality/describe boundaries with descriptive category suffixes."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.ts`
around lines 67 - 559, The test file is over the 500-line limit and should be
split by concern: create separate test files for the "contractToSchemaIR →
planner round-trip" suite, the "planner — additive scenarios" suite, the
"detectDestructiveChanges" suite, and the "planner — type and nullability change
behavior" suite. Move each describe block (identified by the exact titles used
in the file) into its own file named with a descriptive suffix (e.g.,
base.contract-to-schema-ir.test.ts, base.planner-additive.test.ts,
base.detect-destructive.test.ts, base.planner-type-nullability.test.ts),
preserving the tests that reference helpers like contractToSchemaIR,
createPostgresMigrationPlanner, planFromStorages, and detectDestructiveChanges,
and update imports/exports as needed so each new file imports those helpers and
types.
packages/2-sql/3-tooling/family/src/core/migrations/contract-to-schema-ir.ts (1)

63-64: Use ifDefined() consistently for conditional spreads.

This file mixes ifDefined() with inline conditional object spreads; align all conditional properties to ifDefined() for consistency and guideline compliance.

As per coding guidelines: "{packages,examples,test}/**/*.{ts,tsx}: Use ifDefined() from @prisma-next/utils/defined for conditional object spreads instead of inline conditional spread patterns."

Also applies to: 70-71, 78-79, 87-88, 104-105

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/3-tooling/family/src/core/migrations/contract-to-schema-ir.ts`
around lines 63 - 64, Replace inline conditional object spreads that add
optional properties (e.g., ...(column.default != null ? { default:
convertDefault(column.default) } : {})) with the ifDefined() helper from
`@prisma-next/utils/defined` so the optional properties are added consistently;
specifically, update the code paths that set the "default" property (using
convertDefault(column.default)) and the other conditional spreads referenced
around the same block (the similar patterns at the locations you noted) to use
ifDefined(() => ({ default: convertDefault(column.default) })) or ifDefined(()
=> convertDefault(column.default)) as appropriate so the resulting object uses
ifDefined() for all conditional properties.
packages/1-framework/3-tooling/migration/test/io.test.ts (1)

42-43: Prefer deep equality over JSON.stringify equality in assertions.

Using toEqual here gives clearer diffs when assertions fail.

♻️ Suggested test assertion refinement
-    expect(JSON.stringify(pkg.manifest)).toBe(JSON.stringify(manifest));
-    expect(JSON.stringify(pkg.ops)).toBe(JSON.stringify(ops));
+    expect(pkg.manifest).toEqual(manifest);
+    expect(pkg.ops).toEqual(ops);
🤖 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/io.test.ts` around lines 42 -
43, The tests currently compare serialized objects using JSON.stringify for
pkg.manifest and pkg.ops against manifest and ops; replace these stringified
comparisons with deep equality assertions (use
expect(pkg.manifest).toEqual(manifest) and expect(pkg.ops).toEqual(ops)) so test
failures show informative diffs and handle object ordering/structures correctly.
packages/1-framework/3-tooling/cli/test/commands/migration-plan.test.ts (1)

1-3: Use pathe instead of node:path for consistent cross-platform behavior.

Per coding guidelines, prefer pathe over node:path for path manipulation in TypeScript files.

Proposed fix
 import { mkdir, readFile } from 'node:fs/promises';
 import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { join } from 'pathe';

Based on learnings: "In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase."

🤖 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-plan.test.ts`
around lines 1 - 3, Replace the usage of the built-in path import by importing
join from 'pathe' instead of 'node:path' in migration-plan.test.ts; update the
import line that currently reads "import { join } from 'node:path';" to use
"pathe" so all path manipulation in the test (references to join) uses pathe for
consistent cross-platform behavior per guidelines.
packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts (2)

1-2: Use pathe consistently for path operations.

Line 2 imports from node:path while line 17 imports from pathe. Per coding guidelines, use pathe consistently for path manipulation.

Proposed fix
 import { readFile } from 'node:fs/promises';
-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';

Based on learnings: "In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase."

🤖 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-plan.ts` around
lines 1 - 2, Replace the node:path import with pathe: change the import of
relative and resolve from 'node:path' to 'pathe' and ensure any usages in this
module (e.g., code referencing relative(...) and resolve(...), such as in
migration-plan.ts) continue to work with the pathe API; update import line only
and run a quick typecheck to confirm no symbol name changes are needed.

375-443: Consider reusing color formatters from output utilities.

The formatMigrationPlanOutput function defines inline color helpers (green_, yellow_, dim_) that duplicate logic in ../utils/output.ts. Consider extracting and reusing the existing formatters for consistency.

🤖 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-plan.ts` around
lines 375 - 443, The function formatMigrationPlanOutput duplicates inline color
helpers (green_, yellow_, dim_); replace them by importing and using the shared
formatters from ../utils/output.ts (remove green_/yellow_/dim_ declarations and
use the exported formatter functions from that module) and ensure the
flags.color behavior is preserved by passing the flag or using the utils' API
that respects color settings so every occurrence of green_/yellow_/dim_ in
formatMigrationPlanOutput is replaced with the corresponding imported formatter.
packages/1-framework/3-tooling/cli/test/commands/migration-show.test.ts (1)

1-3: Use pathe instead of node:path for consistent cross-platform behavior.

Per coding guidelines, prefer pathe over node:path for path manipulation in TypeScript files.

Proposed fix
 import { mkdir } from 'node:fs/promises';
 import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { join } from 'pathe';

Based on learnings: "In the Prisma-next repository, prefer importing and using 'pathe' over the built-in 'node:path' module for path operations across the codebase."

🤖 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-show.test.ts`
around lines 1 - 3, Replace the node:path import with pathe to ensure
cross-platform path behavior: change the import statement that brings in join
from 'node:path' to import the equivalent join (or join as pathJoin) from
'pathe' and update any usages in this test file (e.g., the join(...) calls used
to build temp paths) to use that pathe join; keep existing imports for mkdir and
tmpdir as-is and ensure TypeScript types remain compatible with pathe's join
function.
packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts (2)

3-3: Use pathe in this TypeScript test file.

Line 3 imports from node:path; switch to pathe to match repo standards.

As per coding guidelines: "**/*.{ts,tsx,mts,cts}: 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-status.test.ts` at
line 3, Replace the node:path import with pathe in the test: find the import
statement that imports join from 'node:path' (used by the
migration-status.test.ts test file) and change it to import join from 'pathe'
(or the named import pattern your repo uses) so all TypeScript tests use pathe
for path manipulation; ensure any other path helper imports in the file follow
the same pathe pattern.

1-570: Split this test file; it exceeds the 500-line limit.

At 570 lines, this file should be broken into focused suites (e.g., migration-status.entries.test.ts and migration-status.output.test.ts) to keep maintenance and navigation manageable.

As per coding guidelines: "**/*.test.ts: Keep test files under 500 lines... split by logical boundaries when exceeded."

🤖 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-status.test.ts`
around lines 1 - 570, The test file migration-status.test.ts is over 500 lines
and should be split into focused suites; extract the buildMigrationEntries tests
(the describe('buildMigrationEntries') block and its helpers:
createTestContract, createManifest, createOp, createTempDir, setupChain) into a
new file (e.g., migration-status.entries.test.ts) and keep the
formatMigrationStatusOutput tests (describe('formatMigrationStatusOutput')) in
migration-status.output.test.ts; ensure both new files import the same utilities
(or move shared helpers to a small test helper module) and update imports for
buildMigrationEntries and formatMigrationStatusOutput accordingly so each file
is under 500 lines and tests still run.
test/integration/test/cli.migration-apply.e2e.test.ts (1)

2-2: Replace node:path with pathe in this TS test.

Line 2 should follow the repo-standard path module.

As per coding guidelines: "**/*.{ts,tsx,mts,cts}: 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 `@test/integration/test/cli.migration-apply.e2e.test.ts` at line 2, Replace the
Node built-in path import with the repo-standard pathe module: change the import
that currently reads "import { join, resolve } from 'node:path';" to import the
same named exports from 'pathe' instead (ensure any uses of join and resolve in
the test remain unchanged and compile with pathe).
packages/1-framework/3-tooling/cli/src/utils/output.ts (2)

1-1: Use pathe instead of node:path in this TypeScript module.

Line 1 imports from node:path; repo rules require pathe for TS path handling.

Suggested change
-import { relative } from 'node:path';
+import { relative } from 'pathe';

As per coding guidelines: "**/*.{ts,tsx,mts,cts}: 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/src/utils/output.ts` at line 1, Replace
the node:path import with pathe: change the import statement that currently
imports "relative" from "node:path" to import "relative" from "pathe" so the
module follows the repo TypeScript path-handling rule; update any usages of the
relative symbol in this file
(packages/1-framework/3-tooling/cli/src/utils/output.ts) to continue using
relative as before.

937-1041: Avoid duplicating migration result shapes in output formatting.

MigrationShowResult/MigrationStatus* are redefined here and can drift from command-layer types (they already differ in fields). Please extract a shared type module and reuse it from both command and output formatters.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/3-tooling/cli/src/utils/output.ts` around lines 937 -
1041, The file duplicates migration result types (MigrationShowResult,
MigrationStatusEntry, MigrationStatusResult, StatusDiagnostic) which can drift
from the command-layer types; extract these shared interfaces into a single
exported types module (e.g., migrations-types) and update
formatMigrationShowOutput and any callers to import and use the shared types
instead of local redefinitions so the shape is authoritative and reused across
command and output layers.
packages/1-framework/3-tooling/cli/src/control-api/client.ts (1)

422-422: Use ifDefined() for conditional spread consistency.

This inline conditional spread can be replaced with the project-standard helper already used in this file.

Suggested change
-      ...(onProgress ? { onProgress } : {}),
+      ...ifDefined('onProgress', onProgress),

As per coding guidelines: "{packages,examples,test}/**/*.{ts,tsx}: Use ifDefined() from @prisma-next/utils/defined for conditional object spreads instead of inline conditional spread patterns."

🤖 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/control-api/client.ts` at line 422,
Replace the inline conditional spread ...(onProgress ? { onProgress } : {}) with
the project-standard helper ifDefined to keep consistency; locate the object
where onProgress is being spread (the spread containing onProgress) and change
it to use ifDefined({ onProgress }) and ensure the existing import of ifDefined
from '@prisma-next/utils/defined' is used (or add it if missing).
packages/1-framework/3-tooling/cli/test/commands/migration-apply.test.ts (1)

3-3: Switch this test file to pathe imports.

Line 3 uses node:path; this repo standardizes on pathe in TypeScript files.

As per coding guidelines: "**/*.{ts,tsx,mts,cts}: 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-apply.test.ts` at
line 3, Replace the Node built-in path import with pathe: change the import
"import { join } from 'node:path';" to "import { join } from 'pathe';" so the
test uses the repo-standard pathe module (ensure any other path helpers in this
file also import from pathe rather than node:path, e.g., references to join).
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts (1)

389-389: Use ifDefined() for this conditional spread.

Line 389 uses inline conditional object spread; this repo standard prefers ifDefined() for that pattern.

As per coding guidelines: “Use ifDefined() from @prisma-next/utils/defined for conditional object spreads instead of inline conditional spread patterns.”

🤖 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` at line
389, Replace the inline conditional spread ...(markerHash !== undefined ? {
markerHash } : {}) with the repository standard ifDefined() helper: import
ifDefined from '@prisma-next/utils/defined' (or from the module's exports) and
use ...ifDefined({ markerHash }) in the same location inside migration-status.ts
(the symbol to update is markerHash and the helper is ifDefined).
packages/1-framework/3-tooling/cli/src/commands/migration-show.ts (1)

1-1: Switch this file to pathe for path operations.

Line 1 uses node:path; this command file should use pathe for cross-platform TypeScript path handling consistency.

♻️ Proposed fix
-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';
🤖 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-show.ts` at line 1,
Replace the node:path import with pathe: change the import of relative and
resolve from 'node:path' to 'pathe' and ensure all uses of relative(...) and
resolve(...) in this file (e.g., any calls referenced in migration-show.ts)
continue to work with pathe; update any type imports or call sites if necessary
to match pathe's API so path operations are cross-platform consistent.

@saevarb
saevarb force-pushed the feat/on-disk-migrations-v2 branch from fda3de4 to 8ecf6a6 Compare March 3, 2026 15:52
Base automatically changed from feat/db-update to main March 3, 2026 16:03
@saevarb
saevarb force-pushed the feat/on-disk-migrations-v2 branch from 8ecf6a6 to 5325816 Compare March 3, 2026 16:14

@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: 14

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

♻️ Duplicate comments (17)
packages/2-sql/3-tooling/family/src/core/migrations/contract-to-schema-ir.ts (1)

25-27: ⚠️ Potential issue | 🟠 Major

Escape single quotes in literal string defaults.

String values containing single quotes (e.g., O'Reilly) will produce invalid SQL ('O'Reilly'). This can corrupt default-diff behavior during planning.

Proposed fix
   if (typeof def.value === 'string') {
-    return `'${def.value}'`;
+    return `'${def.value.replaceAll("'", "''")}'`;
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/3-tooling/family/src/core/migrations/contract-to-schema-ir.ts`
around lines 25 - 27, The code returns a single-quoted string for string
defaults using def.value without escaping, which breaks SQL when the value
contains apostrophes; update the branch that checks typeof def.value ===
'string' to escape single quotes inside def.value by doubling each single-quote
character before wrapping it in single quotes (i.e., replace every ' with ''),
so the returned SQL literal is valid; locate the expression that currently
returns `'${def.value}'` and apply this escape transformation to def.value (or
call a shared SQL-escape helper) so default-diff and planning behave correctly.
packages/1-framework/1-core/migration/control-plane/src/config-validation.ts (1)

247-253: ⚠️ Potential issue | 🟠 Major

Reject arrays for config.migrations.

At Line [249], arrays are currently accepted (typeof [] === 'object'), so migrations: [] incorrectly passes validation.

🐛 Minimal fix
   if (configObj['migrations'] !== undefined) {
     const migrations = configObj['migrations'];
-    if (!migrations || typeof migrations !== 'object') {
+    if (!migrations || typeof migrations !== 'object' || Array.isArray(migrations)) {
       throw errorConfigValidation('migrations', {
         why: 'Config.migrations must be an object',
       });
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/1-core/migration/control-plane/src/config-validation.ts`
around lines 247 - 253, The current validation in config-validation.ts accepts
arrays because it only checks typeof migrations === 'object'; update the check
for configObj['migrations'] so that arrays are rejected by also testing
Array.isArray. Concretely, in the block referencing configObj['migrations'] and
the local variable migrations, change the condition that throws
errorConfigValidation('migrations', ...) to include Array.isArray(migrations)
(i.e., treat arrays as invalid), so migrations must be a non-null object and not
an array before passing validation.
packages/1-framework/3-tooling/migration/src/attestation.ts (1)

33-39: ⚠️ Potential issue | 🟠 Major

Use framed encoding for hash input instead of delimiter join.

Lines 33-39 still concatenate variable-length canonical strings with ":", which is ambiguous. Please switch to length-framed parts (or hash each part first) before final hashing.

Suggested fix
-  const combined = [
-    canonicalManifest,
-    canonicalOps,
-    canonicalFromContract,
-    canonicalToContract,
-  ].join(':');
+  const parts = [
+    canonicalManifest,
+    canonicalOps,
+    canonicalFromContract,
+    canonicalToContract,
+  ];
+  const combined = parts.map((part) => `${part.length}:${part}`).join('|');
🤖 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/attestation.ts` around lines 33
- 39, The current code builds `combined` by joining variable-length strings
(`canonicalManifest`, `canonicalOps`, `canonicalFromContract`,
`canonicalToContract`) with ":" which is ambiguous; change this to a
length-framed or per-part-hash approach before final hashing: either prefix each
part with its byte/char length (e.g. "<len>:<part>") or compute a stable hash
for each part and then concatenate those hashes, then feed the framed/hashed
result into `createHash('sha256')`; update the code around the `combined`
variable and the `createHash` usage so the input to `createHash` is unambiguous
and collision-resistant.
packages/1-framework/3-tooling/migration/src/io.ts (2)

79-90: ⚠️ Potential issue | 🟠 Major

Only collapse ENOENT; rethrow other filesystem errors.

Lines 79-90 and 138-142 currently convert any FS failure into missing-file/empty-dir behavior, which hides permissions and I/O failures (EACCES, EISDIR, etc.).

Suggested fix
   try {
     manifestRaw = await readFile(manifestPath, 'utf-8');
-  } catch {
-    throw errorMissingFile(MANIFEST_FILE, dir);
+  } catch (error) {
+    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+      throw errorMissingFile(MANIFEST_FILE, dir);
+    }
+    throw error;
   }

   let opsRaw: string;
   try {
     opsRaw = await readFile(opsPath, 'utf-8');
-  } catch {
-    throw errorMissingFile(OPS_FILE, dir);
+  } catch (error) {
+    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+      throw errorMissingFile(OPS_FILE, dir);
+    }
+    throw error;
   }
...
   try {
     entries = await readdir(migrationsRoot);
-  } catch {
-    return [];
+  } catch (error) {
+    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+      return [];
+    }
+    throw error;
   }

Also applies to: 138-142

🤖 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/io.ts` around lines 79 - 90, The
current try/catch around readFile calls for manifestPath and opsPath (producing
manifestRaw and opsRaw) always maps any filesystem error to
errorMissingFile(MANIFEST_FILE, dir) / errorMissingFile(OPS_FILE, dir); change
those catches to inspect the thrown error (e.g., err.code) and only convert
ENOENT to errorMissingFile, rethrow any other errors (permissions, EISDIR,
EACCES, etc.); apply the same change to the other analogous block later in the
file (the second readFile pair around ops/manifest handling) so only
missing-file errors are collapsed while other FS errors propagate.

58-71: ⚠️ Potential issue | 🔴 Critical

Make package directory creation atomic to avoid overwrite races.

Lines 58-71 use stat-then-mkdir (recursive: true), which is racy and can still write into an already-created directory. Create the target dir atomically and use exclusive file writes.

Suggested fix
-import { basename, join } from 'pathe';
+import { basename, dirname, join } from 'pathe';

 export async function writeMigrationPackage(
   dir: string,
   manifest: MigrationManifest,
   ops: MigrationOps,
 ): Promise<void> {
-  let exists = false;
-  try {
-    await stat(dir);
-    exists = true;
-  } catch {
-    // directory doesn't exist, which is what we want
-  }
-  if (exists) {
-    throw errorDirectoryExists(dir);
-  }
-
-  await mkdir(dir, { recursive: true });
-  await writeFile(join(dir, MANIFEST_FILE), JSON.stringify(manifest, null, 2));
-  await writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2));
+  await mkdir(dirname(dir), { recursive: true });
+  try {
+    await mkdir(dir);
+  } catch (error) {
+    if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
+      throw errorDirectoryExists(dir);
+    }
+    throw error;
+  }
+
+  await writeFile(join(dir, MANIFEST_FILE), JSON.stringify(manifest, null, 2), { flag: 'wx' });
+  await writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2), { flag: 'wx' });
 }
🤖 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/io.ts` around lines 58 - 71, The
current stat-then-mkdir flow is racy; replace it by attempting to create the
package directory atomically with mkdir(dir) and if mkdir errors with EEXIST
call errorDirectoryExists(dir), otherwise propagate other errors; do not use
recursive:true for the final package dir creation. After the directory is
created, write the manifest and ops files using exclusive/atomic writes: write
each payload to a temporary file in that same dir and then rename to
MANIFEST_FILE and OPS_FILE (or use writeFile with the 'wx' flag) so writes fail
if the files already exist and the final rename is atomic; reference symbols:
stat, mkdir, writeFile, MANIFEST_FILE, OPS_FILE, errorDirectoryExists, dir,
manifest, ops.
packages/1-framework/3-tooling/cli/test/commands/migration-e2e.test.ts (3)

51-58: ⚠️ Potential issue | 🟠 Major

Ephemeral directories are leaked across tests.

createTempDir() creates real filesystem state without teardown, which leaves residue between runs.

🧹 Proposed fix
-import { mkdir } from 'node:fs/promises';
+import { mkdir, rm } from 'node:fs/promises';
 ...
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it } from 'vitest';
+
+const tempDirs = new Set<string>();
 ...
 async function createTempDir(): Promise<string> {
   const dir = join(
     tmpdir(),
     `test-migration-e2e-${Date.now()}-${Math.random().toString(36).slice(2)}`,
   );
   await mkdir(dir, { recursive: true });
+  tempDirs.add(dir);
   return dir;
 }
+
+afterEach(async () => {
+  await Promise.all([...tempDirs].map((dir) => rm(dir, { recursive: true, force: true })));
+  tempDirs.clear();
+});

As per coding guidelines: {test/e2e/**,test/integration/**,packages/1-framework/3-tooling/cli/**}: Tests must clean up their own ephemeral directories.

Also applies to: 60-64, 114-117, 198-200

🤖 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-e2e.test.ts`
around lines 51 - 58, The helper createTempDir currently creates real filesystem
directories with mkdir and never removes them, leaking ephemeral state across
tests; update the test utilities and tests that call createTempDir (and other
places creating temp dirs) to either use fs.mkdtemp for OS-managed temp dirs or
ensure each created directory is removed in a teardown step (afterEach/afterAll)
by calling fs.rm/rimraf on the returned path; specifically modify createTempDir
and tests that call it so they register the created path for cleanup or return a
cleanup function, and add a centralized removal in the test file teardown to
delete the temp directories created by createTempDir (referencing the
createTempDir helper and the test files that call it).

196-242: ⚠️ Potential issue | 🟠 Major

The no-op scenario is asserted without re-running plan.

This case checks leaf equality only; it never performs a second planning call or verifies that migration artifacts remain unchanged.

As per coding guidelines: **/{*.test.ts,*.test-d.ts,test/**,**/test/**}: Avoid tautological tests ... tests must verify behavior, not mirror fixture input.

🤖 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-e2e.test.ts`
around lines 196 - 242, The test currently only checks the leaf hash without
re-running the planner/CLI, so change it to actually perform a second planning
run and assert it returns a no-op and that no new files were written: after
creating and attesting the first migration (using writeMigrationPackage and
attestMigration), invoke the planner/CLI entrypoint used elsewhere in tests to
produce a second plan (the same command the real CLI uses in tests), capture its
result and assert a noOp/early-return flag is true, then call readMigrationsDir
and compare the directory listing (or package list from
readMigrationsDir/reconstructGraph) before and after to ensure no additional
migration dirs/files were created and the leaf (findLeaf) remains the same.

60-281: ⚠️ Potential issue | 🟠 Major

These tests bypass command-level behavior checks.

The suite validates migration-tool functions, but does not invoke CLI handlers or assert process.exit codes, so command contracts are untested.

As per coding guidelines: packages/1-framework/3-tooling/cli/**/*.{test,spec}.ts: Test CLI commands by spying on process.exit() to verify correct exit codes are called.

🤖 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-e2e.test.ts`
around lines 60 - 281, The tests currently exercise library helpers
(verifyMigration, attestMigration, writeMigrationPackage, readMigrationsDir,
reconstructGraph) but do not exercise the CLI command behavior or exit codes;
update the tests (or add new test cases in this file) to import and invoke the
CLI command entrypoint (the exported function that runs the migration CLI) and
spy on process.exit to assert it is called with the correct codes (0 on success,
non-zero on failures/drafts), e.g., wrap invocation so process.exit is
jest.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit')
}) and verify calls after invoking the CLI handler for success, no-op, and draft
scenarios.
packages/1-framework/3-tooling/cli/src/commands/migration-show.ts (1)

233-247: ⚠️ Potential issue | 🟠 Major

Wrap the command action with performAction() for standardized CLI error handling.

This handler currently runs directly; use the shared wrapper to enforce structured error boundaries and fail-fast behavior consistently.

As per coding guidelines: "packages/1-framework/3-tooling/cli/**/commands/**/*.ts: CLI commands must use structured errors, the Result pattern (performAction), and process.exit() for exit codes."

🤖 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-show.ts` around
lines 233 - 247, The action handler in migration-show.ts should be wrapped with
the shared performAction() wrapper to enforce structured errors and the Result
pattern: replace the existing inline async action body so that performAction()
calls your async function which parses flags via parseGlobalFlags(options),
invokes executeMigrationShowCommand(target, options, flags), then passes the
result into handleResult(result, flags, ...) exactly as before (printing JSON or
formatted output) and finally calls process.exit(exitCode); ensure you reference
the same symbols (parseGlobalFlags, executeMigrationShowCommand, handleResult,
formatMigrationShowOutput, performAction) and propagate/return errors through
performAction so standardized CLI error handling is used.
packages/1-framework/3-tooling/cli/src/control-api/operations/migration-apply.ts (2)

76-89: ⚠️ Potential issue | 🟠 Major

Catch thrown validation/runner exceptions and close the edge span on that path.

If validateContractIR(...) or runner.execute(...) throws, this exits without returning MigrationApplyResult and without ending the span as error.

Proposed hardening
-    const destinationContract = familyInstance.validateContractIR(edge.toContract as ContractIR);
-
-    const runnerResult: MigrationRunnerResult = await runner.execute({
-      plan,
-      driver,
-      destinationContract,
-      policy,
-      executionChecks: {
-        prechecks: true,
-        postchecks: true,
-        idempotencyChecks: true,
-      },
-      frameworkComponents,
-    });
+    let runnerResult: MigrationRunnerResult;
+    try {
+      const destinationContract = familyInstance.validateContractIR(edge.toContract as ContractIR);
+      runnerResult = await runner.execute({
+        plan,
+        driver,
+        destinationContract,
+        policy,
+        executionChecks: {
+          prechecks: true,
+          postchecks: true,
+          idempotencyChecks: true,
+        },
+        frameworkComponents,
+      });
+    } catch (error) {
+      onProgress?.({
+        action: 'migrationApply',
+        kind: 'spanEnd',
+        spanId: edgeSpanId,
+        outcome: 'error',
+      });
+      return notOk({
+        code: 'RUNNER_FAILED' as const,
+        summary: `Failed to apply migration ${edge.dirName}`,
+        why: error instanceof Error ? error.message : String(error),
+        meta: { migration: edge.dirName, from: edge.from, to: edge.to },
+      });
+    }
🤖 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/control-api/operations/migration-apply.ts`
around lines 76 - 89, Wrap the calls to familyInstance.validateContractIR(...)
and runner.execute(...) in a try/catch so any thrown validation or runner
exceptions are caught; in the catch, mark/record the error on the edge span (the
same span used around this edge), finish/close the span, and then rethrow or
return a failed MigrationApplyResult as the rest of the function expects.
Specifically, locate the use of validateContractIR and runner.execute in
migration-apply.ts, add a try { const destinationContract = ...; const
runnerResult = await runner.execute(...) } catch (err) { record error on the
edge span, finish the span, and propagate the error (or convert to
MigrationApplyResult error) } so the span is always ended on both success and
failure.

126-127: ⚠️ Potential issue | 🔴 Critical

Guard empty pendingEdges before reading the final hash.

This crashes on no-op input (pendingEdges.length === 0) instead of returning a structured result.

Proposed guard
+  if (pendingEdges.length === 0) {
+    return notOk({
+      code: 'EDGE_NOT_FOUND',
+      summary: 'No pending migrations to apply',
+      why: 'pendingEdges is empty',
+      meta: undefined,
+    });
+  }
   const finalHash = pendingEdges[pendingEdges.length - 1]!.to;
🤖 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/control-api/operations/migration-apply.ts`
around lines 126 - 127, Guard against empty pendingEdges before accessing
pendingEdges[pendingEdges.length - 1]; if pendingEdges.length === 0 return a
structured no-op result instead of reading finalHash. Specifically, add a check
before computing const finalHash = pendingEdges[...] to short-circuit and return
an object with applied (empty or existing applied array), totalOps = 0 (or
compute from applied which will be zero), and finalHash set to the
starting/current hash value in scope (use the existing starting-hash variable
available in this function). This prevents the crash and preserves the expected
result shape without reading pendingEdges.
packages/1-framework/3-tooling/migration/src/dag.ts (2)

240-242: ⚠️ Potential issue | 🟠 Major

Seed orphan traversal from actual graph roots, not only EMPTY_CONTRACT_HASH.

Starting reachability only from the empty sentinel can misclassify valid rooted chains as orphaned when the root from hash is non-empty.

Proposed fix
-  const queue: string[] = [EMPTY_CONTRACT_HASH];
-  reachable.add(EMPTY_CONTRACT_HASH);
+  const queue: string[] = [];
+  const incomingTargets = new Set<string>();
+  for (const edgeList of graph.edges.values()) {
+    for (const edge of edgeList) incomingTargets.add(edge.to);
+  }
+  for (const node of graph.nodes) {
+    if (!incomingTargets.has(node)) {
+      reachable.add(node);
+      queue.push(node);
+    }
+  }
🤖 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/dag.ts` around lines 240 - 242,
The traversal seeds only with EMPTY_CONTRACT_HASH which can mark valid rooted
chains as orphans; instead initialize the queue and reachable set with the real
graph roots (in addition to EMPTY_CONTRACT_HASH) by computing all root hashes
(e.g., nodes whose 'from' is empty or that have no incoming edges) and pushing
those into queue and reachable before the BFS/DFS loop. Update the
initialization around the variables queue, reachable and EMPTY_CONTRACT_HASH so
the traversal begins from all actual roots rather than just the empty sentinel.

32-34: ⚠️ Potential issue | 🟠 Major

Reject duplicate edgeId values during graph reconstruction.

edgeById.set(...) silently overwrites prior edges when IDs collide, which can corrupt parent-chain traversal and path resolution.

Proposed fix
     if (edge.edgeId !== null) {
+      if (edgeById.has(edge.edgeId)) {
+        throw new Error(`Duplicate edgeId detected: ${edge.edgeId}`);
+      }
       edgeById.set(edge.edgeId, edge);
     }
🤖 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/dag.ts` around lines 32 - 34,
During graph reconstruction the code currently uses edgeById.set(edge.edgeId,
edge) which silently overwrites existing entries when edge.edgeId collides;
update the logic around the edgeById population (the block using edge.edgeId and
edgeById.set) to detect duplicates by checking edgeById.has(edge.edgeId) before
setting and reject duplicates (e.g., throw an error or return a failure)
including the duplicate edgeId and involved edge identifiers so the caller can
surface the conflict instead of silently overwriting.
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts (2)

253-254: ⚠️ Potential issue | 🟠 Major

Do not report online mode without a real connectivity check.

In the zero-migration branch, mode is derived from config presence (dbConnection && hasDriver) rather than successful DB access, which can misreport offline/unreachable setups as online.

🤖 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 253 - 254, The code currently sets mode using the config flags
dbConnection && hasDriver in the zero-migration branch (the object with
properties mode and migrations), which can misreport unreachable DBs as
"online"; replace that heuristic with an actual connectivity check: attempt a
lightweight DB operation (e.g., call the existing connection/test utility or
open a client from the driver and run a ping/simple query) and set mode =
'online' only if that attempt succeeds (otherwise 'offline'), leaving
migrations: [] untouched; reference the mode variable and the
dbConnection/hasDriver checks in migration-status.ts and update the
zero-migration branch that returns the object containing mode and migrations to
use the real test result.

419-433: ⚠️ Potential issue | 🟠 Major

Wrap status command execution with performAction().

The action handler currently bypasses the shared command wrapper and its expected error-handling semantics.

As per coding guidelines: “Wrap command logic in performAction() function which catches only CliStructuredError instances and lets other errors propagate for fail-fast behavior.”

🤖 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 419 - 433, The action handler must be wrapped in performAction() to get
the shared error-handling semantics: replace the current body of .action(...) so
it calls await performAction(async () => { const flags =
parseGlobalFlags(options); const result = await
executeMigrationStatusCommand(options, flags); const exitCode =
handleResult(result, flags, (statusResult) => { if (flags.json === 'object') {
console.log(JSON.stringify(statusResult, null, 2)); } else if (!flags.quiet) {
console.log(formatMigrationStatusOutput(statusResult, flags)); } });
process.exit(exitCode); }); — keep the same calls to parseGlobalFlags,
executeMigrationStatusCommand, handleResult, and formatMigrationStatusOutput and
do not add other try/catch blocks (performAction will handle CliStructuredError
only).
packages/1-framework/3-tooling/cli/src/commands/migration-verify.ts (1)

126-140: ⚠️ Potential issue | 🟠 Major

Wrap the action in performAction() instead of calling execute directly.

The command action currently bypasses the shared wrapper, so CliStructuredError handling/fail-fast semantics are inconsistent with other CLI commands.

As per coding guidelines: “Wrap command logic in performAction() function which catches only CliStructuredError instances and lets other errors propagate for fail-fast behavior.”

🤖 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-verify.ts` around
lines 126 - 140, The action handler is calling executeMigrationVerifyCommand
directly and bypasses the shared error wrapper; wrap the body in performAction
so CliStructuredError is caught while other errors propagate. Replace the
current .action implementation that calls parseGlobalFlags,
executeMigrationVerifyCommand, handleResult, and process.exit with a
performAction(async (options: MigrationVerifyOptions) => { ... }) wrapper that
calls parseGlobalFlags(options), awaits executeMigrationVerifyCommand(options,
flags), uses handleResult to format output via
formatMigrationVerifyOutput/JSON/quiet, and then returns the exitCode (or lets
performAction call process.exit); ensure performAction is used instead of direct
invocation to preserve consistent fail-fast semantics.
packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts (1)

370-385: ⚠️ Potential issue | 🟠 Major

Wrap apply command execution in performAction().

The action currently executes directly; this bypasses the standard CLI orchestration contract for structured errors and fail-fast behavior.

As per coding guidelines: “CLI commands must use structured errors (CliStructuredError), the Result pattern (performAction), and process.exit() for exit codes.”

🤖 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-apply.ts` around
lines 370 - 385, Replace the direct action body with a call to performAction so
the command uses the standard Result/structured-error flow: inside the .action
callback, parse flags and startTime as before, then call performAction(async ()
=> executeMigrationApplyCommand(options, flags, startTime), { onSuccess:
(result) => { const exitCode = handleResult(result, flags, (applyResult) => { if
(flags.json === 'object') console.log(JSON.stringify(applyResult, null, 2));
else if (!flags.quiet) console.log(formatMigrationApplyOutput(applyResult,
flags)); }); process.exit(exitCode); } }). Ensure you pass the same inputs
(options, flags, startTime), rely on performAction to normalize errors to
CliStructuredError/Result, and remove the current direct await/try usage around
executeMigrationApplyCommand in the action.
🟡 Minor comments (10)
packages/1-framework/3-tooling/cli/vitest.config.ts-43-48 (1)

43-48: ⚠️ Potential issue | 🟡 Minor

Duplicate coverage exclusion entries.

Lines 43-45 and 46-48 are identical duplicates. Remove the redundant entries.

🧹 Proposed fix to remove duplicates
         'src/commands/migration-apply.ts',
         'src/commands/migration-plan.ts',
         'src/commands/migration-verify.ts',
-        'src/commands/migration-apply.ts',
-        'src/commands/migration-plan.ts',
-        'src/commands/migration-verify.ts',
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/3-tooling/cli/vitest.config.ts` around lines 43 - 48,
The coverage exclusion list in vitest.config.ts contains duplicate entries
('src/commands/migration-apply.ts', 'src/commands/migration-plan.ts',
'src/commands/migration-verify.ts') — remove the redundant repeated entries so
each path appears only once; locate the array (coverage.exclude) that contains
these strings and delete the second set of the three duplicate lines to dedupe
the list.
packages/1-framework/1-core/migration/control-plane/test/config-validation.test.ts-762-770 (1)

762-770: ⚠️ Potential issue | 🟡 Minor

Add a regression test for migrations as an array.

Current additions validate string/non-string cases, but migrations: [] is a critical shape edge case and should be explicitly rejected.

✅ Suggested test addition
   it('throws error when migrations is not an object', () => {
     const config = createValidConfig({ migrations: 'not-an-object' });
     expect(() => validateConfig(config)).toThrow(CliStructuredError);
   });
+
+  it('throws error when migrations is an array', () => {
+    const config = createValidConfig({ migrations: [] });
+    expect(() => validateConfig(config)).toThrow(CliStructuredError);
+  });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/1-framework/1-core/migration/control-plane/test/config-validation.test.ts`
around lines 762 - 770, Add a regression test that ensures validateConfig
rejects migrations when it is an array: use createValidConfig({ migrations: []
}) and assert that calling validateConfig(config) throws CliStructuredError;
place the test alongside the existing cases around the it blocks that test
migrations types so it covers the edge case of an array input being invalid.
packages/1-framework/3-tooling/cli/test/utils/command-helpers.test.ts-1-1 (1)

1-1: ⚠️ Potential issue | 🟡 Minor

Switch test path import to pathe.

Line 1 uses node:path; all TypeScript files in this repo should use pathe for consistent path operations across platforms. The dependency is available in package.json and is already used in production code (src/commands/contract-emit.ts, src/control-api/operations/contract-emit.ts) and other test files in the migration package.

🤖 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/utils/command-helpers.test.ts` at
line 1, Replace the Node built-in path import with pathe: change the import that
currently reads "import { resolve } from 'node:path';" to use "pathe" instead
(import { resolve } from 'pathe';) so the test uses the repo-standard path
utility; update any usages of resolve in command-helpers.test.ts as needed to
ensure consistent cross-platform path handling.
packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts-1-1 (1)

1-1: ⚠️ Potential issue | 🟡 Minor

Use pathe instead of node:path in TypeScript utilities.

Line 1 imports from node:path; this repo standard is pathe for TS path operations. Please switch the import source.

Suggested change
-import { resolve } from 'node:path';
+import { resolve } from 'pathe';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts` at line 1,
Replace the node:path import with the repo-standard pathe import: change "import
{ resolve } from 'node:path';" to import resolve from 'pathe' (or the named
export used across the codebase) and update any call sites in this module that
use resolve if necessary to match pathe's export style; ensure TypeScript types
still resolve and run a quick type-check to confirm no breakages in the utils
that reference resolve.
packages/1-framework/3-tooling/migration/src/errors.ts-103-106 (1)

103-106: ⚠️ Potential issue | 🟡 Minor

errorNoLeaf message text is inconsistent with the error code.

MIGRATION.NO_LEAF currently says “No root edge found,” which is confusing in diagnostics and support triage.

Suggested wording
-    why: `No root edge found in the migration graph (nodes: ${nodes.join(', ')}). Every migration references a parentEdgeId that does not exist, or the graph is empty.`,
+    why: `No leaf node found in the migration graph (nodes: ${nodes.join(', ')}). Every migration may reference a parentEdgeId that does not exist, or the graph is empty/cyclic.`,
🤖 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/errors.ts` around lines 103 -
106, The message for errorNoLeaf is inconsistent with its error code
MIGRATION.NO_LEAF; update the human-readable message (the second argument passed
to MigrationToolsError in function errorNoLeaf) to reflect a missing leaf rather
than a missing root (e.g., replace "No root edge found in the migration graph"
with "No leaf edge found in the migration graph" or "Migration graph has no leaf
node"). Keep the existing code value ('MIGRATION.NO_LEAF') and the detailed
payload (why/fix) unchanged; only modify the short message string in errorNoLeaf
to match the error code.
packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts-511-535 (1)

511-535: ⚠️ Potential issue | 🟡 Minor

The “highlights destructive operations in yellow” test does not verify colorization.

This currently checks only plain text presence, so it passes even if yellow formatting is removed.

Stronger assertion example
-    expect(output).toContain('1 op (1 destructive)');
+    expect(output).toContain('1 op (1 destructive)');
+    expect(output).toMatch(/\x1b\[33m/);
🤖 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-status.test.ts`
around lines 511 - 535, The test "highlights destructive operations in yellow"
currently only checks for plain text; update it to assert the ANSI yellow color
wrapping is present when color is enabled by checking that
formatMigrationStatusOutput (called with parseGlobalFlags({ color: true }))
returns the destructive summary wrapped in the yellow ANSI sequence (e.g.
"\x1b[33m1 op (1 destructive)\x1b[39m" or using \u001b equivalents) instead of
just the plain string, and optionally add a complementary assertion that
parseGlobalFlags({ color: false }) produces the uncolored string; locate the
test and the call sites for formatMigrationStatusOutput and parseGlobalFlags to
make this change.
packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts-147-160 (1)

147-160: ⚠️ Potential issue | 🟡 Minor

Remove the blind double-cast as unknown as Record<string, unknown> and validate the JSON structure explicitly.

The double cast violates the no-blind-cast rule and weakens type safety. After JSON.parse(), use explicit type narrowing with typeof checks to validate that the parsed value contains a storageHash property before accessing it, rather than relying on unsafe casts.

🤖 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-plan.ts` around
lines 147 - 160, Remove the unsafe double-cast by validating the parsed JSON
structure before accessing storageHash: after JSON.parse(contractJsonContent)
assign toContractJson, then check that toContractJson is a non-null object
(typeof toContractJson === 'object' && toContractJson !== null), that it has a
'storageHash' key (Object.prototype.hasOwnProperty.call(...) or 'storageHash' in
toContractJson), and that the value is a string; if those checks fail return the
existing errorContractValidationFailed with context (use contractPathAbsolute),
otherwise safely read and assign toStorageHash as that validated string. Use the
existing variable names (toContractJson, toStorageHash) and the existing error
helper (errorContractValidationFailed) to implement the validation and avoid the
blind cast.
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts-2-2 (1)

2-2: ⚠️ Potential issue | 🟡 Minor

Switch this TS path import from node:path to pathe.

-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';
🤖 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` at line
2, Change the ES import for path utilities to use the pathe package instead of
node:path: replace the import that brings in relative and resolve from
'node:path' with one that imports the same named exports from 'pathe' (i.e.,
import { relative, resolve } from 'pathe'), then rebuild/typecheck to ensure no
other code relies on Node-specific path behavior; check usages of relative and
resolve in this file to confirm they work unchanged.
packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts-2-2 (1)

2-2: ⚠️ Potential issue | 🟡 Minor

Replace node:path import with pathe. This TypeScript module uses relative() and resolve() functions (lines 101, 104, 105, 108) which should be imported from pathe instead of the built-in node:path module.

Proposed fix
-import { relative, resolve } from 'node:path';
+import { relative, resolve } from 'pathe';
🤖 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-apply.ts` at line
2, Replace the import from the Node builtin with the pathe package: change the
import statement that currently pulls relative and resolve from 'node:path' to
import them from 'pathe' instead; ensure any usages of relative() and resolve()
in this file (referenced in migration-apply.ts around the code that computes
migration paths — the calls to relative(...) and resolve(...)) remain unchanged
so they now resolve via pathe.
packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts-90-90 (1)

90-90: ⚠️ Potential issue | 🟡 Minor

Remove the unnecessary cast on migration operations.

pkg.ops is already typed as readonly MigrationPlanOperation[], which is structurally compatible with MigrationApplyEdge['operations']. The as cast hides this compatibility and prevents the type system from catching potential drift between the two types.

-    operations: pkg.ops as MigrationApplyEdge['operations'],
+    operations: pkg.ops,
🤖 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-apply.ts` at line
90, Remove the unnecessary type assertion on pkg.ops: drop the "as
MigrationApplyEdge['operations']" cast so the code uses pkg.ops directly
(pkg.ops is already readonly MigrationPlanOperation[]), allowing the compiler to
verify compatibility with MigrationApplyEdge['operations']; if the compiler then
reports a mismatch, fix the underlying types (either adjust
MigrationPlanOperation or MigrationApplyEdge.operations declaration) rather than
reintroducing a cast.

ℹ️ Review info

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between ecd9328 and a16d76e.

⛔ Files ignored due to path filters (11)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/migration-show/plan.md is excluded by !projects/**
  • projects/migration-show/spec.md is excluded by !projects/**
  • projects/on-disk-migrations/notes.md is excluded by !projects/**
  • projects/on-disk-migrations/plans/code-review-fixes.md is excluded by !projects/**
  • projects/on-disk-migrations/plans/migration-demo-rewrite.plan.md is excluded by !projects/**
  • projects/on-disk-migrations/plans/plan.md is excluded by !projects/**
  • projects/on-disk-migrations/spec.md is excluded by !projects/**
  • projects/on-disk-migrations/specs/migration-apply.spec.md is excluded by !projects/**
  • projects/on-disk-migrations/user-stories.md is excluded by !projects/**
  • projects/on-disk-migrations/verification-scenarios.md is excluded by !projects/**
📒 Files selected for processing (72)
  • .gitignore
  • docs/architecture docs/adrs/ADR 027 - Error Envelope Stable Codes.md
  • packages/1-framework/1-core/migration/control-plane/package.json
  • packages/1-framework/1-core/migration/control-plane/src/config-types.ts
  • packages/1-framework/1-core/migration/control-plane/src/config-validation.ts
  • packages/1-framework/1-core/migration/control-plane/src/constants.ts
  • packages/1-framework/1-core/migration/control-plane/src/exports/constants.ts
  • packages/1-framework/1-core/migration/control-plane/src/migrations.ts
  • packages/1-framework/1-core/migration/control-plane/test/config-validation.test.ts
  • packages/1-framework/1-core/migration/control-plane/tsdown.config.ts
  • packages/1-framework/1-core/migration/control-plane/vitest.config.ts
  • packages/1-framework/3-tooling/cli/README.md
  • packages/1-framework/3-tooling/cli/package.json
  • packages/1-framework/3-tooling/cli/src/cli.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-schema-verify.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-sign.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-verify.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-apply.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-show.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-verify.ts
  • packages/1-framework/3-tooling/cli/src/control-api/client.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-apply.ts
  • packages/1-framework/3-tooling/cli/src/control-api/types.ts
  • packages/1-framework/3-tooling/cli/src/utils/command-helpers.ts
  • packages/1-framework/3-tooling/cli/src/utils/migration-command-scaffold.ts
  • packages/1-framework/3-tooling/cli/src/utils/output.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-apply.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-e2e.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-show.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-verify.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/client.test.ts
  • packages/1-framework/3-tooling/cli/test/output.db-update.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/command-helpers.test.ts
  • packages/1-framework/3-tooling/cli/tsdown.config.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
  • packages/1-framework/3-tooling/migration/README.md
  • packages/1-framework/3-tooling/migration/package.json
  • packages/1-framework/3-tooling/migration/src/attestation.ts
  • packages/1-framework/3-tooling/migration/src/canonicalize-json.ts
  • packages/1-framework/3-tooling/migration/src/dag.ts
  • packages/1-framework/3-tooling/migration/src/errors.ts
  • packages/1-framework/3-tooling/migration/src/exports/attestation.ts
  • packages/1-framework/3-tooling/migration/src/exports/dag.ts
  • packages/1-framework/3-tooling/migration/src/exports/io.ts
  • packages/1-framework/3-tooling/migration/src/exports/types.ts
  • packages/1-framework/3-tooling/migration/src/io.ts
  • packages/1-framework/3-tooling/migration/src/types.ts
  • packages/1-framework/3-tooling/migration/test/attestation.test.ts
  • packages/1-framework/3-tooling/migration/test/canonicalize-json.test.ts
  • packages/1-framework/3-tooling/migration/test/dag.test.ts
  • packages/1-framework/3-tooling/migration/test/fixtures.ts
  • packages/1-framework/3-tooling/migration/test/io.test.ts
  • packages/1-framework/3-tooling/migration/tsconfig.json
  • packages/1-framework/3-tooling/migration/tsconfig.prod.json
  • packages/1-framework/3-tooling/migration/tsdown.config.ts
  • packages/1-framework/3-tooling/migration/vitest.config.ts
  • packages/2-sql/3-tooling/family/src/core/migrations/contract-to-schema-ir.ts
  • packages/2-sql/3-tooling/family/src/exports/control.ts
  • packages/2-sql/3-tooling/family/test/contract-to-schema-ir.test.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.ts
  • test/integration/package.json
  • test/integration/test/cli.migration-apply.e2e.test.ts
  • test/integration/test/cli.migration-plan.e2e.test.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-apply/contract.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-apply/prisma-next.config.with-db.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-plan/contract.ts
  • test/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-plan/prisma-next.config.ts

@wmadden

wmadden commented Mar 3, 2026

Copy link
Copy Markdown
Contributor

What looks solid in this PR (in addition to the blocking items I left inline):

  • The RD-18 migration chain model is a strong shape: separating the contract graph (from/to hashes can revisit) from the operational chain (parentEdgeId) makes traversal/order unambiguous.
  • Guardrails tightened meaningfully in apply/plan: marker reconciliation when no migrations exist, sentinel-marker corruption detection, and the fail-closed check when hashes differ but planning yields zero ops.
  • Tests are hitting the fault lines: chain semantics (revisits/branching) plus apply idempotency/resume coverage gives confidence the runner + marker behavior is correct.

Once the blocking items are addressed, this is on track to be a very reviewable/operationally-safe migration workflow.

wmadden and others added 6 commits March 4, 2026 14:13
Rename edge-oriented migration identifiers and apply-path types to migration-first names so CLI contracts, docs, and diagnostics match the domain language and reduce graph-model leakage.
The error code, message, and function name said 'no leaf' but the
actual trigger is a missing root migration (no migration with
parentMigrationId: null). Renamed to accurately reflect the cause.

Made-with: Cursor
The packages.length === 0 branch in migration apply had a try/finally
without a catch, so connection failures propagated as raw unhandled
exceptions instead of structured CLI errors.

Made-with: Cursor
@saevarb
saevarb force-pushed the feat/on-disk-migrations-v2 branch from b103511 to fabb553 Compare March 4, 2026 13:13
wmadden
wmadden previously approved these changes Mar 4, 2026

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

Good work @saevarb 👍🏻

…em I/O

The default 100ms timeout (200ms in CI) is too tight for tests that
write migration packages to disk, attest them, and read them back.

Made-with: Cursor
@saevarb
saevarb merged commit 013b840 into main Mar 4, 2026
11 checks passed
@saevarb
saevarb deleted the feat/on-disk-migrations-v2 branch March 4, 2026 14:21
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