Skip to content

Route migration/db commands through the control-api seam (TML-3173) - #29911

Merged
wmadden-electric merged 7 commits into
mainfrom
tml-3173-cli-control-client-seam
Aug 7, 2026
Merged

wmadden-electric merged 7 commits into
mainfrom
tml-3173-cli-control-client-seam

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

After this PR, no CLI command module reaches @internal/migration-tools at runtime — every operation goes through the control-api seam. At the top of a command module, the change looks like this:

// before — commands/migrate.ts reaches business logic directly
import { findLatestMigration, isGraphNode, parseContractRef } from '@internal/migration-tools/...';

// after — the same operations, through the seam; only published types remain importable
import type { RefEntry, Refs } from '@internal/migration-tools/refs';
import { refuseMarkerOutsideGraph, resolveContractRef } from '../control-api/operations/...';

Why this matters: the CLI implementation is destined to move to the consolidated prisma CLI repo while the control client stays here as the product's programmatic API. That move is only possible if commands hold no business logic — this PR makes the seam airtight. (Stacked on the project's shaping PR #29909; the reviewable diff is the four TML-3173 commits.)

How it's built up

  • Fourteen command modules re-routed (db-init, db-sign, db-update, migrate, the migration interrogatives, ref), plus the shared status-overlay helper. Command modules keep argv parsing and rendering; policy moves down.
  • New control-api operations wrap each migration-tools touchpoint together with its existing CLI error mapping, returning Result<T, CliStructuredError> (the established db-verify pattern): ref/contract resolution, graph queries, invariant refusals, caught-error mapping, snapshot resolution, safe refs read, ref advancement.
  • Whole policy cores moved verbatim where the command was mostly business logic (ref, migration-new, migration-plan, migration-check, migration-list, migrate --show), with render callbacks (onContextResolved, onSeeded, onPreflightComplete) so the commands still print at exactly the same points.
  • Behavior is pinned, not asserted: zero changes under test/integration/ (~50 journey suites green), goldens untouched except one forced import repath, and the cast ratchet improves (841 → 837).

Verification

@internal/cli build + 1,423 package tests green; full integration suite 314/317 files green (the 3 failures are environmental: a host-timezone artifact that passes under TZ=UTC, and two hook timeouts that pass in isolation); lint:deps, lint:casts green.

Caveat worth knowing

The dependency-cruiser rule added here (cli-commands-no-runtime-migration-tools) is currently dormant: the repo's cruise excludes node_modules/dist, so no cross-package edges exist for any boundary rule to fire on — a pre-existing repo-wide blind spot (TML-3178). The operative enforcement is the runtime-import grep, which returns clean. Coverage of the moved cores is a known pre-existing gap tracked in TML-3179.

Alternatives considered

  • Route only enough to satisfy a lint — rejected: the point is the host-repo port, so whole cores moved where commands were mostly policy.
  • A bespoke import-scanner script instead of the dep-cruiser rule — deferred: one declarative rule in the established tool beats another ad-hoc scanner; the blind spot that currently mutes it is filed to be fixed repo-wide (TML-3178).
  • Renaming the moved execute*Command functions now — deliberately not: keeping names makes the diff mechanically reviewable; renames come with the command→result→renderer reshape in the next slice.

Refs: TML-3173

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added shared capabilities for migration planning, checking, graph visualization, references, and contract resolution.
    • Added offline migrate --show planning with preflight results.
    • Improved migration creation, planning, status, listing, and reference workflows.
    • Expanded the public control API with migration and contract operations.
  • Bug Fixes
    • Standardized structured CLI error handling and validation for invalid paths, markers, invariants, and contract snapshots.
  • Documentation
    • Clarified error guidance for db update and invalid contract files.
  • Tests
    • Added comprehensive coverage for planning, references, graph validation, snapshot resolution, and error handling.

@wmadden-electric
wmadden-electric requested a review from a team as a code owner August 6, 2026 17:32
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

CLI migration commands now delegate core operations to shared control-api modules. The changes add structured reference, planning, validation, ref, and contract-space operations, update public exports, enforce CLI dependency boundaries, and relocate or add tests.

Changes

CLI control API extraction

