Repository navigation
TML-2801: bring the six migration read commands into consistency - #726
Conversation
Make migration log emit { ok: true, entries: [...] } (including the empty
case) via an exported MigrationLogResult type, replacing the bare-array
output. Lift migration graph's inline --json envelope into an exported
MigrationGraphJsonResult type (wire shape unchanged). Update affected
JSON tests to the new log shape.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ssing-DB precondition (D2) Route migration check ref-resolution failures through the shared mapRefResolutionError factory (same envelope as show/status), preserving check's PRECONDITION exit semantics. Extract a single requireLiveDatabase precondition helper (connection + driver) emitting one PN-CLI-4005 envelope with meta.missingFlags, called by both migration log and migration status; status keeps its offline --from path. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Extract looksLikePath / resolveAppTargetPath / findPackageByDirPath from migration-show into src/utils/migration-path-target.ts and import them in both show and check. Give check filesystem-path support: when its positional looks like a path it resolves via the shared helper, otherwise it falls back to parseMigrationRef (D2 error routing) as before; no-arg whole-graph mode and exit codes are unchanged. Align both positional argument help strings to the identical accepted forms (directory name, hash/prefix, ref, or path). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
status hardcoded resolveGlyphMode(false) at both the legend and tree render sites, so it could never produce ASCII output; thread options.ascii === true into both. log table now takes a glyphMode and swaps box-drawing divider/arrow/empty-source glyphs for ASCII when set. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ffline/live phrasing (D5) check now links migration show in its see-also so the read-verb cross-reference graph is symmetric. show and status gain --json examples (every JSON-emitting read verb now demonstrates --json). Offline verbs (list/graph/show/check) state "Offline — does not consult the database." in one unbroken sentence; live verbs (status/log) state "Requires a database connection."; log also notes it merges all spaces. A focused help-text test locks these edits. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: wmadden-electric <[email protected]>
…ce to narrow) (D6) Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: wmadden-electric <[email protected]>
…ions (D7) Extends migration-read-commands-parity.test.ts with four new describe blocks that lock the conventions established by D1–D6 against regressions: - D1 lock (JSON envelope shape): verifies each of the six read verbs emits an object with an `ok` discriminator when called with `--json` rather than a bare array. Drives list, graph, status (--from), and check via the CLI shell with a vi.spyOn config mock; verifies show and log against their exported result types (type-level lock backed by per-command golden tests). - D5 lock (see-also symmetry): asserts check links migration show in its see-also, every verb references ≥2 siblings, and the see-also graph has back-links (no one-way orphan entries). - D2 lock (missing-DB error shape parity): asserts migration log and migration status both produce PN-CLI-4005 with meta.missingFlags: ['--db'] when no database is configured, confirming the shared requireLiveDatabase precondition produces identical envelopes. - D6 lock (check multi-space): confirms enumerateCheckSpaces enumerates all spaces by default (app + postgis from the fixture), --space app narrows, and --space <unknown> emits a structured CliErrorEnvelope (not a bare array). The existing pretty-rendering parity assertions are intact. Mock isolation: the new tests use vi.spyOn (not vi.mock) so they add no new mock-hoisting registrations and require only vi.restoreAllMocks() in afterEach/afterAll — no additional afterAll cleanup needed. Full-suite flake status: the pre-existing order-dependent flake in migration-list-json-golden.test.ts and client.test.ts reproduces on the base tree without these test files (verified via git stash); it is not caused by this slice's additions. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: wmadden-electric <[email protected]>
…--space (F-1) When --space <id> was passed, loadAggregateIntegrityViolations was entirely skipped, meaning hash-mismatch and other aggregate-catalogue violations were never checked for the narrowed space. Fix: always run loadAggregateIntegrityViolations, then filter to violations attributable to the narrowed space (all variants with spaceId === options.space, excluding disjointness which is inherently cross-space with no single spaceId). The no-arg path keeps the unfiltered aggregate pass. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: wmadden-electric <[email protected]>
…pec/plan, review notes Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: wmadden-electric <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughThis PR refactors the ChangesCLI Commands & Features
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
🧹 Nitpick comments (4)
packages/1-framework/3-tooling/cli/test/commands/migration-status-missing-db.test.ts (1)
6-12: ⚡ Quick winPrefer
vi.spyOnon a directconfig-loaderimport instead of module-levelvi.mock.This mock/unmock pattern introduces cross-test lifecycle coupling; a direct import with
vi.spyOnkeeps the setup local and avoids worker-leak cleanup code.Refactor sketch
+import * as configLoader from '../../src/config-loader'; import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; ... -const mocks = vi.hoisted(() => ({ - loadConfig: vi.fn(), -})); - -vi.mock('../../src/config-loader', () => ({ - loadConfig: mocks.loadConfig, -})); ... beforeEach(() => { - vi.resetModules(); + vi.spyOn(configLoader, 'loadConfig'); const commandMocks = setupCommandMocks(); consoleOutput = commandMocks.consoleOutput; cleanup = commandMocks.cleanup; }); ... - afterAll(() => { - // Repo-wide vitest runs with `isolate: false`, so the `vi.mock` leaks - // into the next file in the same worker; unmock to restore it. - vi.doUnmock('../../src/config-loader'); - vi.resetModules(); - }); ... - mocks.loadConfig.mockResolvedValue({ ...baseConfig, db: {} }); + vi.mocked(configLoader.loadConfig).mockResolvedValue({ ...baseConfig, db: {} }); ... - mocks.loadConfig.mockResolvedValue({ ...baseConfig, driver: undefined }); + vi.mocked(configLoader.loadConfig).mockResolvedValue({ ...baseConfig, driver: undefined });As per coding guidelines:
**/*.{test,spec}.{ts,tsx,js,jsx}: Prefer direct imports over module mocks in test files.Also applies to: 59-63
🤖 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/test/commands/migration-status-missing-db.test.ts` around lines 6 - 12, Replace the module-level vi.mock of '../../src/config-loader' with a direct import of the actual module and use vi.spyOn to stub the loadConfig export; locate the current mocks.loadConfig usage and remove the hoisted mocks object and vi.mock call, import { loadConfig } from '../../src/config-loader' instead, and replace references to mocks.loadConfig with a vi.spyOn(loadConfigModule, 'loadConfig').mockImplementation(...) (or mockResolvedValue) in the test setup so the stub is local to the test and avoids cross-test lifecycle coupling.packages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.ts (2)
468-511: ⚡ Quick winRemove newly added section/explanatory comments and rely on test names.
These comments are avoidable here since the surrounding
describe/itblocks already express intent.As per coding guidelines "Don't add comments if avoidable, prefer code that expresses its intent."
Also applies to: 588-590, 637-640, 706-708, 722-724, 781-783
🤖 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/test/commands/migration-read-commands-parity.test.ts` around lines 468 - 511, Remove the newly added explanatory comment blocks that sit above the test sections (the multi-line header comments like the one immediately above the "D1 lock" tests) and rely on the surrounding describe/it titles to convey intent; locate the block using nearby symbols such as makeOfflineConfig and runAndCaptureExit and delete that comment section, and do the same for the other similar comment blocks called out in the review (the additional explanatory headers near other consistency-lock/read tests) so only test code and descriptive test names remain.
474-496: ⚡ Quick winAvoid whole-object
as unknown as LoadedConfigcasts in test fixtures.These double-casts can hide config-shape drift; use typed literals (
const cfg: LoadedConfig = …) so fixture mismatches fail at compile time.As per coding guidelines "Minimize type casts: prefer explicit types that make casts unnecessary… never cast a whole object/class when casting one property would suffice."
Also applies to: 732-746
🤖 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/test/commands/migration-read-commands-parity.test.ts` around lines 474 - 496, The test fixture uses a broad "as unknown as LoadedConfig" cast in makeOfflineConfig which hides shape mismatches; change it to construct a properly typed value (e.g., declare const cfg: LoadedConfig = { ... } and return cfg) or, if only a specific property is unrepresentable, cast that single property only (e.g., mock returns typed as needed) instead of the whole object; apply the same change to the other fixture instance noted (the similar block around the later test). Ensure you keep the existing mocks (vi.fn()) but surface any compile-time type errors by using the explicit LoadedConfig type on the returned object rather than the double-cast.packages/1-framework/3-tooling/cli/test/commands/migration-graph.test.ts (1)
22-28: ⚡ Quick winPrefer direct import stubbing over module-level
vi.mockin this test.Please switch this setup to a direct import +
vi.spyOn(...)stubbing pattern instead of hoisted module mocking, to keep test wiring closer to runtime behavior and align with repo test conventions.As per coding guidelines, `**/*.{test,spec}.{ts,tsx,js,jsx}`: Prefer direct imports over module mocks in test files.Suggested refactor
-import { afterAll, afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import * as configLoader from '../../src/config-loader'; ... -const graphMocks = vi.hoisted(() => ({ - loadConfig: vi.fn(), -})); - -vi.mock('../../src/config-loader', () => ({ - loadConfig: graphMocks.loadConfig, -})); +const loadConfigSpy = vi.spyOn(configLoader, 'loadConfig'); ... - graphMocks.loadConfig.mockResolvedValue(graphBaseConfig(contractPath)); + loadConfigSpy.mockResolvedValue(graphBaseConfig(contractPath)); return contractPath; } ... - afterAll(() => { - vi.doUnmock('../../src/config-loader'); - }); - afterEach(async () => { ... - vi.clearAllMocks(); + vi.restoreAllMocks(); });🤖 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/test/commands/migration-graph.test.ts` around lines 22 - 28, Replace the hoisted module mock with a direct import and spy: remove graphMocks and vi.mock('../../src/config-loader', ...) and instead import { loadConfig } from '../../src/config-loader' at top of the test file, then use vi.spyOn(module, 'loadConfig').mockImplementation(...) (or mockResolvedValue/mockReturnValue as appropriate) to stub behavior; ensure any cleanup uses vi.restoreAllMocks() or spy.mockRestore() so tests don't leak.
🤖 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/test/commands/migration-graph.test.ts`:
- Around line 22-28: Replace the hoisted module mock with a direct import and
spy: remove graphMocks and vi.mock('../../src/config-loader', ...) and instead
import { loadConfig } from '../../src/config-loader' at top of the test file,
then use vi.spyOn(module, 'loadConfig').mockImplementation(...) (or
mockResolvedValue/mockReturnValue as appropriate) to stub behavior; ensure any
cleanup uses vi.restoreAllMocks() or spy.mockRestore() so tests don't leak.
In
`@packages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.ts`:
- Around line 468-511: Remove the newly added explanatory comment blocks that
sit above the test sections (the multi-line header comments like the one
immediately above the "D1 lock" tests) and rely on the surrounding describe/it
titles to convey intent; locate the block using nearby symbols such as
makeOfflineConfig and runAndCaptureExit and delete that comment section, and do
the same for the other similar comment blocks called out in the review (the
additional explanatory headers near other consistency-lock/read tests) so only
test code and descriptive test names remain.
- Around line 474-496: The test fixture uses a broad "as unknown as
LoadedConfig" cast in makeOfflineConfig which hides shape mismatches; change it
to construct a properly typed value (e.g., declare const cfg: LoadedConfig = {
... } and return cfg) or, if only a specific property is unrepresentable, cast
that single property only (e.g., mock returns typed as needed) instead of the
whole object; apply the same change to the other fixture instance noted (the
similar block around the later test). Ensure you keep the existing mocks
(vi.fn()) but surface any compile-time type errors by using the explicit
LoadedConfig type on the returned object rather than the double-cast.
In
`@packages/1-framework/3-tooling/cli/test/commands/migration-status-missing-db.test.ts`:
- Around line 6-12: Replace the module-level vi.mock of
'../../src/config-loader' with a direct import of the actual module and use
vi.spyOn to stub the loadConfig export; locate the current mocks.loadConfig
usage and remove the hoisted mocks object and vi.mock call, import { loadConfig
} from '../../src/config-loader' instead, and replace references to
mocks.loadConfig with a vi.spyOn(loadConfigModule,
'loadConfig').mockImplementation(...) (or mockResolvedValue) in the test setup
so the stub is local to the test and avoids cross-test lifecycle coupling.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 83d23237-043d-4e0d-a5d5-b6eca1fc094d
⛔ Files ignored due to path filters (5)
projects/migration-graph-rendering/read-command-consistency-audit.mdis excluded by!projects/**projects/migration-graph-rendering/read-command-consistency-followups.mdis excluded by!projects/**projects/migration-graph-rendering/slices/read-command-consistency/code-review.mdis excluded by!projects/**projects/migration-graph-rendering/slices/read-command-consistency/plan.mdis excluded by!projects/**projects/migration-graph-rendering/slices/read-command-consistency/spec.mdis excluded by!projects/**
📒 Files selected for processing (23)
packages/1-framework/1-core/errors/src/control.tspackages/1-framework/3-tooling/cli/src/commands/migration-check.tspackages/1-framework/3-tooling/cli/src/commands/migration-graph.tspackages/1-framework/3-tooling/cli/src/commands/migration-log.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/utils/cli-errors.tspackages/1-framework/3-tooling/cli/src/utils/formatters/migration-log-table.tspackages/1-framework/3-tooling/cli/src/utils/migration-path-target.tspackages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space-command.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-check-multi-space.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-check-path-target.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-check-ref-error.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-graph.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-legend-commands.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-log.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-read-commands-parity.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-read-help-text.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-show.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-status-missing-db.test.tspackages/1-framework/3-tooling/cli/test/commands/read-commands-json-golden.test.tspackages/1-framework/3-tooling/cli/test/utils/formatters/migration-log-table.test.tspackages/1-framework/3-tooling/cli/test/utils/require-live-database.test.ts
…or self-contained mock migration-status-missing-db.test.ts was not self-contained: it used a static import of createMigrationStatusCommand at the top of the file. With isolate:false, if migration-status.ts was already loaded by a prior file (without the config-loader mock active), vi.mock hoisting could not re-patch the already-bound loadConfig reference. In CI's file ordering (migration-read-help-text.test.ts precedes it and loads migration-status without any mock), loadConfig ran for real, found no config file, and threw errorConfigFileNotFound before reaching the requireLiveDatabase precondition the tests assert. Fix: remove the static import; use dynamic import inside each test body (after vi.resetModules() in beforeEach). This ensures each test gets a fresh module load where vi.mock intercepts config-loader correctly. The pattern mirrors cross-consumer-integrity.test.ts and the other well-behaved cli test files. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…olate:false cleanup) Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…rran-0fe9fd Signed-off-by: Will Madden <[email protected]> # Conflicts: # packages/1-framework/3-tooling/cli/src/utils/cli-errors.ts
98be567 to
cb8f073
Compare
Brings the
migrationread-verb family —status,list,graph,log,show,check— into line on the axes a prior audit flagged (projects/migration-graph-rendering/read-command-consistency-audit.md, findings F1–F7): JSON envelope shape, error path, params, decoration flags, help text, and multi-space behaviour. Most of it is wiring existing shared primitives into the commands that had drifted; one piece (multi-spacecheck) is a real behaviour change. An extended parity test locks the conventions so they can't re-drift.Changes
--jsonenvelopes (F3):migration logemitted a bare array andmigration graphbuilt its JSON inline; both now emit a{ ok, … }object with a co-located exported type (MigrationLogResult→{ ok, entries }incl. the empty case;MigrationGraphJsonResult). The other four already conformed.migration check's inline ref-resolution error strings now route through the sharedmapRefResolutionError(matchingshow/status), preserving itsPRECONDITIONexit. A newrequireLiveDatabasehelper (cli-errors.ts) giveslogandstatusone identical missing-DB envelope withmeta.missingFlags.show's path-resolution helpers move tomigration-path-target.tsand are now shared withcheck, somigration check <path>resolves a migration directory likeshowdoes; both positional help strings describe the same forms.--asciiwhere glyphs are drawn (F4):status(which hardcoded unicode) andlog's table now honour--ascii, matchinglist/graph.show/checkdraw no laned-tree glyphs and are unchanged.check's see-also now linksmigration show; every JSON-emitting verb has a--jsonexample; offline/live phrasing is uniform across the family.migration checkis multi-space (F1, the spine): the holistic check validated only the app space; it now validates every contract space by default, with--space <id>to narrow — reusing the sameaggregate.spaces()enumeration andisValidSpaceId/errorInvalidSpaceId/errorSpaceNotFoundmachinerylistuses.--spacealso runs the aggregate integrity pass filtered to that space, so narrowing never weakens validation. Single-target mode stays app-only (noted as a follow-up); exit codes and result shape are unchanged.migration-read-commands-parity.test.ts(previously rendering-only) now asserts the{ ok, … }envelope, see-also symmetry, the shared missing-DB error shape, andcheck's multi-space behaviour across all six verbs.Why
The read-command redesign shipped
list/graph/status/logas separate verbs incrementally, so consistency drifted: the same conceptual input (name a migration, name a contract space, hit a missing DB) was handled differently per command. Routing each command through the primitives that already existed — rather than inventing per-command behaviour — is both the fix and the guard against recurrence, which is why the parity test is part of the slice rather than a follow-up. The one genuine behaviour change, multi-spacecheck, also closes a latent gap: integrity problems in non-app spaces previously passed silently.checkkeeps its command-specific exit codes (OK/PRECONDITION/INTEGRITY_FAILED) — that's Style-Guide-sanctioned for a verify verb and intentionally left as-is.Out of scope:
migrateand the authoring verbs; the control-api ↔ CLI surface reconciliation (TML-2780);ref list; whethershow/checkshould accept the contract-reference grammar; real--spaceonshow(rejected — it resolves a single pinned migration).Note for CI: the
@prisma-next/clipackage runs vitest withisolate: false, and there's a pre-existing order-dependent flake intest/control-api/client.test.ts(and occasionallymigration-list-json-golden.test.ts) from config-loader mock bleed across files. It reproduces on the base tree with this branch's test files stashed, so it is not introduced here; the package typecheck,lint:deps, and targeted suites are clean, and the full suite passes on the large majority of runs.Closes TML-2801.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Refactor