Repository navigation
feat(migrations): on-disk migration planning, serialization, and apply - #184
Conversation
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 TML-1937 [PN] M2: On-disk persistence + DAG
Build the on-disk migration format, file management, edge attestation, and DAG reconstruction.\n\nScope:\n- TML-1938 [PN] M3: CLI commands + E2E flows
Build CLI commands ( |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds an on-disk migrations system: new Changes
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)
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
|
@prisma-next/runtime-executor
@prisma-next/sql-runtime
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/contract-authoring
@prisma-next/contract-ts
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/cli
@prisma-next/emitter
@prisma-next/eslint-plugin
@prisma-next/migration-tools
@prisma-next/vite-plugin-contract-emit
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/family-sql
@prisma-next/sql-kysely-lane
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-lane
@prisma-next/target-postgres
@prisma-next/adapter-postgres
@prisma-next/driver-postgres
@prisma-next/core-control-plane
@prisma-next/core-execution-plane
@prisma-next/config
@prisma-next/contract
@prisma-next/operations
@prisma-next/plan
@prisma-next/utils
commit: |
5e0a8a4 to
271d5c2
Compare
37d5b77 to
8aa25ae
Compare
There was a problem hiding this comment.
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 | 🔴 CriticalAttestation input is still forgeable via unframed concat and excludes
parentEdgeId.Two integrity problems remain: graph linkage (
parentEdgeId) is not covered by the hash, andjoin(':')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 | 🟡 MinorRemove 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 | 🟡 MinorSame unknown
typesproperty issue.As noted in the migration-plan config, the
typesfield on line 17 is not part of theContractConfiginterface.🐛 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 | 🟡 MinorRemove unknown
typesproperty from contract config.The
ContractConfiginterface only definessourceandoutputproperties. Per the interface documentation, the.d.tstypes file is automatically colocated with theoutputpath (e.g.,contract.json→contract.d.ts). Thetypesfield 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 | 🟡 MinorUse an ops-specific error instead of manifest error for
ops.jsonvalidation 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 | 🟡 MinorAdd cleanup for created temp directories.
createTempDir()creates real directories under OS temp, but this file never removes them. AddafterEachcleanup 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 | 🟡 MinorReplace
node:pathwithpatheimport on line 3.This TypeScript test file imports from
node:pathbut should usepathefor cross-platform path manipulation consistency. Update line 3 from:import { join } from 'node:path';to:
import { join } from 'pathe';The
pathepackage 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 | 🟡 MinorDuplicate 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 | 🟡 MinorThe 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 | 🟡 MinorTemporary 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 like20260301_initis 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 | 🟡 MinorReplace
node:pathwithpathein this TypeScript file.Line 2 imports from
node:path, which violates the repository standard for TypeScript path manipulation. Usepatheinstead 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 | 🟡 MinorUse
patheinstead ofnode:pathfor path operations in this TypeScript CLI command.Line 2 imports from
node:path, but the project standard is to usepathefor all TypeScript path manipulation. This is already established in other CLI command files likecontract-emit.tsandmigration-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 | 🟡 MinorRemove redundant cast—
pkg.opsis already correctly typed asMigrationPlanOperation[].The
MigrationPackagetype definesops: MigrationOps, andMigrationOpsis a type alias forreadonly MigrationPlanOperation[]. The cast on line 184 is unnecessary since the type is already correct through proper interface typing. Remove the cast and accesspkg.opsdirectly.🤖 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 | 🟡 MinorFix the type mismatch in
MigrationApplyEdgeto eliminate the blind cast on line 90.The cast
as MigrationApplyEdge['operations']on line 90 is unnecessary becausepkg.ops(typed asMigrationPlanOperation[]) should be directly assignable to the expected type. The root cause is thatMigrationApplyEdge.operationsdefinesoperationClassasstring, whileMigrationPlanOperation.operationClassis the more specific typeMigrationOperationClass('additive' | 'widening' | 'destructive'). Update theMigrationApplyEdgeinterface to declareoperationClass: MigrationOperationClassinstead ofstring, 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 | 🟡 MinorRemove the unnecessary blind cast when reading package operations.
Line 121 casts
pkg?.ops ?? []toreadonly MigrationPlanOperation[], but this cast is redundant. Thepkg?.opsproperty is already typed asMigrationOps(which expands toreadonly 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 coversLine 16andLine 17, so those two lines are redundant. Consider keeping only.cursorfor 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 entriesLines 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: Usepatheinstead ofnode:pathfor path operations.Per coding guidelines and learnings from PR
#191, preferpatheovernode: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: Usepatheinstead ofnode:pathfor path operations in tests.Per coding guidelines, prefer
patheovernode:pathacross 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: Usepatheinstead ofnode:pathfor path operations.Per coding guidelines and learnings from PR
#191, preferpatheovernode: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: Usepatheinstead ofnode:pathfor path operations.Per coding guidelines and learnings from PR
#191, preferpatheovernode:pathfor 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: Usepatheinstead ofnode:pathfor path operations.Per coding guidelines and learnings from PR
#191, preferpatheovernode: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: Usepatheinstead ofnode:pathfor path operations.Per coding guidelines and learnings from PR
#191, preferpatheovernode: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 singletoMatchObject()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 individualexpect().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 sharedcreateContractIR()factory instead of manualContractIRliterals.Manual assembly here duplicates contract shape and is brittle as
ContractIRevolves.As per coding guidelines: "
**/*.test.ts: Use factory functions likecreateContractIR()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: Usepatheinstead ofnode:pathin this TypeScript test.This file imports
joinfromnode:path; repo rules requirepathefor TS path handling consistency.Suggested diff
-import { join } from 'node:path'; +import { join } from 'pathe';As per coding guidelines: "
**/*.{ts,tsx,mts,cts}: Usepatheinstead ofnode:pathfor path manipulation in TypeScript files."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/test/commands/migration-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-stringifyorjson-stringify-deterministic. These handle edge cases such astoJSONmethods, 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 normalizingmigrations.dirdefault indefineConfig().The JSDoc states "Defaults to 'migrations'" but
defineConfig()doesn't apply this default, unlikecontract.outputwhich is normalized on line 148. This could lead to inconsistent behavior where callers expect the default but receiveundefined.♻️ 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.tsfiles.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: UseifDefined()consistently for conditional spreads.This file mixes
ifDefined()with inline conditional object spreads; align all conditional properties toifDefined()for consistency and guideline compliance.As per coding guidelines: "
{packages,examples,test}/**/*.{ts,tsx}: UseifDefined()from@prisma-next/utils/definedfor 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 overJSON.stringifyequality in assertions.Using
toEqualhere 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: Usepatheinstead ofnode:pathfor consistent cross-platform behavior.Per coding guidelines, prefer
patheovernode:pathfor 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: Usepatheconsistently for path operations.Line 2 imports from
node:pathwhile line 17 imports frompathe. Per coding guidelines, usepatheconsistently 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
formatMigrationPlanOutputfunction 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: Usepatheinstead ofnode:pathfor consistent cross-platform behavior.Per coding guidelines, prefer
patheovernode:pathfor 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: Usepathein this TypeScript test file.Line 3 imports from
node:path; switch topatheto match repo standards.As per coding guidelines: "
**/*.{ts,tsx,mts,cts}: Usepatheinstead ofnode:pathfor path manipulation in TypeScript files."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/test/commands/migration-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.tsandmigration-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: Replacenode:pathwithpathein this TS test.Line 2 should follow the repo-standard path module.
As per coding guidelines: "
**/*.{ts,tsx,mts,cts}: Usepatheinstead ofnode:pathfor path manipulation in TypeScript files."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@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: Usepatheinstead ofnode:pathin this TypeScript module.Line 1 imports from
node:path; repo rules requirepathefor TS path handling.Suggested change
-import { relative } from 'node:path'; +import { relative } from 'pathe';As per coding guidelines: "
**/*.{ts,tsx,mts,cts}: Usepatheinstead ofnode:pathfor path manipulation in TypeScript files."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/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: UseifDefined()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}: UseifDefined()from@prisma-next/utils/definedfor 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 topatheimports.Line 3 uses
node:path; this repo standardizes onpathein TypeScript files.As per coding guidelines: "
**/*.{ts,tsx,mts,cts}: Usepatheinstead ofnode:pathfor path manipulation in TypeScript files."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/test/commands/migration-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: UseifDefined()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/definedfor 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 topathefor path operations.Line 1 uses
node:path; this command file should usepathefor 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.
fda3de4 to
8ecf6a6
Compare
8ecf6a6 to
5325816
Compare
There was a problem hiding this comment.
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 | 🟠 MajorEscape 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 | 🟠 MajorReject arrays for
config.migrations.At Line [249], arrays are currently accepted (
typeof [] === 'object'), somigrations: []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 | 🟠 MajorUse 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 | 🟠 MajorOnly 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 | 🔴 CriticalMake 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 | 🟠 MajorEphemeral 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 | 🟠 MajorThe 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 | 🟠 MajorThese tests bypass command-level behavior checks.
The suite validates migration-tool functions, but does not invoke CLI handlers or assert
process.exitcodes, 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 | 🟠 MajorWrap 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), andprocess.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 | 🟠 MajorCatch thrown validation/runner exceptions and close the edge span on that path.
If
validateContractIR(...)orrunner.execute(...)throws, this exits without returningMigrationApplyResultand 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 | 🔴 CriticalGuard empty
pendingEdgesbefore 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 | 🟠 MajorSeed 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
fromhash 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 | 🟠 MajorReject duplicate
edgeIdvalues 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 | 🟠 MajorDo not report
onlinemode 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 | 🟠 MajorWrap 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 onlyCliStructuredErrorinstances 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 | 🟠 MajorWrap the action in
performAction()instead of calling execute directly.The command action currently bypasses the shared wrapper, so
CliStructuredErrorhandling/fail-fast semantics are inconsistent with other CLI commands.As per coding guidelines: “Wrap command logic in
performAction()function which catches onlyCliStructuredErrorinstances 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 | 🟠 MajorWrap 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), andprocess.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 | 🟡 MinorDuplicate 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 | 🟡 MinorAdd a regression test for
migrationsas 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 | 🟡 MinorSwitch test path import to
pathe.Line 1 uses
node:path; all TypeScript files in this repo should usepathefor consistent path operations across platforms. The dependency is available inpackage.jsonand 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 | 🟡 MinorUse
patheinstead ofnode:pathin TypeScript utilities.Line 1 imports from
node:path; this repo standard ispathefor 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
errorNoLeafmessage text is inconsistent with the error code.
MIGRATION.NO_LEAFcurrently 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 | 🟡 MinorThe “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 | 🟡 MinorRemove 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 withtypeofchecks to validate that the parsed value contains astorageHashproperty 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 | 🟡 MinorSwitch this TS path import from
node:pathtopathe.-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 | 🟡 MinorReplace
node:pathimport withpathe. This TypeScript module usesrelative()andresolve()functions (lines 101, 104, 105, 108) which should be imported frompatheinstead of the built-innode:pathmodule.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 | 🟡 MinorRemove the unnecessary cast on migration operations.
pkg.opsis already typed asreadonly MigrationPlanOperation[], which is structurally compatible withMigrationApplyEdge['operations']. Theascast 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
⛔ Files ignored due to path filters (11)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/migration-show/plan.mdis excluded by!projects/**projects/migration-show/spec.mdis excluded by!projects/**projects/on-disk-migrations/notes.mdis excluded by!projects/**projects/on-disk-migrations/plans/code-review-fixes.mdis excluded by!projects/**projects/on-disk-migrations/plans/migration-demo-rewrite.plan.mdis excluded by!projects/**projects/on-disk-migrations/plans/plan.mdis excluded by!projects/**projects/on-disk-migrations/spec.mdis excluded by!projects/**projects/on-disk-migrations/specs/migration-apply.spec.mdis excluded by!projects/**projects/on-disk-migrations/user-stories.mdis excluded by!projects/**projects/on-disk-migrations/verification-scenarios.mdis excluded by!projects/**
📒 Files selected for processing (72)
.gitignoredocs/architecture docs/adrs/ADR 027 - Error Envelope Stable Codes.mdpackages/1-framework/1-core/migration/control-plane/package.jsonpackages/1-framework/1-core/migration/control-plane/src/config-types.tspackages/1-framework/1-core/migration/control-plane/src/config-validation.tspackages/1-framework/1-core/migration/control-plane/src/constants.tspackages/1-framework/1-core/migration/control-plane/src/exports/constants.tspackages/1-framework/1-core/migration/control-plane/src/migrations.tspackages/1-framework/1-core/migration/control-plane/test/config-validation.test.tspackages/1-framework/1-core/migration/control-plane/tsdown.config.tspackages/1-framework/1-core/migration/control-plane/vitest.config.tspackages/1-framework/3-tooling/cli/README.mdpackages/1-framework/3-tooling/cli/package.jsonpackages/1-framework/3-tooling/cli/src/cli.tspackages/1-framework/3-tooling/cli/src/commands/db-schema-verify.tspackages/1-framework/3-tooling/cli/src/commands/db-sign.tspackages/1-framework/3-tooling/cli/src/commands/db-verify.tspackages/1-framework/3-tooling/cli/src/commands/migration-apply.tspackages/1-framework/3-tooling/cli/src/commands/migration-plan.tspackages/1-framework/3-tooling/cli/src/commands/migration-show.tspackages/1-framework/3-tooling/cli/src/commands/migration-status.tspackages/1-framework/3-tooling/cli/src/commands/migration-verify.tspackages/1-framework/3-tooling/cli/src/control-api/client.tspackages/1-framework/3-tooling/cli/src/control-api/operations/migration-apply.tspackages/1-framework/3-tooling/cli/src/control-api/types.tspackages/1-framework/3-tooling/cli/src/utils/command-helpers.tspackages/1-framework/3-tooling/cli/src/utils/migration-command-scaffold.tspackages/1-framework/3-tooling/cli/src/utils/output.tspackages/1-framework/3-tooling/cli/test/commands/migration-apply.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-e2e.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-plan.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-show.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-status.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-verify.test.tspackages/1-framework/3-tooling/cli/test/control-api/client.test.tspackages/1-framework/3-tooling/cli/test/output.db-update.test.tspackages/1-framework/3-tooling/cli/test/utils/command-helpers.test.tspackages/1-framework/3-tooling/cli/tsdown.config.tspackages/1-framework/3-tooling/cli/vitest.config.tspackages/1-framework/3-tooling/migration/README.mdpackages/1-framework/3-tooling/migration/package.jsonpackages/1-framework/3-tooling/migration/src/attestation.tspackages/1-framework/3-tooling/migration/src/canonicalize-json.tspackages/1-framework/3-tooling/migration/src/dag.tspackages/1-framework/3-tooling/migration/src/errors.tspackages/1-framework/3-tooling/migration/src/exports/attestation.tspackages/1-framework/3-tooling/migration/src/exports/dag.tspackages/1-framework/3-tooling/migration/src/exports/io.tspackages/1-framework/3-tooling/migration/src/exports/types.tspackages/1-framework/3-tooling/migration/src/io.tspackages/1-framework/3-tooling/migration/src/types.tspackages/1-framework/3-tooling/migration/test/attestation.test.tspackages/1-framework/3-tooling/migration/test/canonicalize-json.test.tspackages/1-framework/3-tooling/migration/test/dag.test.tspackages/1-framework/3-tooling/migration/test/fixtures.tspackages/1-framework/3-tooling/migration/test/io.test.tspackages/1-framework/3-tooling/migration/tsconfig.jsonpackages/1-framework/3-tooling/migration/tsconfig.prod.jsonpackages/1-framework/3-tooling/migration/tsdown.config.tspackages/1-framework/3-tooling/migration/vitest.config.tspackages/2-sql/3-tooling/family/src/core/migrations/contract-to-schema-ir.tspackages/2-sql/3-tooling/family/src/exports/control.tspackages/2-sql/3-tooling/family/test/contract-to-schema-ir.test.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.tstest/integration/package.jsontest/integration/test/cli.migration-apply.e2e.test.tstest/integration/test/cli.migration-plan.e2e.test.tstest/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-apply/contract.tstest/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-apply/prisma-next.config.with-db.tstest/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-plan/contract.tstest/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/migration-plan/prisma-next.config.ts
|
What looks solid in this PR (in addition to the blocking items I left inline):
Once the blocking items are addressed, this is on track to be a very reviewable/operationally-safe migration workflow. |
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
b103511 to
fabb553
Compare
…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
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.
migration plan): Diffs two contracts without a DB connection. UsescontractToSchemaIR()to synthesize aSqlSchemaIRfrom the previous contract, then feeds it into the existingPostgresMigrationPlanner— no new planner needed. Supports additive, widening, and destructive operations.migration.json+ops.jsonserialization, edge attestation (computeEdgeId,attestMigration,verifyMigration), DAG reconstruction with cycle/orphan detection.migration plan— offline diff → attested packagemigration apply— read pending migrations from DAG, execute sequentially against a live DB viaControlClientmigration verify— re-attest / validate integrityArchitecture
Key implementation details (migration apply)
ControlClient, consistent withdb initanddb updateorigin: nullfor first migration (runner expects no marker on fresh DB, notEMPTY_CONTRACT_HASH)familyInstance.validateContractIR()before passing to runnerTest plan
contractToSchemaIRconversion (15 tests)detectDestructiveChanges(7 tests)pnpm test:allpassespnpm lint:depscleanpnpm typecheckcleanSummary by CodeRabbit
New Features
Documentation
Tests
Chores