Repository navigation
feat(cli): add graph renderer for migration status - #258
Conversation
|
Important Review skippedToo many files! This PR contains 238 files, which is 88 over the limit of 150. ⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (238)
You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughAdds graph rendering and mapping modules, integrates dagre for layout, refactors migration-status to compute per-edge statuses and render optional terminal graphs, introduces prefix-based migration bundle resolution, and adds extensive unit and integration tests for graph rendering and status diagnostics. Changes
Sequence Diagram(s)sequenceDiagram
participant CLI as CLI
participant FS as File/Bundle Reader
participant Graph as Migration Graph Service
participant Deriver as deriveEdgeStatuses
participant Mapper as migrationGraphToRenderInput
participant Layout as dagre (layout)
participant Renderer as graphRenderer.render
CLI->>FS: load refs, bundles, manifests
CLI->>Graph: load migration graph, marker, contractHash
CLI->>Deriver: deriveEdgeStatuses(graph, target, contract, marker, mode)
Deriver-->>CLI: EdgeStatus[] (applied/pending/unreachable)
CLI->>Mapper: map graph + EdgeStatus[] + refs + mode
Mapper->>Layout: request node/edge layout
Layout-->>Mapper: positioned polylines
Mapper->>Renderer: render positioned graph with colors/labels/truncation
Renderer-->>CLI: rendered terminal string
CLI->>User: display output / JSON (omit internal fields in JSON)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 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/runtime-executor
@prisma-next/sql-runtime
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/contract-authoring
@prisma-next/contract-ts
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/cli
@prisma-next/emitter
@prisma-next/eslint-plugin
@prisma-next/migration-tools
@prisma-next/vite-plugin-contract-emit
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/family-sql
@prisma-next/sql-kysely-lane
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-lane-sql-builder-new
@prisma-next/sql-lane
@prisma-next/target-postgres
@prisma-next/adapter-postgres
@prisma-next/driver-postgres
@prisma-next/core-control-plane
@prisma-next/core-execution-plane
@prisma-next/config
@prisma-next/contract
@prisma-next/operations
@prisma-next/plan
@prisma-next/utils
commit: |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (4)
test/integration/test/cli-journeys/migration-status-diagnostics.e2e.test.ts (1)
1-607: Consider splitting if this file grows further.At ~608 lines, this file is slightly above the 500-line guideline. Given the comprehensive end-to-end nature covering 13 distinct diagnostic scenarios, it's acceptable as-is. However, if additional scenarios are added, consider splitting by category (offline/online/divergent).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/cli-journeys/migration-status-diagnostics.e2e.test.ts` around lines 1 - 607, The test file describe('migration status diagnostics') is long (~608 lines) and should be split if it grows further: extract grouped describes into separate test files (e.g., offline scenarios, online scenarios, divergent graph scenarios) while keeping shared helpers (setupJourney, runMigrationStatus, runContractEmit, runMigrationPlan, runMigrationApply, runDbUpdate, swapContract, useDevDatabase, timeouts) imported from ../utils/journey-test-helpers; preserve the top-level withTempDir wrapper or replicate it in each new file to create temp dirs, and move related it(...) blocks (like the offline "no migrations..." tests, the online "fresh DB..." through "JSON output shape" tests, and the divergent/ref tests) into their own files so each file stays under ~500 lines and test semantics remain identical.packages/1-framework/3-tooling/cli/src/commands/migration-status.ts (1)
785-815: Minor inconsistency:formatStatusSummaryusesresult.migrationsstatus but counts could differ fromedgeStatuses.
buildMigrationEntriescomputes status via chain traversal, whilederiveEdgeStatusesuses path analysis. For complex graphs (diamonds, forks), these could produce different counts.Consider using
edgeStatusesfor consistency ifmode === 'online':💡 Suggested fix for consistent status counts
function formatStatusSummary(result: MigrationStatusResult, colorize: boolean): string { const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s); const lines: string[] = []; - const hasUnknown = result.migrations.some((e) => e.status === 'unknown'); - const pendingCount = result.migrations.filter((e) => e.status === 'pending').length; + const hasUnknown = result.mode === 'offline' || result.migrations.some((e) => e.status === 'unknown'); + const pendingCount = result.edgeStatuses?.filter((e) => e.status === 'pending').length ?? 0;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts` around lines 785 - 815, formatStatusSummary currently computes hasUnknown and pendingCount from result.migrations which can differ from the edge-level statuses produced by deriveEdgeStatuses/buildMigrationEntries for complex graphs; update formatStatusSummary to use result.edgeStatuses (or deriveEdgeStatuses result) when result.mode === 'online' to compute hasUnknown/pendingCount so the summary reflects edge-level status counts consistently, and guard for missing edgeStatuses by falling back to result.migrations if needed (referencing formatStatusSummary, result.migrations, result.edgeStatuses, deriveEdgeStatuses, buildMigrationEntries).packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts (1)
192-197: Fallback path uses last forward chain edge — verify this is always valid.When no relevant paths are found, the code falls back to the tip of the forward chain. If
forwardChainis empty,lastEdgeisundefinedandfallbackHashbecomesEMPTY_CONTRACT_HASH, which may result in a single-node path.This is acceptable as a defensive fallback, but consider adding a comment explaining this edge case.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts` around lines 192 - 197, The fallback branch handling relevantPaths === 0 currently takes the lastEdge from graph.forwardChain and uses EMPTY_CONTRACT_HASH when forwardChain is empty, which can produce a single-node path; update the block around relevantPaths, graph.forwardChain, lastEdge, fallbackHash and addPathFromRoot to include a concise comment explaining that when forwardChain is empty we intentionally fall back to EMPTY_CONTRACT_HASH resulting in a single-node path as a defensive default, and ensure the comment documents why that behavior is acceptable and when it will occur.packages/1-framework/3-tooling/cli/src/utils/formatters/graph-render.ts (1)
792-824: Exponential variant enumeration is O(2^N) — acceptable for typical graphs.The
selectBestVariantfunction enumerates all 2^N combinations of bend directions. For typical migration graphs where dagre produces mostly orthogonal layouts, N (diagonal count) is usually 0-3, making this fine in practice.Consider adding a guard if concerned about adversarial inputs:
💡 Optional safeguard for large diagonal counts
+ // Cap variant enumeration to avoid exponential blowup on pathological inputs + const MAX_DIAGONALS = 10; + if (diagCount > MAX_DIAGONALS) { + // Fall back to horizontal-first for all diagonals + const poly = buildVariant(rawPoints, bitsToBends(0, diagCount)); + const labelPos = label ? findLabelPlacement(poly, label, grid, src.y) : undefined; + return { poly, labelPos }; + } + const numVariants = 1 << diagCount;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/utils/formatters/graph-render.ts` around lines 792 - 824, selectBestVariant currently enumerates 2^diagCount combinations via bitsToBends/buildVariant which can blow up for large or adversarial diagCount; add a protective guard in selectBestVariant to cap work: if diagCount exceeds a safe threshold (e.g., 10) then fall back to a deterministic or greedy strategy (for example use bitsToBends(0) and a few random/heuristic variants) or limit numVariants to a maximum and sample variants instead of full enumeration; reference selectBestVariant, diagCount, bitsToBends, buildVariant, countCorners, polyLength, and findLabelPlacement when implementing the guard so the early-return or sampling uses the same scoring logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/1-framework/3-tooling/cli/test/commands/migration-plan.test.ts`:
- Around line 338-387: The test currently only verifies there are two matching
candidates (candidates / prefix) but doesn't exercise the resolver or assert the
promised failure; replace or extend the test to call the actual resolver used
for `--from` resolution (the code that consumes readMigrationsDir results) with
the prefix 'sha256:abc' and assert it rejects/throws the ambiguity error (i.e.,
the ambiguous-prefix error path) instead of just checking candidates length;
locate the resolution logic that handles `--from` (the function invoked by the
migration plan command that resolves a migration by prefix) and make the test
assert that calling it with the packages and prefix results in the expected
thrown/rejected error.
- Around line 275-337: The "without sha256: scheme" test is tautological because
it used a needle that already contained "sha256:"; change it to use a plain
prefix (e.g. const prefix = 'abcdef') and then locate the migration by matching
the manifest.to with the scheme added (e.g. find package where
p.manifest.to.startsWith(`sha256:${prefix}`)), keeping the manifest.to assertion
and toContract equality; update the test named it('matches by prefix without
sha256: scheme', ...) to use that plain prefix and the adjusted find predicate
so the test verifies resolver behavior rather than mirroring the fixture.
---
Nitpick comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migration-status.ts`:
- Around line 785-815: formatStatusSummary currently computes hasUnknown and
pendingCount from result.migrations which can differ from the edge-level
statuses produced by deriveEdgeStatuses/buildMigrationEntries for complex
graphs; update formatStatusSummary to use result.edgeStatuses (or
deriveEdgeStatuses result) when result.mode === 'online' to compute
hasUnknown/pendingCount so the summary reflects edge-level status counts
consistently, and guard for missing edgeStatuses by falling back to
result.migrations if needed (referencing formatStatusSummary, result.migrations,
result.edgeStatuses, deriveEdgeStatuses, buildMigrationEntries).
In
`@packages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.ts`:
- Around line 192-197: The fallback branch handling relevantPaths === 0
currently takes the lastEdge from graph.forwardChain and uses
EMPTY_CONTRACT_HASH when forwardChain is empty, which can produce a single-node
path; update the block around relevantPaths, graph.forwardChain, lastEdge,
fallbackHash and addPathFromRoot to include a concise comment explaining that
when forwardChain is empty we intentionally fall back to EMPTY_CONTRACT_HASH
resulting in a single-node path as a defensive default, and ensure the comment
documents why that behavior is acceptable and when it will occur.
In `@packages/1-framework/3-tooling/cli/src/utils/formatters/graph-render.ts`:
- Around line 792-824: selectBestVariant currently enumerates 2^diagCount
combinations via bitsToBends/buildVariant which can blow up for large or
adversarial diagCount; add a protective guard in selectBestVariant to cap work:
if diagCount exceeds a safe threshold (e.g., 10) then fall back to a
deterministic or greedy strategy (for example use bitsToBends(0) and a few
random/heuristic variants) or limit numVariants to a maximum and sample variants
instead of full enumeration; reference selectBestVariant, diagCount,
bitsToBends, buildVariant, countCorners, polyLength, and findLabelPlacement when
implementing the guard so the early-return or sampling uses the same scoring
logic.
In `@test/integration/test/cli-journeys/migration-status-diagnostics.e2e.test.ts`:
- Around line 1-607: The test file describe('migration status diagnostics') is
long (~608 lines) and should be split if it grows further: extract grouped
describes into separate test files (e.g., offline scenarios, online scenarios,
divergent graph scenarios) while keeping shared helpers (setupJourney,
runMigrationStatus, runContractEmit, runMigrationPlan, runMigrationApply,
runDbUpdate, swapContract, useDevDatabase, timeouts) imported from
../utils/journey-test-helpers; preserve the top-level withTempDir wrapper or
replicate it in each new file to create temp dirs, and move related it(...)
blocks (like the offline "no migrations..." tests, the online "fresh DB..."
through "JSON output shape" tests, and the divergent/ref tests) into their own
files so each file stays under ~500 lines and test semantics remain identical.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: c9badc60-f015-41d1-a925-527d89d064e8
⛔ Files ignored due to path filters (5)
packages/1-framework/3-tooling/cli/test/utils/formatters/__snapshots__/graph-render.test.ts.snapis excluded by!**/*.snapprojects/graph-based-migrations/issue-triage.mdis excluded by!projects/**projects/graph-based-migrations/plans/migration-status-graph-rendering-plan.mdis excluded by!projects/**projects/graph-based-migrations/specs/migration-status-graph-rendering.spec.mdis excluded by!projects/**projects/graph-based-migrations/specs/target-resolution-design.mdis excluded by!projects/**
📒 Files selected for processing (14)
packages/1-framework/3-tooling/cli/package.jsonpackages/1-framework/3-tooling/cli/src/commands/migration-plan.tspackages/1-framework/3-tooling/cli/src/commands/migration-status.tspackages/1-framework/3-tooling/cli/src/utils/formatters/graph-migration-mapper.tspackages/1-framework/3-tooling/cli/src/utils/formatters/graph-render.tspackages/1-framework/3-tooling/cli/src/utils/formatters/graph-types.tspackages/1-framework/3-tooling/cli/src/utils/formatters/migrations.tspackages/1-framework/3-tooling/cli/src/utils/global-flags.tspackages/1-framework/3-tooling/cli/test/commands/derive-edge-statuses.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-plan.test.tspackages/1-framework/3-tooling/cli/test/commands/migration-status.test.tspackages/1-framework/3-tooling/cli/test/utils/formatters/graph-render.test.tspackages/1-framework/3-tooling/cli/test/utils/formatters/test-graphs.tstest/integration/test/cli-journeys/migration-status-diagnostics.e2e.test.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
test/integration/test/cli-journeys/divergence-and-refs.e2e.test.ts (1)
77-78: Use one object matcher for related status payload fields.These are related checks on the same object and can be consolidated for consistency with test style rules.
♻️ Suggested refactor
- expect(statusData.ok, 'L.04: ok').toBe(true); - expect(statusData.targetHash, 'L.04: target is C3 (contract hash)').toBe(c3Hash); + expect(statusData, 'L.04: status payload').toMatchObject({ + ok: true, + targetHash: c3Hash, + });As per coding guidelines, "
**/*.test.ts: Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/cli-journeys/divergence-and-refs.e2e.test.ts` around lines 77 - 78, Replace the two separate assertions on the status payload with a single object matcher: update the assertions on statusData (currently using expect(statusData.ok) and expect(statusData.targetHash)) to one expect(statusData).toMatchObject({ ok: true, targetHash: c3Hash }) so the related fields are asserted together consistent with test style; ensure you import or use toMatchObject from the test framework if needed and keep the original message context if required.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@test/integration/test/cli-journeys/divergence-and-refs.e2e.test.ts`:
- Around line 77-78: Replace the two separate assertions on the status payload
with a single object matcher: update the assertions on statusData (currently
using expect(statusData.ok) and expect(statusData.targetHash)) to one
expect(statusData).toMatchObject({ ok: true, targetHash: c3Hash }) so the
related fields are asserted together consistent with test style; ensure you
import or use toMatchObject from the test framework if needed and keep the
original message context if required.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 2fcf4b13-4c44-4113-aeca-2c9006ed33b9
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (4)
test/integration/test/cli-journeys/divergence-and-refs.e2e.test.tstest/integration/test/cli-journeys/migration-status-diagnostics.e2e.test.tstest/integration/test/cli-journeys/multi-step-migration.e2e.test.tstest/integration/test/cli-journeys/schema-evolution-migrations.e2e.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- test/integration/test/cli-journeys/migration-status-diagnostics.e2e.test.ts
There was a problem hiding this comment.
🧹 Nitpick comments (2)
packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts (2)
445-446: Avoid hardcoding the hash scheme at Line [445].
'sha256:'is duplicated here and can drift from the canonical hash format. Derive the scheme from a shared constant/helper instead.Proposed refactor
export function resolveBundleByPrefix<T extends { manifest: { to: string } }>( bundles: readonly T[], needle: string, ): Result<T, PrefixResolutionFailure> { const exact = bundles.find((p) => p.manifest.to === needle); if (exact) return ok(exact); - const prefixWithScheme = needle.startsWith('sha256:') ? needle : `sha256:${needle}`; + const hashScheme = EMPTY_CONTRACT_HASH.split(':', 1)[0]!; + const prefixWithScheme = needle.startsWith(`${hashScheme}:`) + ? needle + : `${hashScheme}:${needle}`; const candidates = bundles.filter((p) => p.manifest.to.startsWith(prefixWithScheme)); if (candidates.length === 1) return ok(candidates[0]!); if (candidates.length > 1) return notOk({ reason: 'ambiguous', count: candidates.length }); return notOk({ reason: 'not-found' }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts` around lines 445 - 446, The code hardcodes 'sha256:' when building prefixWithScheme and filtering bundles; replace the literal with the canonical shared constant or helper (e.g., HASH_SCHEME or getHashPrefix()) so the logic uses the single source of truth: import the shared constant/helper and change the check/concat around needle (the prefixWithScheme creation) and the bundles.filter predicate (manifest.to.startsWith(prefixWithScheme)) to use that constant/helper instead of the literal 'sha256:'.
428-437: Consider removing the long JSDoc for this internal helper.The name/signature already communicates intent; this comment is likely unnecessary churn in command code.
As per coding guidelines: "Don't add comments if avoidable; prefer code which expresses its intent."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts` around lines 428 - 437, Remove the long JSDoc block that begins "/** Resolve a migration bundle by exact hash or prefix match..." which documents the internal helper that resolves a migration bundle; instead delete the multi-line comment block and, if a short hint is needed, replace it with a single-line comment or rely on the function name/signature itself (the internal helper exported for testing) to convey intent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts`:
- Around line 445-446: The code hardcodes 'sha256:' when building
prefixWithScheme and filtering bundles; replace the literal with the canonical
shared constant or helper (e.g., HASH_SCHEME or getHashPrefix()) so the logic
uses the single source of truth: import the shared constant/helper and change
the check/concat around needle (the prefixWithScheme creation) and the
bundles.filter predicate (manifest.to.startsWith(prefixWithScheme)) to use that
constant/helper instead of the literal 'sha256:'.
- Around line 428-437: Remove the long JSDoc block that begins "/** Resolve a
migration bundle by exact hash or prefix match..." which documents the internal
helper that resolves a migration bundle; instead delete the multi-line comment
block and, if a short hint is needed, replace it with a single-line comment or
rely on the function name/signature itself (the internal helper exported for
testing) to convey intent.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 2e66855d-299b-4dab-8e5e-bbebd6bec652
📒 Files selected for processing (2)
packages/1-framework/3-tooling/cli/src/commands/migration-plan.tspackages/1-framework/3-tooling/cli/test/commands/migration-plan.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/1-framework/3-tooling/cli/test/commands/migration-plan.test.ts
wmadden
left a comment
There was a problem hiding this comment.
Pre-emptive approval
This is a pre-emptive approval — the architecture is sound, the test coverage is strong, and the implementation is generally clean. Please address the inline comments below or respond explaining why you'd prefer not to, then merge without waiting for re-review.
Full review artifacts are on the branch at projects/graph-based-migrations/specs/reviews/pr-258/:
system-design-review.mdcode-review.md(findings below are from this file)walkthrough.md
What looks solid
- Renderer architecture:
CharGridwith direction bitmasks → box-drawing character resolution is elegant and correct. The color-priority system and ANSI run-batching are well-implemented. - 35+ topology test fixtures: The
test-graphs.tscatalog is thorough and well-organized from simple to complex. The snapshot-based testing approach is appropriate for visual output. deriveEdgeStatusestest coverage: 14 focused tests with clear scenario descriptions (not just "should X" — they explain the user situation).- E2e journey tests: 13 realistic end-to-end scenarios covering the full diagnostic matrix. These provide strong confidence in user-visible behavior.
- Spec alignment: All checkable acceptance criteria are implemented and checked off.
- CVD-safe palette: No red/green. Icons carry meaning independent of color.
--no-coloroutput is fully functional. - Commit history: Clean, logical commits with intent-focused messages. Each commit is a coherent unit.
Finding index
| ID | Severity | Summary |
|---|---|---|
| F01 | blocking | formatStatusSummary uses result.migrations counts, diverges from edgeStatuses |
| F02 | blocking | Global-flags behavioral change is cross-cutting and underscoped |
| F03 | non-blocking | migration-plan.test.ts prefix tests are tautological |
| F04 | non-blocking | No unit tests for migrationGraphToRenderInput |
| F05 | non-blocking | MigrationStatusResult conflates internal and public shapes |
| F06 | non-blocking | Fallback path uses last forward-chain edge — fragile default |
| F07 | non-blocking | Exponential variant enumeration has no cap |
Add an ASCII graph renderer for `migration status` that visualizes the migration DAG in the terminal. Uses dagre for automatic layout, then stamps orthogonal polylines onto a CharGrid with box-drawing characters. Key features: - Default view shows relevant subgraph (union of paths to contract, DB, ref) - `--graph` flag shows the full migration graph with all branches - Applied/pending/diverged status icons (✓/⧗/✗) with CVD-safe colors - Truncation with `--limit N` (default 10) and marker-aware expansion - Detached contract node rendering when contract is ahead of migrations - Prefix matching for `migration plan --from` flag Includes project spec, plan, target resolution design doc, and issue triage. Made-with: Cursor
- Fix empty DB (no marker) showing no status icons: treat root as effective marker so all edges to target are marked pending - Fix marker-in-graph check: use graph.nodes.has() instead of checking the display chain, so DB on a different branch is recognized - Fix relevant path computation: prefer ref→contract and marker→contract routes over independent BFS root→contract which may pick wrong branch - Fix edge status derivation: also mark target→contract edges as pending when contract is reachable from the ref target - Fix detached contract node alignment: align with bottom-most node instead of spine target - Fix contract diagnostic: fire in diverged early-return path and when a ref is active, consolidate to fewer locations - Bold node hashes for nodes with markers regardless of spine membership - Legend always shows all statuses, rendered right after graph - Improve diagnostic wording: "No migration exists for the current contract", "No path between database marker and ref", "multiple valid migration paths" Made-with: Cursor
Bring spec and plan up to date with all implemented changes: - Single renderer architecture (no registry, no --renderer flag) - Three-state edge status (applied/pending/diverged via deriveEdgeStatuses) - Continuity-aware relevant path computation - Detached node alignment, legend, diagnostics - All deleted files documented Delete render-fixture.ts — fixture testing is done through the CLI directly with switched migration dirs. Made-with: Cursor
- Add dagreOptions to GraphRenderOptions for caller-controlled layout - Default ranksep: 4 (branching), caller passes ranksep: 1 for linear - Add isLinearGraph() to detect single-chain graphs at call site - Delete graph-layout.ts (dead code from pre-Dagre layout engine) - Remove dead types: BranchTree, LayoutNode, LayoutEdge, GraphLayout Made-with: Cursor
…igration Previously compared contractHash !== targetHash, which falsely fired when --ref pointed to a different branch but the contract already had a planned migration in the graph. Made-with: Cursor
…ct node - Bail out early when DB marker is not in the graph and differs from the contract hash (DB was updated outside the migration system). Shows a clear diagnostic with actionable hints instead of a confusing graph. - When marker === contract and both are off-graph, proceed normally — the detached contract node now carries both db and contract markers. - Fix summary icon: use warning when diagnostics contain warnings, not green checkmark. - Triage: document ledger read gap (deriveEdgeStatuses uses graph path instead of ledger for applied status). Made-with: Cursor
Made-with: Cursor
- Extract EdgeStatusKind ('applied' | 'pending' | 'diverged') and use
it in EdgeStatus, MigrationStatusEntry, and STATUS_ICON map
- Replace conditional icon chain with STATUS_ICON record lookup
- Fix graph jargon: 'edge(s)' -> 'migration(s)' in summarizeRefDistance
Made-with: Cursor
'Unreachable' more accurately describes edges that apply cannot reach from the current DB marker position. Update source, spec, and plan. Made-with: Cursor
- Remove hasUnreachable from formatStatusSummary — buildMigrationEntries never sets 'unreachable', so the check was always false - Guard CONTRACT.AHEAD diagnostic to only fire when targetHash is resolved, avoiding redundant diagnostic alongside MIGRATION.DIVERGED Made-with: Cursor
- deriveEdgeStatuses: 14 tests covering linear chain, empty DB (undefined and root marker), fully applied, branching with marker on different branch, diamond deduplication, ref target with contract beyond, and off-graph contract - isLinearGraph: 5 tests covering single node, linear chain, branching, detached nodes, and empty graph - Add db update hint to MARKER_NOT_IN_GRAPH diagnostic - Note test-graphs cleanup as open item in plan Made-with: Cursor
- Rewrite test comments to explain user scenarios, not implementation - Remove unreachable 'marker equals root' test (db sign always uses the contract hash, never the empty sentinel) - Add 'empty contract hash' test for the beyondTarget guard - Add 'diamond deduplication' test for assignedKeys correctness - Triage: detached contract node placement with --ref on wrong branch Made-with: Cursor
Spec: - Fix remaining 'Diverged' → 'Unreachable' in edge status and palette - Add known-gap note: CONTRACT.AHEAD missing when contract unreachable from chosen --ref branch Plan: - Remove completed 'reduce vertical spacing' from deferred items - Add deriveEdgeStatuses and isLinearGraph to test coverage table Issue triage: - Delete resolved issues (branch labels, backward labels, target resolution) — all were bugs in the deleted edge-centric renderer - Update backward edge misalignment with annotated snapshot - Update spine terminology issue with current function names - Add new issue: detached contract node placement with --ref Made-with: Cursor
…ode review issues Replace findDiagonalIndices index array with countDiagonals + inline detection, eliminating a cross-array indexing pattern that was correct but easy to misread. Introduce BendDirection type and bitsToBends helper to replace raw numeric choices with self-documenting values. Fix test-graphs node() helper to use GraphNode['style'] instead of hardcoded 'detached' literal. Triage two code review issues: lastEdge fallback (root fix is to make unreadable contract a hard error) and MigrationStatusResult conflating internal/public shapes. Made-with: Cursor
The early bail-out at lines 522-561 already exits when the marker is off-graph and differs from the contract. After that guard, markerAccountedFor is always true, making both !markerAccountedFor branches (summary and diagnostic) unreachable dead code. Made-with: Cursor
…tries
The summary text ('N pending migrations') was computed from
buildMigrationEntries (chain-based logic), while the visual graph used
deriveEdgeStatuses (full-graph path analysis). When the DB marker was on
a different branch, the chain-based logic produced 'unknown' statuses
and the summary incorrectly said 'up to date'.
Move deriveEdgeStatuses call into executeMigrationStatusCommand so both
the summary and the visual use the same source of truth. Store edge
statuses on the result to avoid recomputation in the CLI handler.
Remove dead knownStatuses/hasKnownStatus functions.
Made-with: Cursor
- Fix --limit help text: default is 10, not 'show all' - Replace green with cyan for summary checkmark (CVD-safe palette) - Fix contract path routing: try both marker->contract and ref->contract independently so diamond collaboration graphs show both legs - Merge double JSDoc on deriveEdgeStatuses into single block Made-with: Cursor
- Check off all implemented acceptance criteria in spec - Fix relevant-path wording to match implementation (tries both marker→contract and ref→contract independently) - Add rationale for why the default view isn't a simple linear list - Expand ledger issue with schema gap analysis and full fix plan - Resolve spec TODOs, refine summary framing, add deferred items - Update plan to reflect all code review fixes Made-with: Cursor
…ract case
- Summary is now neutral ("N migration(s) on disk") instead of mixing
explanation with action guidance
- Marker-not-in-graph diagnostic promoted to warn so hint renders in
terminal output
- CONTRACT.AHEAD suppressed when marker === contract (both off-graph)
to avoid redundant "run migration plan" guidance
- Extract determineLimit() helper for --limit flag parsing
Made-with: Cursor
13 end-to-end scenarios covering the summary, diagnostics, and hints produced by `migration status` across realistic user situations: offline empty, offline with contract, offline with migrations, fresh DB, happy path, pending, contract ahead, marker off-graph (both variants), JSON output shape, divergent graph, wrong-branch marker, and ref resolution. Also adds the MIGRATION.NO_MARKER diagnostic for fresh databases (no marker row), which one of the journey tests exercises. Made-with: Cursor
Made-with: Cursor
- Consolidate offline scenarios into single it() to fix chdir race - Add timeout for offline test (runs emit + plan) - Update divergence test: status auto-resolves via contract hash - Lowercase status assertions to match new graph legend format Made-with: Cursor
Extract inline --from prefix resolution into a testable function using Result<T, PrefixResolutionFailure>. Update the ambiguous-prefix test to call the actual resolver and assert the failure shape instead of just counting candidates. Made-with: Cursor
Extract entry() and buildGraph() into shared test/utils/graph-helpers.ts. Add 8 focused tests covering path computation (linear, diamond, unreachable fallback, no-targets fallback), status icon/colorHint baking, spineTarget resolution, ref markers, offline mode, and detached contract nodes. Made-with: Cursor
Pass edgeStatuses into buildMigrationEntries so entries use the graph-based status (applied/pending/unreachable) instead of the chain-based heuristic. Eliminates divergence between summary counts and graph display. 'unknown' now only appears in offline mode. Made-with: Cursor
- Replace tautological Array.find() prefix tests with calls to resolveBundleByPrefix, exercising the actual resolver logic - Fix "without sha256: scheme" test to actually omit the scheme - Add timeout to graph render test describes for CI stability Made-with: Cursor
8298ff4 to
e5856b8
Compare
closes TML-2100
Intent
Replace the table-based
migration statusoutput with an ASCII graph renderer so users can see migration topology — branches, forks, diamonds, and rollback cycles — directly in their terminal. The default view answers "what wouldmigration applydo?" by showing only the relevant subgraph (the apply path plus any forks that explain why action is needed). An opt-in--graphflag shows the full migration graph. This eliminates theAMBIGUOUS_LEAFcrash on divergent graphs and introduces three-state edge status (applied/pending/unreachable) so users can see exactly which migrations are actionable.Change map
RenderGraph,GraphNode,GraphEdge,GraphRenderOptionsMigrationGraph→ genericRenderGraphwith markers and status icons--fromprefix matchingderiveEdgeStatusesunit tests--fromprefix matching testsThe story
Introduce a domain-agnostic graph renderer. A new
graph-render.tsmodule uses Dagre for Sugiyama-style layout (rank assignment + coordinate placement), then stamps the result onto aCharGrid— a sparse character canvas that resolves box-drawing junctions, color priority, and label placement. The renderer knows nothing about migrations; it acceptsRenderGraph(nodes with markers, edges with optional labels and color hints) and produces ASCII output. This is the bulk of new code (~1300 lines).Define generic graph types as a stable interface boundary.
graph-types.tsintroducesRenderGraph(immutable directed graph with adjacency-list indexing),GraphNode(with typed markers: db, contract, ref, custom),GraphEdge(withcolorHintfor CVD-safe edge coloring), andGraphRenderOptions(spine target, truncation limit, dagre overrides). These types form the contract between the migration-specific mapper and the domain-agnostic renderer.Build the migration-to-graph mapping layer.
graph-migration-mapper.tstranslatesMigrationGraph+ CLI status info intoRenderGraph. It computes relevant paths with continuity-aware routing (tries marker→contract and ref→contract independently, not BFS shortest path from root), bakes status icons (✓/⧗/✗) into edge labels, setscolorHintfor CVD-safe coloring, and attaches typed markers (db, contract, ref) to nodes.Rewrite target resolution to eliminate
findLeaf. The old code calledfindLeaf(graph)as a fallback, which threwAMBIGUOUS_LEAFon divergent graphs. The new resolution chain is:--refhash → contract hash (if in graph) → single reachable leaf → diverged full-graph fallback with aMIGRATION.DIVERGEDdiagnostic. This meansmigration statusnever crashes on a valid graph shape.Add three-state edge status derivation.
deriveEdgeStatusesuses path analysis across the full graph to assign per-edge status: applied (root→marker path), pending (marker→target path, plus target→contract when a ref is active), and unreachable (root→target edges that are neither applied nor pending — the DB is on a different branch). Empty DB treats root as the effective marker.Replace the CLI output pipeline. The old
formatMigrationStatusOutput(table-based formatter) is removed. The CLI handler now: (a) maps the status result toRenderGraphviamigrationGraphToRenderInput, (b) extracts the relevant subgraph for the default view or passes the full graph for--graph, (c) detects linear graphs to use compact layout (ranksep: 1), (d) renders viagraphRenderer.render(), and (e) appends a legend and summary with diagnostics.--limit/--allflags control truncation (default 10).Handle edge cases with early bail-outs and diagnostics. Marker-not-in-graph (DB managed via
db update) bails out early with recovery hints. Contract-ahead fires when no migration produces the current contract hash. Detached contract nodes render with dashed connectors when the contract is not in the graph.Add prefix matching for
migration plan --from. As a cross-command improvement discovered during testing,--fromnow supports prefix matching (with or withoutsha256:scheme), with disambiguation when multiple candidates match.Behavior changes & evidence
Adds Dagre-based ASCII graph renderer for migration topology visualization: Introduces
GraphRendererinterface with a singlerender(graph, options)method backed by Dagre layout. Supports linear chains, branches, diamonds, rollback cycles, detached contract nodes, and truncation with┊elided-history indicator. CVD-safe palette (cyan/yellow/magenta, no red/green). Box-drawing characters for connectors. Deterministic output.Adds migration-to-graph mapping with status icons and continuity-aware path computation:
migrationGraphToRenderInputtranslates the migration domain into generic graph types, baking status icons into edge labels and computing relevant paths for the default subgraph view. Path computation tries both marker→contract and ref→contract independently (not root→contract BFS) so diamond topologies show both legs.extractRelevantSubgraphmulti-path union, deduplication, marker preservationAdds three-state edge status derivation (
deriveEdgeStatuses): Computes applied/pending/unreachable status per edge using graph-wide path analysis. Applied = root→marker. Pending = marker→target (+ target→contract for ref scenarios). Unreachable = root→target edges that are neither — meaning the DB is on a different branch. Empty DB treats root as effective marker.applycan't reach these edges without the DB first changing branches.Target resolution replaces
findLeafwith contract-hash-first fallback chain:migration statusno longer callsfindLeaf(graph). Target resolution:--refhash → contract hash (if in graph) → single reachable leaf → diverged (full-graph view withMIGRATION.DIVERGEDdiagnostic). Divergent graphs render successfully with all branches visible instead of crashing.findLeafthrowsAMBIGUOUS_LEAFon multi-leaf graphs.migration statusis a read-only display command — it should never hard-fail on a valid graph shape.MIGRATION.DIVERGEDdiagnostic path. No dedicated unit test; behavior verified through the command flow.Adds truncation with marker-aware expansion (
--limit/--all): Long graphs truncate to the last N edges (default 10) with a┊ (M earlier migrations)indicator. Truncation expands beyond the limit when needed to keep contract and DB markers visible.--alldisables truncation.truncateGraph,findSpinePath,renderwith truncationAdds
isLinearGraphfor compact linear layout: Detects single-chain graphs (no branching, ignoring detached nodes) and passesranksep: 1so the output is vertically compact.Adds marker-not-in-graph early bail-out with recovery diagnostics: When the DB marker is off-graph and differs from the contract,
migration statusbails out early — no graph is rendered, only aMIGRATION.MARKER_NOT_IN_GRAPHdiagnostic with actionable hints (db sign, db update, contract infer, db verify). When marker equals contract (both off-graph), proceeds normally — the detached node shows both markers.Adds
MIGRATION.NO_MARKERdiagnostic for fresh databases: When connected to a database that has no marker row (never initialized), emits a warning with a hint to runmigration apply. Previously this state was silent — the user saw pending migrations but no explanation of why they were pending.Adds
--graphflag for full migration graph: The--graphflag renders the entire migration graph (all branches, diamonds, cycles) instead of just the relevant subgraph. When the graph is diverged (no single target),--graphis used automatically.--graphor diverged → full graph, else → relevant subgraphgraph-render.test.ts.Adds prefix matching for
migration plan --from:--fromnow supports prefix matching with or without thesha256:scheme. Ambiguous prefixes (matching multiple migrations) return a clear error.migration statusoutput and should be able to use them directly.Removes
formatMigrationStatusOutputand privatizes helpers:formatMigrationStatusOutput(the old table formatter) is deleted frommigrations.ts.resolveDisplayChainandbuildMigrationEntriesare made module-private (no longer exported). No behavior change — these were only consumed internally.buildMigrationEntriesandresolveDisplayChainnowfunction(notexport function)Replaces graph jargon in user-facing messages: "edge(s)" → "migration(s)" in ref distance summaries. "marker" → "database marker" in no-path message.
MIGRATION.MARKER_DIVERGED→MIGRATION.MARKER_NOT_IN_GRAPHwith clearer messaging. No behavior change beyond wording.Adds
@dagrejs/dagredependency: New production dependency for graph layout."@dagrejs/dagre": "^3.0.0"Compatibility / migration / risk
migration statusoutput changes from a table to an ASCII graph. Scripts parsing the old table format will break. The--jsonoutput is preserved and should be used for programmatic consumption.MigrationStatusResultgains internal fields (graph,bundles,edgeStatuses,activeRefHash,activeRefName,diverged) but they are stripped before JSON serialization. The--jsonoutput shape is backward-compatible except thatMigrationStatusEntry.statusnow includes'unreachable'in addition to'applied' | 'pending' | 'unknown'.MIGRATION.MARKER_DIVERGED→MIGRATION.MARKER_NOT_IN_GRAPH. Any automation matching on diagnostic codes will need updating.findLeafno longer called frommigration status: TheAMBIGUOUS_LEAFerror can no longer be triggered bymigration status. This is intentional — divergent graphs now render successfully.@dagrejs/dagre ^3.0.0added to the CLI package. Pure JS, no native modules.Known issues
deriveEdgeStatusesuses graph path, not ledger, for applied status (high): Afterdb update, edges show as✓ appliedeven though no migrations were executed. Requires addingreadLedger()to the control plane stack and threadingdirName/migrationIdthrough the runner. See issue triage.--ref stagingis used and the contract is reachable only from a different branch, no diagnostic fires. The detached contract node also renders on the wrong branch.MigrationStatusResultconflates internal and public shapes (medium): The--jsonhandler manually strips internal fields. A dedicated public shape type would provide compile-time safety.Follow-ups
migration planneeds optional--dbsupport: So--fromdefaults to the DB marker when online, preventing unusable migrations.migration status: Added — 13 diagnostic journey tests inmigration-status-diagnostics.e2e.test.ts.Non-goals / intentionally out of scope
findLeaf/findPath: These remain formigration planandmigration apply.Made with Cursor
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Chores