@prisma-next/cli 0.5.0-dev.4 → 0.5.0-dev.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/agent-skill-mongo.md +63 -31
  2. package/dist/agent-skill-postgres.md +1 -1
  3. package/dist/cli.mjs +119 -13
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/{client-TG7rbCWT.mjs → client-CrsnY58k.mjs} +4 -4
  6. package/dist/{client-TG7rbCWT.mjs.map → client-CrsnY58k.mjs.map} +1 -1
  7. package/dist/commands/contract-emit.mjs +2 -2
  8. package/dist/commands/contract-infer.mjs +2 -2
  9. package/dist/commands/db-init.mjs +7 -7
  10. package/dist/commands/db-schema.mjs +5 -5
  11. package/dist/commands/db-sign.mjs +7 -7
  12. package/dist/commands/db-update.mjs +7 -7
  13. package/dist/commands/db-verify.mjs +7 -7
  14. package/dist/commands/migration-apply.mjs +6 -6
  15. package/dist/commands/migration-new.mjs +5 -5
  16. package/dist/commands/migration-plan.mjs +6 -6
  17. package/dist/commands/migration-ref.d.mts +1 -1
  18. package/dist/commands/migration-ref.mjs +4 -4
  19. package/dist/commands/migration-show.d.mts +1 -1
  20. package/dist/commands/migration-show.mjs +6 -6
  21. package/dist/commands/migration-status.mjs +2 -2
  22. package/dist/{config-loader-_W4T21X1.mjs → config-loader-C25b63rJ.mjs} +1 -1
  23. package/dist/{config-loader-_W4T21X1.mjs.map → config-loader-C25b63rJ.mjs.map} +1 -1
  24. package/dist/config-loader.mjs +1 -1
  25. package/dist/contract-emit--feXyNd7.mjs +4 -0
  26. package/dist/{contract-emit-DpPjuFy-.mjs → contract-emit-NJ01hiiv.mjs} +8 -8
  27. package/dist/{contract-emit-DpPjuFy-.mjs.map → contract-emit-NJ01hiiv.mjs.map} +1 -1
  28. package/dist/{contract-emit-CQfj7xJn.mjs → contract-emit-V5SSitUT.mjs} +6 -6
  29. package/dist/{contract-emit-CQfj7xJn.mjs.map → contract-emit-V5SSitUT.mjs.map} +1 -1
  30. package/dist/{contract-enrichment-CGW6mm-E.mjs → contract-enrichment-CAOELa-H.mjs} +1 -1
  31. package/dist/{contract-enrichment-CGW6mm-E.mjs.map → contract-enrichment-CAOELa-H.mjs.map} +1 -1
  32. package/dist/{contract-infer-BS4kIX9c.mjs → contract-infer-D9cC3rJm.mjs} +4 -4
  33. package/dist/{contract-infer-BS4kIX9c.mjs.map → contract-infer-D9cC3rJm.mjs.map} +1 -1
  34. package/dist/exports/control-api.mjs +4 -4
  35. package/dist/exports/index.mjs +2 -2
  36. package/dist/exports/init-output.d.mts +39 -0
  37. package/dist/exports/init-output.d.mts.map +1 -0
  38. package/dist/exports/init-output.mjs +3 -0
  39. package/dist/{extract-operation-statements-DZUJNmL3.mjs → extract-operation-statements-DsFfxXVZ.mjs} +2 -2
  40. package/dist/{extract-operation-statements-DZUJNmL3.mjs.map → extract-operation-statements-DsFfxXVZ.mjs.map} +1 -1
  41. package/dist/{extract-sql-ddl-DDMX-9mz.mjs → extract-sql-ddl-D9UbZDyz.mjs} +1 -1
  42. package/dist/{extract-sql-ddl-DDMX-9mz.mjs.map → extract-sql-ddl-D9UbZDyz.mjs.map} +1 -1
  43. package/dist/{framework-components-DfZKQBQ2.mjs → framework-components-Cr--XBKy.mjs} +2 -2
  44. package/dist/{framework-components-DfZKQBQ2.mjs.map → framework-components-Cr--XBKy.mjs.map} +1 -1
  45. package/dist/init-C5220SY9.mjs +2062 -0
  46. package/dist/init-C5220SY9.mjs.map +1 -0
  47. package/dist/{inspect-live-schema-BsoFVoS1.mjs → inspect-live-schema-yrHAvG71.mjs} +6 -6
  48. package/dist/{inspect-live-schema-BsoFVoS1.mjs.map → inspect-live-schema-yrHAvG71.mjs.map} +1 -1
  49. package/dist/migration-cli.mjs +1 -1
  50. package/dist/{migration-command-scaffold-DOXnheFa.mjs → migration-command-scaffold-B3B09et6.mjs} +6 -6
  51. package/dist/{migration-command-scaffold-DOXnheFa.mjs.map → migration-command-scaffold-B3B09et6.mjs.map} +1 -1
  52. package/dist/{migration-status-Ry3TnEya.mjs → migration-status-DUMiH8_G.mjs} +6 -6
  53. package/dist/{migration-status-Ry3TnEya.mjs.map → migration-status-DUMiH8_G.mjs.map} +1 -1
  54. package/dist/{migrations-fU0xoKjS.mjs → migrations-Bo5WtTla.mjs} +2 -2
  55. package/dist/{migrations-fU0xoKjS.mjs.map → migrations-Bo5WtTla.mjs.map} +1 -1
  56. package/dist/output-BpcQrnnq.mjs +103 -0
  57. package/dist/output-BpcQrnnq.mjs.map +1 -0
  58. package/dist/{progress-adapter-B-YvmcDu.mjs → progress-adapter-DvQWB1nK.mjs} +1 -1
  59. package/dist/{progress-adapter-B-YvmcDu.mjs.map → progress-adapter-DvQWB1nK.mjs.map} +1 -1
  60. package/dist/quick-reference-mongo.md +34 -13
  61. package/dist/quick-reference-postgres.md +11 -9
  62. package/dist/{result-handler-BJwA7ufw.mjs → result-handler-Ba3zWQsI.mjs} +4 -77
  63. package/dist/result-handler-Ba3zWQsI.mjs.map +1 -0
  64. package/dist/{terminal-ui-C5k88MmW.mjs → terminal-ui-C3ZLwQxK.mjs} +76 -2
  65. package/dist/terminal-ui-C3ZLwQxK.mjs.map +1 -0
  66. package/dist/{validate-contract-deps-esa-VQ0h.mjs → validate-contract-deps-B_Cs29TL.mjs} +1 -1
  67. package/dist/{validate-contract-deps-esa-VQ0h.mjs.map → validate-contract-deps-B_Cs29TL.mjs.map} +1 -1
  68. package/dist/{verify-bl__PkXk.mjs → verify-Bkycc-Tf.mjs} +2 -2
  69. package/dist/{verify-bl__PkXk.mjs.map → verify-Bkycc-Tf.mjs.map} +1 -1
  70. package/package.json +21 -16
  71. package/src/commands/init/detect-pnpm-catalog.ts +141 -0
  72. package/src/commands/init/errors.ts +254 -0
  73. package/src/commands/init/exit-codes.ts +62 -0
  74. package/src/commands/init/hygiene-gitattributes.ts +97 -0
  75. package/src/commands/init/hygiene-gitignore.ts +48 -0
  76. package/src/commands/init/hygiene-package-scripts.ts +91 -0
  77. package/src/commands/init/index.ts +112 -7
  78. package/src/commands/init/init.ts +766 -144
  79. package/src/commands/init/inputs.ts +421 -0
  80. package/src/commands/init/output.ts +147 -0
  81. package/src/commands/init/probe-db.ts +308 -0
  82. package/src/commands/init/reinit-cleanup.ts +83 -0
  83. package/src/commands/init/templates/agent-skill-mongo.md +63 -31
  84. package/src/commands/init/templates/agent-skill-postgres.md +1 -1
  85. package/src/commands/init/templates/agent-skill.ts +25 -3
  86. package/src/commands/init/templates/code-templates.ts +125 -32
  87. package/src/commands/init/templates/env.ts +80 -0
  88. package/src/commands/init/templates/quick-reference-mongo.md +34 -13
  89. package/src/commands/init/templates/quick-reference-postgres.md +11 -9
  90. package/src/commands/init/templates/quick-reference.ts +42 -3
  91. package/src/commands/init/templates/tsconfig.ts +167 -5
  92. package/src/exports/init-output.ts +10 -0
  93. package/dist/contract-emit-fhNwwhkQ.mjs +0 -4
  94. package/dist/init-CQfo_4Ro.mjs +0 -430
  95. package/dist/init-CQfo_4Ro.mjs.map +0 -1
  96. package/dist/result-handler-BJwA7ufw.mjs.map +0 -1
  97. package/dist/terminal-ui-C5k88MmW.mjs.map +0 -1
  98. /package/dist/{cli-errors-C0JhVj0c.d.mts → cli-errors-BFYgBH3L.d.mts} +0 -0
  99. /package/dist/{cli-errors-DHq6GQGu.mjs → cli-errors-Cd79vmTH.mjs} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"migration-status-Ry3TnEya.mjs","names":["STATUS_ICON: Record<EdgeStatusKind, string>","nodeList: GraphNode[]","markers: NodeMarker[]","edgeList: GraphEdge[]","relevantPaths: string[][]","spineTargetHash: string","contractMarkers: NodeMarker[]","REF_COLORS: ColorFn[]","BOX_CHAR: Record<number, string>","tags: InlineTag[]","rows: string[]","runColor: ColorFn | undefined","ch: string","color: ColorFn | undefined","deduped: Point[]","bends: BendDirection[]","result: Point[]","final: Point[]","best: (Point & { score: number }) | undefined","segments: Segment[]","candidates: Point[]","bestPoly: Point[] | null","bestLabel: Point | undefined","edgeNames: string[]","edgeEntries: EdgeEntry[]","dagrePoints: Point[]","role: EdgeEntry['role']","drawnEdges: DrawnEdge[]","ax: number | undefined","ay: number | undefined","arrow: string | undefined","path: string[]","graphRenderer: GraphRenderer","statuses: EdgeStatus[]","entries: MigrationStatusEntry[]","status: EdgeStatusKind | 'unknown'","activeRefName: string | undefined","activeRefHash: string | undefined","allRefs: Refs","statusRefs: StatusRef[]","details: Array<{ label: string; value: string }>","diagnostics: StatusDiagnostic[]","contractHash: string","bundles: readonly MigrationBundle[]","graph: MigrationGraph","targetHash: string | undefined","markerHash: string | undefined","mode: 'online' | 'offline'","hints: string[]","summary: string","pathDecision: MigrationStatusResult['pathDecision']","lines: string[]"],"sources":["../src/utils/formatters/graph-types.ts","../src/utils/formatters/graph-migration-mapper.ts","../src/utils/formatters/graph-render.ts","../src/commands/migration-status.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// Generic graph renderer types — domain-agnostic\n// ---------------------------------------------------------------------------\n\n/** A typed marker attached to a node. Different marker kinds get different visual treatment. */\nexport type NodeMarker =\n | { readonly kind: 'db' }\n | { readonly kind: 'ref'; readonly name: string; readonly active?: boolean }\n | { readonly kind: 'contract'; readonly planned: boolean }\n | { readonly kind: 'custom'; readonly label: string };\n\n/** A node in the graph. Rendered as ○ with optional typed markers. */\nexport interface GraphNode {\n readonly id: string;\n /** Typed markers rendered inline on the node row */\n readonly markers?: readonly NodeMarker[] | undefined;\n /** Detached nodes use a dashed connector (e.g. unplanned contract) */\n readonly style?: 'normal' | 'detached' | undefined;\n}\n\n/** A directed edge between two nodes. Carries an optional label rendered on the edge line. */\nexport interface GraphEdge {\n readonly from: string;\n readonly to: string;\n /** Edge line text, e.g. \"20260101_init ✓ abc12..\" */\n readonly label?: string;\n /**\n * Visual color hint for the edge. Overrides the default role-based\n * coloring (spine/branch/backward) when set.\n *\n * - `'applied'` — cyan (CVD-safe: completed/done)\n * - `'pending'` — yellow (CVD-safe: waiting/upcoming)\n * - `'unreachable'` — magenta (CVD-safe: DB on a different branch)\n */\n readonly colorHint?: 'applied' | 'pending' | 'unreachable';\n /**\n * Edge rendering style.\n * - `'solid'` (default) — normal edge with `│` connector\n * - `'dashed'` — draft/phantom edge with `┊` connector, excluded from path resolution\n */\n readonly style?: 'solid' | 'dashed';\n}\n\n/**\n * Immutable directed graph with adjacency-list indexing.\n *\n * Built once from flat arrays of nodes and edges, then passed around as\n * the primary graph representation for rendering, traversal, truncation,\n * and subgraph extraction.\n */\nexport class RenderGraph {\n readonly nodes: readonly GraphNode[];\n readonly edges: readonly GraphEdge[];\n\n /** Forward adjacency: node id → outgoing edges. */\n readonly forward: ReadonlyMap<string, readonly GraphEdge[]>;\n /** Set of node ids that have at least one incoming edge. */\n readonly incomingNodes: ReadonlySet<string>;\n /** Node lookup by id. */\n readonly nodeById: ReadonlyMap<string, GraphNode>;\n\n constructor(nodes: readonly GraphNode[], edges: readonly GraphEdge[]) {\n this.nodes = nodes;\n this.edges = edges;\n\n const fwd = new Map<string, GraphEdge[]>();\n const inc = new Set<string>();\n const byId = new Map<string, GraphNode>();\n\n for (const n of nodes) {\n byId.set(n.id, n);\n }\n for (const e of edges) {\n const list = fwd.get(e.from);\n if (list) list.push(e);\n else fwd.set(e.from, [e]);\n inc.add(e.to);\n }\n\n this.forward = fwd;\n this.incomingNodes = inc;\n this.nodeById = byId;\n }\n\n /** Outgoing edges from a node (empty array if none). */\n outgoing(nodeId: string): readonly GraphEdge[] {\n return this.forward.get(nodeId) ?? [];\n }\n}\n\n/** Options controlling graph rendering. */\nexport interface GraphRenderOptions {\n /** Node id for the spine endpoint */\n readonly spineTarget: string;\n /** Root node id. Defaults to the node with no incoming edges. */\n readonly rootId?: string;\n /** Enable ANSI colour output */\n readonly colorize?: boolean;\n /** Terminal width. Default 80. */\n readonly maxWidth?: number;\n /**\n * Truncate to show at most this many spine edges. `undefined` = no truncation.\n * The effective limit expands to include any DB or contract markers on the spine.\n */\n readonly limit?: number | undefined;\n /**\n * Override dagre layout parameters. Merged over defaults:\n * `{ ranksep: 4, nodesep: 6, marginx: 2, marginy: 1 }`.\n *\n * When `ranksep` is ≤ 1, labels are placed inline on the arrowhead row\n * instead of in a separate label-placement pass (there isn't enough\n * vertical space for a dedicated label row).\n */\n readonly dagreOptions?: {\n readonly ranksep?: number;\n readonly nodesep?: number;\n readonly marginx?: number;\n readonly marginy?: number;\n };\n}\n","/**\n * Maps MigrationGraph + status info to the generic graph renderer types.\n */\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { findPath } from '@prisma-next/migration-tools/dag';\nimport type { MigrationGraph } from '@prisma-next/migration-tools/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\nimport type { StatusRef } from '../migration-types';\nimport {\n type GraphEdge,\n type GraphNode,\n type GraphRenderOptions,\n type NodeMarker,\n RenderGraph,\n} from './graph-types';\n\nexport type EdgeStatusKind = 'applied' | 'pending' | 'unreachable';\n\nconst STATUS_ICON: Record<EdgeStatusKind, string> = {\n applied: ' ✓',\n pending: ' ⧗',\n unreachable: ' ✗',\n};\n\n/** Shorten a contract hash for display: strip sha256: prefix, take 7 chars. */\nfunction shortHash(hash: string): string {\n const stripped = hash.startsWith('sha256:') ? hash.slice(7) : hash;\n return stripped.slice(0, 7);\n}\n\nfunction toShortId(hash: string): string {\n return hash === EMPTY_CONTRACT_HASH ? '∅' : shortHash(hash);\n}\n\n/** Minimal per-edge status from the CLI's status result. */\nexport interface EdgeStatus {\n readonly dirName: string;\n readonly status: EdgeStatusKind;\n}\n\nexport interface MigrationGraphInput {\n readonly graph: MigrationGraph;\n readonly mode: 'online' | 'offline';\n readonly markerHash?: string | undefined;\n readonly contractHash: string;\n readonly refs?: readonly StatusRef[] | undefined;\n readonly activeRefHash?: string | undefined;\n readonly activeRefName?: string | undefined;\n /**\n * Per-edge applied/pending status from the ledger. When provided, status\n * icons (✓/⧗) are baked into edge labels. Undefined in offline mode.\n */\n readonly edgeStatuses?: readonly EdgeStatus[] | undefined;\n}\n\nexport interface MigrationRenderInput {\n readonly graph: RenderGraph;\n readonly options: GraphRenderOptions;\n /** All relevant paths (root→contract, root→marker, root→ref). */\n readonly relevantPaths: readonly (readonly string[])[];\n}\n\n/**\n * Convert a MigrationGraph + status info into the generic graph renderer types.\n */\nexport function migrationGraphToRenderInput(input: MigrationGraphInput): MigrationRenderInput {\n const { graph, mode, markerHash, contractHash, refs, activeRefHash, edgeStatuses } = input;\n\n const statusByDirName = new Map(edgeStatuses?.map((e) => [e.dirName, e.status]));\n\n // Build nodes\n const nodeList: GraphNode[] = [];\n for (const nodeId of graph.nodes) {\n const markers: NodeMarker[] = [];\n\n // DB marker\n if (mode === 'online' && markerHash === nodeId) {\n markers.push({ kind: 'db' });\n }\n\n // Ref markers\n if (refs) {\n for (const ref of refs) {\n if (ref.hash === nodeId) {\n markers.push({ kind: 'ref', name: ref.name, active: ref.active });\n }\n }\n }\n\n // Contract marker\n if (contractHash === nodeId && contractHash !== EMPTY_CONTRACT_HASH) {\n markers.push({ kind: 'contract', planned: true });\n }\n\n nodeList.push({\n id: toShortId(nodeId),\n markers: markers.length > 0 ? markers : undefined,\n });\n }\n\n // Build edges\n const edgeList: GraphEdge[] = [];\n\n for (const [, entries] of graph.forwardChain) {\n for (const entry of entries) {\n const status = statusByDirName.get(entry.dirName);\n const icon = status ? STATUS_ICON[status] : '';\n const label = `${entry.dirName}${icon}`;\n\n edgeList.push({\n from: toShortId(entry.from),\n to: toShortId(entry.to),\n label,\n ...ifDefined('colorHint', status),\n });\n }\n }\n\n // Compute paths to all interesting targets so the default view shows the\n // minimal subgraph that covers everything relevant: contract, DB marker, ref.\n const relevantPaths: string[][] = [];\n const rootId = EMPTY_CONTRACT_HASH;\n\n function addPathFromRoot(targetHash: string): void {\n if (!graph.nodes.has(targetHash)) return;\n const raw = findPath(graph, rootId, targetHash);\n if (raw && raw.length > 0) {\n relevantPaths.push([toShortId(rootId), ...raw.map((e) => toShortId(e.to))]);\n }\n }\n\n function addPathBetween(fromHash: string, toHash: string): void {\n /* v8 ignore next -- @preserve */\n if (!graph.nodes.has(fromHash) || !graph.nodes.has(toHash)) return;\n const raw = findPath(graph, fromHash, toHash);\n if (raw && raw.length > 0) {\n relevantPaths.push([toShortId(fromHash), ...raw.map((e) => toShortId(e.to))]);\n }\n }\n\n // 1. Path to the DB marker\n if (mode === 'online' && markerHash) {\n addPathFromRoot(markerHash);\n }\n\n // 2. Path to the ref\n if (activeRefHash && activeRefHash !== markerHash) {\n addPathFromRoot(activeRefHash);\n }\n\n // 3. Path(s) to the contract — prefer continuing from marker and/or ref\n // rather than an independent root→contract (which BFS may route through\n // an unrelated branch). When both marker and ref exist, try both paths\n // so that the diamond (two branches converging at the contract) is visible.\n if (contractHash !== EMPTY_CONTRACT_HASH) {\n let contractReached = false;\n\n if (markerHash && markerHash !== contractHash) {\n const markerReaches = findPath(graph, markerHash, contractHash);\n if (markerReaches) {\n addPathBetween(markerHash, contractHash);\n contractReached = true;\n }\n }\n\n if (activeRefHash && activeRefHash !== markerHash && activeRefHash !== contractHash) {\n const refReaches = findPath(graph, activeRefHash, contractHash);\n if (refReaches) {\n addPathBetween(activeRefHash, contractHash);\n contractReached = true;\n }\n }\n\n if (!contractReached && contractHash !== (markerHash ?? activeRefHash)) {\n addPathFromRoot(contractHash);\n }\n }\n\n // Fall back: if no paths were found, try the tip of the forward chain.\n if (relevantPaths.length === 0) {\n const lastEdge = [...graph.forwardChain.values()].flat().pop();\n const fallbackHash = lastEdge?.to ?? EMPTY_CONTRACT_HASH;\n addPathFromRoot(fallbackHash);\n }\n\n // Spine target for rendering (edge coloring, detached node alignment).\n let spineTargetHash: string;\n\n if (activeRefHash && graph.nodes.has(activeRefHash)) {\n spineTargetHash = activeRefHash;\n } else if (contractHash !== EMPTY_CONTRACT_HASH && graph.nodes.has(contractHash)) {\n spineTargetHash = contractHash;\n } else {\n const lastEdge = [...graph.forwardChain.values()].flat().pop();\n spineTargetHash = lastEdge?.to ?? EMPTY_CONTRACT_HASH;\n }\n\n // Contract not in the migration graph — connect from spine target with a\n // dashed edge so the user can see the gap (contract has changed but no\n // migration has been planned yet).\n if (contractHash !== EMPTY_CONTRACT_HASH && !graph.nodes.has(contractHash)) {\n const contractMarkers: NodeMarker[] = [];\n if (mode === 'online' && markerHash === contractHash) {\n contractMarkers.push({ kind: 'db' });\n }\n contractMarkers.push({ kind: 'contract', planned: false });\n nodeList.push({\n id: shortHash(contractHash),\n markers: contractMarkers,\n });\n\n if (graph.nodes.has(spineTargetHash) || spineTargetHash === EMPTY_CONTRACT_HASH) {\n edgeList.push({\n from: toShortId(spineTargetHash),\n to: shortHash(contractHash),\n style: 'dashed',\n });\n }\n }\n\n return {\n graph: new RenderGraph(nodeList, edgeList),\n options: {\n spineTarget: toShortId(spineTargetHash),\n rootId: '∅',\n colorize: true,\n },\n relevantPaths,\n };\n}\n","/**\n * Terminal graph renderer.\n *\n * Renders directed graphs as ASCII/box-drawing art for terminal output. Uses\n * dagre for automatic layout (rank assignment + coordinate placement), then\n * stamps the result onto a {@link CharGrid} — a sparse character canvas that\n * resolves box-drawing junctions, color priority, and label placement.\n *\n * ## Rendering pipeline\n *\n * 1. **Layout** — dagre assigns (x, y) coordinates to nodes and polyline\n * control points to edges. We use `rankdir: 'TB'` (top-to-bottom).\n * 2. **Orthogonalization** — dagre's polylines may contain diagonal segments.\n * {@link selectBestVariant} resolves each diagonal into an L-shaped bend,\n * enumerating all 2^N combinations and picking the variant with fewest\n * corners and shortest total length.\n * 3. **Edge stamping** — orthogonal segments are stamped onto the CharGrid as\n * directional bitmasks. The grid resolves overlapping directions into the\n * correct box-drawing character (│, ─, ┌, ┼, etc.).\n * 4. **Label placement** — edge labels are placed adjacent to their polyline\n * segments, preferring horizontal (branch-specific) segments over shared\n * vertical trunks to avoid ambiguity.\n * 5. **Arrowheads** — ▾ ▴ ◂ ▸ placed one cell before the terminal point.\n * 6. **Node stamping** — `○ nodeId` with inline marker tags (db, contract,\n * ref names).\n * 7. **Elided indicator** — when truncation is active, `┊ (N earlier\n * migrations)` is stamped above the visible root.\n * 8. **Detached nodes** — rendered below the graph with `◇` and a dotted\n * connector.\n *\n * ## Graph filtering\n *\n * The caller controls what graph is rendered: the full graph, or a subgraph\n * extracted via {@link extractRelevantSubgraph} (union of relevant paths).\n * The renderer itself is agnostic — it renders whatever graph it receives.\n *\n * Truncation is supported via `options.limit`.\n *\n * ## Color accessibility\n *\n * Uses a CVD-safe palette — no red/green contrast. Shape and icon always\n * carry meaning; color only reinforces.\n */\nimport dagre from '@dagrejs/dagre';\nimport { bold, cyan, dim, magenta, yellow } from 'colorette';\nimport {\n type GraphEdge,\n type GraphNode,\n type GraphRenderOptions,\n type NodeMarker,\n RenderGraph,\n} from './graph-types';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** A 2D point on the character grid (integer coordinates). */\ninterface Point {\n x: number;\n y: number;\n}\n\n/** An orthogonal line segment between two points on the character grid. */\ninterface Segment {\n readonly from: Point;\n readonly to: Point;\n}\n\nfunction segment(from: Point, to: Point): Segment {\n return { from, to };\n}\n\nfunction isVertical(seg: Segment): boolean {\n return seg.from.x === seg.to.x;\n}\n\nfunction manhattanLength(seg: Segment): number {\n return Math.abs(seg.to.x - seg.from.x) + Math.abs(seg.to.y - seg.from.y);\n}\n\n/** A function that wraps a string with an ANSI color escape sequence. */\ntype ColorFn = (s: string) => string;\n\n// ---------------------------------------------------------------------------\n// CVD-safe color palette\n//\n// No red/green contrast. Shape/icon always carries meaning; color reinforces.\n// ---------------------------------------------------------------------------\n\n/** Color functions for each semantic role in the graph. */\ninterface GraphColors {\n spine: ColorFn;\n branch: ColorFn;\n backward: ColorFn;\n applied: ColorFn;\n pending: ColorFn;\n unreachable: ColorFn;\n node: ColorFn;\n label: ColorFn;\n marker: ColorFn;\n /** Rotating color for ref markers — cycles through the palette by index. */\n ref: (index: number) => ColorFn;\n}\n\n/** Rotating palette for ref marker names, cycling through these for each ref. */\nconst REF_COLORS: ColorFn[] = [yellow, magenta, bold, cyan];\n\n/** Build the color palette, respecting the `colorize` flag. When false, all color functions become identity. */\nfunction buildColors(colorize: boolean): GraphColors {\n const c = (fn: ColorFn): ColorFn => (colorize ? fn : (s) => s);\n return {\n spine: c(cyan),\n branch: c(dim),\n backward: c(magenta),\n applied: c(cyan),\n pending: c(yellow),\n unreachable: c(magenta),\n node: c(cyan),\n label: c(dim),\n marker: c(bold),\n ref: (index: number) => c(REF_COLORS[index % REF_COLORS.length]!),\n };\n}\n\n/** Map a `colorHint` value to its color function, or `undefined` for no hint. */\nfunction resolveHintColor(hint: GraphEdge['colorHint'], colors: GraphColors): ColorFn | undefined {\n if (hint === 'applied') return colors.applied;\n if (hint === 'pending') return colors.pending;\n if (hint === 'unreachable') return colors.unreachable;\n return undefined;\n}\n\n/**\n * Edge drawing priorities — higher priority wins when edges overlap on the\n * same grid cell. Backward edges are drawn on top so rollback paths remain\n * visible over spine and branch edges.\n */\nconst PRIORITY = {\n branch: 1,\n spine: 2,\n backward: 3,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Direction bitmask → box-drawing character\n//\n// Each grid cell accumulates a bitmask of connected directions (UP, DOWN,\n// LEFT, RIGHT). The bitmask is then mapped to the appropriate Unicode\n// box-drawing character. For example, UP|RIGHT → └, all four → ┼.\n// ---------------------------------------------------------------------------\n\nconst DIR = {\n up: 1,\n down: 2,\n left: 4,\n right: 8,\n dashed: 16,\n} as const;\n\n/** Arrow characters for edge termination (one cell before the target node). */\nconst ARROW = { up: '▴', down: '▾', left: '◂', right: '▸' };\n\n/** Maps a direction bitmask to its box-drawing character. */\nconst BOX_CHAR: Record<number, string> = {\n 0: ' ',\n [DIR.up]: '│',\n [DIR.down]: '│',\n [DIR.up | DIR.down]: '│',\n [DIR.left]: '─',\n [DIR.right]: '─',\n [DIR.left | DIR.right]: '─',\n [DIR.down | DIR.right]: '┌',\n [DIR.down | DIR.left]: '┐',\n [DIR.up | DIR.right]: '└',\n [DIR.up | DIR.left]: '┘',\n [DIR.up | DIR.down | DIR.right]: '├',\n [DIR.up | DIR.down | DIR.left]: '┤',\n [DIR.left | DIR.right | DIR.down]: '┬',\n [DIR.left | DIR.right | DIR.up]: '┴',\n [DIR.up | DIR.down | DIR.left | DIR.right]: '┼',\n // Dashed variants — straight segments only, corners fall back to solid\n [DIR.up | DIR.dashed]: '┊',\n [DIR.down | DIR.dashed]: '┊',\n [DIR.up | DIR.down | DIR.dashed]: '┊',\n [DIR.left | DIR.dashed]: '┈',\n [DIR.right | DIR.dashed]: '┈',\n [DIR.left | DIR.right | DIR.dashed]: '┈',\n};\n\n// ---------------------------------------------------------------------------\n// Inline marker tags\n//\n// Markers (db, contract, ref, custom) are rendered inline after the node id:\n// ○ abc1234 ◆ db prod\n// ---------------------------------------------------------------------------\n\n/** A single rendered tag: the display text and the color function to apply. */\ninterface InlineTag {\n text: string;\n color: ColorFn;\n}\n\n/**\n * Convert a node's markers into renderable inline tags.\n *\n * - `db` → `◆ db`\n * - `contract` → `◆ contract` (applied) or `◇ contract` (planned)\n * - `ref` → the ref name, colored from the rotating {@link REF_COLORS} palette\n * - `custom` → the custom label\n */\nfunction buildInlineTags(markers: readonly NodeMarker[], colors: GraphColors): InlineTag[] {\n const tags: InlineTag[] = [];\n const refNames = markers\n .filter((m): m is NodeMarker & { kind: 'ref' } => m.kind === 'ref')\n .map((m) => m.name);\n\n for (const m of markers) {\n if (m.kind === 'db') {\n tags.push({ text: '◆ db', color: colors.marker });\n } else if (m.kind === 'contract') {\n tags.push({ text: m.planned ? '◆ contract' : '◇ contract', color: colors.marker });\n } else if (m.kind === 'ref') {\n tags.push({ text: m.name, color: colors.ref(refNames.indexOf(m.name)) });\n } else if (m.kind === 'custom') {\n tags.push({ text: m.label, color: colors.marker });\n }\n }\n return tags;\n}\n\n/** Total character width of inline tags including leading spaces (0 if no tags). */\nfunction inlineTagsWidth(tags: InlineTag[]): number {\n if (tags.length === 0) return 0;\n return tags.reduce((w, t) => w + 1 + t.text.length, 0);\n}\n\n// ---------------------------------------------------------------------------\n// Character grid with color priority\n//\n// The grid is the central rendering canvas. It supports two layers:\n//\n// 1. **Connections** — direction bitmasks at (x, y) cells, resolved to\n// box-drawing characters at render time. When multiple edges cross the\n// same cell, their direction bits are OR'd together (e.g. UP|RIGHT → └).\n// Color follows a priority system so higher-priority edges (backward >\n// spine > branch) visually dominate at intersections.\n//\n// 2. **Text stamps** — literal characters placed at (x, y), such as node\n// ids, labels, arrowheads, and markers. Text stamps override connections\n// at the same position.\n//\n// The grid also tracks **reserved areas** (node label regions) so that\n// label-placement heuristics can avoid overlapping node text.\n// ---------------------------------------------------------------------------\n\n/** Tracks the winning color for a grid cell based on edge priority. */\ninterface CellColor {\n color: ColorFn | undefined;\n priority: number;\n}\n\n/**\n * Sparse character canvas for terminal graph rendering.\n *\n * Coordinates are unbounded integers — the grid auto-expands as content is\n * added and trims to the bounding box on {@link render}.\n */\nclass CharGrid {\n private connections = new Map<string, number>();\n private cellColors = new Map<string, CellColor>();\n private chars = new Map<string, { ch: string; color: ColorFn | undefined }>();\n private reserved = new Set<string>();\n private minX = Number.POSITIVE_INFINITY;\n private maxX = Number.NEGATIVE_INFINITY;\n private minY = Number.POSITIVE_INFINITY;\n private maxY = Number.NEGATIVE_INFINITY;\n\n private key(x: number, y: number): string {\n return `${x},${y}`;\n }\n\n /** Expand the bounding box to include (x, y). */\n private touch(x: number, y: number): void {\n if (x < this.minX) this.minX = x;\n if (x > this.maxX) this.maxX = x;\n if (y < this.minY) this.minY = y;\n if (y > this.maxY) this.maxY = y;\n }\n\n /**\n * Add a directional connection at (x, y). Multiple calls at the same cell\n * are OR'd together — e.g. `addConnection(x, y, UP)` then\n * `addConnection(x, y, RIGHT)` produces a └ corner. Color follows\n * priority: higher-priority edges win at shared cells.\n */\n addConnection(\n x: number,\n y: number,\n dir: number,\n color?: ColorFn,\n priority: number = PRIORITY.branch,\n ): void {\n this.touch(x, y);\n const k = this.key(x, y);\n this.connections.set(k, (this.connections.get(k) ?? 0) | dir);\n const existing = this.cellColors.get(k);\n if (!existing || priority >= existing.priority) {\n this.cellColors.set(k, { color, priority });\n }\n }\n\n /** Stamp a horizontal edge segment from x1 to x2 at row y. */\n markHorizontal(\n y: number,\n x1: number,\n x2: number,\n color?: ColorFn,\n priority?: number,\n extraBits = 0,\n ): void {\n const lo = Math.min(x1, x2);\n const hi = Math.max(x1, x2);\n /* v8 ignore next -- @preserve */\n if (lo === hi) return;\n this.addConnection(lo, y, DIR.right | extraBits, color, priority);\n for (let x = lo + 1; x < hi; x++)\n this.addConnection(x, y, DIR.left | DIR.right | extraBits, color, priority);\n this.addConnection(hi, y, DIR.left | extraBits, color, priority);\n }\n\n /** Stamp a vertical edge segment from y1 to y2 at column x. */\n markVertical(\n x: number,\n y1: number,\n y2: number,\n color?: ColorFn,\n priority?: number,\n extraBits = 0,\n ): void {\n const lo = Math.min(y1, y2);\n const hi = Math.max(y1, y2);\n /* v8 ignore next -- @preserve */\n if (lo === hi) return;\n this.addConnection(x, lo, DIR.down | extraBits, color, priority);\n for (let y = lo + 1; y < hi; y++)\n this.addConnection(x, y, DIR.up | DIR.down | extraBits, color, priority);\n this.addConnection(x, hi, DIR.up | extraBits, color, priority);\n }\n\n /** Place literal text at (x, y). Each character occupies one cell. Text stamps override connections. */\n stampText(x: number, y: number, text: string, color?: ColorFn): void {\n for (let i = 0; i < text.length; i++) {\n const cx = x + i;\n this.touch(cx, y);\n this.chars.set(this.key(cx, y), { ch: text[i]!, color });\n }\n }\n\n /** True if (x, y) has stamped text or is in a reserved area (node labels). */\n hasLabel(x: number, y: number): boolean {\n return this.chars.has(this.key(x, y)) || this.reserved.has(this.key(x, y));\n }\n\n /** True if (x, y) has any directional connection (an edge passes through). */\n hasConnection(x: number, y: number): boolean {\n return (this.connections.get(this.key(x, y)) ?? 0) !== 0;\n }\n\n /** True if (x, y) has stamped text (not just a reserved area). */\n hasText(x: number, y: number): boolean {\n return this.chars.has(this.key(x, y));\n }\n\n /** Reserve a horizontal span so label placement avoids it. Used for node id + marker regions. */\n reserveArea(x: number, y: number, width: number): void {\n for (let i = 0; i < width; i++) this.reserved.add(this.key(x + i, y));\n }\n\n /** The largest y coordinate with content — used for positioning detached nodes below the graph. */\n getMaxY(): number {\n return this.maxY;\n }\n\n /**\n * Render the grid to a multi-line string.\n *\n * Iterates row by row over the bounding box, resolving each cell to either\n * its stamped text character or the box-drawing character for its\n * connection bitmask. Consecutive characters with the same color are\n * batched into a single ANSI-wrapped run for efficiency.\n */\n render(): string {\n /* v8 ignore next -- @preserve */\n if (this.minX === Number.POSITIVE_INFINITY) return '(empty)';\n\n const rows: string[] = [];\n for (let y = this.minY; y <= this.maxY; y++) {\n let row = '';\n let runChars = '';\n let runColor: ColorFn | undefined;\n\n const flush = () => {\n if (runChars.length === 0) return;\n row += runColor ? runColor(runChars) : runChars;\n runChars = '';\n };\n\n for (let x = this.minX; x <= this.maxX; x++) {\n const k = this.key(x, y);\n let ch: string;\n let color: ColorFn | undefined;\n\n const label = this.chars.get(k);\n if (label) {\n ch = label.ch;\n color = label.color;\n } else {\n const conn = this.connections.get(k) ?? 0;\n // Dashed corners don't exist — strip the bit and fall back to solid\n ch = BOX_CHAR[conn] ?? BOX_CHAR[conn & ~DIR.dashed] ?? ' ';\n color = conn === 0 ? undefined : this.cellColors.get(k)?.color;\n }\n\n if (color !== runColor) {\n flush();\n runColor = color;\n }\n runChars += ch;\n }\n flush();\n rows.push(row.trimEnd());\n }\n\n while (rows.length > 0 && rows[rows.length - 1] === '') rows.pop();\n return rows.join('\\n');\n }\n}\n\n// ---------------------------------------------------------------------------\n// Spine detection — BFS shortest path from root to target\n//\n// The renderer operates on generic GraphNode/GraphEdge, not MigrationGraph,\n// so it cannot use domain-specific pathfinding. These two BFS functions\n// re-derive the spine from the generic edge list.\n// ---------------------------------------------------------------------------\n\n/**\n * Find the set of edge keys (`\"from→to\"`) on the shortest path from\n * `rootId` to `targetId`. Used to color spine edges distinctly from\n * branch edges in the rendered output.\n *\n * Returns an empty set if no path exists.\n */\nfunction findSpineEdges(graph: RenderGraph, rootId: string, targetId: string): Set<string> {\n const visited = new Set([rootId]);\n const parent = new Map<string, GraphEdge>();\n const queue = [rootId];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current === targetId) {\n const spineEdges = new Set<string>();\n let node = targetId;\n while (parent.has(node)) {\n const edge = parent.get(node)!;\n spineEdges.add(`${edge.from}→${edge.to}`);\n node = edge.from;\n }\n return spineEdges;\n }\n for (const edge of graph.outgoing(current)) {\n if (!visited.has(edge.to)) {\n visited.add(edge.to);\n parent.set(edge.to, edge);\n queue.push(edge.to);\n }\n }\n }\n return new Set();\n}\n\n// ---------------------------------------------------------------------------\n// Orthogonal polyline builder — variant-based\n//\n// Dagre produces polyline control points that may contain diagonal segments\n// (two consecutive points that differ in both x and y). Terminal rendering\n// requires strictly orthogonal segments (horizontal or vertical only).\n//\n// To resolve diagonals, we insert an L-shaped bend at each one. Each diagonal\n// has two possible resolutions (horizontal-first or vertical-first), so N\n// diagonals produce 2^N candidate polylines. We enumerate all variants and\n// pick the one with the fewest corners and shortest total length.\n// ---------------------------------------------------------------------------\n\n/**\n * Prepend `src` and append `tgt` to dagre's control points, round to\n * integers, and deduplicate consecutive identical points.\n */\nfunction prepareRawPoints(src: Point, dagrePoints: Point[], tgt: Point): Point[] {\n const raw = [src, ...dagrePoints, tgt];\n const rounded = raw.map((p) => ({ x: Math.round(p.x), y: Math.round(p.y) }));\n const deduped: Point[] = [rounded[0]!];\n for (let i = 1; i < rounded.length; i++) {\n const prev = deduped[deduped.length - 1]!;\n const curr = rounded[i]!;\n if (curr.x !== prev.x || curr.y !== prev.y) deduped.push(curr);\n }\n return deduped;\n}\n\nfunction countDiagonals(points: Point[]): number {\n let count = 0;\n for (let i = 1; i < points.length; i++) {\n const prev = points[i - 1]!;\n const curr = points[i]!;\n if (prev.x !== curr.x && prev.y !== curr.y) count++;\n }\n return count;\n}\n\ntype BendDirection = 'horizontal-first' | 'vertical-first';\n\n/**\n * Decode a bitmask into an array of bend directions.\n *\n * Each bit selects how one diagonal is converted to an orthogonal corner:\n * 0 → horizontal-first, 1 → vertical-first. Used by {@link selectBestVariant}\n * to enumerate all 2^N combinations.\n */\nfunction bitsToBends(bits: number, count: number): BendDirection[] {\n const bends: BendDirection[] = [];\n for (let k = 0; k < count; k++) {\n bends.push((bits >> k) & 1 ? 'vertical-first' : 'horizontal-first');\n }\n return bends;\n}\n\n/**\n * Build one polyline variant by resolving each diagonal with the given bend direction.\n *\n * Diagonals are detected inline: when the last emitted point and the next\n * input point differ in both x and y, the segment is diagonal and is\n * resolved using the next value from `bends`. The result is deduplicated\n * to remove zero-length segments created when a bend coincides with an\n * adjacent point.\n */\nfunction buildVariant(points: Point[], bends: BendDirection[]): Point[] {\n /* v8 ignore next -- @preserve */\n if (points.length < 2) return points;\n\n let bendIdx = 0;\n const result: Point[] = [points[0]!];\n for (let i = 1; i < points.length; i++) {\n const prev = result[result.length - 1]!;\n const curr = points[i]!;\n\n if (prev.x === curr.x || prev.y === curr.y) {\n result.push(curr);\n } else {\n const bend = bends[bendIdx++] ?? 'horizontal-first';\n if (bend === 'horizontal-first') {\n result.push({ x: curr.x, y: prev.y });\n } else {\n result.push({ x: prev.x, y: curr.y });\n }\n result.push(curr);\n }\n }\n\n const final: Point[] = [result[0]!];\n for (let i = 1; i < result.length; i++) {\n const prev = final[final.length - 1]!;\n const curr = result[i]!;\n if (curr.x !== prev.x || curr.y !== prev.y) final.push(curr);\n }\n return final;\n}\n\n/** Count the number of direction changes (corners) in an orthogonal polyline. */\nfunction countCorners(poly: Point[]): number {\n let corners = 0;\n for (let i = 1; i < poly.length - 1; i++) {\n const a = poly[i - 1]!;\n const b = poly[i]!;\n const c = poly[i + 1]!;\n const d1Vert = a.x === b.x;\n const d2Vert = b.x === c.x;\n if (d1Vert !== d2Vert) corners++;\n }\n return corners;\n}\n\n/** Manhattan length of a polyline (sum of absolute x and y deltas). */\nfunction polyLength(poly: Point[]): number {\n let len = 0;\n for (let i = 0; i < poly.length - 1; i++) {\n len += Math.abs(poly[i + 1]!.x - poly[i]!.x) + Math.abs(poly[i + 1]!.y - poly[i]!.y);\n }\n return len;\n}\n\n// ---------------------------------------------------------------------------\n// Label placement\n//\n// Edge labels (migration names) are placed adjacent to polyline segments.\n// The algorithm generates candidate positions along each segment, scores\n// them, and picks the best. Key heuristics:\n//\n// - **Horizontal segment preference**: when a polyline has both vertical and\n// horizontal segments, horizontal segments are boosted because they\n// uniquely identify a branch, while vertical segments often share column\n// space with the trunk. This prevents labels from \"jumping\" when node\n// widths change.\n// - **Source adjacency penalty**: positions within ±1 row of the source node\n// are penalized — labels there look like they belong to an incoming edge.\n// - **Whitespace bonus**: positions with clear space above and below score\n// higher for readability.\n// ---------------------------------------------------------------------------\n\n/**\n * Find the best (x, y) position to place an edge label adjacent to its\n * polyline. Returns null if no collision-free position exists.\n *\n * @param poly - The orthogonalized polyline for the edge.\n * @param label - The label text to place.\n * @param grid - The character grid (used for collision checks).\n * @param srcY - Y coordinate of the source node (for adjacency penalty).\n */\nfunction findLabelPlacement(\n poly: Point[],\n label: string,\n grid: CharGrid,\n srcY?: number,\n): Point | undefined {\n const segments = polyToSegments(poly);\n\n let best: (Point & { score: number }) | undefined;\n\n for (const seg of segments) {\n const candidates = segmentLabelCandidates(seg, label.length);\n for (const pos of candidates) {\n if (labelCollides(grid, pos.x, pos.y, label)) continue;\n const score = scoreLabelCandidate(pos, seg, segments, label, grid, srcY);\n if (!best || score > best.score) best = { x: pos.x, y: pos.y, score };\n }\n }\n\n return best;\n}\n\n/** Convert a polyline into non-zero-length segments. */\nfunction polyToSegments(poly: readonly Point[]): Segment[] {\n const segments: Segment[] = [];\n for (let i = 0; i < poly.length - 1; i++) {\n const seg = segment(poly[i]!, poly[i + 1]!);\n if (manhattanLength(seg) > 0) segments.push(seg);\n }\n return segments;\n}\n\n/**\n * Generate all candidate (x, y) positions for placing a label adjacent\n * to a single segment. Positions are perpendicular to the segment:\n *\n * - Vertical segments: left and right, at every y along the segment.\n * - Horizontal segments: above and below, at every x where the label fits.\n */\nfunction segmentLabelCandidates(seg: Segment, labelLen: number): Point[] {\n const candidates: Point[] = [];\n\n if (isVertical(seg)) {\n const minY = Math.min(seg.from.y, seg.to.y);\n const maxY = Math.max(seg.from.y, seg.to.y);\n for (const x of [seg.from.x + 2, seg.from.x - labelLen - 1]) {\n for (let y = minY; y <= maxY; y++) {\n candidates.push({ x, y });\n }\n }\n } else {\n const minX = Math.min(seg.from.x, seg.to.x);\n const maxX = Math.max(seg.from.x, seg.to.x);\n for (const dy of [-1, 1]) {\n const y = seg.from.y + dy;\n for (let x = minX; x <= maxX - labelLen + 1; x++) {\n candidates.push({ x, y });\n }\n }\n }\n\n return candidates;\n}\n\n/**\n * Score a candidate label position. Higher is better.\n *\n * Combines: segment length, surrounding whitespace, distance from\n * segment midpoint, source-node proximity penalty, and segment-position\n * bonus (horizontal/later segments preferred when the edge has bends).\n *\n * @param pos - Candidate position (top-left corner of the label text).\n * @param seg - The segment this candidate is adjacent to.\n * @param allSegments - All segments of the edge polyline (for segment-position bonus).\n * @param label - The label text (used for width and whitespace probing).\n * @param grid - The character grid (used for whitespace checks).\n * @param srcY - Y coordinate of the edge's source node (penalizes labels\n * that would appear to belong to the node rather than the edge).\n */\nfunction scoreLabelCandidate(\n pos: Point,\n seg: Segment,\n allSegments: readonly Segment[],\n label: string,\n grid: CharGrid,\n srcY?: number,\n): number {\n const len = manhattanLength(seg);\n const midX = Math.round((seg.from.x + seg.to.x) / 2);\n const midY = Math.round((seg.from.y + seg.to.y) / 2);\n\n let score = len;\n\n // Whitespace above/below the label improves readability.\n for (let dy = 1; dy <= 2; dy++) {\n if (!rowHasContent(grid, pos.x, pos.y - dy, label.length)) score += 3;\n if (!rowHasContent(grid, pos.x, pos.y + dy, label.length)) score += 3;\n }\n\n // Prefer positions near the segment midpoint.\n const labelCenterX = pos.x + Math.floor(label.length / 2);\n score -= (Math.abs(labelCenterX - midX) + Math.abs(pos.y - midY)) * 2;\n\n const labelCenterY = pos.y + Math.floor(label.length / 2);\n score -= (Math.abs(labelCenterY - midY) + Math.abs(pos.x - midX)) * 2;\n\n // Prefer labels to the right of a vertical segment\n if (isVertical(seg) && pos.x > seg.from.x) {\n score += 10;\n }\n\n // Penalize positions adjacent to the source node — labels there\n // look like they belong to the incoming edge above.\n if (srcY !== undefined && Math.abs(pos.y - srcY) <= 1) score -= 20;\n\n // Horizontal segments uniquely identify a branch, while the initial\n // vertical drop from the source often shares column space with the trunk.\n // Boost horizontal and later segments so labels land on the branch.\n const hasHorizontalSeg = allSegments.some((s) => !isVertical(s));\n if (hasHorizontalSeg) {\n if (!isVertical(seg)) score += 15;\n const segIndex = allSegments.indexOf(seg);\n score += (segIndex / allSegments.length) * 5;\n }\n\n return score;\n}\n\n/** True if any cell in the horizontal span [x, x+width) at row y has content. */\nfunction rowHasContent(grid: CharGrid, x: number, y: number, width: number): boolean {\n for (let i = 0; i < width; i++) {\n if (grid.hasLabel(x + i, y) || grid.hasConnection(x + i, y)) return true;\n }\n return false;\n}\n\n/**\n * Check if placing `text` at (x, y) would collide with existing content.\n * Checks one cell of padding on each side to keep labels visually separated.\n */\nfunction labelCollides(grid: CharGrid, x: number, y: number, text: string): boolean {\n for (let i = -1; i <= text.length; i++) {\n const cx = x + i;\n if (grid.hasLabel(cx, y)) return true;\n if (i >= 0 && i < text.length && grid.hasConnection(cx, y)) return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Joint variant selection\n//\n// Combines diagonal resolution with label placement in a single pass. For\n// each of the 2^N polyline variants, we compute a score based on corner\n// count, total length, and whether the label can be placed. The variant\n// with the lowest score wins.\n// ---------------------------------------------------------------------------\n\n/** A resolved polyline paired with its best label position (if any). */\ninterface PolyWithLabel {\n poly: Point[];\n labelPos: Point | undefined;\n}\n\n/**\n * Resolve dagre's polyline into the best orthogonal variant and find the\n * optimal label position in a single pass.\n *\n * Enumerates all 2^N diagonal resolutions, scores each by:\n * - `corners * 10` — fewer corners preferred\n * - `+ manhattan length` — shorter paths preferred\n * - `+ 100` penalty if the label couldn't be placed\n *\n * For edges with no diagonals, the polyline is used as-is.\n */\nfunction selectBestVariant(\n src: Point,\n dagrePoints: Point[],\n tgt: Point,\n label: string | undefined,\n grid: CharGrid,\n): PolyWithLabel {\n const rawPoints = prepareRawPoints(src, dagrePoints, tgt);\n const diagCount = countDiagonals(rawPoints);\n\n if (diagCount === 0) {\n const poly = buildVariant(rawPoints, []);\n const labelPos = label ? findLabelPlacement(poly, label, grid, src.y) : undefined;\n return { poly, labelPos };\n }\n\n // Each diagonal must be converted to an orthogonal corner — either\n // horizontal-first or vertical-first. With N diagonals that's 2^N\n // combinations, enumerated via bitmask: we count from 0 to 2^N - 1,\n // and every number represents a different combination of bend directions.\n const numVariants = 1 << diagCount;\n let bestPoly: Point[] | null = null;\n let bestLabel: Point | undefined;\n let bestScore = Number.POSITIVE_INFINITY;\n\n for (let bits = 0; bits < numVariants; bits++) {\n const bends = bitsToBends(bits, diagCount);\n const poly = buildVariant(rawPoints, bends);\n\n const corners = countCorners(poly);\n const len = polyLength(poly);\n const labelPos = label ? findLabelPlacement(poly, label, grid, src.y) : undefined;\n\n const labelPenalty = label && !labelPos ? 100 : 0;\n const score = corners * 10 + len + labelPenalty;\n\n if (score < bestScore) {\n bestScore = score;\n bestPoly = poly;\n bestLabel = labelPos;\n }\n }\n\n return {\n poly: bestPoly ?? buildVariant(rawPoints, bitsToBends(0, diagCount)),\n labelPos: bestLabel,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Subgraph extraction\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the subgraph containing only the nodes and forward-moving edges\n * along the given path.\n *\n * Backward (rollback) edges are excluded even if both endpoints are on the\n * path — only edges where `from` precedes `to` in path order are kept.\n */\nexport function extractSubgraph(graph: RenderGraph, path: readonly string[]): RenderGraph {\n const pathIndex = new Map(path.map((id, i) => [id, i]));\n const nodeSet = new Set(path);\n // Always keep dashed edges and their endpoints\n for (const e of graph.edges) {\n if (e.style === 'dashed') {\n nodeSet.add(e.from);\n nodeSet.add(e.to);\n }\n }\n const filteredNodes = graph.nodes.filter((n) => nodeSet.has(n.id));\n const filteredEdges = graph.edges.filter((e) => {\n if (e.style === 'dashed') return true;\n const fromIdx = pathIndex.get(e.from);\n const toIdx = pathIndex.get(e.to);\n return fromIdx !== undefined && toIdx !== undefined && fromIdx < toIdx;\n });\n return new RenderGraph(filteredNodes, filteredEdges);\n}\n\n/**\n * Extract the subgraph covering the union of multiple paths.\n *\n * Each path is an ordered list of node ids (root → target). The result\n * contains every node on any path plus every forward edge between\n * consecutive nodes on any path. Detached nodes are always included.\n *\n * When all paths overlap (the common case), the result is identical to\n * a single-path extract. When paths diverge (e.g. DB marker on a\n * different branch than the contract), the result naturally includes the\n * fork and both branches — exactly the minimal information needed.\n */\nexport function extractRelevantSubgraph(\n graph: RenderGraph,\n paths: readonly (readonly string[])[],\n): RenderGraph {\n const nodeSet = new Set<string>();\n const edgePairs = new Set<string>();\n\n for (const path of paths) {\n for (let i = 0; i < path.length; i++) {\n nodeSet.add(path[i]!);\n if (i > 0) {\n edgePairs.add(`${path[i - 1]!}\\0${path[i]!}`);\n }\n }\n }\n\n // Always keep dashed (draft) edges and their endpoints\n const dashedEdges = graph.edges.filter((e) => e.style === 'dashed');\n for (const e of dashedEdges) {\n nodeSet.add(e.from);\n nodeSet.add(e.to);\n }\n\n const filteredNodes = graph.nodes.filter((n) => nodeSet.has(n.id));\n const filteredEdges = graph.edges.filter(\n (e) => edgePairs.has(`${e.from}\\0${e.to}`) || e.style === 'dashed',\n );\n return new RenderGraph(filteredNodes, filteredEdges);\n}\n\n// ---------------------------------------------------------------------------\n// Truncation — keep last N spine edges, expand for markers\n// ---------------------------------------------------------------------------\n\n/** Result of {@link truncateGraph} — the visible subgraph plus truncation metadata. */\nexport interface TruncationResult {\n readonly graph: RenderGraph;\n /** Number of spine edges hidden by truncation (0 = nothing truncated). */\n readonly elidedCount: number;\n /** The visible portion of the spine (subset of the input spine). */\n readonly spine: readonly string[];\n}\n\n/**\n * Truncate a graph to the last `limit` spine edges from the spine target.\n * The window expands to include any node carrying a db or contract marker\n * so those are never truncated away.\n *\n * For the full graph: keeps all branches that fork from the visible spine window.\n * For the spine view: caller should call extractSubgraph first, then truncate.\n */\nexport function truncateGraph(\n graph: RenderGraph,\n spine: readonly string[],\n limit: number,\n): TruncationResult {\n if (spine.length <= 1 || limit >= spine.length - 1) {\n return { graph, elidedCount: 0, spine };\n }\n\n // Find the earliest spine node that has a db or contract marker\n let earliestMarkerIdx = spine.length;\n for (let i = 0; i < spine.length; i++) {\n const n = graph.nodeById.get(spine[i]!);\n if (n?.markers?.some((m) => m.kind === 'db' || m.kind === 'contract')) {\n earliestMarkerIdx = i;\n break;\n }\n }\n\n // Effective limit: expand to include markers\n // spine has N+1 nodes for N edges; we want the last `effectiveEdges` edges,\n // which means keeping the last `effectiveEdges + 1` nodes\n const markerDistance = spine.length - 1 - earliestMarkerIdx;\n const effectiveEdges = Math.max(limit, markerDistance);\n\n if (effectiveEdges >= spine.length - 1) {\n return { graph, elidedCount: 0, spine };\n }\n\n const keepFromIdx = spine.length - 1 - effectiveEdges;\n const truncatedSpine = spine.slice(keepFromIdx);\n const visibleSpineSet = new Set(truncatedSpine);\n\n // Include any node reachable from visible spine nodes\n // (branches that fork from visible portion)\n const reachable = new Set(visibleSpineSet);\n const queue = [...truncatedSpine];\n while (queue.length > 0) {\n const current = queue.shift()!;\n for (const edge of graph.outgoing(current)) {\n if (!reachable.has(edge.to)) {\n reachable.add(edge.to);\n queue.push(edge.to);\n }\n }\n }\n\n const truncatedNodes = graph.nodes.filter((n) => reachable.has(n.id));\n const truncatedEdges = graph.edges.filter((e) => reachable.has(e.from) && reachable.has(e.to));\n const elidedCount = spine.length - 1 - effectiveEdges;\n\n return {\n graph: new RenderGraph(truncatedNodes, truncatedEdges),\n elidedCount,\n spine: truncatedSpine,\n };\n}\n\n/**\n * After truncation the original root may not be in the visible graph.\n * Find the first node with no incoming edges as a fallback root.\n */\nfunction findVisibleRoot(graph: RenderGraph, layoutNodes: readonly GraphNode[]): string {\n return layoutNodes.find((n) => !graph.incomingNodes.has(n.id))?.id ?? layoutNodes[0]?.id ?? '∅';\n}\n\n// ---------------------------------------------------------------------------\n// Core layout + render pipeline\n// ---------------------------------------------------------------------------\n\n/**\n * The main rendering pipeline: dagre layout → edge stamping → label\n * placement → arrowheads → nodes → elided indicator → detached nodes.\n *\n * Called by {@link render} after optional truncation. Receives nodes/edges\n * and produces the final multi-line string.\n *\n * @param graph - The graph to render (may include detached nodes, which are\n * rendered below the main graph rather than laid out by dagre).\n * @param options - Render options (rootId, spineTarget, colorize).\n * @param elidedCount - If > 0, a `┊ (N earlier migrations)` indicator\n * is stamped above the visible root node.\n */\nfunction layoutAndRender(graph: RenderGraph, options: GraphRenderOptions, elidedCount = 0): string {\n const colorize = options.colorize ?? true;\n const colors = buildColors(colorize);\n\n const layoutNodes = graph.nodes;\n const layoutNodeIds = new Set(layoutNodes.map((n) => n.id));\n const requestedRoot = options.rootId ?? layoutNodes[0]?.id ?? '∅';\n const rootId = layoutNodeIds.has(requestedRoot)\n ? requestedRoot\n : findVisibleRoot(graph, layoutNodes);\n\n const spineEdgeKeys = findSpineEdges(graph, rootId, options.spineTarget);\n\n const g = new dagre.graphlib.Graph({ multigraph: true });\n const dagreDefaults = { ranksep: 4, nodesep: 6, marginx: 2, marginy: 1 };\n g.setGraph({ rankdir: 'TB', ...dagreDefaults, ...options.dagreOptions });\n g.setDefaultEdgeLabel(() => ({}));\n\n for (const node of layoutNodes) {\n const tags = buildInlineTags(node.markers ?? [], colors);\n const tagWidth = inlineTagsWidth(tags);\n g.setNode(node.id, { width: node.id.length + 6 + tagWidth, height: 1 });\n }\n\n const edgeNames: string[] = [];\n for (let i = 0; i < graph.edges.length; i++) {\n const edge = graph.edges[i]!;\n const name = `e${i}`;\n edgeNames.push(name);\n g.setEdge(edge.from, edge.to, { label: edge.label ?? '' }, name);\n }\n\n dagre.layout(g);\n\n const nodePos = new Map<string, Point>();\n for (const id of g.nodes()) {\n const n = g.node(id);\n nodePos.set(id, { x: Math.round(n.x), y: Math.round(n.y) });\n }\n\n const grid = new CharGrid();\n\n // Reserve node label areas so edges and labels avoid them\n for (const node of layoutNodes) {\n const pos = nodePos.get(node.id);\n /* v8 ignore next -- @preserve */\n if (!pos) continue;\n const tags = buildInlineTags(node.markers ?? [], colors);\n const tagWidth = inlineTagsWidth(tags);\n grid.reserveArea(pos.x - 1, pos.y, node.id.length + 4 + tagWidth);\n }\n\n // --- Prepare edge metadata ---\n type EdgeEntry = {\n idx: number;\n edge: GraphEdge;\n dagrePoints: Point[];\n src: Point;\n tgt: Point;\n role: 'spine' | 'branch' | 'backward';\n edgeColor: ColorFn;\n priority: number;\n };\n const edgeEntries: EdgeEntry[] = [];\n\n for (let i = 0; i < graph.edges.length; i++) {\n const edge = graph.edges[i]!;\n const name = edgeNames[i]!;\n if (!name || !nodePos.has(edge.from) || !nodePos.has(edge.to)) continue;\n\n const src = nodePos.get(edge.from)!;\n const tgt = nodePos.get(edge.to)!;\n const dagreEdge = g.edge({ v: edge.from, w: edge.to, name });\n const dagrePoints: Point[] = dagreEdge?.points ?? [];\n\n const isBackward = tgt.y < src.y;\n const isSpine = spineEdgeKeys.has(`${edge.from}→${edge.to}`);\n const role: EdgeEntry['role'] = isBackward ? 'backward' : isSpine ? 'spine' : 'branch';\n const hintColor = resolveHintColor(edge.colorHint, colors);\n const edgeColor =\n hintColor ??\n (role === 'backward' ? colors.backward : role === 'spine' ? colors.spine : colors.branch);\n const priority =\n role === 'backward' ? PRIORITY.backward : role === 'spine' ? PRIORITY.spine : PRIORITY.branch;\n\n edgeEntries.push({ idx: i, edge, dagrePoints, src, tgt, role, edgeColor, priority });\n }\n\n // --- Pass 1: Draw all edges ---\n type DrawnEdge = { edge: GraphEdge; poly: Point[]; role: EdgeEntry['role']; srcY: number };\n const drawnEdges: DrawnEdge[] = [];\n\n for (const entry of edgeEntries) {\n const { edge, dagrePoints, src, tgt, edgeColor, priority } = entry;\n\n const { poly } = selectBestVariant(src, dagrePoints, tgt, edge.label, grid);\n\n const dashedBit = edge.style === 'dashed' ? DIR.dashed : 0;\n for (let j = 0; j < poly.length - 1; j++) {\n const a = poly[j]!;\n const b = poly[j + 1]!;\n if (a.y === b.y) {\n grid.markHorizontal(a.y, a.x, b.x, edgeColor, priority, dashedBit);\n } else if (a.x === b.x) {\n grid.markVertical(a.x, a.y, b.y, edgeColor, priority, dashedBit);\n }\n }\n\n drawnEdges.push({ edge, poly, role: entry.role, srcY: src.y });\n }\n\n // --- Pass 2: Place labels (longest first) ---\n const labelOrder = [...drawnEdges]\n .map((de, i) => ({ ...de, i }))\n .filter((de) => de.edge.label)\n .sort((a, b) => (b.edge.label?.length ?? 0) - (a.edge.label?.length ?? 0));\n\n for (const { edge, poly, role, srcY } of labelOrder) {\n /* v8 ignore next -- @preserve */\n if (!edge.label) continue;\n const labelPos = findLabelPlacement(poly, edge.label, grid, srcY);\n if (labelPos) {\n const labelColor =\n resolveHintColor(edge.colorHint, colors) ??\n (role === 'backward' ? colors.backward : role === 'spine' ? colors.spine : colors.label);\n grid.stampText(labelPos.x, labelPos.y, edge.label, labelColor);\n }\n }\n\n // --- Pass 3: Arrowheads ---\n for (const { edge, poly, role } of drawnEdges) {\n /* v8 ignore next -- @preserve */\n if (poly.length < 2) continue;\n const last = poly[poly.length - 1]!;\n const prev = poly[poly.length - 2]!;\n\n const edgeColor =\n resolveHintColor(edge.colorHint, colors) ??\n (role === 'backward' ? colors.backward : role === 'spine' ? colors.spine : colors.branch);\n\n let ax: number | undefined;\n let ay: number | undefined;\n let arrow: string | undefined;\n\n if (prev.x === last.x) {\n if (last.y > prev.y) {\n ax = last.x;\n ay = last.y - 1;\n arrow = ARROW.down;\n } else {\n ax = last.x;\n ay = last.y + 1;\n arrow = ARROW.up;\n }\n } else {\n if (last.x > prev.x) {\n ax = last.x - 1;\n ay = last.y;\n arrow = ARROW.right;\n } else {\n ax = last.x + 1;\n ay = last.y;\n arrow = ARROW.left;\n }\n }\n\n if (ax !== undefined && ay !== undefined && arrow && !grid.hasText(ax, ay)) {\n grid.stampText(ax, ay, arrow, edgeColor);\n }\n }\n\n // --- Draw nodes ---\n const spineNodeIds = new Set<string>();\n for (const key of spineEdgeKeys) {\n const [from, to] = key.split('→');\n if (from) spineNodeIds.add(from);\n if (to) spineNodeIds.add(to);\n }\n\n for (const node of layoutNodes) {\n const pos = nodePos.get(node.id);\n if (!pos) continue;\n\n const isSpineNode = spineNodeIds.has(node.id);\n const nodeColor = isSpineNode ? colors.spine : colors.branch;\n\n grid.stampText(pos.x, pos.y, '○', nodeColor);\n grid.stampText(pos.x + 1, pos.y, ' ');\n const hasMarkers = node.markers && node.markers.length > 0;\n grid.stampText(pos.x + 2, pos.y, node.id, isSpineNode || hasMarkers ? bold : dim);\n\n const tags = buildInlineTags(node.markers ?? [], colors);\n if (tags.length > 0) {\n let bx = pos.x + 2 + node.id.length;\n for (const tag of tags) {\n grid.stampText(bx, pos.y, ' ');\n bx++;\n grid.stampText(bx, pos.y, tag.text, tag.color);\n bx += tag.text.length;\n }\n }\n }\n\n // --- Elided indicator above root ---\n if (elidedCount > 0) {\n const topNodeId =\n layoutNodes.find((n) => !graph.incomingNodes.has(n.id))?.id ?? layoutNodes[0]?.id;\n const rootPos = topNodeId ? nodePos.get(topNodeId) : undefined;\n if (rootPos) {\n const label = elidedCount === 1 ? '1 earlier migration' : `${elidedCount} earlier migrations`;\n const topY = rootPos.y - 3;\n grid.stampText(rootPos.x, topY, '┊', colors.label);\n grid.stampText(rootPos.x, topY + 1, '┊', colors.label);\n grid.stampText(rootPos.x + 2, topY + 1, `(${label})`, colors.label);\n grid.stampText(rootPos.x, topY + 2, '┊', colors.label);\n }\n }\n\n return grid.render();\n}\n\n// ---------------------------------------------------------------------------\n// GraphRenderer implementation\n// ---------------------------------------------------------------------------\n\n/**\n * BFS to find the ordered node path from `rootId` to `targetId`.\n * Used for truncation — the spine path determines which edges to keep.\n *\n * Returns `[rootId]` if no path exists.\n */\nfunction findSpinePath(graph: RenderGraph, rootId: string, targetId: string): string[] {\n const visited = new Set([rootId]);\n const parent = new Map<string, string>();\n const queue = [rootId];\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current === targetId) {\n const path: string[] = [];\n let node = targetId;\n while (node !== rootId) {\n path.unshift(node);\n node = parent.get(node)!;\n }\n path.unshift(rootId);\n return path;\n }\n for (const edge of graph.outgoing(current)) {\n if (!visited.has(edge.to)) {\n visited.add(edge.to);\n parent.set(edge.to, current);\n queue.push(edge.to);\n }\n }\n }\n return [rootId];\n}\n\n/**\n * Render a graph with optional truncation.\n *\n * The caller decides what to pass in: the full graph for `--graph`, or a\n * subgraph extracted via {@link extractRelevantSubgraph} for the default view.\n */\nfunction render(graph: RenderGraph, options: GraphRenderOptions): string {\n if (options.limit !== undefined) {\n const spine = findSpinePath(\n graph,\n options.rootId ?? graph.nodes[0]?.id ?? '∅',\n options.spineTarget,\n );\n const { graph: truncated, elidedCount } = truncateGraph(graph, spine, options.limit);\n return layoutAndRender(truncated, options, elidedCount);\n }\n return layoutAndRender(graph, options);\n}\n\nexport interface GraphRenderer {\n render(graph: RenderGraph, options: GraphRenderOptions): string;\n}\n\nexport const graphRenderer: GraphRenderer = {\n render,\n};\n\n/** True if the graph is a single linear chain (no branching), ignoring dashed edges. */\nexport function isLinearGraph(graph: RenderGraph): boolean {\n for (const node of graph.nodes) {\n const solidOutgoing = graph.outgoing(node.id).filter((e) => e.style !== 'dashed');\n if (solidOutgoing.length > 1) return false;\n }\n return true;\n}\n","import type { MigrationPlanOperation } from '@prisma-next/framework-components/control';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport {\n findPath,\n findPathWithDecision,\n findReachableLeaves,\n} from '@prisma-next/migration-tools/dag';\nimport type { Refs } from '@prisma-next/migration-tools/refs';\nimport { readRefs, resolveRef } from '@prisma-next/migration-tools/refs';\nimport type {\n MigrationBundle,\n MigrationChainEntry,\n MigrationGraph,\n} from '@prisma-next/migration-tools/types';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { cyan, dim, magenta, yellow } from 'colorette';\nimport { Command } from 'commander';\n\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport { type CliStructuredError, errorRuntime, errorUnexpected } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n loadAllBundles,\n maskConnectionUrl,\n readContractEnvelope,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n toPathDecisionResult,\n} from '../utils/command-helpers';\nimport {\n type EdgeStatus,\n type EdgeStatusKind,\n migrationGraphToRenderInput,\n} from '../utils/formatters/graph-migration-mapper';\nimport {\n extractRelevantSubgraph,\n graphRenderer,\n isLinearGraph,\n} from '../utils/formatters/graph-render';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport type { StatusDiagnostic, StatusRef } from '../utils/migration-types';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationStatusOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly ref?: string;\n readonly graph?: boolean;\n readonly limit?: string;\n readonly all?: boolean;\n}\n\nexport interface MigrationStatusEntry {\n readonly dirName: string;\n readonly from: string;\n readonly to: string;\n readonly migrationId: string;\n readonly operationCount: number;\n readonly operationSummary: string;\n readonly hasDestructive: boolean;\n readonly status: EdgeStatusKind | 'unknown';\n}\n\nexport type { StatusDiagnostic, StatusRef } from '../utils/migration-types';\n\nexport interface MigrationStatusResult {\n readonly ok: true;\n readonly mode: 'online' | 'offline';\n readonly migrations: readonly MigrationStatusEntry[];\n readonly markerHash?: string;\n readonly targetHash: string;\n readonly contractHash: string;\n readonly refs?: readonly StatusRef[];\n readonly pathDecision?: {\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n readonly selectedPath: readonly {\n readonly dirName: string;\n readonly migrationId: string;\n readonly from: string;\n readonly to: string;\n }[];\n };\n readonly summary: string;\n readonly diagnostics: readonly StatusDiagnostic[];\n readonly graph?: MigrationGraph;\n readonly bundles?: readonly MigrationBundle[];\n readonly edgeStatuses?: readonly EdgeStatus[];\n readonly activeRefHash?: string;\n readonly activeRefName?: string;\n readonly diverged?: boolean;\n}\n\nfunction summarizeOps(ops: readonly MigrationPlanOperation[]): {\n summary: string;\n hasDestructive: boolean;\n} {\n if (ops.length === 0) return { summary: '0 ops', hasDestructive: false };\n\n const classes = new Map<string, number>();\n for (const op of ops) {\n classes.set(op.operationClass, (classes.get(op.operationClass) ?? 0) + 1);\n }\n\n const hasDestructive = classes.has('destructive');\n const count = ops.length;\n const noun = count === 1 ? 'op' : 'ops';\n\n if (classes.size === 1) {\n const cls = [...classes.keys()][0]!;\n return { summary: `${count} ${noun} (all ${cls})`, hasDestructive };\n }\n\n const destructiveCount = classes.get('destructive');\n if (destructiveCount) {\n return { summary: `${count} ${noun} (${destructiveCount} destructive)`, hasDestructive };\n }\n\n const parts = [...classes.entries()].map(([cls, n]) => `${n} ${cls}`);\n return { summary: `${count} ${noun} (${parts.join(', ')})`, hasDestructive };\n}\n\n/**\n * Derive per-edge status across the full graph using path analysis.\n *\n * - **applied**: edge is on the path from root to the DB marker\n * - **pending**: edge is on the path from the DB marker to the target\n * (and the marker is reachable from root, i.e. it's on the same branch)\n * - **unreachable**: edge is on the path from root to the target but the DB\n * marker is on a different branch — `apply` can't reach these edges\n * without the DB first moving to this branch\n *\n * Returns statuses only for edges that have a known status (skips offline\n * and edges not on any relevant path).\n *\n * @internal Exported for testing only.\n */\nexport function deriveEdgeStatuses(\n graph: MigrationGraph,\n targetHash: string,\n contractHash: string,\n markerHash: string | undefined,\n mode: 'online' | 'offline',\n): EdgeStatus[] {\n if (mode === 'offline') return [];\n\n const edgeKey = (e: MigrationChainEntry) => `${e.from}\\0${e.to}`;\n\n // No marker = empty DB — treat root as the marker (nothing applied, everything pending)\n const effectiveMarker = markerHash ?? EMPTY_CONTRACT_HASH;\n\n const appliedPath =\n markerHash !== undefined ? findPath(graph, EMPTY_CONTRACT_HASH, markerHash) : null;\n\n const pendingPath = findPath(graph, effectiveMarker, targetHash);\n const targetPath = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n\n const statuses: EdgeStatus[] = [];\n const assignedKeys = new Set<string>();\n\n // Applied edges (root → marker)\n if (appliedPath) {\n for (const e of appliedPath) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'applied' });\n }\n }\n\n // Pending edges (marker → target)\n if (pendingPath) {\n for (const e of pendingPath) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'pending' });\n }\n }\n\n // Pending edges beyond the target: target → contract (when target is a ref\n // and the contract is reachable from it)\n if (\n contractHash !== EMPTY_CONTRACT_HASH &&\n contractHash !== targetHash &&\n graph.nodes.has(contractHash)\n ) {\n const beyondTarget = findPath(graph, targetHash, contractHash);\n if (beyondTarget) {\n for (const e of beyondTarget) {\n if (!assignedKeys.has(edgeKey(e))) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'pending' });\n }\n }\n }\n }\n\n // Unreachable edges: on the path from root to the target but neither applied\n // nor pending. This covers two cases:\n // 1. Marker can't reach target at all (different branch entirely)\n // 2. Marker reaches target via a different route, leaving some root→target\n // edges orphaned (e.g. a fork where one branch was applied and apply\n // will continue through the other)\n if (targetPath) {\n for (const e of targetPath) {\n if (!assignedKeys.has(edgeKey(e))) {\n statuses.push({ dirName: e.dirName, status: 'unreachable' });\n }\n }\n }\n\n return statuses;\n}\n\n/**\n * @param mode — 'online' if we connected to the database, 'offline' otherwise\n * @param markerHash — the marker hash from the database, or undefined if no marker row / offline\n */\nfunction buildMigrationEntries(\n chain: readonly MigrationChainEntry[],\n packages: readonly MigrationBundle[],\n mode: 'online' | 'offline',\n markerHash: string | undefined,\n edgeStatuses?: readonly EdgeStatus[],\n): MigrationStatusEntry[] {\n const pkgByDirName = new Map(packages.map((p) => [p.dirName, p]));\n const statusByDirName = edgeStatuses\n ? new Map(edgeStatuses.map((e) => [e.dirName, e.status]))\n : undefined;\n\n const markerInChain = markerHash === undefined || chain.some((e) => e.to === markerHash);\n\n const entries: MigrationStatusEntry[] = [];\n let reachedMarker = mode === 'online' && markerHash === undefined;\n\n for (const migration of chain) {\n const pkg = pkgByDirName.get(migration.dirName);\n const ops = (pkg?.ops ?? []) as readonly MigrationPlanOperation[];\n const { summary, hasDestructive } = summarizeOps(ops);\n\n let status: EdgeStatusKind | 'unknown';\n const edgeStatus = statusByDirName?.get(migration.dirName);\n if (edgeStatus) {\n status = edgeStatus;\n } else if (mode === 'offline' || !markerInChain) {\n status = 'unknown';\n } else if (reachedMarker) {\n status = 'pending';\n } else {\n status = 'applied';\n }\n\n entries.push({\n dirName: migration.dirName,\n from: migration.from,\n to: migration.to,\n migrationId: migration.migrationId,\n operationCount: ops.length,\n operationSummary: summary,\n hasDestructive,\n status,\n });\n\n if (!reachedMarker && migration.to === markerHash) {\n reachedMarker = true;\n }\n }\n\n return entries;\n}\n\n/**\n * Resolve the migration chain to display in status output.\n *\n * When offline or the marker is at EMPTY, the chain is simply the shortest\n * path from EMPTY to the target — all structural paths are equivalent per\n * the spec, so the deterministic shortest path is the canonical display.\n *\n * When online with a non-empty marker, the chain routes *through* the marker:\n * EMPTY→marker (applied history) + marker→target (pending edges). This ensures\n * the displayed chain includes the marker node so applied/pending status is\n * correct. Without this, BFS from EMPTY to target could pick a shortest path\n * that bypasses the marker entirely (e.g. in a diamond graph), causing the\n * marker to appear \"diverged\" when it isn't.\n */\nfunction resolveDisplayChain(\n graph: MigrationGraph,\n targetHash: string,\n markerHash: string | undefined,\n): readonly MigrationChainEntry[] | null {\n if (markerHash === undefined) {\n return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n }\n\n const toMarker = findPath(graph, EMPTY_CONTRACT_HASH, markerHash);\n // Marker unreachable from EMPTY — show the target chain anyway.\n // The caller detects this via markerInChain and emits a divergence diagnostic.\n if (!toMarker) return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n\n if (markerHash === targetHash) return toMarker;\n\n const fromMarker = findPath(graph, markerHash, targetHash);\n if (fromMarker) return [...toMarker, ...fromMarker];\n\n // Marker is ahead of target (or on a disconnected branch).\n // Try the inverse: target→marker. If it succeeds, the marker is ahead —\n // show the full chain from EMPTY through the target and on to the marker.\n const toTarget = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n if (!toTarget) return null;\n\n const targetToMarker = findPath(graph, targetHash, markerHash);\n if (targetToMarker) return [...toTarget, ...targetToMarker];\n\n // Genuinely disconnected — show EMPTY→target; caller handles divergence diagnostic.\n return toTarget;\n}\n\nconst DEFAULT_LIMIT = 10;\n\nfunction determineLimit(opts: MigrationStatusOptions) {\n if (opts.all) {\n // No limit\n return;\n }\n if (!opts.limit) {\n return DEFAULT_LIMIT;\n }\n const parsed = Number.parseInt(opts.limit, 10);\n if (Number.isNaN(parsed)) {\n return DEFAULT_LIMIT;\n }\n return parsed;\n}\n\nasync function executeMigrationStatusCommand(\n options: MigrationStatusOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<MigrationStatusResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, migrationsRelative, refsDir } = resolveMigrationPaths(\n options.config,\n config,\n );\n\n const dbConnection = options.db ?? config.db?.connection;\n const hasDriver = !!config.driver;\n\n let activeRefName: string | undefined;\n let activeRefHash: string | undefined;\n let allRefs: Refs = {};\n try {\n allRefs = await readRefs(refsDir);\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code },\n }),\n );\n }\n throw error;\n }\n\n if (options.ref) {\n activeRefName = options.ref;\n try {\n activeRefHash = resolveRef(allRefs, activeRefName).hash;\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code },\n }),\n );\n }\n throw error;\n }\n }\n\n const statusRefs: StatusRef[] = Object.entries(allRefs).map(([name, entry]) => ({\n name,\n hash: entry.hash,\n active: name === activeRefName,\n }));\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: migrationsRelative },\n ];\n if (dbConnection && hasDriver) {\n details.push({ label: 'database', value: maskConnectionUrl(String(dbConnection)) });\n }\n if (activeRefName) {\n details.push({ label: 'ref', value: activeRefName });\n }\n const header = formatStyledHeader({\n command: 'migration status',\n description: 'Show migration history and applied status',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n const diagnostics: StatusDiagnostic[] = [];\n let contractHash: string = EMPTY_CONTRACT_HASH;\n try {\n const envelope = await readContractEnvelope(config);\n contractHash = envelope.storageHash;\n } catch (error) {\n diagnostics.push({\n code: 'CONTRACT.UNREADABLE',\n severity: 'warn',\n message: `Could not read contract: ${error instanceof Error ? error.message : 'unknown error'}`,\n hints: [\"Run 'prisma-next contract emit' to generate a valid contract\"],\n });\n }\n\n let bundles: readonly MigrationBundle[];\n let graph: MigrationGraph;\n try {\n ({ bundles, graph } = await loadAllBundles(migrationsDir));\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, { why: error.why, fix: error.fix, meta: { code: error.code } }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n if (bundles.length === 0) {\n if (contractHash !== EMPTY_CONTRACT_HASH) {\n diagnostics.push({\n code: 'CONTRACT.AHEAD',\n severity: 'warn',\n message: 'No migration exists for the current contract',\n hints: [\n \"Run 'prisma-next migration plan' to generate a migration for the current contract\",\n ],\n });\n }\n return ok({\n ok: true,\n mode: dbConnection && hasDriver ? 'online' : 'offline',\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: 'No migrations found',\n diagnostics,\n });\n }\n\n let targetHash: string | undefined;\n\n if (activeRefHash) {\n targetHash = activeRefHash;\n } else if (graph.nodes.has(contractHash)) {\n targetHash = contractHash;\n } else {\n const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);\n if (leaves.length === 1) {\n targetHash = leaves[0];\n } else {\n diagnostics.push({\n code: 'MIGRATION.DIVERGED',\n severity: 'warn',\n message: 'There are multiple valid migration paths — you must select a target',\n hints: [\n \"Use '--ref <name>' to select a target\",\n \"Or 'prisma-next migration ref set <name> <hash>' to create one\",\n ],\n });\n }\n }\n\n let markerHash: string | undefined;\n let mode: 'online' | 'offline' = 'offline';\n\n if (dbConnection && hasDriver) {\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n try {\n await client.connect(dbConnection);\n markerHash = (await client.readMarker())?.storageHash;\n mode = 'online';\n } catch {\n if (!flags.json && !flags.quiet) {\n ui.warn('Could not connect to database — showing offline status');\n }\n } finally {\n await client.close();\n }\n }\n\n // Marker exists but is not in the migration graph and doesn't match the\n // contract hash. The DB is at an unknown state relative to the graph.\n // Bail out early with a clear diagnostic instead of rendering a confusing\n // graph with no statuses.\n //\n // When marker === contract (both off-graph), the DB matches the current\n // contract — proceed normally; the detached contract node will carry both\n // the db and contract markers.\n if (\n mode === 'online' &&\n markerHash !== undefined &&\n !graph.nodes.has(markerHash) &&\n markerHash !== contractHash\n ) {\n const hints: string[] = [];\n if (graph.nodes.has(contractHash)) {\n hints.push(\n \"Run 'prisma-next db sign' to overwrite the marker if the database already matches the contract\",\n \"Run 'prisma-next db update' to push the current contract to the database\",\n \"Run 'prisma-next contract infer' to make your contract match the database\",\n \"Run 'prisma-next db verify' to inspect the database state\",\n );\n } else {\n hints.push(\n \"Run 'prisma-next db update' to push the current contract to the database\",\n \"Run 'prisma-next contract infer' to make your contract match the database\",\n \"Run 'prisma-next db verify' to inspect the database state\",\n );\n }\n diagnostics.push({\n code: 'MIGRATION.MARKER_NOT_IN_HISTORY',\n severity: 'warn',\n message:\n 'Database was updated outside the migration system (marker does not match any migration)',\n hints,\n });\n return ok({\n ok: true,\n mode,\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: `${bundles.length} migration(s) on disk`,\n diagnostics,\n markerHash,\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n });\n }\n\n if (mode === 'online' && markerHash === undefined) {\n diagnostics.push({\n code: 'MIGRATION.NO_MARKER',\n severity: 'warn',\n message: 'Database has not been initialized — no migration marker found',\n hints: [\"Run 'prisma-next migration apply' to apply pending migrations\"],\n });\n }\n\n // Contract diagnostic — fires when no migration produces the current contract hash.\n // Suppressed when: (a) graph is diverged (MIGRATION.DIVERGED already guides the user),\n // (b) marker === contract and both off-graph (marker-not-in-graph diagnostic covers it).\n if (\n targetHash &&\n contractHash !== EMPTY_CONTRACT_HASH &&\n !graph.nodes.has(contractHash) &&\n markerHash !== contractHash\n ) {\n diagnostics.push({\n code: 'CONTRACT.AHEAD',\n severity: 'warn',\n message: 'Contract has changed since the last migration was planned',\n hints: [\"Run 'prisma-next migration plan' to generate a migration for the current contract\"],\n });\n }\n\n if (!targetHash) {\n return ok({\n ok: true,\n mode,\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: `${bundles.length} migration(s) on disk`,\n diagnostics,\n ...ifDefined('markerHash', markerHash),\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n graph,\n bundles,\n diverged: true,\n });\n }\n\n const chain = resolveDisplayChain(graph, targetHash, markerHash);\n\n if (!chain) {\n return notOk(\n errorRuntime('Cannot reconstruct migration history', {\n why: `No path from ${EMPTY_CONTRACT_HASH} to target ${targetHash}`,\n fix: 'The migration history may have gaps. Check the migrations directory for missing or corrupted packages.',\n }),\n );\n }\n\n const edgeStatuses = deriveEdgeStatuses(graph, targetHash, contractHash, markerHash, mode);\n const entries = buildMigrationEntries(chain, bundles, mode, markerHash, edgeStatuses);\n\n const pendingCount = edgeStatuses.filter((e) => e.status === 'pending').length;\n const appliedCount = edgeStatuses.filter((e) => e.status === 'applied').length;\n\n let summary: string;\n if (mode === 'online') {\n if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {\n summary = `${bundles.length} migration(s) on disk`;\n } else if (activeRefHash && markerHash !== undefined) {\n summary = summarizeRefDistance(graph, markerHash, activeRefHash, activeRefName!);\n } else if (pendingCount === 0) {\n summary = `Database is up to date (${appliedCount} migration${appliedCount !== 1 ? 's' : ''} applied)`;\n } else if (markerHash === undefined) {\n summary = `${pendingCount} pending migration(s) — database has no marker`;\n } else {\n summary = `${pendingCount} pending migration(s) — run 'prisma-next migration apply' to apply`;\n }\n } else {\n summary = `${entries.length} migration(s) on disk`;\n }\n\n if (mode === 'online') {\n if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {\n diagnostics.push({\n code: 'MIGRATION.MARKER_NOT_IN_HISTORY',\n severity: 'warn',\n message:\n 'Database matches the current contract but was updated directly (not via migration apply)',\n hints: [\"Run 'prisma-next migration plan' to plan a migration to your current contract\"],\n });\n } else if (pendingCount > 0) {\n diagnostics.push({\n code: 'MIGRATION.DATABASE_BEHIND',\n severity: 'info',\n message: `${pendingCount} migration(s) pending`,\n hints: [\"Run 'prisma-next migration apply' to apply pending migrations\"],\n });\n } else {\n diagnostics.push({\n code: 'MIGRATION.UP_TO_DATE',\n severity: 'info',\n message: 'Database is up to date',\n hints: [],\n });\n }\n }\n\n let pathDecision: MigrationStatusResult['pathDecision'];\n if (mode === 'online' && markerHash !== undefined) {\n const decision = findPathWithDecision(graph, markerHash, targetHash, activeRefName);\n if (decision) {\n pathDecision = toPathDecisionResult(decision);\n }\n }\n\n const result: MigrationStatusResult = {\n ok: true,\n mode,\n migrations: entries,\n targetHash,\n contractHash,\n summary,\n diagnostics,\n ...ifDefined('markerHash', markerHash),\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n ...ifDefined('pathDecision', pathDecision),\n graph,\n bundles,\n edgeStatuses,\n ...ifDefined('activeRefHash', activeRefHash),\n ...ifDefined('activeRefName', activeRefName),\n };\n return ok(result);\n}\n\nexport function createMigrationStatusCommand(): Command {\n const command = new Command('status');\n setCommandDescriptions(\n command,\n 'Show migration history and applied status',\n 'Displays the migration history in order. When a database connection\\n' +\n 'is available, shows which migrations are applied and which are pending.\\n' +\n 'Without a database connection, shows the history from disk only.',\n );\n setCommandExamples(command, [\n 'prisma-next migration status',\n 'prisma-next migration status --db $DATABASE_URL',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--ref <name>', 'Target ref name from migrations/refs/')\n .option('--graph', 'Show the full migration graph with all branches')\n .option('--limit <n>', 'Maximum number of migrations to display (default: 10)')\n .option('--all', 'Show full history (disables truncation)')\n .action(async (options: MigrationStatusOptions) => {\n const flags = parseGlobalFlags(options);\n\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n const result = await executeMigrationStatusCommand(options, flags, ui);\n\n const exitCode = handleResult(result, flags, ui, (statusResult) => {\n if (flags.json) {\n const {\n graph: _g,\n bundles: _b,\n edgeStatuses: _es,\n activeRefHash: _arh,\n activeRefName: _arn,\n diverged: _d,\n ...jsonResult\n } = statusResult;\n ui.output(JSON.stringify(jsonResult, null, 2));\n } else if (!flags.quiet) {\n const colorize = flags.color !== false;\n\n if (statusResult.graph) {\n const limit = determineLimit(options);\n const renderInput = migrationGraphToRenderInput({\n graph: statusResult.graph,\n mode: statusResult.mode,\n markerHash: statusResult.markerHash,\n contractHash: statusResult.contractHash,\n refs: statusResult.refs,\n activeRefHash: statusResult.activeRefHash,\n activeRefName: statusResult.activeRefName,\n edgeStatuses: statusResult.edgeStatuses,\n });\n\n const graphToRender =\n options.graph || statusResult.diverged\n ? renderInput.graph\n : extractRelevantSubgraph(renderInput.graph, renderInput.relevantPaths);\n const dagreOptions =\n !options.graph && isLinearGraph(graphToRender) ? { ranksep: 1 } : undefined;\n const renderOptions = {\n ...renderInput.options,\n colorize,\n ...ifDefined('limit', limit),\n ...ifDefined('dagreOptions', dagreOptions),\n };\n const graphOutput = graphRenderer.render(graphToRender, renderOptions);\n ui.log(graphOutput);\n if (statusResult.mode === 'online') {\n ui.log(formatLegend(colorize));\n }\n }\n ui.log('');\n ui.log(formatStatusSummary(statusResult, colorize));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n\nfunction formatLegend(colorize: boolean): string {\n const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);\n const parts = [\n `${c(cyan, '✓')} applied`,\n `${c(yellow, '⧗')} pending`,\n `${c(magenta, '✗')} unreachable`,\n ];\n return c(dim, parts.join(' '));\n}\n\nfunction formatStatusSummary(result: MigrationStatusResult, colorize: boolean): string {\n const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);\n const lines: string[] = [];\n\n const hasUnknown = result.migrations.some((e) => e.status === 'unknown');\n const pendingCount = result.migrations.filter((e) => e.status === 'pending').length;\n\n const hasWarnings = result.diagnostics?.some((d) => d.severity === 'warn') ?? false;\n\n if (result.mode === 'online') {\n if (hasUnknown || hasWarnings) {\n lines.push(`${c(yellow, '⚠')} ${result.summary}`);\n } else if (pendingCount === 0) {\n lines.push(`${c(cyan, '✔')} ${result.summary}`);\n } else {\n lines.push(`${c(yellow, '⧗')} ${result.summary}`);\n }\n } else {\n lines.push(result.summary);\n }\n\n const warnings = result.diagnostics?.filter((d) => d.severity === 'warn') ?? [];\n for (const diag of warnings) {\n lines.push(`${c(yellow, '⚠')} ${diag.message}`);\n for (const hint of diag.hints) {\n lines.push(` ${c(dim, hint)}`);\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction summarizeRefDistance(\n graph: MigrationGraph,\n markerHash: string,\n refHash: string,\n refName: string,\n): string {\n if (markerHash === refHash) return `At ref \"${refName}\" target`;\n\n const pathToRef = findPath(graph, markerHash, refHash);\n if (pathToRef) return `${pathToRef.length} migration(s) behind ref \"${refName}\"`;\n\n const pathFromRef = findPath(graph, refHash, markerHash);\n if (pathFromRef) return `${pathFromRef.length} migration(s) ahead of ref \"${refName}\"`;\n\n return `No path between database marker and ref \"${refName}\" target`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkDA,IAAa,cAAb,MAAyB;CACvB,AAAS;CACT,AAAS;;CAGT,AAAS;;CAET,AAAS;;CAET,AAAS;CAET,YAAY,OAA6B,OAA6B;AACpE,OAAK,QAAQ;AACb,OAAK,QAAQ;EAEb,MAAM,sBAAM,IAAI,KAA0B;EAC1C,MAAM,sBAAM,IAAI,KAAa;EAC7B,MAAM,uBAAO,IAAI,KAAwB;AAEzC,OAAK,MAAM,KAAK,MACd,MAAK,IAAI,EAAE,IAAI,EAAE;AAEnB,OAAK,MAAM,KAAK,OAAO;GACrB,MAAM,OAAO,IAAI,IAAI,EAAE,KAAK;AAC5B,OAAI,KAAM,MAAK,KAAK,EAAE;OACjB,KAAI,IAAI,EAAE,MAAM,CAAC,EAAE,CAAC;AACzB,OAAI,IAAI,EAAE,GAAG;;AAGf,OAAK,UAAU;AACf,OAAK,gBAAgB;AACrB,OAAK,WAAW;;;CAIlB,SAAS,QAAsC;AAC7C,SAAO,KAAK,QAAQ,IAAI,OAAO,IAAI,EAAE;;;;;;;;;ACnEzC,MAAMA,cAA8C;CAClD,SAAS;CACT,SAAS;CACT,aAAa;CACd;;AAGD,SAAS,UAAU,MAAsB;AAEvC,SADiB,KAAK,WAAW,UAAU,GAAG,KAAK,MAAM,EAA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I;AAE9E,KAAI,OAAO,SAAS,SAClB,KAAI,cAAc,YAChB,OAAM,KAAK,GAAG,EAAE,QAAQ,IAAI,CAAC,GAAG,OAAO,UAAU;UACxC,iBAAiB,EAC1B,OAAM,KAAK,GAAG,EAAE,MAAM,IAAI,CAAC,GAAG,OAAO,UAAU;KAE/C,OAAM,KAAK,GAAG,EAAE,QAAQ,IAAI,CAAC,GAAG,OAAO,UAAU;KAGnD,OAAM,KAAK,OAAO,QAAQ;CAG5B,MAAM,WAAW,OAAO,aAAa,QAAQ,MAAM,EAAE,aAAa,OAAO,IAAI,EAAE;AAC/E,MAAK,MAAM,QAAQ,UAAU;AAC3B,QAAM,KAAK,GAAG,EAAE,QAAQ,IAAI,CAAC,GAAG,KAAK,UAAU;AAC/C,OAAK,MAAM,QAAQ,KAAK,MACtB,OAAM,KAAK,KAAK,EAAE,KAAK,KAAK,GAAG;;AAInC,QAAO,MAAM,KAAK,KAAK;;AAGzB,SAAS,qBACP,OACA,YACA,SACA,SACQ;AACR,KAAI,eAAe,QAAS,QAAO,WAAW,QAAQ;CAEtD,MAAM,YAAY,SAAS,OAAO,YAAY,QAAQ;AACtD,KAAI,UAAW,QAAO,GAAG,UAAU,OAAO,4BAA4B,QAAQ;CAE9E,MAAM,cAAc,SAAS,OAAO,SAAS,WAAW;AACxD,KAAI,YAAa,QAAO,GAAG,YAAY,OAAO,8BAA8B,QAAQ;AAEpF,QAAO,4CAA4C,QAAQ"}
1
+ {"version":3,"file":"migration-status-DUMiH8_G.mjs","names":["STATUS_ICON: Record<EdgeStatusKind, string>","nodeList: GraphNode[]","markers: NodeMarker[]","edgeList: GraphEdge[]","relevantPaths: string[][]","spineTargetHash: string","contractMarkers: NodeMarker[]","REF_COLORS: ColorFn[]","BOX_CHAR: Record<number, string>","tags: InlineTag[]","rows: string[]","runColor: ColorFn | undefined","ch: string","color: ColorFn | undefined","deduped: Point[]","bends: BendDirection[]","result: Point[]","final: Point[]","best: (Point & { score: number }) | undefined","segments: Segment[]","candidates: Point[]","bestPoly: Point[] | null","bestLabel: Point | undefined","edgeNames: string[]","edgeEntries: EdgeEntry[]","dagrePoints: Point[]","role: EdgeEntry['role']","drawnEdges: DrawnEdge[]","ax: number | undefined","ay: number | undefined","arrow: string | undefined","path: string[]","graphRenderer: GraphRenderer","statuses: EdgeStatus[]","entries: MigrationStatusEntry[]","status: EdgeStatusKind | 'unknown'","activeRefName: string | undefined","activeRefHash: string | undefined","allRefs: Refs","statusRefs: StatusRef[]","details: Array<{ label: string; value: string }>","diagnostics: StatusDiagnostic[]","contractHash: string","bundles: readonly MigrationBundle[]","graph: MigrationGraph","targetHash: string | undefined","markerHash: string | undefined","mode: 'online' | 'offline'","hints: string[]","summary: string","pathDecision: MigrationStatusResult['pathDecision']","lines: string[]"],"sources":["../src/utils/formatters/graph-types.ts","../src/utils/formatters/graph-migration-mapper.ts","../src/utils/formatters/graph-render.ts","../src/commands/migration-status.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// Generic graph renderer types — domain-agnostic\n// ---------------------------------------------------------------------------\n\n/** A typed marker attached to a node. Different marker kinds get different visual treatment. */\nexport type NodeMarker =\n | { readonly kind: 'db' }\n | { readonly kind: 'ref'; readonly name: string; readonly active?: boolean }\n | { readonly kind: 'contract'; readonly planned: boolean }\n | { readonly kind: 'custom'; readonly label: string };\n\n/** A node in the graph. Rendered as ○ with optional typed markers. */\nexport interface GraphNode {\n readonly id: string;\n /** Typed markers rendered inline on the node row */\n readonly markers?: readonly NodeMarker[] | undefined;\n /** Detached nodes use a dashed connector (e.g. unplanned contract) */\n readonly style?: 'normal' | 'detached' | undefined;\n}\n\n/** A directed edge between two nodes. Carries an optional label rendered on the edge line. */\nexport interface GraphEdge {\n readonly from: string;\n readonly to: string;\n /** Edge line text, e.g. \"20260101_init ✓ abc12..\" */\n readonly label?: string;\n /**\n * Visual color hint for the edge. Overrides the default role-based\n * coloring (spine/branch/backward) when set.\n *\n * - `'applied'` — cyan (CVD-safe: completed/done)\n * - `'pending'` — yellow (CVD-safe: waiting/upcoming)\n * - `'unreachable'` — magenta (CVD-safe: DB on a different branch)\n */\n readonly colorHint?: 'applied' | 'pending' | 'unreachable';\n /**\n * Edge rendering style.\n * - `'solid'` (default) — normal edge with `│` connector\n * - `'dashed'` — draft/phantom edge with `┊` connector, excluded from path resolution\n */\n readonly style?: 'solid' | 'dashed';\n}\n\n/**\n * Immutable directed graph with adjacency-list indexing.\n *\n * Built once from flat arrays of nodes and edges, then passed around as\n * the primary graph representation for rendering, traversal, truncation,\n * and subgraph extraction.\n */\nexport class RenderGraph {\n readonly nodes: readonly GraphNode[];\n readonly edges: readonly GraphEdge[];\n\n /** Forward adjacency: node id → outgoing edges. */\n readonly forward: ReadonlyMap<string, readonly GraphEdge[]>;\n /** Set of node ids that have at least one incoming edge. */\n readonly incomingNodes: ReadonlySet<string>;\n /** Node lookup by id. */\n readonly nodeById: ReadonlyMap<string, GraphNode>;\n\n constructor(nodes: readonly GraphNode[], edges: readonly GraphEdge[]) {\n this.nodes = nodes;\n this.edges = edges;\n\n const fwd = new Map<string, GraphEdge[]>();\n const inc = new Set<string>();\n const byId = new Map<string, GraphNode>();\n\n for (const n of nodes) {\n byId.set(n.id, n);\n }\n for (const e of edges) {\n const list = fwd.get(e.from);\n if (list) list.push(e);\n else fwd.set(e.from, [e]);\n inc.add(e.to);\n }\n\n this.forward = fwd;\n this.incomingNodes = inc;\n this.nodeById = byId;\n }\n\n /** Outgoing edges from a node (empty array if none). */\n outgoing(nodeId: string): readonly GraphEdge[] {\n return this.forward.get(nodeId) ?? [];\n }\n}\n\n/** Options controlling graph rendering. */\nexport interface GraphRenderOptions {\n /** Node id for the spine endpoint */\n readonly spineTarget: string;\n /** Root node id. Defaults to the node with no incoming edges. */\n readonly rootId?: string;\n /** Enable ANSI colour output */\n readonly colorize?: boolean;\n /** Terminal width. Default 80. */\n readonly maxWidth?: number;\n /**\n * Truncate to show at most this many spine edges. `undefined` = no truncation.\n * The effective limit expands to include any DB or contract markers on the spine.\n */\n readonly limit?: number | undefined;\n /**\n * Override dagre layout parameters. Merged over defaults:\n * `{ ranksep: 4, nodesep: 6, marginx: 2, marginy: 1 }`.\n *\n * When `ranksep` is ≤ 1, labels are placed inline on the arrowhead row\n * instead of in a separate label-placement pass (there isn't enough\n * vertical space for a dedicated label row).\n */\n readonly dagreOptions?: {\n readonly ranksep?: number;\n readonly nodesep?: number;\n readonly marginx?: number;\n readonly marginy?: number;\n };\n}\n","/**\n * Maps MigrationGraph + status info to the generic graph renderer types.\n */\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { findPath } from '@prisma-next/migration-tools/dag';\nimport type { MigrationGraph } from '@prisma-next/migration-tools/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\nimport type { StatusRef } from '../migration-types';\nimport {\n type GraphEdge,\n type GraphNode,\n type GraphRenderOptions,\n type NodeMarker,\n RenderGraph,\n} from './graph-types';\n\nexport type EdgeStatusKind = 'applied' | 'pending' | 'unreachable';\n\nconst STATUS_ICON: Record<EdgeStatusKind, string> = {\n applied: ' ✓',\n pending: ' ⧗',\n unreachable: ' ✗',\n};\n\n/** Shorten a contract hash for display: strip sha256: prefix, take 7 chars. */\nfunction shortHash(hash: string): string {\n const stripped = hash.startsWith('sha256:') ? hash.slice(7) : hash;\n return stripped.slice(0, 7);\n}\n\nfunction toShortId(hash: string): string {\n return hash === EMPTY_CONTRACT_HASH ? '∅' : shortHash(hash);\n}\n\n/** Minimal per-edge status from the CLI's status result. */\nexport interface EdgeStatus {\n readonly dirName: string;\n readonly status: EdgeStatusKind;\n}\n\nexport interface MigrationGraphInput {\n readonly graph: MigrationGraph;\n readonly mode: 'online' | 'offline';\n readonly markerHash?: string | undefined;\n readonly contractHash: string;\n readonly refs?: readonly StatusRef[] | undefined;\n readonly activeRefHash?: string | undefined;\n readonly activeRefName?: string | undefined;\n /**\n * Per-edge applied/pending status from the ledger. When provided, status\n * icons (✓/⧗) are baked into edge labels. Undefined in offline mode.\n */\n readonly edgeStatuses?: readonly EdgeStatus[] | undefined;\n}\n\nexport interface MigrationRenderInput {\n readonly graph: RenderGraph;\n readonly options: GraphRenderOptions;\n /** All relevant paths (root→contract, root→marker, root→ref). */\n readonly relevantPaths: readonly (readonly string[])[];\n}\n\n/**\n * Convert a MigrationGraph + status info into the generic graph renderer types.\n */\nexport function migrationGraphToRenderInput(input: MigrationGraphInput): MigrationRenderInput {\n const { graph, mode, markerHash, contractHash, refs, activeRefHash, edgeStatuses } = input;\n\n const statusByDirName = new Map(edgeStatuses?.map((e) => [e.dirName, e.status]));\n\n // Build nodes\n const nodeList: GraphNode[] = [];\n for (const nodeId of graph.nodes) {\n const markers: NodeMarker[] = [];\n\n // DB marker\n if (mode === 'online' && markerHash === nodeId) {\n markers.push({ kind: 'db' });\n }\n\n // Ref markers\n if (refs) {\n for (const ref of refs) {\n if (ref.hash === nodeId) {\n markers.push({ kind: 'ref', name: ref.name, active: ref.active });\n }\n }\n }\n\n // Contract marker\n if (contractHash === nodeId && contractHash !== EMPTY_CONTRACT_HASH) {\n markers.push({ kind: 'contract', planned: true });\n }\n\n nodeList.push({\n id: toShortId(nodeId),\n markers: markers.length > 0 ? markers : undefined,\n });\n }\n\n // Build edges\n const edgeList: GraphEdge[] = [];\n\n for (const [, entries] of graph.forwardChain) {\n for (const entry of entries) {\n const status = statusByDirName.get(entry.dirName);\n const icon = status ? STATUS_ICON[status] : '';\n const label = `${entry.dirName}${icon}`;\n\n edgeList.push({\n from: toShortId(entry.from),\n to: toShortId(entry.to),\n label,\n ...ifDefined('colorHint', status),\n });\n }\n }\n\n // Compute paths to all interesting targets so the default view shows the\n // minimal subgraph that covers everything relevant: contract, DB marker, ref.\n const relevantPaths: string[][] = [];\n const rootId = EMPTY_CONTRACT_HASH;\n\n function addPathFromRoot(targetHash: string): void {\n if (!graph.nodes.has(targetHash)) return;\n const raw = findPath(graph, rootId, targetHash);\n if (raw && raw.length > 0) {\n relevantPaths.push([toShortId(rootId), ...raw.map((e) => toShortId(e.to))]);\n }\n }\n\n function addPathBetween(fromHash: string, toHash: string): void {\n /* v8 ignore next -- @preserve */\n if (!graph.nodes.has(fromHash) || !graph.nodes.has(toHash)) return;\n const raw = findPath(graph, fromHash, toHash);\n if (raw && raw.length > 0) {\n relevantPaths.push([toShortId(fromHash), ...raw.map((e) => toShortId(e.to))]);\n }\n }\n\n // 1. Path to the DB marker\n if (mode === 'online' && markerHash) {\n addPathFromRoot(markerHash);\n }\n\n // 2. Path to the ref\n if (activeRefHash && activeRefHash !== markerHash) {\n addPathFromRoot(activeRefHash);\n }\n\n // 3. Path(s) to the contract — prefer continuing from marker and/or ref\n // rather than an independent root→contract (which BFS may route through\n // an unrelated branch). When both marker and ref exist, try both paths\n // so that the diamond (two branches converging at the contract) is visible.\n if (contractHash !== EMPTY_CONTRACT_HASH) {\n let contractReached = false;\n\n if (markerHash && markerHash !== contractHash) {\n const markerReaches = findPath(graph, markerHash, contractHash);\n if (markerReaches) {\n addPathBetween(markerHash, contractHash);\n contractReached = true;\n }\n }\n\n if (activeRefHash && activeRefHash !== markerHash && activeRefHash !== contractHash) {\n const refReaches = findPath(graph, activeRefHash, contractHash);\n if (refReaches) {\n addPathBetween(activeRefHash, contractHash);\n contractReached = true;\n }\n }\n\n if (!contractReached && contractHash !== (markerHash ?? activeRefHash)) {\n addPathFromRoot(contractHash);\n }\n }\n\n // Fall back: if no paths were found, try the tip of the forward chain.\n if (relevantPaths.length === 0) {\n const lastEdge = [...graph.forwardChain.values()].flat().pop();\n const fallbackHash = lastEdge?.to ?? EMPTY_CONTRACT_HASH;\n addPathFromRoot(fallbackHash);\n }\n\n // Spine target for rendering (edge coloring, detached node alignment).\n let spineTargetHash: string;\n\n if (activeRefHash && graph.nodes.has(activeRefHash)) {\n spineTargetHash = activeRefHash;\n } else if (contractHash !== EMPTY_CONTRACT_HASH && graph.nodes.has(contractHash)) {\n spineTargetHash = contractHash;\n } else {\n const lastEdge = [...graph.forwardChain.values()].flat().pop();\n spineTargetHash = lastEdge?.to ?? EMPTY_CONTRACT_HASH;\n }\n\n // Contract not in the migration graph — connect from spine target with a\n // dashed edge so the user can see the gap (contract has changed but no\n // migration has been planned yet).\n if (contractHash !== EMPTY_CONTRACT_HASH && !graph.nodes.has(contractHash)) {\n const contractMarkers: NodeMarker[] = [];\n if (mode === 'online' && markerHash === contractHash) {\n contractMarkers.push({ kind: 'db' });\n }\n contractMarkers.push({ kind: 'contract', planned: false });\n nodeList.push({\n id: shortHash(contractHash),\n markers: contractMarkers,\n });\n\n if (graph.nodes.has(spineTargetHash) || spineTargetHash === EMPTY_CONTRACT_HASH) {\n edgeList.push({\n from: toShortId(spineTargetHash),\n to: shortHash(contractHash),\n style: 'dashed',\n });\n }\n }\n\n return {\n graph: new RenderGraph(nodeList, edgeList),\n options: {\n spineTarget: toShortId(spineTargetHash),\n rootId: '∅',\n colorize: true,\n },\n relevantPaths,\n };\n}\n","/**\n * Terminal graph renderer.\n *\n * Renders directed graphs as ASCII/box-drawing art for terminal output. Uses\n * dagre for automatic layout (rank assignment + coordinate placement), then\n * stamps the result onto a {@link CharGrid} — a sparse character canvas that\n * resolves box-drawing junctions, color priority, and label placement.\n *\n * ## Rendering pipeline\n *\n * 1. **Layout** — dagre assigns (x, y) coordinates to nodes and polyline\n * control points to edges. We use `rankdir: 'TB'` (top-to-bottom).\n * 2. **Orthogonalization** — dagre's polylines may contain diagonal segments.\n * {@link selectBestVariant} resolves each diagonal into an L-shaped bend,\n * enumerating all 2^N combinations and picking the variant with fewest\n * corners and shortest total length.\n * 3. **Edge stamping** — orthogonal segments are stamped onto the CharGrid as\n * directional bitmasks. The grid resolves overlapping directions into the\n * correct box-drawing character (│, ─, ┌, ┼, etc.).\n * 4. **Label placement** — edge labels are placed adjacent to their polyline\n * segments, preferring horizontal (branch-specific) segments over shared\n * vertical trunks to avoid ambiguity.\n * 5. **Arrowheads** — ▾ ▴ ◂ ▸ placed one cell before the terminal point.\n * 6. **Node stamping** — `○ nodeId` with inline marker tags (db, contract,\n * ref names).\n * 7. **Elided indicator** — when truncation is active, `┊ (N earlier\n * migrations)` is stamped above the visible root.\n * 8. **Detached nodes** — rendered below the graph with `◇` and a dotted\n * connector.\n *\n * ## Graph filtering\n *\n * The caller controls what graph is rendered: the full graph, or a subgraph\n * extracted via {@link extractRelevantSubgraph} (union of relevant paths).\n * The renderer itself is agnostic — it renders whatever graph it receives.\n *\n * Truncation is supported via `options.limit`.\n *\n * ## Color accessibility\n *\n * Uses a CVD-safe palette — no red/green contrast. Shape and icon always\n * carry meaning; color only reinforces.\n */\nimport dagre from '@dagrejs/dagre';\nimport { bold, cyan, dim, magenta, yellow } from 'colorette';\nimport {\n type GraphEdge,\n type GraphNode,\n type GraphRenderOptions,\n type NodeMarker,\n RenderGraph,\n} from './graph-types';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** A 2D point on the character grid (integer coordinates). */\ninterface Point {\n x: number;\n y: number;\n}\n\n/** An orthogonal line segment between two points on the character grid. */\ninterface Segment {\n readonly from: Point;\n readonly to: Point;\n}\n\nfunction segment(from: Point, to: Point): Segment {\n return { from, to };\n}\n\nfunction isVertical(seg: Segment): boolean {\n return seg.from.x === seg.to.x;\n}\n\nfunction manhattanLength(seg: Segment): number {\n return Math.abs(seg.to.x - seg.from.x) + Math.abs(seg.to.y - seg.from.y);\n}\n\n/** A function that wraps a string with an ANSI color escape sequence. */\ntype ColorFn = (s: string) => string;\n\n// ---------------------------------------------------------------------------\n// CVD-safe color palette\n//\n// No red/green contrast. Shape/icon always carries meaning; color reinforces.\n// ---------------------------------------------------------------------------\n\n/** Color functions for each semantic role in the graph. */\ninterface GraphColors {\n spine: ColorFn;\n branch: ColorFn;\n backward: ColorFn;\n applied: ColorFn;\n pending: ColorFn;\n unreachable: ColorFn;\n node: ColorFn;\n label: ColorFn;\n marker: ColorFn;\n /** Rotating color for ref markers — cycles through the palette by index. */\n ref: (index: number) => ColorFn;\n}\n\n/** Rotating palette for ref marker names, cycling through these for each ref. */\nconst REF_COLORS: ColorFn[] = [yellow, magenta, bold, cyan];\n\n/** Build the color palette, respecting the `colorize` flag. When false, all color functions become identity. */\nfunction buildColors(colorize: boolean): GraphColors {\n const c = (fn: ColorFn): ColorFn => (colorize ? fn : (s) => s);\n return {\n spine: c(cyan),\n branch: c(dim),\n backward: c(magenta),\n applied: c(cyan),\n pending: c(yellow),\n unreachable: c(magenta),\n node: c(cyan),\n label: c(dim),\n marker: c(bold),\n ref: (index: number) => c(REF_COLORS[index % REF_COLORS.length]!),\n };\n}\n\n/** Map a `colorHint` value to its color function, or `undefined` for no hint. */\nfunction resolveHintColor(hint: GraphEdge['colorHint'], colors: GraphColors): ColorFn | undefined {\n if (hint === 'applied') return colors.applied;\n if (hint === 'pending') return colors.pending;\n if (hint === 'unreachable') return colors.unreachable;\n return undefined;\n}\n\n/**\n * Edge drawing priorities — higher priority wins when edges overlap on the\n * same grid cell. Backward edges are drawn on top so rollback paths remain\n * visible over spine and branch edges.\n */\nconst PRIORITY = {\n branch: 1,\n spine: 2,\n backward: 3,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Direction bitmask → box-drawing character\n//\n// Each grid cell accumulates a bitmask of connected directions (UP, DOWN,\n// LEFT, RIGHT). The bitmask is then mapped to the appropriate Unicode\n// box-drawing character. For example, UP|RIGHT → └, all four → ┼.\n// ---------------------------------------------------------------------------\n\nconst DIR = {\n up: 1,\n down: 2,\n left: 4,\n right: 8,\n dashed: 16,\n} as const;\n\n/** Arrow characters for edge termination (one cell before the target node). */\nconst ARROW = { up: '▴', down: '▾', left: '◂', right: '▸' };\n\n/** Maps a direction bitmask to its box-drawing character. */\nconst BOX_CHAR: Record<number, string> = {\n 0: ' ',\n [DIR.up]: '│',\n [DIR.down]: '│',\n [DIR.up | DIR.down]: '│',\n [DIR.left]: '─',\n [DIR.right]: '─',\n [DIR.left | DIR.right]: '─',\n [DIR.down | DIR.right]: '┌',\n [DIR.down | DIR.left]: '┐',\n [DIR.up | DIR.right]: '└',\n [DIR.up | DIR.left]: '┘',\n [DIR.up | DIR.down | DIR.right]: '├',\n [DIR.up | DIR.down | DIR.left]: '┤',\n [DIR.left | DIR.right | DIR.down]: '┬',\n [DIR.left | DIR.right | DIR.up]: '┴',\n [DIR.up | DIR.down | DIR.left | DIR.right]: '┼',\n // Dashed variants — straight segments only, corners fall back to solid\n [DIR.up | DIR.dashed]: '┊',\n [DIR.down | DIR.dashed]: '┊',\n [DIR.up | DIR.down | DIR.dashed]: '┊',\n [DIR.left | DIR.dashed]: '┈',\n [DIR.right | DIR.dashed]: '┈',\n [DIR.left | DIR.right | DIR.dashed]: '┈',\n};\n\n// ---------------------------------------------------------------------------\n// Inline marker tags\n//\n// Markers (db, contract, ref, custom) are rendered inline after the node id:\n// ○ abc1234 ◆ db prod\n// ---------------------------------------------------------------------------\n\n/** A single rendered tag: the display text and the color function to apply. */\ninterface InlineTag {\n text: string;\n color: ColorFn;\n}\n\n/**\n * Convert a node's markers into renderable inline tags.\n *\n * - `db` → `◆ db`\n * - `contract` → `◆ contract` (applied) or `◇ contract` (planned)\n * - `ref` → the ref name, colored from the rotating {@link REF_COLORS} palette\n * - `custom` → the custom label\n */\nfunction buildInlineTags(markers: readonly NodeMarker[], colors: GraphColors): InlineTag[] {\n const tags: InlineTag[] = [];\n const refNames = markers\n .filter((m): m is NodeMarker & { kind: 'ref' } => m.kind === 'ref')\n .map((m) => m.name);\n\n for (const m of markers) {\n if (m.kind === 'db') {\n tags.push({ text: '◆ db', color: colors.marker });\n } else if (m.kind === 'contract') {\n tags.push({ text: m.planned ? '◆ contract' : '◇ contract', color: colors.marker });\n } else if (m.kind === 'ref') {\n tags.push({ text: m.name, color: colors.ref(refNames.indexOf(m.name)) });\n } else if (m.kind === 'custom') {\n tags.push({ text: m.label, color: colors.marker });\n }\n }\n return tags;\n}\n\n/** Total character width of inline tags including leading spaces (0 if no tags). */\nfunction inlineTagsWidth(tags: InlineTag[]): number {\n if (tags.length === 0) return 0;\n return tags.reduce((w, t) => w + 1 + t.text.length, 0);\n}\n\n// ---------------------------------------------------------------------------\n// Character grid with color priority\n//\n// The grid is the central rendering canvas. It supports two layers:\n//\n// 1. **Connections** — direction bitmasks at (x, y) cells, resolved to\n// box-drawing characters at render time. When multiple edges cross the\n// same cell, their direction bits are OR'd together (e.g. UP|RIGHT → └).\n// Color follows a priority system so higher-priority edges (backward >\n// spine > branch) visually dominate at intersections.\n//\n// 2. **Text stamps** — literal characters placed at (x, y), such as node\n// ids, labels, arrowheads, and markers. Text stamps override connections\n// at the same position.\n//\n// The grid also tracks **reserved areas** (node label regions) so that\n// label-placement heuristics can avoid overlapping node text.\n// ---------------------------------------------------------------------------\n\n/** Tracks the winning color for a grid cell based on edge priority. */\ninterface CellColor {\n color: ColorFn | undefined;\n priority: number;\n}\n\n/**\n * Sparse character canvas for terminal graph rendering.\n *\n * Coordinates are unbounded integers — the grid auto-expands as content is\n * added and trims to the bounding box on {@link render}.\n */\nclass CharGrid {\n private connections = new Map<string, number>();\n private cellColors = new Map<string, CellColor>();\n private chars = new Map<string, { ch: string; color: ColorFn | undefined }>();\n private reserved = new Set<string>();\n private minX = Number.POSITIVE_INFINITY;\n private maxX = Number.NEGATIVE_INFINITY;\n private minY = Number.POSITIVE_INFINITY;\n private maxY = Number.NEGATIVE_INFINITY;\n\n private key(x: number, y: number): string {\n return `${x},${y}`;\n }\n\n /** Expand the bounding box to include (x, y). */\n private touch(x: number, y: number): void {\n if (x < this.minX) this.minX = x;\n if (x > this.maxX) this.maxX = x;\n if (y < this.minY) this.minY = y;\n if (y > this.maxY) this.maxY = y;\n }\n\n /**\n * Add a directional connection at (x, y). Multiple calls at the same cell\n * are OR'd together — e.g. `addConnection(x, y, UP)` then\n * `addConnection(x, y, RIGHT)` produces a └ corner. Color follows\n * priority: higher-priority edges win at shared cells.\n */\n addConnection(\n x: number,\n y: number,\n dir: number,\n color?: ColorFn,\n priority: number = PRIORITY.branch,\n ): void {\n this.touch(x, y);\n const k = this.key(x, y);\n this.connections.set(k, (this.connections.get(k) ?? 0) | dir);\n const existing = this.cellColors.get(k);\n if (!existing || priority >= existing.priority) {\n this.cellColors.set(k, { color, priority });\n }\n }\n\n /** Stamp a horizontal edge segment from x1 to x2 at row y. */\n markHorizontal(\n y: number,\n x1: number,\n x2: number,\n color?: ColorFn,\n priority?: number,\n extraBits = 0,\n ): void {\n const lo = Math.min(x1, x2);\n const hi = Math.max(x1, x2);\n /* v8 ignore next -- @preserve */\n if (lo === hi) return;\n this.addConnection(lo, y, DIR.right | extraBits, color, priority);\n for (let x = lo + 1; x < hi; x++)\n this.addConnection(x, y, DIR.left | DIR.right | extraBits, color, priority);\n this.addConnection(hi, y, DIR.left | extraBits, color, priority);\n }\n\n /** Stamp a vertical edge segment from y1 to y2 at column x. */\n markVertical(\n x: number,\n y1: number,\n y2: number,\n color?: ColorFn,\n priority?: number,\n extraBits = 0,\n ): void {\n const lo = Math.min(y1, y2);\n const hi = Math.max(y1, y2);\n /* v8 ignore next -- @preserve */\n if (lo === hi) return;\n this.addConnection(x, lo, DIR.down | extraBits, color, priority);\n for (let y = lo + 1; y < hi; y++)\n this.addConnection(x, y, DIR.up | DIR.down | extraBits, color, priority);\n this.addConnection(x, hi, DIR.up | extraBits, color, priority);\n }\n\n /** Place literal text at (x, y). Each character occupies one cell. Text stamps override connections. */\n stampText(x: number, y: number, text: string, color?: ColorFn): void {\n for (let i = 0; i < text.length; i++) {\n const cx = x + i;\n this.touch(cx, y);\n this.chars.set(this.key(cx, y), { ch: text[i]!, color });\n }\n }\n\n /** True if (x, y) has stamped text or is in a reserved area (node labels). */\n hasLabel(x: number, y: number): boolean {\n return this.chars.has(this.key(x, y)) || this.reserved.has(this.key(x, y));\n }\n\n /** True if (x, y) has any directional connection (an edge passes through). */\n hasConnection(x: number, y: number): boolean {\n return (this.connections.get(this.key(x, y)) ?? 0) !== 0;\n }\n\n /** True if (x, y) has stamped text (not just a reserved area). */\n hasText(x: number, y: number): boolean {\n return this.chars.has(this.key(x, y));\n }\n\n /** Reserve a horizontal span so label placement avoids it. Used for node id + marker regions. */\n reserveArea(x: number, y: number, width: number): void {\n for (let i = 0; i < width; i++) this.reserved.add(this.key(x + i, y));\n }\n\n /** The largest y coordinate with content — used for positioning detached nodes below the graph. */\n getMaxY(): number {\n return this.maxY;\n }\n\n /**\n * Render the grid to a multi-line string.\n *\n * Iterates row by row over the bounding box, resolving each cell to either\n * its stamped text character or the box-drawing character for its\n * connection bitmask. Consecutive characters with the same color are\n * batched into a single ANSI-wrapped run for efficiency.\n */\n render(): string {\n /* v8 ignore next -- @preserve */\n if (this.minX === Number.POSITIVE_INFINITY) return '(empty)';\n\n const rows: string[] = [];\n for (let y = this.minY; y <= this.maxY; y++) {\n let row = '';\n let runChars = '';\n let runColor: ColorFn | undefined;\n\n const flush = () => {\n if (runChars.length === 0) return;\n row += runColor ? runColor(runChars) : runChars;\n runChars = '';\n };\n\n for (let x = this.minX; x <= this.maxX; x++) {\n const k = this.key(x, y);\n let ch: string;\n let color: ColorFn | undefined;\n\n const label = this.chars.get(k);\n if (label) {\n ch = label.ch;\n color = label.color;\n } else {\n const conn = this.connections.get(k) ?? 0;\n // Dashed corners don't exist — strip the bit and fall back to solid\n ch = BOX_CHAR[conn] ?? BOX_CHAR[conn & ~DIR.dashed] ?? ' ';\n color = conn === 0 ? undefined : this.cellColors.get(k)?.color;\n }\n\n if (color !== runColor) {\n flush();\n runColor = color;\n }\n runChars += ch;\n }\n flush();\n rows.push(row.trimEnd());\n }\n\n while (rows.length > 0 && rows[rows.length - 1] === '') rows.pop();\n return rows.join('\\n');\n }\n}\n\n// ---------------------------------------------------------------------------\n// Spine detection — BFS shortest path from root to target\n//\n// The renderer operates on generic GraphNode/GraphEdge, not MigrationGraph,\n// so it cannot use domain-specific pathfinding. These two BFS functions\n// re-derive the spine from the generic edge list.\n// ---------------------------------------------------------------------------\n\n/**\n * Find the set of edge keys (`\"from→to\"`) on the shortest path from\n * `rootId` to `targetId`. Used to color spine edges distinctly from\n * branch edges in the rendered output.\n *\n * Returns an empty set if no path exists.\n */\nfunction findSpineEdges(graph: RenderGraph, rootId: string, targetId: string): Set<string> {\n const visited = new Set([rootId]);\n const parent = new Map<string, GraphEdge>();\n const queue = [rootId];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current === targetId) {\n const spineEdges = new Set<string>();\n let node = targetId;\n while (parent.has(node)) {\n const edge = parent.get(node)!;\n spineEdges.add(`${edge.from}→${edge.to}`);\n node = edge.from;\n }\n return spineEdges;\n }\n for (const edge of graph.outgoing(current)) {\n if (!visited.has(edge.to)) {\n visited.add(edge.to);\n parent.set(edge.to, edge);\n queue.push(edge.to);\n }\n }\n }\n return new Set();\n}\n\n// ---------------------------------------------------------------------------\n// Orthogonal polyline builder — variant-based\n//\n// Dagre produces polyline control points that may contain diagonal segments\n// (two consecutive points that differ in both x and y). Terminal rendering\n// requires strictly orthogonal segments (horizontal or vertical only).\n//\n// To resolve diagonals, we insert an L-shaped bend at each one. Each diagonal\n// has two possible resolutions (horizontal-first or vertical-first), so N\n// diagonals produce 2^N candidate polylines. We enumerate all variants and\n// pick the one with the fewest corners and shortest total length.\n// ---------------------------------------------------------------------------\n\n/**\n * Prepend `src` and append `tgt` to dagre's control points, round to\n * integers, and deduplicate consecutive identical points.\n */\nfunction prepareRawPoints(src: Point, dagrePoints: Point[], tgt: Point): Point[] {\n const raw = [src, ...dagrePoints, tgt];\n const rounded = raw.map((p) => ({ x: Math.round(p.x), y: Math.round(p.y) }));\n const deduped: Point[] = [rounded[0]!];\n for (let i = 1; i < rounded.length; i++) {\n const prev = deduped[deduped.length - 1]!;\n const curr = rounded[i]!;\n if (curr.x !== prev.x || curr.y !== prev.y) deduped.push(curr);\n }\n return deduped;\n}\n\nfunction countDiagonals(points: Point[]): number {\n let count = 0;\n for (let i = 1; i < points.length; i++) {\n const prev = points[i - 1]!;\n const curr = points[i]!;\n if (prev.x !== curr.x && prev.y !== curr.y) count++;\n }\n return count;\n}\n\ntype BendDirection = 'horizontal-first' | 'vertical-first';\n\n/**\n * Decode a bitmask into an array of bend directions.\n *\n * Each bit selects how one diagonal is converted to an orthogonal corner:\n * 0 → horizontal-first, 1 → vertical-first. Used by {@link selectBestVariant}\n * to enumerate all 2^N combinations.\n */\nfunction bitsToBends(bits: number, count: number): BendDirection[] {\n const bends: BendDirection[] = [];\n for (let k = 0; k < count; k++) {\n bends.push((bits >> k) & 1 ? 'vertical-first' : 'horizontal-first');\n }\n return bends;\n}\n\n/**\n * Build one polyline variant by resolving each diagonal with the given bend direction.\n *\n * Diagonals are detected inline: when the last emitted point and the next\n * input point differ in both x and y, the segment is diagonal and is\n * resolved using the next value from `bends`. The result is deduplicated\n * to remove zero-length segments created when a bend coincides with an\n * adjacent point.\n */\nfunction buildVariant(points: Point[], bends: BendDirection[]): Point[] {\n /* v8 ignore next -- @preserve */\n if (points.length < 2) return points;\n\n let bendIdx = 0;\n const result: Point[] = [points[0]!];\n for (let i = 1; i < points.length; i++) {\n const prev = result[result.length - 1]!;\n const curr = points[i]!;\n\n if (prev.x === curr.x || prev.y === curr.y) {\n result.push(curr);\n } else {\n const bend = bends[bendIdx++] ?? 'horizontal-first';\n if (bend === 'horizontal-first') {\n result.push({ x: curr.x, y: prev.y });\n } else {\n result.push({ x: prev.x, y: curr.y });\n }\n result.push(curr);\n }\n }\n\n const final: Point[] = [result[0]!];\n for (let i = 1; i < result.length; i++) {\n const prev = final[final.length - 1]!;\n const curr = result[i]!;\n if (curr.x !== prev.x || curr.y !== prev.y) final.push(curr);\n }\n return final;\n}\n\n/** Count the number of direction changes (corners) in an orthogonal polyline. */\nfunction countCorners(poly: Point[]): number {\n let corners = 0;\n for (let i = 1; i < poly.length - 1; i++) {\n const a = poly[i - 1]!;\n const b = poly[i]!;\n const c = poly[i + 1]!;\n const d1Vert = a.x === b.x;\n const d2Vert = b.x === c.x;\n if (d1Vert !== d2Vert) corners++;\n }\n return corners;\n}\n\n/** Manhattan length of a polyline (sum of absolute x and y deltas). */\nfunction polyLength(poly: Point[]): number {\n let len = 0;\n for (let i = 0; i < poly.length - 1; i++) {\n len += Math.abs(poly[i + 1]!.x - poly[i]!.x) + Math.abs(poly[i + 1]!.y - poly[i]!.y);\n }\n return len;\n}\n\n// ---------------------------------------------------------------------------\n// Label placement\n//\n// Edge labels (migration names) are placed adjacent to polyline segments.\n// The algorithm generates candidate positions along each segment, scores\n// them, and picks the best. Key heuristics:\n//\n// - **Horizontal segment preference**: when a polyline has both vertical and\n// horizontal segments, horizontal segments are boosted because they\n// uniquely identify a branch, while vertical segments often share column\n// space with the trunk. This prevents labels from \"jumping\" when node\n// widths change.\n// - **Source adjacency penalty**: positions within ±1 row of the source node\n// are penalized — labels there look like they belong to an incoming edge.\n// - **Whitespace bonus**: positions with clear space above and below score\n// higher for readability.\n// ---------------------------------------------------------------------------\n\n/**\n * Find the best (x, y) position to place an edge label adjacent to its\n * polyline. Returns null if no collision-free position exists.\n *\n * @param poly - The orthogonalized polyline for the edge.\n * @param label - The label text to place.\n * @param grid - The character grid (used for collision checks).\n * @param srcY - Y coordinate of the source node (for adjacency penalty).\n */\nfunction findLabelPlacement(\n poly: Point[],\n label: string,\n grid: CharGrid,\n srcY?: number,\n): Point | undefined {\n const segments = polyToSegments(poly);\n\n let best: (Point & { score: number }) | undefined;\n\n for (const seg of segments) {\n const candidates = segmentLabelCandidates(seg, label.length);\n for (const pos of candidates) {\n if (labelCollides(grid, pos.x, pos.y, label)) continue;\n const score = scoreLabelCandidate(pos, seg, segments, label, grid, srcY);\n if (!best || score > best.score) best = { x: pos.x, y: pos.y, score };\n }\n }\n\n return best;\n}\n\n/** Convert a polyline into non-zero-length segments. */\nfunction polyToSegments(poly: readonly Point[]): Segment[] {\n const segments: Segment[] = [];\n for (let i = 0; i < poly.length - 1; i++) {\n const seg = segment(poly[i]!, poly[i + 1]!);\n if (manhattanLength(seg) > 0) segments.push(seg);\n }\n return segments;\n}\n\n/**\n * Generate all candidate (x, y) positions for placing a label adjacent\n * to a single segment. Positions are perpendicular to the segment:\n *\n * - Vertical segments: left and right, at every y along the segment.\n * - Horizontal segments: above and below, at every x where the label fits.\n */\nfunction segmentLabelCandidates(seg: Segment, labelLen: number): Point[] {\n const candidates: Point[] = [];\n\n if (isVertical(seg)) {\n const minY = Math.min(seg.from.y, seg.to.y);\n const maxY = Math.max(seg.from.y, seg.to.y);\n for (const x of [seg.from.x + 2, seg.from.x - labelLen - 1]) {\n for (let y = minY; y <= maxY; y++) {\n candidates.push({ x, y });\n }\n }\n } else {\n const minX = Math.min(seg.from.x, seg.to.x);\n const maxX = Math.max(seg.from.x, seg.to.x);\n for (const dy of [-1, 1]) {\n const y = seg.from.y + dy;\n for (let x = minX; x <= maxX - labelLen + 1; x++) {\n candidates.push({ x, y });\n }\n }\n }\n\n return candidates;\n}\n\n/**\n * Score a candidate label position. Higher is better.\n *\n * Combines: segment length, surrounding whitespace, distance from\n * segment midpoint, source-node proximity penalty, and segment-position\n * bonus (horizontal/later segments preferred when the edge has bends).\n *\n * @param pos - Candidate position (top-left corner of the label text).\n * @param seg - The segment this candidate is adjacent to.\n * @param allSegments - All segments of the edge polyline (for segment-position bonus).\n * @param label - The label text (used for width and whitespace probing).\n * @param grid - The character grid (used for whitespace checks).\n * @param srcY - Y coordinate of the edge's source node (penalizes labels\n * that would appear to belong to the node rather than the edge).\n */\nfunction scoreLabelCandidate(\n pos: Point,\n seg: Segment,\n allSegments: readonly Segment[],\n label: string,\n grid: CharGrid,\n srcY?: number,\n): number {\n const len = manhattanLength(seg);\n const midX = Math.round((seg.from.x + seg.to.x) / 2);\n const midY = Math.round((seg.from.y + seg.to.y) / 2);\n\n let score = len;\n\n // Whitespace above/below the label improves readability.\n for (let dy = 1; dy <= 2; dy++) {\n if (!rowHasContent(grid, pos.x, pos.y - dy, label.length)) score += 3;\n if (!rowHasContent(grid, pos.x, pos.y + dy, label.length)) score += 3;\n }\n\n // Prefer positions near the segment midpoint.\n const labelCenterX = pos.x + Math.floor(label.length / 2);\n score -= (Math.abs(labelCenterX - midX) + Math.abs(pos.y - midY)) * 2;\n\n const labelCenterY = pos.y + Math.floor(label.length / 2);\n score -= (Math.abs(labelCenterY - midY) + Math.abs(pos.x - midX)) * 2;\n\n // Prefer labels to the right of a vertical segment\n if (isVertical(seg) && pos.x > seg.from.x) {\n score += 10;\n }\n\n // Penalize positions adjacent to the source node — labels there\n // look like they belong to the incoming edge above.\n if (srcY !== undefined && Math.abs(pos.y - srcY) <= 1) score -= 20;\n\n // Horizontal segments uniquely identify a branch, while the initial\n // vertical drop from the source often shares column space with the trunk.\n // Boost horizontal and later segments so labels land on the branch.\n const hasHorizontalSeg = allSegments.some((s) => !isVertical(s));\n if (hasHorizontalSeg) {\n if (!isVertical(seg)) score += 15;\n const segIndex = allSegments.indexOf(seg);\n score += (segIndex / allSegments.length) * 5;\n }\n\n return score;\n}\n\n/** True if any cell in the horizontal span [x, x+width) at row y has content. */\nfunction rowHasContent(grid: CharGrid, x: number, y: number, width: number): boolean {\n for (let i = 0; i < width; i++) {\n if (grid.hasLabel(x + i, y) || grid.hasConnection(x + i, y)) return true;\n }\n return false;\n}\n\n/**\n * Check if placing `text` at (x, y) would collide with existing content.\n * Checks one cell of padding on each side to keep labels visually separated.\n */\nfunction labelCollides(grid: CharGrid, x: number, y: number, text: string): boolean {\n for (let i = -1; i <= text.length; i++) {\n const cx = x + i;\n if (grid.hasLabel(cx, y)) return true;\n if (i >= 0 && i < text.length && grid.hasConnection(cx, y)) return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Joint variant selection\n//\n// Combines diagonal resolution with label placement in a single pass. For\n// each of the 2^N polyline variants, we compute a score based on corner\n// count, total length, and whether the label can be placed. The variant\n// with the lowest score wins.\n// ---------------------------------------------------------------------------\n\n/** A resolved polyline paired with its best label position (if any). */\ninterface PolyWithLabel {\n poly: Point[];\n labelPos: Point | undefined;\n}\n\n/**\n * Resolve dagre's polyline into the best orthogonal variant and find the\n * optimal label position in a single pass.\n *\n * Enumerates all 2^N diagonal resolutions, scores each by:\n * - `corners * 10` — fewer corners preferred\n * - `+ manhattan length` — shorter paths preferred\n * - `+ 100` penalty if the label couldn't be placed\n *\n * For edges with no diagonals, the polyline is used as-is.\n */\nfunction selectBestVariant(\n src: Point,\n dagrePoints: Point[],\n tgt: Point,\n label: string | undefined,\n grid: CharGrid,\n): PolyWithLabel {\n const rawPoints = prepareRawPoints(src, dagrePoints, tgt);\n const diagCount = countDiagonals(rawPoints);\n\n if (diagCount === 0) {\n const poly = buildVariant(rawPoints, []);\n const labelPos = label ? findLabelPlacement(poly, label, grid, src.y) : undefined;\n return { poly, labelPos };\n }\n\n // Each diagonal must be converted to an orthogonal corner — either\n // horizontal-first or vertical-first. With N diagonals that's 2^N\n // combinations, enumerated via bitmask: we count from 0 to 2^N - 1,\n // and every number represents a different combination of bend directions.\n const numVariants = 1 << diagCount;\n let bestPoly: Point[] | null = null;\n let bestLabel: Point | undefined;\n let bestScore = Number.POSITIVE_INFINITY;\n\n for (let bits = 0; bits < numVariants; bits++) {\n const bends = bitsToBends(bits, diagCount);\n const poly = buildVariant(rawPoints, bends);\n\n const corners = countCorners(poly);\n const len = polyLength(poly);\n const labelPos = label ? findLabelPlacement(poly, label, grid, src.y) : undefined;\n\n const labelPenalty = label && !labelPos ? 100 : 0;\n const score = corners * 10 + len + labelPenalty;\n\n if (score < bestScore) {\n bestScore = score;\n bestPoly = poly;\n bestLabel = labelPos;\n }\n }\n\n return {\n poly: bestPoly ?? buildVariant(rawPoints, bitsToBends(0, diagCount)),\n labelPos: bestLabel,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Subgraph extraction\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the subgraph containing only the nodes and forward-moving edges\n * along the given path.\n *\n * Backward (rollback) edges are excluded even if both endpoints are on the\n * path — only edges where `from` precedes `to` in path order are kept.\n */\nexport function extractSubgraph(graph: RenderGraph, path: readonly string[]): RenderGraph {\n const pathIndex = new Map(path.map((id, i) => [id, i]));\n const nodeSet = new Set(path);\n // Always keep dashed edges and their endpoints\n for (const e of graph.edges) {\n if (e.style === 'dashed') {\n nodeSet.add(e.from);\n nodeSet.add(e.to);\n }\n }\n const filteredNodes = graph.nodes.filter((n) => nodeSet.has(n.id));\n const filteredEdges = graph.edges.filter((e) => {\n if (e.style === 'dashed') return true;\n const fromIdx = pathIndex.get(e.from);\n const toIdx = pathIndex.get(e.to);\n return fromIdx !== undefined && toIdx !== undefined && fromIdx < toIdx;\n });\n return new RenderGraph(filteredNodes, filteredEdges);\n}\n\n/**\n * Extract the subgraph covering the union of multiple paths.\n *\n * Each path is an ordered list of node ids (root → target). The result\n * contains every node on any path plus every forward edge between\n * consecutive nodes on any path. Detached nodes are always included.\n *\n * When all paths overlap (the common case), the result is identical to\n * a single-path extract. When paths diverge (e.g. DB marker on a\n * different branch than the contract), the result naturally includes the\n * fork and both branches — exactly the minimal information needed.\n */\nexport function extractRelevantSubgraph(\n graph: RenderGraph,\n paths: readonly (readonly string[])[],\n): RenderGraph {\n const nodeSet = new Set<string>();\n const edgePairs = new Set<string>();\n\n for (const path of paths) {\n for (let i = 0; i < path.length; i++) {\n nodeSet.add(path[i]!);\n if (i > 0) {\n edgePairs.add(`${path[i - 1]!}\\0${path[i]!}`);\n }\n }\n }\n\n // Always keep dashed (draft) edges and their endpoints\n const dashedEdges = graph.edges.filter((e) => e.style === 'dashed');\n for (const e of dashedEdges) {\n nodeSet.add(e.from);\n nodeSet.add(e.to);\n }\n\n const filteredNodes = graph.nodes.filter((n) => nodeSet.has(n.id));\n const filteredEdges = graph.edges.filter(\n (e) => edgePairs.has(`${e.from}\\0${e.to}`) || e.style === 'dashed',\n );\n return new RenderGraph(filteredNodes, filteredEdges);\n}\n\n// ---------------------------------------------------------------------------\n// Truncation — keep last N spine edges, expand for markers\n// ---------------------------------------------------------------------------\n\n/** Result of {@link truncateGraph} — the visible subgraph plus truncation metadata. */\nexport interface TruncationResult {\n readonly graph: RenderGraph;\n /** Number of spine edges hidden by truncation (0 = nothing truncated). */\n readonly elidedCount: number;\n /** The visible portion of the spine (subset of the input spine). */\n readonly spine: readonly string[];\n}\n\n/**\n * Truncate a graph to the last `limit` spine edges from the spine target.\n * The window expands to include any node carrying a db or contract marker\n * so those are never truncated away.\n *\n * For the full graph: keeps all branches that fork from the visible spine window.\n * For the spine view: caller should call extractSubgraph first, then truncate.\n */\nexport function truncateGraph(\n graph: RenderGraph,\n spine: readonly string[],\n limit: number,\n): TruncationResult {\n if (spine.length <= 1 || limit >= spine.length - 1) {\n return { graph, elidedCount: 0, spine };\n }\n\n // Find the earliest spine node that has a db or contract marker\n let earliestMarkerIdx = spine.length;\n for (let i = 0; i < spine.length; i++) {\n const n = graph.nodeById.get(spine[i]!);\n if (n?.markers?.some((m) => m.kind === 'db' || m.kind === 'contract')) {\n earliestMarkerIdx = i;\n break;\n }\n }\n\n // Effective limit: expand to include markers\n // spine has N+1 nodes for N edges; we want the last `effectiveEdges` edges,\n // which means keeping the last `effectiveEdges + 1` nodes\n const markerDistance = spine.length - 1 - earliestMarkerIdx;\n const effectiveEdges = Math.max(limit, markerDistance);\n\n if (effectiveEdges >= spine.length - 1) {\n return { graph, elidedCount: 0, spine };\n }\n\n const keepFromIdx = spine.length - 1 - effectiveEdges;\n const truncatedSpine = spine.slice(keepFromIdx);\n const visibleSpineSet = new Set(truncatedSpine);\n\n // Include any node reachable from visible spine nodes\n // (branches that fork from visible portion)\n const reachable = new Set(visibleSpineSet);\n const queue = [...truncatedSpine];\n while (queue.length > 0) {\n const current = queue.shift()!;\n for (const edge of graph.outgoing(current)) {\n if (!reachable.has(edge.to)) {\n reachable.add(edge.to);\n queue.push(edge.to);\n }\n }\n }\n\n const truncatedNodes = graph.nodes.filter((n) => reachable.has(n.id));\n const truncatedEdges = graph.edges.filter((e) => reachable.has(e.from) && reachable.has(e.to));\n const elidedCount = spine.length - 1 - effectiveEdges;\n\n return {\n graph: new RenderGraph(truncatedNodes, truncatedEdges),\n elidedCount,\n spine: truncatedSpine,\n };\n}\n\n/**\n * After truncation the original root may not be in the visible graph.\n * Find the first node with no incoming edges as a fallback root.\n */\nfunction findVisibleRoot(graph: RenderGraph, layoutNodes: readonly GraphNode[]): string {\n return layoutNodes.find((n) => !graph.incomingNodes.has(n.id))?.id ?? layoutNodes[0]?.id ?? '∅';\n}\n\n// ---------------------------------------------------------------------------\n// Core layout + render pipeline\n// ---------------------------------------------------------------------------\n\n/**\n * The main rendering pipeline: dagre layout → edge stamping → label\n * placement → arrowheads → nodes → elided indicator → detached nodes.\n *\n * Called by {@link render} after optional truncation. Receives nodes/edges\n * and produces the final multi-line string.\n *\n * @param graph - The graph to render (may include detached nodes, which are\n * rendered below the main graph rather than laid out by dagre).\n * @param options - Render options (rootId, spineTarget, colorize).\n * @param elidedCount - If > 0, a `┊ (N earlier migrations)` indicator\n * is stamped above the visible root node.\n */\nfunction layoutAndRender(graph: RenderGraph, options: GraphRenderOptions, elidedCount = 0): string {\n const colorize = options.colorize ?? true;\n const colors = buildColors(colorize);\n\n const layoutNodes = graph.nodes;\n const layoutNodeIds = new Set(layoutNodes.map((n) => n.id));\n const requestedRoot = options.rootId ?? layoutNodes[0]?.id ?? '∅';\n const rootId = layoutNodeIds.has(requestedRoot)\n ? requestedRoot\n : findVisibleRoot(graph, layoutNodes);\n\n const spineEdgeKeys = findSpineEdges(graph, rootId, options.spineTarget);\n\n const g = new dagre.graphlib.Graph({ multigraph: true });\n const dagreDefaults = { ranksep: 4, nodesep: 6, marginx: 2, marginy: 1 };\n g.setGraph({ rankdir: 'TB', ...dagreDefaults, ...options.dagreOptions });\n g.setDefaultEdgeLabel(() => ({}));\n\n for (const node of layoutNodes) {\n const tags = buildInlineTags(node.markers ?? [], colors);\n const tagWidth = inlineTagsWidth(tags);\n g.setNode(node.id, { width: node.id.length + 6 + tagWidth, height: 1 });\n }\n\n const edgeNames: string[] = [];\n for (let i = 0; i < graph.edges.length; i++) {\n const edge = graph.edges[i]!;\n const name = `e${i}`;\n edgeNames.push(name);\n g.setEdge(edge.from, edge.to, { label: edge.label ?? '' }, name);\n }\n\n dagre.layout(g);\n\n const nodePos = new Map<string, Point>();\n for (const id of g.nodes()) {\n const n = g.node(id);\n nodePos.set(id, { x: Math.round(n.x), y: Math.round(n.y) });\n }\n\n const grid = new CharGrid();\n\n // Reserve node label areas so edges and labels avoid them\n for (const node of layoutNodes) {\n const pos = nodePos.get(node.id);\n /* v8 ignore next -- @preserve */\n if (!pos) continue;\n const tags = buildInlineTags(node.markers ?? [], colors);\n const tagWidth = inlineTagsWidth(tags);\n grid.reserveArea(pos.x - 1, pos.y, node.id.length + 4 + tagWidth);\n }\n\n // --- Prepare edge metadata ---\n type EdgeEntry = {\n idx: number;\n edge: GraphEdge;\n dagrePoints: Point[];\n src: Point;\n tgt: Point;\n role: 'spine' | 'branch' | 'backward';\n edgeColor: ColorFn;\n priority: number;\n };\n const edgeEntries: EdgeEntry[] = [];\n\n for (let i = 0; i < graph.edges.length; i++) {\n const edge = graph.edges[i]!;\n const name = edgeNames[i]!;\n if (!name || !nodePos.has(edge.from) || !nodePos.has(edge.to)) continue;\n\n const src = nodePos.get(edge.from)!;\n const tgt = nodePos.get(edge.to)!;\n const dagreEdge = g.edge({ v: edge.from, w: edge.to, name });\n const dagrePoints: Point[] = dagreEdge?.points ?? [];\n\n const isBackward = tgt.y < src.y;\n const isSpine = spineEdgeKeys.has(`${edge.from}→${edge.to}`);\n const role: EdgeEntry['role'] = isBackward ? 'backward' : isSpine ? 'spine' : 'branch';\n const hintColor = resolveHintColor(edge.colorHint, colors);\n const edgeColor =\n hintColor ??\n (role === 'backward' ? colors.backward : role === 'spine' ? colors.spine : colors.branch);\n const priority =\n role === 'backward' ? PRIORITY.backward : role === 'spine' ? PRIORITY.spine : PRIORITY.branch;\n\n edgeEntries.push({ idx: i, edge, dagrePoints, src, tgt, role, edgeColor, priority });\n }\n\n // --- Pass 1: Draw all edges ---\n type DrawnEdge = { edge: GraphEdge; poly: Point[]; role: EdgeEntry['role']; srcY: number };\n const drawnEdges: DrawnEdge[] = [];\n\n for (const entry of edgeEntries) {\n const { edge, dagrePoints, src, tgt, edgeColor, priority } = entry;\n\n const { poly } = selectBestVariant(src, dagrePoints, tgt, edge.label, grid);\n\n const dashedBit = edge.style === 'dashed' ? DIR.dashed : 0;\n for (let j = 0; j < poly.length - 1; j++) {\n const a = poly[j]!;\n const b = poly[j + 1]!;\n if (a.y === b.y) {\n grid.markHorizontal(a.y, a.x, b.x, edgeColor, priority, dashedBit);\n } else if (a.x === b.x) {\n grid.markVertical(a.x, a.y, b.y, edgeColor, priority, dashedBit);\n }\n }\n\n drawnEdges.push({ edge, poly, role: entry.role, srcY: src.y });\n }\n\n // --- Pass 2: Place labels (longest first) ---\n const labelOrder = [...drawnEdges]\n .map((de, i) => ({ ...de, i }))\n .filter((de) => de.edge.label)\n .sort((a, b) => (b.edge.label?.length ?? 0) - (a.edge.label?.length ?? 0));\n\n for (const { edge, poly, role, srcY } of labelOrder) {\n /* v8 ignore next -- @preserve */\n if (!edge.label) continue;\n const labelPos = findLabelPlacement(poly, edge.label, grid, srcY);\n if (labelPos) {\n const labelColor =\n resolveHintColor(edge.colorHint, colors) ??\n (role === 'backward' ? colors.backward : role === 'spine' ? colors.spine : colors.label);\n grid.stampText(labelPos.x, labelPos.y, edge.label, labelColor);\n }\n }\n\n // --- Pass 3: Arrowheads ---\n for (const { edge, poly, role } of drawnEdges) {\n /* v8 ignore next -- @preserve */\n if (poly.length < 2) continue;\n const last = poly[poly.length - 1]!;\n const prev = poly[poly.length - 2]!;\n\n const edgeColor =\n resolveHintColor(edge.colorHint, colors) ??\n (role === 'backward' ? colors.backward : role === 'spine' ? colors.spine : colors.branch);\n\n let ax: number | undefined;\n let ay: number | undefined;\n let arrow: string | undefined;\n\n if (prev.x === last.x) {\n if (last.y > prev.y) {\n ax = last.x;\n ay = last.y - 1;\n arrow = ARROW.down;\n } else {\n ax = last.x;\n ay = last.y + 1;\n arrow = ARROW.up;\n }\n } else {\n if (last.x > prev.x) {\n ax = last.x - 1;\n ay = last.y;\n arrow = ARROW.right;\n } else {\n ax = last.x + 1;\n ay = last.y;\n arrow = ARROW.left;\n }\n }\n\n if (ax !== undefined && ay !== undefined && arrow && !grid.hasText(ax, ay)) {\n grid.stampText(ax, ay, arrow, edgeColor);\n }\n }\n\n // --- Draw nodes ---\n const spineNodeIds = new Set<string>();\n for (const key of spineEdgeKeys) {\n const [from, to] = key.split('→');\n if (from) spineNodeIds.add(from);\n if (to) spineNodeIds.add(to);\n }\n\n for (const node of layoutNodes) {\n const pos = nodePos.get(node.id);\n if (!pos) continue;\n\n const isSpineNode = spineNodeIds.has(node.id);\n const nodeColor = isSpineNode ? colors.spine : colors.branch;\n\n grid.stampText(pos.x, pos.y, '○', nodeColor);\n grid.stampText(pos.x + 1, pos.y, ' ');\n const hasMarkers = node.markers && node.markers.length > 0;\n grid.stampText(pos.x + 2, pos.y, node.id, isSpineNode || hasMarkers ? bold : dim);\n\n const tags = buildInlineTags(node.markers ?? [], colors);\n if (tags.length > 0) {\n let bx = pos.x + 2 + node.id.length;\n for (const tag of tags) {\n grid.stampText(bx, pos.y, ' ');\n bx++;\n grid.stampText(bx, pos.y, tag.text, tag.color);\n bx += tag.text.length;\n }\n }\n }\n\n // --- Elided indicator above root ---\n if (elidedCount > 0) {\n const topNodeId =\n layoutNodes.find((n) => !graph.incomingNodes.has(n.id))?.id ?? layoutNodes[0]?.id;\n const rootPos = topNodeId ? nodePos.get(topNodeId) : undefined;\n if (rootPos) {\n const label = elidedCount === 1 ? '1 earlier migration' : `${elidedCount} earlier migrations`;\n const topY = rootPos.y - 3;\n grid.stampText(rootPos.x, topY, '┊', colors.label);\n grid.stampText(rootPos.x, topY + 1, '┊', colors.label);\n grid.stampText(rootPos.x + 2, topY + 1, `(${label})`, colors.label);\n grid.stampText(rootPos.x, topY + 2, '┊', colors.label);\n }\n }\n\n return grid.render();\n}\n\n// ---------------------------------------------------------------------------\n// GraphRenderer implementation\n// ---------------------------------------------------------------------------\n\n/**\n * BFS to find the ordered node path from `rootId` to `targetId`.\n * Used for truncation — the spine path determines which edges to keep.\n *\n * Returns `[rootId]` if no path exists.\n */\nfunction findSpinePath(graph: RenderGraph, rootId: string, targetId: string): string[] {\n const visited = new Set([rootId]);\n const parent = new Map<string, string>();\n const queue = [rootId];\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current === targetId) {\n const path: string[] = [];\n let node = targetId;\n while (node !== rootId) {\n path.unshift(node);\n node = parent.get(node)!;\n }\n path.unshift(rootId);\n return path;\n }\n for (const edge of graph.outgoing(current)) {\n if (!visited.has(edge.to)) {\n visited.add(edge.to);\n parent.set(edge.to, current);\n queue.push(edge.to);\n }\n }\n }\n return [rootId];\n}\n\n/**\n * Render a graph with optional truncation.\n *\n * The caller decides what to pass in: the full graph for `--graph`, or a\n * subgraph extracted via {@link extractRelevantSubgraph} for the default view.\n */\nfunction render(graph: RenderGraph, options: GraphRenderOptions): string {\n if (options.limit !== undefined) {\n const spine = findSpinePath(\n graph,\n options.rootId ?? graph.nodes[0]?.id ?? '∅',\n options.spineTarget,\n );\n const { graph: truncated, elidedCount } = truncateGraph(graph, spine, options.limit);\n return layoutAndRender(truncated, options, elidedCount);\n }\n return layoutAndRender(graph, options);\n}\n\nexport interface GraphRenderer {\n render(graph: RenderGraph, options: GraphRenderOptions): string;\n}\n\nexport const graphRenderer: GraphRenderer = {\n render,\n};\n\n/** True if the graph is a single linear chain (no branching), ignoring dashed edges. */\nexport function isLinearGraph(graph: RenderGraph): boolean {\n for (const node of graph.nodes) {\n const solidOutgoing = graph.outgoing(node.id).filter((e) => e.style !== 'dashed');\n if (solidOutgoing.length > 1) return false;\n }\n return true;\n}\n","import type { MigrationPlanOperation } from '@prisma-next/framework-components/control';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport {\n findPath,\n findPathWithDecision,\n findReachableLeaves,\n} from '@prisma-next/migration-tools/dag';\nimport type { Refs } from '@prisma-next/migration-tools/refs';\nimport { readRefs, resolveRef } from '@prisma-next/migration-tools/refs';\nimport type {\n MigrationBundle,\n MigrationChainEntry,\n MigrationGraph,\n} from '@prisma-next/migration-tools/types';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { cyan, dim, magenta, yellow } from 'colorette';\nimport { Command } from 'commander';\n\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport { type CliStructuredError, errorRuntime, errorUnexpected } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n loadAllBundles,\n maskConnectionUrl,\n readContractEnvelope,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n toPathDecisionResult,\n} from '../utils/command-helpers';\nimport {\n type EdgeStatus,\n type EdgeStatusKind,\n migrationGraphToRenderInput,\n} from '../utils/formatters/graph-migration-mapper';\nimport {\n extractRelevantSubgraph,\n graphRenderer,\n isLinearGraph,\n} from '../utils/formatters/graph-render';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport type { StatusDiagnostic, StatusRef } from '../utils/migration-types';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationStatusOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly ref?: string;\n readonly graph?: boolean;\n readonly limit?: string;\n readonly all?: boolean;\n}\n\nexport interface MigrationStatusEntry {\n readonly dirName: string;\n readonly from: string;\n readonly to: string;\n readonly migrationId: string;\n readonly operationCount: number;\n readonly operationSummary: string;\n readonly hasDestructive: boolean;\n readonly status: EdgeStatusKind | 'unknown';\n}\n\nexport type { StatusDiagnostic, StatusRef } from '../utils/migration-types';\n\nexport interface MigrationStatusResult {\n readonly ok: true;\n readonly mode: 'online' | 'offline';\n readonly migrations: readonly MigrationStatusEntry[];\n readonly markerHash?: string;\n readonly targetHash: string;\n readonly contractHash: string;\n readonly refs?: readonly StatusRef[];\n readonly pathDecision?: {\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n readonly selectedPath: readonly {\n readonly dirName: string;\n readonly migrationId: string;\n readonly from: string;\n readonly to: string;\n }[];\n };\n readonly summary: string;\n readonly diagnostics: readonly StatusDiagnostic[];\n readonly graph?: MigrationGraph;\n readonly bundles?: readonly MigrationBundle[];\n readonly edgeStatuses?: readonly EdgeStatus[];\n readonly activeRefHash?: string;\n readonly activeRefName?: string;\n readonly diverged?: boolean;\n}\n\nfunction summarizeOps(ops: readonly MigrationPlanOperation[]): {\n summary: string;\n hasDestructive: boolean;\n} {\n if (ops.length === 0) return { summary: '0 ops', hasDestructive: false };\n\n const classes = new Map<string, number>();\n for (const op of ops) {\n classes.set(op.operationClass, (classes.get(op.operationClass) ?? 0) + 1);\n }\n\n const hasDestructive = classes.has('destructive');\n const count = ops.length;\n const noun = count === 1 ? 'op' : 'ops';\n\n if (classes.size === 1) {\n const cls = [...classes.keys()][0]!;\n return { summary: `${count} ${noun} (all ${cls})`, hasDestructive };\n }\n\n const destructiveCount = classes.get('destructive');\n if (destructiveCount) {\n return { summary: `${count} ${noun} (${destructiveCount} destructive)`, hasDestructive };\n }\n\n const parts = [...classes.entries()].map(([cls, n]) => `${n} ${cls}`);\n return { summary: `${count} ${noun} (${parts.join(', ')})`, hasDestructive };\n}\n\n/**\n * Derive per-edge status across the full graph using path analysis.\n *\n * - **applied**: edge is on the path from root to the DB marker\n * - **pending**: edge is on the path from the DB marker to the target\n * (and the marker is reachable from root, i.e. it's on the same branch)\n * - **unreachable**: edge is on the path from root to the target but the DB\n * marker is on a different branch — `apply` can't reach these edges\n * without the DB first moving to this branch\n *\n * Returns statuses only for edges that have a known status (skips offline\n * and edges not on any relevant path).\n *\n * @internal Exported for testing only.\n */\nexport function deriveEdgeStatuses(\n graph: MigrationGraph,\n targetHash: string,\n contractHash: string,\n markerHash: string | undefined,\n mode: 'online' | 'offline',\n): EdgeStatus[] {\n if (mode === 'offline') return [];\n\n const edgeKey = (e: MigrationChainEntry) => `${e.from}\\0${e.to}`;\n\n // No marker = empty DB — treat root as the marker (nothing applied, everything pending)\n const effectiveMarker = markerHash ?? EMPTY_CONTRACT_HASH;\n\n const appliedPath =\n markerHash !== undefined ? findPath(graph, EMPTY_CONTRACT_HASH, markerHash) : null;\n\n const pendingPath = findPath(graph, effectiveMarker, targetHash);\n const targetPath = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n\n const statuses: EdgeStatus[] = [];\n const assignedKeys = new Set<string>();\n\n // Applied edges (root → marker)\n if (appliedPath) {\n for (const e of appliedPath) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'applied' });\n }\n }\n\n // Pending edges (marker → target)\n if (pendingPath) {\n for (const e of pendingPath) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'pending' });\n }\n }\n\n // Pending edges beyond the target: target → contract (when target is a ref\n // and the contract is reachable from it)\n if (\n contractHash !== EMPTY_CONTRACT_HASH &&\n contractHash !== targetHash &&\n graph.nodes.has(contractHash)\n ) {\n const beyondTarget = findPath(graph, targetHash, contractHash);\n if (beyondTarget) {\n for (const e of beyondTarget) {\n if (!assignedKeys.has(edgeKey(e))) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'pending' });\n }\n }\n }\n }\n\n // Unreachable edges: on the path from root to the target but neither applied\n // nor pending. This covers two cases:\n // 1. Marker can't reach target at all (different branch entirely)\n // 2. Marker reaches target via a different route, leaving some root→target\n // edges orphaned (e.g. a fork where one branch was applied and apply\n // will continue through the other)\n if (targetPath) {\n for (const e of targetPath) {\n if (!assignedKeys.has(edgeKey(e))) {\n statuses.push({ dirName: e.dirName, status: 'unreachable' });\n }\n }\n }\n\n return statuses;\n}\n\n/**\n * @param mode — 'online' if we connected to the database, 'offline' otherwise\n * @param markerHash — the marker hash from the database, or undefined if no marker row / offline\n */\nfunction buildMigrationEntries(\n chain: readonly MigrationChainEntry[],\n packages: readonly MigrationBundle[],\n mode: 'online' | 'offline',\n markerHash: string | undefined,\n edgeStatuses?: readonly EdgeStatus[],\n): MigrationStatusEntry[] {\n const pkgByDirName = new Map(packages.map((p) => [p.dirName, p]));\n const statusByDirName = edgeStatuses\n ? new Map(edgeStatuses.map((e) => [e.dirName, e.status]))\n : undefined;\n\n const markerInChain = markerHash === undefined || chain.some((e) => e.to === markerHash);\n\n const entries: MigrationStatusEntry[] = [];\n let reachedMarker = mode === 'online' && markerHash === undefined;\n\n for (const migration of chain) {\n const pkg = pkgByDirName.get(migration.dirName);\n const ops = (pkg?.ops ?? []) as readonly MigrationPlanOperation[];\n const { summary, hasDestructive } = summarizeOps(ops);\n\n let status: EdgeStatusKind | 'unknown';\n const edgeStatus = statusByDirName?.get(migration.dirName);\n if (edgeStatus) {\n status = edgeStatus;\n } else if (mode === 'offline' || !markerInChain) {\n status = 'unknown';\n } else if (reachedMarker) {\n status = 'pending';\n } else {\n status = 'applied';\n }\n\n entries.push({\n dirName: migration.dirName,\n from: migration.from,\n to: migration.to,\n migrationId: migration.migrationId,\n operationCount: ops.length,\n operationSummary: summary,\n hasDestructive,\n status,\n });\n\n if (!reachedMarker && migration.to === markerHash) {\n reachedMarker = true;\n }\n }\n\n return entries;\n}\n\n/**\n * Resolve the migration chain to display in status output.\n *\n * When offline or the marker is at EMPTY, the chain is simply the shortest\n * path from EMPTY to the target — all structural paths are equivalent per\n * the spec, so the deterministic shortest path is the canonical display.\n *\n * When online with a non-empty marker, the chain routes *through* the marker:\n * EMPTY→marker (applied history) + marker→target (pending edges). This ensures\n * the displayed chain includes the marker node so applied/pending status is\n * correct. Without this, BFS from EMPTY to target could pick a shortest path\n * that bypasses the marker entirely (e.g. in a diamond graph), causing the\n * marker to appear \"diverged\" when it isn't.\n */\nfunction resolveDisplayChain(\n graph: MigrationGraph,\n targetHash: string,\n markerHash: string | undefined,\n): readonly MigrationChainEntry[] | null {\n if (markerHash === undefined) {\n return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n }\n\n const toMarker = findPath(graph, EMPTY_CONTRACT_HASH, markerHash);\n // Marker unreachable from EMPTY — show the target chain anyway.\n // The caller detects this via markerInChain and emits a divergence diagnostic.\n if (!toMarker) return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n\n if (markerHash === targetHash) return toMarker;\n\n const fromMarker = findPath(graph, markerHash, targetHash);\n if (fromMarker) return [...toMarker, ...fromMarker];\n\n // Marker is ahead of target (or on a disconnected branch).\n // Try the inverse: target→marker. If it succeeds, the marker is ahead —\n // show the full chain from EMPTY through the target and on to the marker.\n const toTarget = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n if (!toTarget) return null;\n\n const targetToMarker = findPath(graph, targetHash, markerHash);\n if (targetToMarker) return [...toTarget, ...targetToMarker];\n\n // Genuinely disconnected — show EMPTY→target; caller handles divergence diagnostic.\n return toTarget;\n}\n\nconst DEFAULT_LIMIT = 10;\n\nfunction determineLimit(opts: MigrationStatusOptions) {\n if (opts.all) {\n // No limit\n return;\n }\n if (!opts.limit) {\n return DEFAULT_LIMIT;\n }\n const parsed = Number.parseInt(opts.limit, 10);\n if (Number.isNaN(parsed)) {\n return DEFAULT_LIMIT;\n }\n return parsed;\n}\n\nasync function executeMigrationStatusCommand(\n options: MigrationStatusOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<MigrationStatusResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, migrationsRelative, refsDir } = resolveMigrationPaths(\n options.config,\n config,\n );\n\n const dbConnection = options.db ?? config.db?.connection;\n const hasDriver = !!config.driver;\n\n let activeRefName: string | undefined;\n let activeRefHash: string | undefined;\n let allRefs: Refs = {};\n try {\n allRefs = await readRefs(refsDir);\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code },\n }),\n );\n }\n throw error;\n }\n\n if (options.ref) {\n activeRefName = options.ref;\n try {\n activeRefHash = resolveRef(allRefs, activeRefName).hash;\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, {\n why: error.why,\n fix: error.fix,\n meta: { code: error.code },\n }),\n );\n }\n throw error;\n }\n }\n\n const statusRefs: StatusRef[] = Object.entries(allRefs).map(([name, entry]) => ({\n name,\n hash: entry.hash,\n active: name === activeRefName,\n }));\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: migrationsRelative },\n ];\n if (dbConnection && hasDriver) {\n details.push({ label: 'database', value: maskConnectionUrl(String(dbConnection)) });\n }\n if (activeRefName) {\n details.push({ label: 'ref', value: activeRefName });\n }\n const header = formatStyledHeader({\n command: 'migration status',\n description: 'Show migration history and applied status',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n const diagnostics: StatusDiagnostic[] = [];\n let contractHash: string = EMPTY_CONTRACT_HASH;\n try {\n const envelope = await readContractEnvelope(config);\n contractHash = envelope.storageHash;\n } catch (error) {\n diagnostics.push({\n code: 'CONTRACT.UNREADABLE',\n severity: 'warn',\n message: `Could not read contract: ${error instanceof Error ? error.message : 'unknown error'}`,\n hints: [\"Run 'prisma-next contract emit' to generate a valid contract\"],\n });\n }\n\n let bundles: readonly MigrationBundle[];\n let graph: MigrationGraph;\n try {\n ({ bundles, graph } = await loadAllBundles(migrationsDir));\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(\n errorRuntime(error.message, { why: error.why, fix: error.fix, meta: { code: error.code } }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n if (bundles.length === 0) {\n if (contractHash !== EMPTY_CONTRACT_HASH) {\n diagnostics.push({\n code: 'CONTRACT.AHEAD',\n severity: 'warn',\n message: 'No migration exists for the current contract',\n hints: [\n \"Run 'prisma-next migration plan' to generate a migration for the current contract\",\n ],\n });\n }\n return ok({\n ok: true,\n mode: dbConnection && hasDriver ? 'online' : 'offline',\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: 'No migrations found',\n diagnostics,\n });\n }\n\n let targetHash: string | undefined;\n\n if (activeRefHash) {\n targetHash = activeRefHash;\n } else if (graph.nodes.has(contractHash)) {\n targetHash = contractHash;\n } else {\n const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);\n if (leaves.length === 1) {\n targetHash = leaves[0];\n } else {\n diagnostics.push({\n code: 'MIGRATION.DIVERGED',\n severity: 'warn',\n message: 'There are multiple valid migration paths — you must select a target',\n hints: [\n \"Use '--ref <name>' to select a target\",\n \"Or 'prisma-next migration ref set <name> <hash>' to create one\",\n ],\n });\n }\n }\n\n let markerHash: string | undefined;\n let mode: 'online' | 'offline' = 'offline';\n\n if (dbConnection && hasDriver) {\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n try {\n await client.connect(dbConnection);\n markerHash = (await client.readMarker())?.storageHash;\n mode = 'online';\n } catch {\n if (!flags.json && !flags.quiet) {\n ui.warn('Could not connect to database — showing offline status');\n }\n } finally {\n await client.close();\n }\n }\n\n // Marker exists but is not in the migration graph and doesn't match the\n // contract hash. The DB is at an unknown state relative to the graph.\n // Bail out early with a clear diagnostic instead of rendering a confusing\n // graph with no statuses.\n //\n // When marker === contract (both off-graph), the DB matches the current\n // contract — proceed normally; the detached contract node will carry both\n // the db and contract markers.\n if (\n mode === 'online' &&\n markerHash !== undefined &&\n !graph.nodes.has(markerHash) &&\n markerHash !== contractHash\n ) {\n const hints: string[] = [];\n if (graph.nodes.has(contractHash)) {\n hints.push(\n \"Run 'prisma-next db sign' to overwrite the marker if the database already matches the contract\",\n \"Run 'prisma-next db update' to push the current contract to the database\",\n \"Run 'prisma-next contract infer' to make your contract match the database\",\n \"Run 'prisma-next db verify' to inspect the database state\",\n );\n } else {\n hints.push(\n \"Run 'prisma-next db update' to push the current contract to the database\",\n \"Run 'prisma-next contract infer' to make your contract match the database\",\n \"Run 'prisma-next db verify' to inspect the database state\",\n );\n }\n diagnostics.push({\n code: 'MIGRATION.MARKER_NOT_IN_HISTORY',\n severity: 'warn',\n message:\n 'Database was updated outside the migration system (marker does not match any migration)',\n hints,\n });\n return ok({\n ok: true,\n mode,\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: `${bundles.length} migration(s) on disk`,\n diagnostics,\n markerHash,\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n });\n }\n\n if (mode === 'online' && markerHash === undefined) {\n diagnostics.push({\n code: 'MIGRATION.NO_MARKER',\n severity: 'warn',\n message: 'Database has not been initialized — no migration marker found',\n hints: [\"Run 'prisma-next migration apply' to apply pending migrations\"],\n });\n }\n\n // Contract diagnostic — fires when no migration produces the current contract hash.\n // Suppressed when: (a) graph is diverged (MIGRATION.DIVERGED already guides the user),\n // (b) marker === contract and both off-graph (marker-not-in-graph diagnostic covers it).\n if (\n targetHash &&\n contractHash !== EMPTY_CONTRACT_HASH &&\n !graph.nodes.has(contractHash) &&\n markerHash !== contractHash\n ) {\n diagnostics.push({\n code: 'CONTRACT.AHEAD',\n severity: 'warn',\n message: 'Contract has changed since the last migration was planned',\n hints: [\"Run 'prisma-next migration plan' to generate a migration for the current contract\"],\n });\n }\n\n if (!targetHash) {\n return ok({\n ok: true,\n mode,\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: `${bundles.length} migration(s) on disk`,\n diagnostics,\n ...ifDefined('markerHash', markerHash),\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n graph,\n bundles,\n diverged: true,\n });\n }\n\n const chain = resolveDisplayChain(graph, targetHash, markerHash);\n\n if (!chain) {\n return notOk(\n errorRuntime('Cannot reconstruct migration history', {\n why: `No path from ${EMPTY_CONTRACT_HASH} to target ${targetHash}`,\n fix: 'The migration history may have gaps. Check the migrations directory for missing or corrupted packages.',\n }),\n );\n }\n\n const edgeStatuses = deriveEdgeStatuses(graph, targetHash, contractHash, markerHash, mode);\n const entries = buildMigrationEntries(chain, bundles, mode, markerHash, edgeStatuses);\n\n const pendingCount = edgeStatuses.filter((e) => e.status === 'pending').length;\n const appliedCount = edgeStatuses.filter((e) => e.status === 'applied').length;\n\n let summary: string;\n if (mode === 'online') {\n if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {\n summary = `${bundles.length} migration(s) on disk`;\n } else if (activeRefHash && markerHash !== undefined) {\n summary = summarizeRefDistance(graph, markerHash, activeRefHash, activeRefName!);\n } else if (pendingCount === 0) {\n summary = `Database is up to date (${appliedCount} migration${appliedCount !== 1 ? 's' : ''} applied)`;\n } else if (markerHash === undefined) {\n summary = `${pendingCount} pending migration(s) — database has no marker`;\n } else {\n summary = `${pendingCount} pending migration(s) — run 'prisma-next migration apply' to apply`;\n }\n } else {\n summary = `${entries.length} migration(s) on disk`;\n }\n\n if (mode === 'online') {\n if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {\n diagnostics.push({\n code: 'MIGRATION.MARKER_NOT_IN_HISTORY',\n severity: 'warn',\n message:\n 'Database matches the current contract but was updated directly (not via migration apply)',\n hints: [\"Run 'prisma-next migration plan' to plan a migration to your current contract\"],\n });\n } else if (pendingCount > 0) {\n diagnostics.push({\n code: 'MIGRATION.DATABASE_BEHIND',\n severity: 'info',\n message: `${pendingCount} migration(s) pending`,\n hints: [\"Run 'prisma-next migration apply' to apply pending migrations\"],\n });\n } else {\n diagnostics.push({\n code: 'MIGRATION.UP_TO_DATE',\n severity: 'info',\n message: 'Database is up to date',\n hints: [],\n });\n }\n }\n\n let pathDecision: MigrationStatusResult['pathDecision'];\n if (mode === 'online' && markerHash !== undefined) {\n const decision = findPathWithDecision(graph, markerHash, targetHash, activeRefName);\n if (decision) {\n pathDecision = toPathDecisionResult(decision);\n }\n }\n\n const result: MigrationStatusResult = {\n ok: true,\n mode,\n migrations: entries,\n targetHash,\n contractHash,\n summary,\n diagnostics,\n ...ifDefined('markerHash', markerHash),\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n ...ifDefined('pathDecision', pathDecision),\n graph,\n bundles,\n edgeStatuses,\n ...ifDefined('activeRefHash', activeRefHash),\n ...ifDefined('activeRefName', activeRefName),\n };\n return ok(result);\n}\n\nexport function createMigrationStatusCommand(): Command {\n const command = new Command('status');\n setCommandDescriptions(\n command,\n 'Show migration history and applied status',\n 'Displays the migration history in order. When a database connection\\n' +\n 'is available, shows which migrations are applied and which are pending.\\n' +\n 'Without a database connection, shows the history from disk only.',\n );\n setCommandExamples(command, [\n 'prisma-next migration status',\n 'prisma-next migration status --db $DATABASE_URL',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--ref <name>', 'Target ref name from migrations/refs/')\n .option('--graph', 'Show the full migration graph with all branches')\n .option('--limit <n>', 'Maximum number of migrations to display (default: 10)')\n .option('--all', 'Show full history (disables truncation)')\n .action(async (options: MigrationStatusOptions) => {\n const flags = parseGlobalFlags(options);\n\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n const result = await executeMigrationStatusCommand(options, flags, ui);\n\n const exitCode = handleResult(result, flags, ui, (statusResult) => {\n if (flags.json) {\n const {\n graph: _g,\n bundles: _b,\n edgeStatuses: _es,\n activeRefHash: _arh,\n activeRefName: _arn,\n diverged: _d,\n ...jsonResult\n } = statusResult;\n ui.output(JSON.stringify(jsonResult, null, 2));\n } else if (!flags.quiet) {\n const colorize = flags.color !== false;\n\n if (statusResult.graph) {\n const limit = determineLimit(options);\n const renderInput = migrationGraphToRenderInput({\n graph: statusResult.graph,\n mode: statusResult.mode,\n markerHash: statusResult.markerHash,\n contractHash: statusResult.contractHash,\n refs: statusResult.refs,\n activeRefHash: statusResult.activeRefHash,\n activeRefName: statusResult.activeRefName,\n edgeStatuses: statusResult.edgeStatuses,\n });\n\n const graphToRender =\n options.graph || statusResult.diverged\n ? renderInput.graph\n : extractRelevantSubgraph(renderInput.graph, renderInput.relevantPaths);\n const dagreOptions =\n !options.graph && isLinearGraph(graphToRender) ? { ranksep: 1 } : undefined;\n const renderOptions = {\n ...renderInput.options,\n colorize,\n ...ifDefined('limit', limit),\n ...ifDefined('dagreOptions', dagreOptions),\n };\n const graphOutput = graphRenderer.render(graphToRender, renderOptions);\n ui.log(graphOutput);\n if (statusResult.mode === 'online') {\n ui.log(formatLegend(colorize));\n }\n }\n ui.log('');\n ui.log(formatStatusSummary(statusResult, colorize));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n\nfunction formatLegend(colorize: boolean): string {\n const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);\n const parts = [\n `${c(cyan, '✓')} applied`,\n `${c(yellow, '⧗')} pending`,\n `${c(magenta, '✗')} unreachable`,\n ];\n return c(dim, parts.join(' '));\n}\n\nfunction formatStatusSummary(result: MigrationStatusResult, colorize: boolean): string {\n const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);\n const lines: string[] = [];\n\n const hasUnknown = result.migrations.some((e) => e.status === 'unknown');\n const pendingCount = result.migrations.filter((e) => e.status === 'pending').length;\n\n const hasWarnings = result.diagnostics?.some((d) => d.severity === 'warn') ?? false;\n\n if (result.mode === 'online') {\n if (hasUnknown || hasWarnings) {\n lines.push(`${c(yellow, '⚠')} ${result.summary}`);\n } else if (pendingCount === 0) {\n lines.push(`${c(cyan, '✔')} ${result.summary}`);\n } else {\n lines.push(`${c(yellow, '⧗')} ${result.summary}`);\n }\n } else {\n lines.push(result.summary);\n }\n\n const warnings = result.diagnostics?.filter((d) => d.severity === 'warn') ?? [];\n for (const diag of warnings) {\n lines.push(`${c(yellow, '⚠')} ${diag.message}`);\n for (const hint of diag.hints) {\n lines.push(` ${c(dim, hint)}`);\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction summarizeRefDistance(\n graph: MigrationGraph,\n markerHash: string,\n refHash: string,\n refName: string,\n): string {\n if (markerHash === refHash) return `At ref \"${refName}\" target`;\n\n const pathToRef = findPath(graph, markerHash, refHash);\n if (pathToRef) return `${pathToRef.length} migration(s) behind ref \"${refName}\"`;\n\n const pathFromRef = findPath(graph, refHash, markerHash);\n if (pathFromRef) return `${pathFromRef.length} migration(s) ahead of ref \"${refName}\"`;\n\n return `No path between database marker and ref \"${refName}\" target`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkDA,IAAa,cAAb,MAAyB;CACvB,AAAS;CACT,AAAS;;CAGT,AAAS;;CAET,AAAS;;CAET,AAAS;CAET,YAAY,OAA6B,OAA6B;AACpE,OAAK,QAAQ;AACb,OAAK,QAAQ;EAEb,MAAM,sBAAM,IAAI,KAA0B;EAC1C,MAAM,sBAAM,IAAI,KAAa;EAC7B,MAAM,uBAAO,IAAI,KAAwB;AAEzC,OAAK,MAAM,KAAK,MACd,MAAK,IAAI,EAAE,IAAI,EAAE;AAEnB,OAAK,MAAM,KAAK,OAAO;GACrB,MAAM,OAAO,IAAI,IAAI,EAAE,KAAK;AAC5B,OAAI,KAAM,MAAK,KAAK,EAAE;OACjB,KAAI,IAAI,EAAE,MAAM,CAAC,EAAE,CAAC;AACzB,OAAI,IAAI,EAAE,GAAG;;AAGf,OAAK,UAAU;AACf,OAAK,gBAAgB;AACrB,OAAK,WAAW;;;CAIlB,SAAS,QAAsC;AAC7C,SAAO,KAAK,QAAQ,IAAI,OAAO,IAAI,EAAE;;;;;;;;;ACnEzC,MAAMA,cAA8C;CAClD,SAAS;CACT,SAAS;CACT,aAAa;CACd;;AAGD,SAAS,UAAU,MAAsB;AAEvC,SADiB,KAAK,WAAW,UAAU,G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