Layer / File(s) Summary
Shared resolution and validation operations
dependency-cruiser.config.mjs, packages/1-framework/3-tooling/cli/src/control-api/operations/*
Added shared reference, snapshot, ref-advancement, graph, invariant, error, aggregate-loader, and status operations. Runtime imports from CLI commands to migration tooling are restricted.
Migration planning and contract-space seeding
packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts, migration-plan.ts, migration-new.ts, contract-space-seed-phase.ts
Added migration preview, planning, migration creation, and contract-space seed-phase implementations with structured results and filesystem writes.
Migration read and integrity operations
packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts, migration-graph.ts, migration-list.ts
Added migration checks, target resolution, graph projections, list projections, filtering, summaries, and integrity validation.
CLI command delegation
packages/1-framework/3-tooling/cli/src/commands/*
Removed local migration-tool implementations from CLI commands. Commands now call control-api operations and return structured failures directly.
Public exports and validation coverage
packages/1-framework/3-tooling/cli/src/exports/control-api.ts, packages/1-framework/3-tooling/cli/test/*, docs/reference/error-reference.md
Exported the new operations and types. Updated imports, tests, error documentation, coverage configuration, and migration error exports.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant ControlAPI
  participant MigrationTools
  participant Filesystem
  CLI->>ControlAPI: execute migration operation
  ControlAPI->>MigrationTools: resolve and validate migration data
  ControlAPI->>Filesystem: read or write refs, snapshots, and packages
  Filesystem-->>ControlAPI: operation data
  ControlAPI-->>CLI: structured result
Loading

Possibly related PRs

  • prisma/prisma#29919: Refactors structured error handling in overlapping CLI migration command files.

Suggested reviewers: wmadden

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the primary change: routing migration and database CLI commands through the control-api seam.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-3173-cli-control-client-seam

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions

github-actions Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size
postgres / no-emit 167.84 KB (0%)
postgres / emit 145.99 KB (0%)
mongo / no-emit 100.42 KB (0%)
mongo / emit 90.25 KB (0%)
cf-worker / no-emit 192.49 KB (0%)
cf-worker / emit 168.32 KB (0%)

@wmadden-electric
wmadden-electric force-pushed the tml-3173-cli-control-client-seam branch from f059a41 to e60628c Compare August 7, 2026 08:53
@wmadden-electric
wmadden-electric changed the base branch from tml-3172-consolidate-clis-shaping to main August 7, 2026 08:53
@pkg-pr-new

pkg-pr-new Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

prisma-next

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

@prisma/orm-extension-arktype-json

npm i https://pkg.pr.new/@prisma/orm-extension-arktype-json@29911

@prisma/orm-extension-middleware-cache

npm i https://pkg.pr.new/@prisma/orm-extension-middleware-cache@29911

@prisma/orm-extension-paradedb

npm i https://pkg.pr.new/@prisma/orm-extension-paradedb@29911

@prisma/orm-extension-pgvector

npm i https://pkg.pr.new/@prisma/orm-extension-pgvector@29911

@prisma/orm-extension-postgis

npm i https://pkg.pr.new/@prisma/orm-extension-postgis@29911

@prisma/orm-extension-supabase

npm i https://pkg.pr.new/@prisma/orm-extension-supabase@29911

@prisma/orm-family-mongo

npm i https://pkg.pr.new/@prisma/orm-family-mongo@29911

@prisma/orm-family-sql

npm i https://pkg.pr.new/@prisma/orm-family-sql@29911

@prisma/orm-framework

npm i https://pkg.pr.new/@prisma/orm-framework@29911

@prisma/orm-mongo

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

@prisma/orm-postgres

npm i https://pkg.pr.new/@prisma/orm-postgres@29911

@prisma/orm-sqlite

npm i https://pkg.pr.new/@prisma/orm-sqlite@29911

@prisma/orm-target-mongo

npm i https://pkg.pr.new/@prisma/orm-target-mongo@29911

@prisma/orm-target-postgres

npm i https://pkg.pr.new/@prisma/orm-target-postgres@29911

@prisma/orm-target-sqlite

npm i https://pkg.pr.new/@prisma/orm-target-sqlite@29911

@prisma/orm-toolchain

npm i https://pkg.pr.new/@prisma/orm-toolchain@29911

commit: d2d4b85

@wmadden wmadden changed the title refactor(cli): route migration/db commands through the control-api seam (TML-3173) Route migration/db commands through the control-api seam (TML-3173) Aug 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (8)
packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts (1)

556-567: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Confirm the duplicate fromHash snapshot write.

Lines 493-496 already write the snapshot for fromHash with the same snapshotStartContract content. Lines 564-567 repeat that write in the delta branch. The store is keyed by hash and write-if-absent, so the second call is a no-op on content. Remove the second call, or state why the repeat is needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts`
around lines 556 - 567, Remove the redundant writeContractSnapshot call for
fromHash in the delta migration branch after writeDestinationSnapshot, since the
same snapshotStartContract content is already written earlier and snapshots are
keyed by hash. Preserve the existing planned package and destination snapshot
writes.
packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts (2)

421-421: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the shared APP_SPACE_ID constant.

Lines 421 and 509 compare spaceId against the string literal 'app'. packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts line 9 imports APP_SPACE_ID from @internal/framework-components/control. Use the same constant here so the app-space identity has one definition.

Also applies to: 509-509

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts`
at line 421, Update the app-space lookups in the migration-check logic,
including the `scopedSpaces.find` call and the corresponding comparison near the
second occurrence, to use the shared `APP_SPACE_ID` constant imported from
`@internal/framework-components/control` instead of the `'app'` literals.

312-331: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Document or narrow the silent aggregate-check failure path.

migration check reaches loadAggregateIntegrityViolations only after successful graph checks, and this catch converts any contract read/parse/deserialization or checkIntegrity error into zero violations. Make this intended fail-open behavior explicit in the doc comment, or reject/load-check it so unreadable contracts cannot hide as success.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts`
around lines 312 - 331, Document the intentional fail-open behavior in
loadAggregateIntegrityViolations, explicitly stating that contract read, parse,
deserialization, aggregate loading, or checkIntegrity failures return no
violations after graph checks have succeeded. Keep the existing
catch-and-empty-result behavior unless the function is changed to propagate
these errors instead.
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts (1)

299-316: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Avoid re-reading the contract after buildReadAggregate.

buildReadAggregate already reads the contract twice internally: it calls readContractEnvelope(config) to derive contractHash, and it calls loadContractRawSafely(config) to build the app contract. See packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-aggregate-loader.ts lines 352-370.

This caller then repeats both reads. Line 305 calls readContractEnvelope(config) again only to produce the CONTRACT.UNREADABLE diagnostic. Line 316 calls loadContractRawSafely(config) again only to decide whether to run the corruption check. The contract file is therefore parsed four times per migration status run.

Return the envelope outcome and the raw contract from buildReadAggregate, then consume them here. That removes the duplicate I/O and keeps one read site for the contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts` around
lines 299 - 316, Update buildReadAggregate to return the readContractEnvelope
outcome and loadContractRawSafely result alongside its existing aggregate and
contractHash values. In the migration status flow, consume those returned values
for the CONTRACT.UNREADABLE diagnostic and corruption-check decision, removing
the direct readContractEnvelope and loadContractRawSafely calls while preserving
their current behavior.
packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts (1)

185-187: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the array copy.

buildMigrationSpaceGraphEntries returns readonly MigrationSpaceGraphEntry[], and MigrationGraphResult.spaces accepts that type. The spread allocates a second array for no benefit.

♻️ Proposed refactor
-  const spaces: MigrationSpaceGraphEntry[] = [
-    ...buildMigrationSpaceGraphEntries({ aggregate, scopedSpaces }),
-  ];
+  const spaces: readonly MigrationSpaceGraphEntry[] = buildMigrationSpaceGraphEntries({
+    aggregate,
+    scopedSpaces,
+  });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts` around
lines 185 - 187, Remove the spread-based array copy in the initialization of
spaces and assign the readonly result of buildMigrationSpaceGraphEntries({
aggregate, scopedSpaces }) directly to it, preserving the existing
MigrationGraphResult.spaces typing.
packages/1-framework/3-tooling/cli/src/commands/migrate.ts (1)

233-239: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid the non-null assertion on the marker-hash lookup.

renderMarkerHashBySpace is keyed by [aggregate.app, ...aggregate.extensions] in executeMigrateShowPlan, and line 175 rebuilds the same list, so the lookup succeeds today. The assertion couples this render loop to that construction detail. Read the hash only inside the usedLiveMarker branch and drop the assertion.

♻️ Proposed refactor
-      const liveMarkerHash = plan.renderMarkerHashBySpace.get(space.spaceId)!;
+      const liveMarkerHash = plan.renderMarkerHashBySpace.get(space.spaceId);
       const tree = renderMigrationGraphCommand({
         grid,
         rowModel,
         contractHash,
         isAppSpace: isApp,
-        ...(plan.usedLiveMarker ? { dbHash: liveMarkerHash } : {}),
+        ...(plan.usedLiveMarker && liveMarkerHash !== undefined ? { dbHash: liveMarkerHash } : {}),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/src/commands/migrate.ts` around lines 233
- 239, Update the render loop around renderMigrationGraphCommand to remove the
non-null assertion from renderMarkerHashBySpace.get(space.spaceId). Only look up
and pass the marker hash inside the plan.usedLiveMarker branch, while preserving
the existing dbHash behavior when live markers are enabled.
packages/1-framework/3-tooling/cli/src/commands/migration-check.ts (1)

62-94: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

The aggregate is loaded twice per migration check run.

Line 62 loads the aggregate through buildReadAggregate. Line 87 calls loadAggregateIntegrityViolations, which loads the contract file and builds a second ContractSpaceAggregate internally. Every migration directory is read twice.

Change loadAggregateIntegrityViolations to accept the already loaded aggregate, and pass loadedAggregate.value.aggregate from this call site.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-check.ts` around
lines 62 - 94, Update loadAggregateIntegrityViolations to accept an existing
ContractSpaceAggregate instead of loading and building one internally, then pass
loadedAggregate.value.aggregate from the migration check flow after
buildReadAggregate succeeds. Preserve the existing violation loading and
filtering behavior while eliminating the second aggregate construction.
packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts (1)

222-236: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Narrow config.driver directly instead of using a non-null assertion.

Line 222 tests hasDriver, which is a separate boolean. TypeScript cannot narrow config.driver from it, so line 234 needs !. Test config.driver at line 222 to remove the assertion.

♻️ Proposed refactor
-    if (!dbConnection || !hasDriver) {
+    const driver = config.driver;
+    if (!dbConnection || !driver) {
       return notOk(
         errorDatabaseConnectionRequired({
           why: 'A database connection is required to read the live marker for migrate --show',
           commandName: 'migrate --show',
         }),
       );
     }
     const client = createControlClient({
       family: config.family,
       target: config.target,
       adapter: config.adapter,
-      driver: config.driver!,
+      driver,
       extensions: config.extensions ?? [],
     });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts`
around lines 222 - 236, Update the guard before createControlClient to validate
config.driver directly alongside dbConnection, so TypeScript narrows the
property and the driver! assertion can be removed. Preserve the existing error
response and client configuration, using the narrowed config.driver value for
the driver field.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-snapshot-resolution.ts`:
- Around line 25-40: Update ResolveContractRefToSnapshotOptions to a
discriminated union keyed by fallbackToEmitted: require missingBundleFlag in the
false branch while preserving its optional or absent status for the true branch.
Ensure callers of the missing-bundle path cannot construct options without the
required flag.
- Around line 96-126: Update the emitted-contract handling in the surrounding
resolution function so readFile, JSON.parse, null, and non-object shape failures
are converted into a CliStructuredError identifying
options.contractPathAbsolute. Return these failures through notOk rather than
rethrowing them, while preserving the existing MigrationToolsError and
CliStructuredError handling and successful storageHash matching behavior.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-seed-phase.ts`:
- Around line 109-128: Remove the __pack field from the planInputs descriptors
and eliminate the bare cast in the planAllSpaces callback. Build
descriptorBySpace before calling planAllSpaces, then use each planner input’s
spaceId to retrieve the corresponding contract-space descriptor and its
migrations, preserving the existing ordering and duplicate detection behavior.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts`:
- Around line 71-84: Update the non-ENOENT branch in
executeMigrationNewCommand’s contractJsonContent readFile handling to return a
structured failure using the same errorUnexpected pattern as migration-plan,
instead of rethrowing the filesystem error. Preserve the existing
notOk/errorRuntime response for missing contract files and ensure all read
failures satisfy the declared Result return type.
- Around line 173-180: Replace remaining reads of the non-existent target.id
property with config.target.targetId in the migration CLI operations. Update the
unsupported-migration message in migration-new.ts, the corresponding read in
migration-show.ts, and the migration-plan.ts message at the referenced range; no
other behavior should change.

---

Nitpick comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migrate.ts`:
- Around line 233-239: Update the render loop around renderMigrationGraphCommand
to remove the non-null assertion from
renderMarkerHashBySpace.get(space.spaceId). Only look up and pass the marker
hash inside the plan.usedLiveMarker branch, while preserving the existing dbHash
behavior when live markers are enabled.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-check.ts`:
- Around line 62-94: Update loadAggregateIntegrityViolations to accept an
existing ContractSpaceAggregate instead of loading and building one internally,
then pass loadedAggregate.value.aggregate from the migration check flow after
buildReadAggregate succeeds. Preserve the existing violation loading and
filtering behavior while eliminating the second aggregate construction.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts`:
- Around line 185-187: Remove the spread-based array copy in the initialization
of spaces and assign the readonly result of buildMigrationSpaceGraphEntries({
aggregate, scopedSpaces }) directly to it, preserving the existing
MigrationGraphResult.spaces typing.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 299-316: Update buildReadAggregate to return the
readContractEnvelope outcome and loadContractRawSafely result alongside its
existing aggregate and contractHash values. In the migration status flow,
consume those returned values for the CONTRACT.UNREADABLE diagnostic and
corruption-check decision, removing the direct readContractEnvelope and
loadContractRawSafely calls while preserving their current behavior.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts`:
- Around line 222-236: Update the guard before createControlClient to validate
config.driver directly alongside dbConnection, so TypeScript narrows the
property and the driver! assertion can be removed. Preserve the existing error
response and client configuration, using the narrowed config.driver value for
the driver field.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts`:
- Line 421: Update the app-space lookups in the migration-check logic, including
the `scopedSpaces.find` call and the corresponding comparison near the second
occurrence, to use the shared `APP_SPACE_ID` constant imported from
`@internal/framework-components/control` instead of the `'app'` literals.
- Around line 312-331: Document the intentional fail-open behavior in
loadAggregateIntegrityViolations, explicitly stating that contract read, parse,
deserialization, aggregate loading, or checkIntegrity failures return no
violations after graph checks have succeeded. Keep the existing
catch-and-empty-result behavior unless the function is changed to propagate
these errors instead.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts`:
- Around line 556-567: Remove the redundant writeContractSnapshot call for
fromHash in the delta migration branch after writeDestinationSnapshot, since the
same snapshotStartContract content is already written earlier and snapshots are
keyed by hash. Preserve the existing planned package and destination snapshot
writes.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9912c2e8-2725-44fd-b88f-d2a005c7ce97

📥 Commits

Reviewing files that changed from the base of the PR and between 6406655 and e60628c.

📒 Files selected for processing (65)
  • dependency-cruiser.config.mjs
  • packages/1-framework/3-tooling/cli/src/commands/db-init.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-sign.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-update.ts
  • packages/1-framework/3-tooling/cli/src/commands/migrate.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-log.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-show.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/commands/ref.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/caught-errors.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-at-errors.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-snapshot-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-aggregate-loader.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-seed-phase.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-run.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-verify.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/graph-queries.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/invariants.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-status-overlay.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/plan-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-advancement.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/refs.ts
  • packages/1-framework/3-tooling/cli/src/exports/control-api.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-snapshot-consistency.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-list.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-command.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-renderer.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref-error-mapping.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status-overlay.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/read-commands-json-golden.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/ref.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/aggregate-loader-preflight.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/build-read-aggregate.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/caught-errors.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-snapshot-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-aggregate-loader.ac15.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-seed-phase.mongo.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-seed-phase.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/graph-queries.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/invariants.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/map-integrity-violations.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migrate-show-plan.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migration-graph-entries.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/plan-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/refs.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
💤 Files with no reviewable changes (2)
  • packages/1-framework/3-tooling/cli/vitest.config.ts
  • packages/1-framework/3-tooling/cli/test/utils/ref-advancement.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 5

🧹 Nitpick comments (8)
packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts (1)

556-567: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Confirm the duplicate fromHash snapshot write.

Lines 493-496 already write the snapshot for fromHash with the same snapshotStartContract content. Lines 564-567 repeat that write in the delta branch. The store is keyed by hash and write-if-absent, so the second call is a no-op on content. Remove the second call, or state why the repeat is needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts`
around lines 556 - 567, Remove the redundant writeContractSnapshot call for
fromHash in the delta migration branch after writeDestinationSnapshot, since the
same snapshotStartContract content is already written earlier and snapshots are
keyed by hash. Preserve the existing planned package and destination snapshot
writes.
packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts (2)

421-421: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the shared APP_SPACE_ID constant.

Lines 421 and 509 compare spaceId against the string literal 'app'. packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts line 9 imports APP_SPACE_ID from @internal/framework-components/control. Use the same constant here so the app-space identity has one definition.

Also applies to: 509-509

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts`
at line 421, Update the app-space lookups in the migration-check logic,
including the `scopedSpaces.find` call and the corresponding comparison near the
second occurrence, to use the shared `APP_SPACE_ID` constant imported from
`@internal/framework-components/control` instead of the `'app'` literals.

312-331: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Document or narrow the silent aggregate-check failure path.

migration check reaches loadAggregateIntegrityViolations only after successful graph checks, and this catch converts any contract read/parse/deserialization or checkIntegrity error into zero violations. Make this intended fail-open behavior explicit in the doc comment, or reject/load-check it so unreadable contracts cannot hide as success.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts`
around lines 312 - 331, Document the intentional fail-open behavior in
loadAggregateIntegrityViolations, explicitly stating that contract read, parse,
deserialization, aggregate loading, or checkIntegrity failures return no
violations after graph checks have succeeded. Keep the existing
catch-and-empty-result behavior unless the function is changed to propagate
these errors instead.
packages/1-framework/3-tooling/cli/src/commands/migration-status.ts (1)

299-316: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Avoid re-reading the contract after buildReadAggregate.

buildReadAggregate already reads the contract twice internally: it calls readContractEnvelope(config) to derive contractHash, and it calls loadContractRawSafely(config) to build the app contract. See packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-aggregate-loader.ts lines 352-370.

This caller then repeats both reads. Line 305 calls readContractEnvelope(config) again only to produce the CONTRACT.UNREADABLE diagnostic. Line 316 calls loadContractRawSafely(config) again only to decide whether to run the corruption check. The contract file is therefore parsed four times per migration status run.

Return the envelope outcome and the raw contract from buildReadAggregate, then consume them here. That removes the duplicate I/O and keeps one read site for the contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts` around
lines 299 - 316, Update buildReadAggregate to return the readContractEnvelope
outcome and loadContractRawSafely result alongside its existing aggregate and
contractHash values. In the migration status flow, consume those returned values
for the CONTRACT.UNREADABLE diagnostic and corruption-check decision, removing
the direct readContractEnvelope and loadContractRawSafely calls while preserving
their current behavior.
packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts (1)

185-187: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the array copy.

buildMigrationSpaceGraphEntries returns readonly MigrationSpaceGraphEntry[], and MigrationGraphResult.spaces accepts that type. The spread allocates a second array for no benefit.

♻️ Proposed refactor
-  const spaces: MigrationSpaceGraphEntry[] = [
-    ...buildMigrationSpaceGraphEntries({ aggregate, scopedSpaces }),
-  ];
+  const spaces: readonly MigrationSpaceGraphEntry[] = buildMigrationSpaceGraphEntries({
+    aggregate,
+    scopedSpaces,
+  });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts` around
lines 185 - 187, Remove the spread-based array copy in the initialization of
spaces and assign the readonly result of buildMigrationSpaceGraphEntries({
aggregate, scopedSpaces }) directly to it, preserving the existing
MigrationGraphResult.spaces typing.
packages/1-framework/3-tooling/cli/src/commands/migrate.ts (1)

233-239: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid the non-null assertion on the marker-hash lookup.

renderMarkerHashBySpace is keyed by [aggregate.app, ...aggregate.extensions] in executeMigrateShowPlan, and line 175 rebuilds the same list, so the lookup succeeds today. The assertion couples this render loop to that construction detail. Read the hash only inside the usedLiveMarker branch and drop the assertion.

♻️ Proposed refactor
-      const liveMarkerHash = plan.renderMarkerHashBySpace.get(space.spaceId)!;
+      const liveMarkerHash = plan.renderMarkerHashBySpace.get(space.spaceId);
       const tree = renderMigrationGraphCommand({
         grid,
         rowModel,
         contractHash,
         isAppSpace: isApp,
-        ...(plan.usedLiveMarker ? { dbHash: liveMarkerHash } : {}),
+        ...(plan.usedLiveMarker && liveMarkerHash !== undefined ? { dbHash: liveMarkerHash } : {}),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/src/commands/migrate.ts` around lines 233
- 239, Update the render loop around renderMigrationGraphCommand to remove the
non-null assertion from renderMarkerHashBySpace.get(space.spaceId). Only look up
and pass the marker hash inside the plan.usedLiveMarker branch, while preserving
the existing dbHash behavior when live markers are enabled.
packages/1-framework/3-tooling/cli/src/commands/migration-check.ts (1)

62-94: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

The aggregate is loaded twice per migration check run.

Line 62 loads the aggregate through buildReadAggregate. Line 87 calls loadAggregateIntegrityViolations, which loads the contract file and builds a second ContractSpaceAggregate internally. Every migration directory is read twice.

Change loadAggregateIntegrityViolations to accept the already loaded aggregate, and pass loadedAggregate.value.aggregate from this call site.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-check.ts` around
lines 62 - 94, Update loadAggregateIntegrityViolations to accept an existing
ContractSpaceAggregate instead of loading and building one internally, then pass
loadedAggregate.value.aggregate from the migration check flow after
buildReadAggregate succeeds. Preserve the existing violation loading and
filtering behavior while eliminating the second aggregate construction.
packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts (1)

222-236: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Narrow config.driver directly instead of using a non-null assertion.

Line 222 tests hasDriver, which is a separate boolean. TypeScript cannot narrow config.driver from it, so line 234 needs !. Test config.driver at line 222 to remove the assertion.

♻️ Proposed refactor
-    if (!dbConnection || !hasDriver) {
+    const driver = config.driver;
+    if (!dbConnection || !driver) {
       return notOk(
         errorDatabaseConnectionRequired({
           why: 'A database connection is required to read the live marker for migrate --show',
           commandName: 'migrate --show',
         }),
       );
     }
     const client = createControlClient({
       family: config.family,
       target: config.target,
       adapter: config.adapter,
-      driver: config.driver!,
+      driver,
       extensions: config.extensions ?? [],
     });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts`
around lines 222 - 236, Update the guard before createControlClient to validate
config.driver directly alongside dbConnection, so TypeScript narrows the
property and the driver! assertion can be removed. Preserve the existing error
response and client configuration, using the narrowed config.driver value for
the driver field.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-snapshot-resolution.ts`:
- Around line 25-40: Update ResolveContractRefToSnapshotOptions to a
discriminated union keyed by fallbackToEmitted: require missingBundleFlag in the
false branch while preserving its optional or absent status for the true branch.
Ensure callers of the missing-bundle path cannot construct options without the
required flag.
- Around line 96-126: Update the emitted-contract handling in the surrounding
resolution function so readFile, JSON.parse, null, and non-object shape failures
are converted into a CliStructuredError identifying
options.contractPathAbsolute. Return these failures through notOk rather than
rethrowing them, while preserving the existing MigrationToolsError and
CliStructuredError handling and successful storageHash matching behavior.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-seed-phase.ts`:
- Around line 109-128: Remove the __pack field from the planInputs descriptors
and eliminate the bare cast in the planAllSpaces callback. Build
descriptorBySpace before calling planAllSpaces, then use each planner input’s
spaceId to retrieve the corresponding contract-space descriptor and its
migrations, preserving the existing ordering and duplicate detection behavior.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts`:
- Around line 71-84: Update the non-ENOENT branch in
executeMigrationNewCommand’s contractJsonContent readFile handling to return a
structured failure using the same errorUnexpected pattern as migration-plan,
instead of rethrowing the filesystem error. Preserve the existing
notOk/errorRuntime response for missing contract files and ensure all read
failures satisfy the declared Result return type.
- Around line 173-180: Replace remaining reads of the non-existent target.id
property with config.target.targetId in the migration CLI operations. Update the
unsupported-migration message in migration-new.ts, the corresponding read in
migration-show.ts, and the migration-plan.ts message at the referenced range; no
other behavior should change.

---

Nitpick comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migrate.ts`:
- Around line 233-239: Update the render loop around renderMigrationGraphCommand
to remove the non-null assertion from
renderMarkerHashBySpace.get(space.spaceId). Only look up and pass the marker
hash inside the plan.usedLiveMarker branch, while preserving the existing dbHash
behavior when live markers are enabled.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-check.ts`:
- Around line 62-94: Update loadAggregateIntegrityViolations to accept an
existing ContractSpaceAggregate instead of loading and building one internally,
then pass loadedAggregate.value.aggregate from the migration check flow after
buildReadAggregate succeeds. Preserve the existing violation loading and
filtering behavior while eliminating the second aggregate construction.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts`:
- Around line 185-187: Remove the spread-based array copy in the initialization
of spaces and assign the readonly result of buildMigrationSpaceGraphEntries({
aggregate, scopedSpaces }) directly to it, preserving the existing
MigrationGraphResult.spaces typing.

In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 299-316: Update buildReadAggregate to return the
readContractEnvelope outcome and loadContractRawSafely result alongside its
existing aggregate and contractHash values. In the migration status flow,
consume those returned values for the CONTRACT.UNREADABLE diagnostic and
corruption-check decision, removing the direct readContractEnvelope and
loadContractRawSafely calls while preserving their current behavior.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts`:
- Around line 222-236: Update the guard before createControlClient to validate
config.driver directly alongside dbConnection, so TypeScript narrows the
property and the driver! assertion can be removed. Preserve the existing error
response and client configuration, using the narrowed config.driver value for
the driver field.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts`:
- Line 421: Update the app-space lookups in the migration-check logic, including
the `scopedSpaces.find` call and the corresponding comparison near the second
occurrence, to use the shared `APP_SPACE_ID` constant imported from
`@internal/framework-components/control` instead of the `'app'` literals.
- Around line 312-331: Document the intentional fail-open behavior in
loadAggregateIntegrityViolations, explicitly stating that contract read, parse,
deserialization, aggregate loading, or checkIntegrity failures return no
violations after graph checks have succeeded. Keep the existing
catch-and-empty-result behavior unless the function is changed to propagate
these errors instead.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts`:
- Around line 556-567: Remove the redundant writeContractSnapshot call for
fromHash in the delta migration branch after writeDestinationSnapshot, since the
same snapshotStartContract content is already written earlier and snapshots are
keyed by hash. Preserve the existing planned package and destination snapshot
writes.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9912c2e8-2725-44fd-b88f-d2a005c7ce97

📥 Commits

Reviewing files that changed from the base of the PR and between 6406655 and e60628c.

📒 Files selected for processing (65)
  • dependency-cruiser.config.mjs
  • packages/1-framework/3-tooling/cli/src/commands/db-init.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-sign.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-update.ts
  • packages/1-framework/3-tooling/cli/src/commands/migrate.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-log.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-show.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/commands/ref.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/caught-errors.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-at-errors.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-snapshot-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-aggregate-loader.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-seed-phase.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-run.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-verify.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/graph-queries.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/invariants.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-status-overlay.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/plan-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-advancement.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/refs.ts
  • packages/1-framework/3-tooling/cli/src/exports/control-api.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-snapshot-consistency.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-list.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-command.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-renderer.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref-error-mapping.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status-overlay.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/read-commands-json-golden.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/ref.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/aggregate-loader-preflight.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/build-read-aggregate.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/caught-errors.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-snapshot-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-aggregate-loader.ac15.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-seed-phase.mongo.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-seed-phase.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/graph-queries.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/invariants.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/map-integrity-violations.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migrate-show-plan.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migration-graph-entries.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/plan-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/refs.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
💤 Files with no reviewable changes (2)
  • packages/1-framework/3-tooling/cli/vitest.config.ts
  • packages/1-framework/3-tooling/cli/test/utils/ref-advancement.test.ts
🛑 Comments failed to post (1)
packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-seed-phase.ts (1)

109-128: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Remove the __pack smuggling and the bare as cast.

Line 124 uses a bare as cast in production code. The coding guidelines forbid bare as casts outside tests and as const. The cast exists only because __pack is attached to the plan input at line 113 and must be read back at line 127.

The descriptorBySpace map at lines 133-139 already provides the same lookup. Build that map before planAllSpaces, then resolve migrations by spaceId inside the planner callback. This removes the extra field and the cast.

♻️ Proposed refactor
+  const descriptorBySpace = new Map<
+    string,
+    NonNullable<SeedPhaseExtensionInput['contractSpace']>
+  >();
+  for (const pack of inputs.extensions) {
+    if (pack.contractSpace !== undefined) descriptorBySpace.set(pack.id, pack.contractSpace);
+  }
+
   const planInputs = inputs.extensions
     .filter(
       (
         pack,
       ): pack is SeedPhaseExtensionInput & {
         contractSpace: NonNullable<SeedPhaseExtensionInput['contractSpace']>;
       } => pack.contractSpace !== undefined,
     )
     .map((pack) => ({
       spaceId: pack.id,
       priorContract: null,
       newContract: pack.contractSpace.contractJson,
-      __pack: pack.contractSpace,
     }));
 
   const planned: readonly SpacePlanOutput<DescriptorMigrationPackage>[] = planAllSpaces(
     planInputs,
-    (input) =>
-      (
-        input as typeof input & {
-          readonly __pack: NonNullable<SeedPhaseExtensionInput['contractSpace']>;
-        }
-      ).__pack.migrations,
+    (input) => descriptorBySpace.get(input.spaceId)?.migrations ?? [],
   );
-
-  // Reassemble a spaceId → descriptor lookup so the loop below can read
-  // the contractJson / headRef without leaking the typed-cast back into
-  // `planAllSpaces`'s output shape.
-  const descriptorBySpace = new Map<
-    string,
-    NonNullable<SeedPhaseExtensionInput['contractSpace']>
-  >();
-  for (const pack of inputs.extensions) {
-    if (pack.contractSpace !== undefined) descriptorBySpace.set(pack.id, pack.contractSpace);
-  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-seed-phase.ts`
around lines 109 - 128, Remove the __pack field from the planInputs descriptors
and eliminate the bare cast in the planAllSpaces callback. Build
descriptorBySpace before calling planAllSpaces, then use each planner input’s
spaceId to retrieve the corresponding contract-space descriptor and its
migrations, preserving the existing ordering and duplicate detection behavior.

Source: Coding guidelines

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts (1)

493-567: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the duplicate start-snapshot write.

Line 493 writes the fromHash snapshot from snapshotStartContract. Line 564 repeats the same call with the same arguments after the delta leg. The write is idempotent, so behavior is unchanged, but the second call is redundant disk I/O.

Keep only the write at line 493, which already runs on both auto-baseline exits.

♻️ Proposed change
       await writeDestinationSnapshot(toStorageHash);
-      await writeContractSnapshot(migrationsDir, fromHash, {
-        contractJson: snapshotStartContract.contractJson,
-        contractDts: snapshotStartContract.contractDts,
-      });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts`
around lines 493 - 567, Remove the second writeContractSnapshot call after
writeDestinationSnapshot in the delta migration flow, keeping the earlier call
that writes snapshotStartContract for fromHash. Do not alter the surrounding
delta planning or destination snapshot behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts`:
- Around line 218-376: Wrap the mutation prologue in
executeMigrationPlanCommand, including createProjectSpecifierResolver,
runContractSpaceSeedPhase, and related calls before the existing catch, in a
structured-error guard. Map MigrationToolsError and unknown exceptions to the
command’s Result<MigrationPlanResult, CliStructuredError> failure shape before
any promise rejection escapes; preserve existing success and callback behavior.
- Around line 100-106: Replace the bare cast in the failure branch of the
migration planning flow with the appropriate cast helper from
`@internal/utils/casts`, using castAs for the supported conversion of
plannerResult.conflicts to readonly CliErrorConflict[]. Also update the other
bare casts in this file, including the error handling around the code property
and the casts near lines 256 and 450: prefer a NodeJS.ErrnoException property
guard for code, use castAs for supported upcasts, and use blindCast<T, "Reason">
only where explicit justification is required.

---

Nitpick comments:
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts`:
- Around line 493-567: Remove the second writeContractSnapshot call after
writeDestinationSnapshot in the delta migration flow, keeping the earlier call
that writes snapshotStartContract for fromHash. Do not alter the surrounding
delta planning or destination snapshot behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 8d4244ac-aa0e-4b8c-9bf1-c29814325a15

📥 Commits

Reviewing files that changed from the base of the PR and between 9678f60 and bfd0829.

📒 Files selected for processing (65)
  • dependency-cruiser.config.mjs
  • packages/1-framework/3-tooling/cli/src/commands/db-init.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-sign.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-update.ts
  • packages/1-framework/3-tooling/cli/src/commands/migrate.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-log.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-show.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/commands/ref.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/caught-errors.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-at-errors.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-snapshot-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-aggregate-loader.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-seed-phase.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-run.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-verify.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/graph-queries.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/invariants.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-status-overlay.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/plan-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-advancement.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/refs.ts
  • packages/1-framework/3-tooling/cli/src/exports/control-api.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-snapshot-consistency.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-list.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-command.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-renderer.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref-error-mapping.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status-overlay.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/read-commands-json-golden.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/ref.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/aggregate-loader-preflight.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/build-read-aggregate.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/caught-errors.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-snapshot-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-aggregate-loader.ac15.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-seed-phase.mongo.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-seed-phase.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/graph-queries.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/invariants.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/map-integrity-violations.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migrate-show-plan.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migration-graph-entries.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/plan-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/refs.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
💤 Files with no reviewable changes (2)
  • packages/1-framework/3-tooling/cli/test/utils/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/vitest.config.ts
🚧 Files skipped from review as they are similar to previous changes (60)
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-at-errors.ts
  • packages/1-framework/3-tooling/cli/test/control-api/build-read-aggregate.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/plan-resolution.ts
  • packages/1-framework/3-tooling/cli/test/control-api/aggregate-loader-preflight.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-seed-phase.mongo.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref-error-mapping.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-aggregate-loader.ac15.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-aggregate-loader.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/caught-errors.ts
  • packages/1-framework/3-tooling/cli/test/control-api/caught-errors.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-snapshot-consistency.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-run.ts
  • packages/1-framework/3-tooling/cli/test/control-api/graph-queries.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/refs.ts
  • packages/1-framework/3-tooling/cli/test/control-api/map-integrity-violations.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migration-graph-entries.test.ts
  • dependency-cruiser.config.mjs
  • packages/1-framework/3-tooling/cli/src/commands/db-sign.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-graph.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-renderer.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-space-seed-phase.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-list.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/plan-resolution.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-status-overlay.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-verify.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/ref.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-list.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-status-overlay.test.ts
  • packages/1-framework/3-tooling/cli/src/exports/control-api.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migrate-show-plan.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/invariants.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-snapshot-resolution.test.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-graph.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-list.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-init.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/invariants.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space.test.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-log.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-resolution.test.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-status.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-update.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/graph-queries.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-command.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts
  • packages/1-framework/3-tooling/cli/test/control-api/refs.test.ts
  • packages/1-framework/3-tooling/cli/src/commands/migrate.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-seed-phase.ts
  • packages/1-framework/3-tooling/cli/test/commands/read-commands-json-golden.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-advancement.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-snapshot-resolution.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-check.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-check.ts

wmadden-electric added a commit that referenced this pull request Aug 7, 2026
…d-contract boundary

resolveContractRefToSnapshot rethrew emitted-contract readFile, JSON.parse,
and shape failures (a JSON null crashed on property access), bypassing the
Result<_, CliStructuredError> contract. Existing registry codes only: an
ENOENT read maps to CLI.FILE_NOT_FOUND naming contractPathAbsolute (the
migration-plan precedent); other read failures map to CLI.UNEXPECTED; parse
failures and non-object values map to MIGRATION.CONTRACT_DESERIALIZATION_FAILED
with the path and underlying message (errorContractDeserializationFailed is
now exported from @internal/migration-tools/errors). The options type is now
a discriminated union so fallbackToEmitted: false requires missingBundleFlag
at compile time. Tests cover ENOENT, invalid JSON, JSON null, and the
type-level requirement; the two error-reference entries gain the new
producing sites.

Addresses two review threads on PR #29911.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric added a commit that referenced this pull request Aug 7, 2026
executeMigrationPlanCommand's prologue (config load, context resolution,
from/to resolution, seed phase) ran before the planner-phase try block, so
a throw there escaped the Result contract. The exported function is now a
thin wrapper whose catch maps CliStructuredError, MigrationToolsError, and
unknown errors exactly like the existing planner-phase catch; tests cover a
MigrationToolsError and an unknown prologue throw.

Also replaces the file's bare as casts: castAs for the conflicts upcast and
the JSON.parse-to-unknown conversions, and a property-presence isEnoent
guard instead of casting to read error.code.

Addresses two review threads on PR #29911.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 7 commits August 7, 2026 17:13
Relocate the tests for the utils modules moving under
src/control-api/operations/ into test/control-api/, repath policy-core
imports in the command tests, and add direct tests for the new seam
operations (ref-resolution, graph-queries, invariants, caught-errors,
contract-snapshot-resolution, refs, migration-graph entries,
migrate --show plan core, ref-advancement wrappers). Red until the
operations land.

Refs: TML-3173

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Move the shared policy modules (plan-resolution, ref-advancement,
contract-space aggregate loader, seed phase, contract-at error mapping,
status overlay) and the migration-check/list/new/plan/ref/migrate-show
cores into src/control-api/operations/, add the client-free seam
operations (ref-resolution, graph-queries, invariants, caught-errors,
contract-snapshot-resolution, refs, migration-graph entries), and
reroute every command module so no file under src/commands/ imports
@internal/migration-tools at runtime. Export the new surface from
src/exports/control-api.ts and enforce the boundary with a
dependency-cruiser rule (tsPreCompilationDeps: "specify" labels pure
type-only edges).

Refs: TML-3173

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Assert ok/value on the Result class instead of literal object equality,
pin the CLI.UNEXPECTED envelope shape for the missing-bundle refusal,
and drive the readMigrationRefs rethrow case through a real ENOTDIR
failure instead of module mocking (which the shared module registry
ignores in full-suite runs).

Refs: TML-3173

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The loader now lives under src/control-api/operations/, which the
existing src/control-api/** coverage exclusion already covers.

Refs: TML-3173

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…d-contract boundary

resolveContractRefToSnapshot rethrew emitted-contract readFile, JSON.parse,
and shape failures (a JSON null crashed on property access), bypassing the
Result<_, CliStructuredError> contract. Existing registry codes only: an
ENOENT read maps to CLI.FILE_NOT_FOUND naming contractPathAbsolute (the
migration-plan precedent); other read failures map to CLI.UNEXPECTED; parse
failures and non-object values map to MIGRATION.CONTRACT_DESERIALIZATION_FAILED
with the path and underlying message (errorContractDeserializationFailed is
now exported from @internal/migration-tools/errors). The options type is now
a discriminated union so fallbackToEmitted: false requires missingBundleFlag
at compile time. Tests cover ENOENT, invalid JSON, JSON null, and the
type-level requirement; the two error-reference entries gain the new
producing sites.

Addresses two review threads on PR #29911.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
executeMigrationPlanCommand's prologue (config load, context resolution,
from/to resolution, seed phase) ran before the planner-phase try block, so
a throw there escaped the Result contract. The exported function is now a
thin wrapper whose catch maps CliStructuredError, MigrationToolsError, and
unknown errors exactly like the existing planner-phase catch; tests cover a
MigrationToolsError and an unknown prologue throw.

Also replaces the file's bare as casts: castAs for the conflicts upcast and
the JSON.parse-to-unknown conversions, and a property-presence isEnoent
guard instead of casting to read error.code.

Addresses two review threads on PR #29911.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ypes

The rebase onto main (PR #29919 merged) left three sites still using the
deleted mapMigrationToolsError: the emitted-contract deserialization
mappings in contract-snapshot-resolution and the migration-plan prologue
guard's MigrationToolsError branch (now dead — CliStructuredError.is
matches the subclass). All are direct passthrough now, and envelope
assertions read the top-level code instead of the old meta-smuggled one.

This also upgrades the earlier review fix at the emitted-contract
boundary to the original review intent: main now supports cause, so the
ENOENT, unexpected-read, and JSON-parse failure sites attach the
underlying error as cause (MigrationToolsError and
errorContractDeserializationFailed gain an optional cause for this); the
path stays in the message. The shape-failure site has no underlying
throwable and carries none.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/1-framework/3-tooling/cli/src/control-api/operations/caught-errors.ts (1)

7-7: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the redundant behavior comment.

The function name, return type, and branches express this behavior. Keep a comment only if it documents a constraint that the code cannot express.

As per coding guidelines, “Avoid comments when possible; prefer code that expresses its intent.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/caught-errors.ts`
at line 7, Remove the redundant behavior comment above the function in
caught-errors.ts; keep the function name, return type, and existing branches
unchanged.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@packages/1-framework/3-tooling/cli/src/control-api/operations/caught-errors.ts`:
- Line 7: Remove the redundant behavior comment above the function in
caught-errors.ts; keep the function name, return type, and existing branches
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: d53b6229-d36c-4dbe-ac4c-27e3e452f48f

📥 Commits

Reviewing files that changed from the base of the PR and between a393858 and d2d4b85.

📒 Files selected for processing (34)
  • docs/reference/error-reference.md
  • packages/1-framework/3-tooling/cli/src/commands/db-init.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-update.ts
  • packages/1-framework/3-tooling/cli/src/commands/migrate.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/caught-errors.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-at-errors.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-snapshot-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-aggregate-loader.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-run.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/invariants.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/plan-resolution.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-advancement.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/refs.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-list.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-command.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref-error-mapping.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/ref.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/aggregate-loader-preflight.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/caught-errors.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-snapshot-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/invariants.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migration-plan-prologue.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/plan-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/refs.test.ts
  • packages/1-framework/3-tooling/migration/src/errors.ts
🚧 Files skipped from review as they are similar to previous changes (30)
  • packages/1-framework/3-tooling/cli/test/control-api/aggregate-loader-preflight.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/plan-resolution.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-ref-error-mapping.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-list.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-at-errors.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-plan-command.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/refs.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/db-run.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/refs.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-show.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/plan-resolution.ts
  • packages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/caught-errors.test.ts
  • docs/reference/error-reference.md
  • packages/1-framework/3-tooling/cli/src/control-api/operations/invariants.ts
  • packages/1-framework/3-tooling/cli/test/control-api/ref-advancement.test.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-init.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-new.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-snapshot-resolution.ts
  • packages/1-framework/3-tooling/cli/test/control-api/invariants.test.ts
  • packages/1-framework/3-tooling/cli/src/commands/migrate.ts
  • packages/1-framework/3-tooling/cli/test/control-api/migration-plan-prologue.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-space-aggregate-loader.ts
  • packages/1-framework/3-tooling/cli/src/commands/db-update.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate-show.ts
  • packages/1-framework/3-tooling/cli/test/commands/ref.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/ref-advancement.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/migrate.ts

Merged via the queue into main with commit d0c8333 Aug 7, 2026
17 checks passed
@wmadden-electric
wmadden-electric deleted the tml-3173-cli-control-client-seam branch August 7, 2026 15:34
Thegreatsura pushed a commit to Thegreatsura/prisma that referenced this pull request Aug 8, 2026
…r on results (prisma#29925)

Extracts the durable decisions from the consolidate-clis (TML-3172)
Drive project into a repo ADR, so the project's working artifacts
(decision-record branch, PR prisma#29917) can be discarded rather than merged.

Records: errors structured at origin with no catch-all codes;
`envelope.code` as the only machine-branching surface (explicit-code
`errorRuntime`, no `meta.code`); the shared `Result` shape with the
single `ok` discriminator; and the `MigrationToolsError` collapse into
`CliStructuredError`. All already implemented on main via prisma#29919 and
prisma#29911; composer's siblings are its ADR-0043/0044 (merged in
prisma/composer#205).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Documentation**
* Added an architecture decision record documenting standardized
structured errors and explicit, machine-readable error codes.
* Clarified consistent operation result handling through a single
success/failure indicator.
* Documented unified error hierarchies, preserved error causes, direct
error propagation, and guidance for maintaining error references.
* Updated the architecture decision record index to include the new
guidance.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants