@prisma-next/cli 0.12.0-dev.3 → 0.12.0-dev.30

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 (149) hide show
  1. package/dist/cli.mjs +180 -163
  2. package/dist/cli.mjs.map +1 -1
  3. package/dist/{client-KgJorIvG.mjs → client-xeWpMlq1.mjs} +39 -15
  4. package/dist/client-xeWpMlq1.mjs.map +1 -0
  5. package/dist/{command-helpers-Bbw1GbwL.mjs → command-helpers-DK_5ItoJ.mjs} +284 -24
  6. package/dist/command-helpers-DK_5ItoJ.mjs.map +1 -0
  7. package/dist/commands/contract-emit.mjs +1 -1
  8. package/dist/commands/contract-infer.mjs +1 -1
  9. package/dist/commands/db-init.mjs +4 -5
  10. package/dist/commands/db-init.mjs.map +1 -1
  11. package/dist/commands/db-schema.mjs +3 -3
  12. package/dist/commands/db-sign.mjs +4 -4
  13. package/dist/commands/db-update.d.mts.map +1 -1
  14. package/dist/commands/db-update.mjs +10 -7
  15. package/dist/commands/db-update.mjs.map +1 -1
  16. package/dist/commands/db-verify.mjs +1 -1
  17. package/dist/commands/migrate.d.mts +1 -1
  18. package/dist/commands/migrate.mjs +5 -6
  19. package/dist/commands/migrate.mjs.map +1 -1
  20. package/dist/commands/migration-check.mjs +1 -1
  21. package/dist/commands/migration-graph.d.mts +13 -7
  22. package/dist/commands/migration-graph.d.mts.map +1 -1
  23. package/dist/commands/migration-graph.mjs +171 -2
  24. package/dist/commands/migration-graph.mjs.map +1 -0
  25. package/dist/commands/migration-list.d.mts +24 -26
  26. package/dist/commands/migration-list.d.mts.map +1 -1
  27. package/dist/commands/migration-list.mjs +2 -190
  28. package/dist/commands/migration-log.d.mts +6 -18
  29. package/dist/commands/migration-log.d.mts.map +1 -1
  30. package/dist/commands/migration-log.mjs +1 -137
  31. package/dist/commands/migration-new.mjs +3 -3
  32. package/dist/commands/migration-plan.d.mts +1 -1
  33. package/dist/commands/migration-plan.mjs +1 -1
  34. package/dist/commands/migration-show.d.mts +1 -1
  35. package/dist/commands/migration-show.mjs +3 -4
  36. package/dist/commands/migration-show.mjs.map +1 -1
  37. package/dist/commands/migration-status.d.mts +41 -141
  38. package/dist/commands/migration-status.d.mts.map +1 -1
  39. package/dist/commands/migration-status.mjs +2 -759
  40. package/dist/commands/ref.d.mts +1 -1
  41. package/dist/commands/ref.mjs +3 -3
  42. package/dist/commands/telemetry/index.d.mts +7 -0
  43. package/dist/commands/telemetry/index.d.mts.map +1 -0
  44. package/dist/commands/telemetry/index.mjs +2 -0
  45. package/dist/{contract-at-errors-BxP-TOMl.mjs → contract-at-errors-DG3kjgoz.mjs} +2 -2
  46. package/dist/{contract-at-errors-BxP-TOMl.mjs.map → contract-at-errors-DG3kjgoz.mjs.map} +1 -1
  47. package/dist/{contract-emit-D-4jrNve.mjs → contract-emit-BO0l6fnT.mjs} +3 -3
  48. package/dist/{contract-emit-D-4jrNve.mjs.map → contract-emit-BO0l6fnT.mjs.map} +1 -1
  49. package/dist/{contract-emit-DxcGl4Uq.mjs → contract-emit-C0Bs0VRj.mjs} +3 -3
  50. package/dist/{contract-emit-DxcGl4Uq.mjs.map → contract-emit-C0Bs0VRj.mjs.map} +1 -1
  51. package/dist/{contract-infer-D8uEbJuu.mjs → contract-infer-2wtPflGH.mjs} +3 -3
  52. package/dist/{contract-infer-D8uEbJuu.mjs.map → contract-infer-2wtPflGH.mjs.map} +1 -1
  53. package/dist/{contract-space-aggregate-loader-DvZwdkrr.mjs → contract-space-aggregate-loader-Dbr3-jHF.mjs} +4 -4
  54. package/dist/{contract-space-aggregate-loader-DvZwdkrr.mjs.map → contract-space-aggregate-loader-Dbr3-jHF.mjs.map} +1 -1
  55. package/dist/{db-verify-v_vUKXTU.mjs → db-verify-CxHiSiTG.mjs} +4 -4
  56. package/dist/{db-verify-v_vUKXTU.mjs.map → db-verify-CxHiSiTG.mjs.map} +1 -1
  57. package/dist/exports/control-api.d.mts +1 -1
  58. package/dist/exports/control-api.d.mts.map +1 -1
  59. package/dist/exports/control-api.mjs +2 -2
  60. package/dist/exports/index.mjs +1 -1
  61. package/dist/exports/init-output.mjs +1 -1
  62. package/dist/{framework-components-fYXjz_in.mjs → framework-components-CxOVKAAh.mjs} +2 -2
  63. package/dist/{framework-components-fYXjz_in.mjs.map → framework-components-CxOVKAAh.mjs.map} +1 -1
  64. package/dist/{global-flags-DEHjV8_s.d.mts → global-flags-DG4uY5tV.d.mts} +1 -1
  65. package/dist/{global-flags-DEHjV8_s.d.mts.map → global-flags-DG4uY5tV.d.mts.map} +1 -1
  66. package/dist/{init-Cv9UzWL5.mjs → init-R272pxux.mjs} +5 -58
  67. package/dist/init-R272pxux.mjs.map +1 -0
  68. package/dist/{inspect-live-schema-C6ohV_oQ.mjs → inspect-live-schema-RekOwfi5.mjs} +3 -3
  69. package/dist/{inspect-live-schema-C6ohV_oQ.mjs.map → inspect-live-schema-RekOwfi5.mjs.map} +1 -1
  70. package/dist/{migration-check-BiBJoYYW.mjs → migration-check-Dc0cOhKH.mjs} +2 -2
  71. package/dist/{migration-check-BiBJoYYW.mjs.map → migration-check-Dc0cOhKH.mjs.map} +1 -1
  72. package/dist/{migration-command-scaffold-CjvwO6at.mjs → migration-command-scaffold-ApB3NxWY.mjs} +3 -3
  73. package/dist/{migration-command-scaffold-CjvwO6at.mjs.map → migration-command-scaffold-ApB3NxWY.mjs.map} +1 -1
  74. package/dist/migration-graph-space-render-dmLLWift.mjs +1966 -0
  75. package/dist/migration-graph-space-render-dmLLWift.mjs.map +1 -0
  76. package/dist/migration-list-C5sXrl0U.mjs +228 -0
  77. package/dist/migration-list-C5sXrl0U.mjs.map +1 -0
  78. package/dist/migration-list-types-DS63IdFd.d.mts +23 -0
  79. package/dist/migration-list-types-DS63IdFd.d.mts.map +1 -0
  80. package/dist/migration-log-DD_vCbYW.mjs +203 -0
  81. package/dist/migration-log-DD_vCbYW.mjs.map +1 -0
  82. package/dist/{migration-plan-9DJ7q7_z.mjs → migration-plan-CeTjQOIG.mjs} +5 -5
  83. package/dist/{migration-plan-9DJ7q7_z.mjs.map → migration-plan-CeTjQOIG.mjs.map} +1 -1
  84. package/dist/migration-status-qV8ctwPy.mjs +432 -0
  85. package/dist/migration-status-qV8ctwPy.mjs.map +1 -0
  86. package/dist/{output-B60Gw5fu.mjs → output-CF_hqzI-.mjs} +1 -1
  87. package/dist/{output-B60Gw5fu.mjs.map → output-CF_hqzI-.mjs.map} +1 -1
  88. package/dist/{ref-advancement-DUZqsue6.mjs → ref-advancement-V1o-9LVK.mjs} +1 -1
  89. package/dist/{ref-advancement-DUZqsue6.mjs.map → ref-advancement-V1o-9LVK.mjs.map} +1 -1
  90. package/dist/telemetry-S-NGi9U6.mjs +122 -0
  91. package/dist/telemetry-S-NGi9U6.mjs.map +1 -0
  92. package/dist/{types-Dt_SfqFm.d.mts → types-Mh7mdPHM.d.mts} +13 -2
  93. package/dist/types-Mh7mdPHM.d.mts.map +1 -0
  94. package/dist/{verify-DCA9Sldu.mjs → verify-BdI-BgYi.mjs} +2 -2
  95. package/dist/{verify-DCA9Sldu.mjs.map → verify-BdI-BgYi.mjs.map} +1 -1
  96. package/package.json +22 -19
  97. package/src/cli.ts +5 -0
  98. package/src/commands/db-update.ts +7 -1
  99. package/src/commands/init/index.ts +6 -35
  100. package/src/commands/init/init.ts +1 -14
  101. package/src/commands/init/inputs.ts +0 -75
  102. package/src/commands/migration-graph.ts +143 -82
  103. package/src/commands/migration-list.ts +55 -25
  104. package/src/commands/migration-log.ts +23 -89
  105. package/src/commands/migration-status-overlay.ts +61 -0
  106. package/src/commands/migration-status.ts +431 -1055
  107. package/src/commands/telemetry/index.ts +107 -0
  108. package/src/commands/telemetry/status.ts +67 -0
  109. package/src/control-api/client.ts +11 -1
  110. package/src/control-api/operations/apply.ts +1 -0
  111. package/src/control-api/operations/db-apply.ts +24 -1
  112. package/src/control-api/operations/migration-apply.ts +10 -3
  113. package/src/control-api/types.ts +16 -1
  114. package/src/utils/cli-errors.ts +17 -0
  115. package/src/utils/formatters/errors.ts +11 -0
  116. package/src/utils/formatters/migration-graph-lane-colors.ts +194 -0
  117. package/src/utils/formatters/migration-graph-layout.ts +51 -7
  118. package/src/utils/formatters/migration-graph-rows.ts +128 -15
  119. package/src/utils/formatters/migration-graph-space-render.ts +138 -0
  120. package/src/utils/formatters/migration-graph-tree-render.ts +405 -77
  121. package/src/utils/formatters/migration-list-data-column.ts +4 -91
  122. package/src/utils/formatters/migration-list-graph-topology.ts +68 -90
  123. package/src/utils/formatters/migration-list-render.ts +122 -70
  124. package/src/utils/formatters/migration-list-styler.ts +48 -5
  125. package/src/utils/formatters/migration-log-table.ts +190 -0
  126. package/src/utils/formatters/migrations.ts +25 -1
  127. package/src/utils/global-flags.ts +35 -0
  128. package/src/utils/legend.ts +38 -0
  129. package/src/utils/telemetry.ts +68 -32
  130. package/dist/client-KgJorIvG.mjs.map +0 -1
  131. package/dist/command-helpers-Bbw1GbwL.mjs.map +0 -1
  132. package/dist/commands/migration-list.mjs.map +0 -1
  133. package/dist/commands/migration-log.mjs.map +0 -1
  134. package/dist/commands/migration-status.mjs.map +0 -1
  135. package/dist/graph-render-rFAqZujX.mjs +0 -1081
  136. package/dist/graph-render-rFAqZujX.mjs.map +0 -1
  137. package/dist/init-Cv9UzWL5.mjs.map +0 -1
  138. package/dist/migration-graph-D7DVUElV.mjs +0 -1232
  139. package/dist/migration-graph-D7DVUElV.mjs.map +0 -1
  140. package/dist/migration-list-styler-BRwF4-gy.mjs +0 -399
  141. package/dist/migration-list-styler-BRwF4-gy.mjs.map +0 -1
  142. package/dist/migration-types-D2FW63pr.d.mts +0 -15
  143. package/dist/migration-types-D2FW63pr.d.mts.map +0 -1
  144. package/dist/migrations-Cv2jxNNK.mjs +0 -228
  145. package/dist/migrations-Cv2jxNNK.mjs.map +0 -1
  146. package/dist/types-Dt_SfqFm.d.mts.map +0 -1
  147. package/src/utils/formatters/graph-migration-mapper.ts +0 -235
  148. package/src/utils/formatters/graph-render.ts +0 -1323
  149. package/src/utils/formatters/graph-types.ts +0 -120
@@ -1,14 +1,7 @@
1
- import type { Contract } from '@prisma-next/contract/types';
2
- import {
3
- createControlStack,
4
- type MigrationPlanOperation,
5
- } from '@prisma-next/framework-components/control';
6
- import {
7
- type ContractMarkerRecordLike,
8
- type ContractSpaceAggregate,
9
- graphWalkStrategy,
10
- loadContractSpaceAggregate,
11
- requireHeadRef,
1
+ import type { LedgerEntryRecord } from '@prisma-next/contract/types';
2
+ import type {
3
+ ContractMarkerRecordLike,
4
+ ContractSpaceMember,
12
5
  } from '@prisma-next/migration-tools/aggregate';
13
6
  import { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';
14
7
  import {
@@ -16,26 +9,19 @@ import {
16
9
  errorUnknownInvariant,
17
10
  MigrationToolsError,
18
11
  } from '@prisma-next/migration-tools/errors';
19
- import type { MigrationEdge, MigrationGraph } from '@prisma-next/migration-tools/graph';
20
- import {
21
- findPath,
22
- findPathWithDecision,
23
- findReachableLeaves,
24
- } from '@prisma-next/migration-tools/migration-graph';
25
- import type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';
12
+ import { findPath, findPathWithDecision } from '@prisma-next/migration-tools/migration-graph';
26
13
  import { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';
27
14
  import type { RefEntry, Refs } from '@prisma-next/migration-tools/refs';
28
15
  import { readRefs } from '@prisma-next/migration-tools/refs';
29
16
  import { ifDefined } from '@prisma-next/utils/defined';
30
17
  import { notOk, ok, type Result } from '@prisma-next/utils/result';
31
- import { cyan, dim, magenta, yellow } from 'colorette';
18
+ import { dim, yellow } from 'colorette';
32
19
  import { Command } from 'commander';
33
-
34
20
  import { loadConfig } from '../config-loader';
35
21
  import { createControlClient } from '../control-api/client';
36
22
  import {
37
23
  CliStructuredError,
38
- errorRuntime,
24
+ errorDatabaseConnectionRequired,
39
25
  errorUnexpected,
40
26
  mapMigrationToolsError,
41
27
  mapRefResolutionError,
@@ -49,518 +35,225 @@ import {
49
35
  setCommandDescriptions,
50
36
  setCommandExamples,
51
37
  setCommandSeeAlso,
52
- toPathDecisionResult,
53
38
  toStructuralEdge,
54
39
  } from '../utils/command-helpers';
55
40
  import {
56
- appContractStandInFromIdentity,
41
+ buildReadAggregate,
57
42
  loadContractRawSafely,
58
- refuseContractSpaceIntegrity,
59
43
  refusePackageCorruptionOnAggregate,
60
44
  } from '../utils/contract-space-aggregate-loader';
61
- import { toDeclaredExtensionsFromRaw } from '../utils/extension-pack-inputs';
62
- import {
63
- type EdgeStatus,
64
- type EdgeStatusKind,
65
- migrationGraphToRenderInput,
66
- } from '../utils/formatters/graph-migration-mapper';
67
45
  import {
68
- extractRelevantSubgraph,
69
- graphRenderer,
70
- isLinearGraph,
71
- } from '../utils/formatters/graph-render';
46
+ computeGlobalMaxDirNameWidth,
47
+ computeGlobalMaxEdgeTreePrefixWidth,
48
+ indentMigrationGraphTreeBlock,
49
+ renderMigrationGraphSpaceTree,
50
+ } from '../utils/formatters/migration-graph-space-render';
51
+ import type { MigrationEdgeAnnotation } from '../utils/formatters/migration-graph-tree-render';
52
+ import { renderMigrationGraphLegend } from '../utils/formatters/migration-graph-tree-render';
53
+ import type { MigrationListEntry } from '../utils/formatters/migration-list-types';
72
54
  import { formatStyledHeader } from '../utils/formatters/styled';
73
55
  import type { CommonCommandOptions } from '../utils/global-flags';
74
56
  import { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';
75
- import type { StatusDiagnostic, StatusRef } from '../utils/migration-types';
57
+ import { shouldShowLegend, validateLegendOptions } from '../utils/legend';
58
+ import type { StatusDiagnostic } from '../utils/migration-types';
76
59
  import { handleResult } from '../utils/result-handler';
77
60
  import { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';
61
+ import {
62
+ listRefsByContractHash,
63
+ migrationSpaceListEntriesFromAggregate,
64
+ runMigrationList,
65
+ } from './migration-list';
66
+ import {
67
+ appliedHashesFromLedger,
68
+ deriveStatusEdgeAnnotations,
69
+ statusForMigrationHash,
70
+ } from './migration-status-overlay';
78
71
 
79
72
  interface MigrationStatusOptions extends CommonCommandOptions {
80
73
  readonly db?: string;
81
74
  readonly config?: string;
82
75
  readonly to?: string;
83
76
  readonly from?: string;
77
+ readonly space?: string;
78
+ readonly legend?: boolean;
84
79
  }
85
80
 
86
- export interface MigrationStatusEntry {
87
- readonly dirName: string;
88
- readonly from: string;
89
- readonly to: string;
90
- readonly migrationHash: string;
91
- readonly operationCount: number;
92
- readonly operationSummary: string;
93
- readonly hasDestructive: boolean;
94
- readonly status: EdgeStatusKind | 'unknown';
81
+ export interface MigrationStatusMigrationEntry extends MigrationListEntry {
82
+ readonly status: 'applied' | 'pending' | null;
95
83
  }
96
84
 
97
- /**
98
- * Per-space status row in the aggregate-shaped status output.
99
- *
100
- * Surfaces, for each contract space:
101
- *
102
- * - `headHash`: the on-disk head ref's hash (where the space is going).
103
- * - `markerHash`: the live marker hash for the space, or null if no
104
- * marker has been written yet (greenfield, or pre-`migrate`).
105
- * - `pendingCount`: number of migration edges between marker and head.
106
- * Computed via {@link graphWalkStrategy}; 0 means the space is
107
- * already at head.
108
- * - `status`: convenience tag the formatter uses to pick a glyph.
109
- * `'never-planned'` is reserved for spaces with non-empty head but
110
- * no on-disk migrations — which shouldn't happen if the loader's
111
- * integrity check passes.
112
- *
113
- * Online-only fields (`markerHash`, `status`) are absent when the
114
- * command runs without a database connection.
115
- */
116
- export interface MigrationStatusSpaceEntry {
85
+ export interface MigrationStatusSpaceResult {
117
86
  readonly spaceId: string;
118
- readonly kind: 'app' | 'extension';
119
- readonly headHash: string;
120
- readonly markerHash?: string | null;
121
- readonly pendingCount?: number;
122
- readonly status?: 'up-to-date' | 'pending' | 'no-marker' | 'never-planned' | 'unreachable';
123
- }
124
-
125
- /**
126
- * Sum per-space `pendingCount` into a cross-space total, but only when
127
- * every loaded space reports a defined `pendingCount`. Returns
128
- * `undefined` if any space is on the marker-unknown / offline path
129
- * (where `pendingCount` is intentionally absent), so JSON consumers can
130
- * distinguish "no pending" from "unknown".
131
- */
132
- export function computeTotalPendingAcrossSpaces(
133
- spaces: readonly MigrationStatusSpaceEntry[],
134
- ): number | undefined {
135
- if (spaces.length === 0) return undefined;
136
- let total = 0;
137
- for (const s of spaces) {
138
- if (s.pendingCount === undefined) return undefined;
139
- total += s.pendingCount;
140
- }
141
- return total;
87
+ readonly markerHash: string | null;
88
+ readonly targetHash: string;
89
+ readonly migrations: readonly MigrationStatusMigrationEntry[];
142
90
  }
143
91
 
144
- export type { StatusDiagnostic, StatusRef } from '../utils/migration-types';
145
-
146
92
  export interface MigrationStatusResult {
147
93
  readonly ok: true;
148
- readonly mode: 'online' | 'offline';
149
- readonly migrations: readonly MigrationStatusEntry[];
150
- readonly markerHash?: string;
151
- readonly targetHash: string;
152
- readonly contractHash: string;
153
- readonly refs?: readonly StatusRef[];
154
- /** Required invariants from the active ref, sorted ascending. Always present (`[]` when no `--ref` or the ref declares none) — knowable offline. */
155
- readonly requiredInvariants: readonly string[];
156
- /**
157
- * Invariants the marker has applied at least once, intersected with
158
- * `requiredInvariants` for display relevance. JSON consumers see only the
159
- * subset overlapping the active ref's required set — the full unfiltered
160
- * marker invariant list lives on `marker.invariants` (control plane) and
161
- * is not surfaced here. Present only in `mode === 'online'`; absent when
162
- * offline (the marker is unknown, not empty).
163
- */
164
- readonly appliedInvariants?: readonly string[];
165
- /** required − applied. Present only in `mode === 'online'`; absent when offline. */
166
- readonly missingInvariants?: readonly string[];
167
- readonly pathDecision?: {
168
- readonly fromHash: string;
169
- readonly toHash: string;
170
- readonly alternativeCount: number;
171
- readonly tieBreakReasons: readonly string[];
172
- readonly refName?: string;
173
- readonly requiredInvariants: readonly string[];
174
- readonly satisfiedInvariants: readonly string[];
175
- readonly selectedPath: readonly {
176
- readonly dirName: string;
177
- readonly migrationHash: string;
178
- readonly from: string;
179
- readonly to: string;
180
- readonly invariants: readonly string[];
181
- }[];
182
- };
94
+ readonly spaces: readonly MigrationStatusSpaceResult[];
183
95
  readonly summary: string;
96
+ readonly missingInvariantsLine?: string;
184
97
  readonly diagnostics: readonly StatusDiagnostic[];
185
- /**
186
- * Aggregate enumeration of every on-disk contract space (app +
187
- * extensions), in canonical schedule order (extensions
188
- * alphabetically, then app). Present whenever the aggregate loader
189
- * succeeded; absent in early-error returns (e.g. unreadable
190
- * migrations directory) where the existing diagnostics already
191
- * surface the failure.
192
- *
193
- * The top-level fields (`migrations`, `markerHash`, `targetHash`,
194
- * `pathDecision`, …) describe the **app member** specifically.
195
- * Per-space detail for extension members lives only on this list.
196
- */
197
- readonly spaces?: readonly MigrationStatusSpaceEntry[];
198
- /** Cross-space pending-migration total (sum of `spaces[].pendingCount`). Present when `spaces` is. */
199
- readonly totalPendingAcrossSpaces?: number;
200
- readonly graph?: MigrationGraph;
201
- readonly bundles?: readonly OnDiskMigrationPackage[];
202
- readonly edgeStatuses?: readonly EdgeStatus[];
203
- readonly activeRefHash?: string;
204
- readonly activeRefName?: string;
205
- readonly diverged?: boolean;
98
+ readonly treeSections: readonly MigrationStatusTreeSection[];
206
99
  }
207
100
 
208
- function summarizeOps(ops: readonly MigrationPlanOperation[]): {
209
- summary: string;
210
- hasDestructive: boolean;
211
- } {
212
- if (ops.length === 0) return { summary: '0 ops', hasDestructive: false };
213
-
214
- const classes = new Map<string, number>();
215
- for (const op of ops) {
216
- classes.set(op.operationClass, (classes.get(op.operationClass) ?? 0) + 1);
217
- }
218
-
219
- const hasDestructive = classes.has('destructive');
220
- const count = ops.length;
221
- const noun = count === 1 ? 'op' : 'ops';
222
-
223
- if (classes.size === 1) {
224
- const cls = [...classes.keys()][0]!;
225
- return { summary: `${count} ${noun} (all ${cls})`, hasDestructive };
226
- }
227
-
228
- const destructiveCount = classes.get('destructive');
229
- if (destructiveCount) {
230
- return { summary: `${count} ${noun} (${destructiveCount} destructive)`, hasDestructive };
231
- }
232
-
233
- const parts = [...classes.entries()].map(([cls, n]) => `${n} ${cls}`);
234
- return { summary: `${count} ${noun} (${parts.join(', ')})`, hasDestructive };
101
+ export interface MigrationStatusTreeSection {
102
+ readonly spaceId: string;
103
+ readonly tree: string;
104
+ readonly showHeading: boolean;
235
105
  }
236
106
 
237
- /**
238
- * Derive per-edge status across the full graph using path analysis.
239
- *
240
- * - **applied**: edge is on the path from root to the DB marker
241
- * - **pending**: edge is on the path from the DB marker to the target
242
- * (and the marker is reachable from root, i.e. it's on the same branch)
243
- * - **unreachable**: edge is on the path from root to the target but the DB
244
- * marker is on a different branch — `apply` can't reach these edges
245
- * without the DB first moving to this branch
246
- *
247
- * Returns statuses only for edges that have a known status (skips offline
248
- * and edges not on any relevant path).
249
- *
250
- * @internal Exported for testing only.
251
- */
252
- export function deriveEdgeStatuses(
253
- graph: MigrationGraph,
254
- targetHash: string,
255
- contractHash: string,
256
- markerHash: string | undefined,
257
- mode: 'online' | 'offline',
258
- ): EdgeStatus[] {
259
- if (mode === 'offline') return [];
260
-
261
- const edgeKey = (e: MigrationEdge) => `${e.from}\0${e.to}`;
107
+ export type { StatusDiagnostic, StatusRef } from '../utils/migration-types';
262
108
 
263
- // No marker = empty DB — treat root as the marker (nothing applied, everything pending)
264
- const effectiveMarker = markerHash ?? EMPTY_CONTRACT_HASH;
109
+ function shortDisplayHash(hash: string): string {
110
+ const stripped = hash.startsWith('sha256:') ? hash.slice(7) : hash;
111
+ return stripped.slice(0, 12);
112
+ }
265
113
 
266
- const appliedPath =
267
- markerHash !== undefined ? findPath(graph, EMPTY_CONTRACT_HASH, markerHash) : null;
114
+ function resolveTarget(contractHash: string, activeRefHash: string | undefined): string {
115
+ return activeRefHash ?? contractHash;
116
+ }
268
117
 
269
- const pendingPath = findPath(graph, effectiveMarker, targetHash);
270
- const targetPath = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);
118
+ function buildStatusMigrations(
119
+ listMigrations: readonly MigrationListEntry[],
120
+ annotations: ReadonlyMap<string, MigrationEdgeAnnotation>,
121
+ ): readonly MigrationStatusMigrationEntry[] {
122
+ return listMigrations.map((migration) => ({
123
+ ...migration,
124
+ status: statusForMigrationHash(migration.migrationHash, annotations),
125
+ }));
126
+ }
271
127
 
272
- const statuses: EdgeStatus[] = [];
273
- const assignedKeys = new Set<string>();
128
+ function renderSpaceTree(args: {
129
+ readonly member: ContractSpaceMember;
130
+ readonly liveContractHash: string;
131
+ readonly migrations: readonly MigrationListEntry[];
132
+ readonly markerHash: string | undefined;
133
+ readonly showDbMarker: boolean;
134
+ readonly statusOverlay: ReadonlyMap<string, MigrationEdgeAnnotation>;
135
+ readonly colorize: boolean;
136
+ readonly glyphMode: 'unicode' | 'ascii';
137
+ readonly globalMaxEdgeTreePrefixWidth?: number;
138
+ readonly globalMaxDirNameWidth?: number;
139
+ }): string {
140
+ const graph = args.member.graph();
141
+ if (graph.nodes.size === 0) {
142
+ return '';
143
+ }
144
+ return renderMigrationGraphSpaceTree({
145
+ graph,
146
+ migrations: args.migrations,
147
+ liveContractHash: args.liveContractHash,
148
+ refsByHash: listRefsByContractHash(args.member),
149
+ statusOverlayByHash: args.statusOverlay,
150
+ colorize: args.colorize,
151
+ glyphMode: args.glyphMode,
152
+ ...(args.showDbMarker && args.markerHash !== undefined ? { dbHash: args.markerHash } : {}),
153
+ ...(args.globalMaxEdgeTreePrefixWidth !== undefined
154
+ ? { globalMaxEdgeTreePrefixWidth: args.globalMaxEdgeTreePrefixWidth }
155
+ : {}),
156
+ ...(args.globalMaxDirNameWidth !== undefined
157
+ ? { globalMaxDirNameWidth: args.globalMaxDirNameWidth }
158
+ : {}),
159
+ });
160
+ }
274
161
 
275
- // Applied edges (root marker)
276
- if (appliedPath) {
277
- for (const e of appliedPath) {
278
- assignedKeys.add(edgeKey(e));
279
- statuses.push({ dirName: e.dirName, status: 'applied' });
280
- }
281
- }
162
+ function countPending(migrations: readonly MigrationStatusMigrationEntry[]): number {
163
+ return migrations.filter((m) => m.status === 'pending').length;
164
+ }
282
165
 
283
- // Pending edges (marker → target)
284
- if (pendingPath) {
285
- for (const e of pendingPath) {
286
- assignedKeys.add(edgeKey(e));
287
- statuses.push({ dirName: e.dirName, status: 'pending' });
288
- }
289
- }
166
+ export function buildNoPathSummary(args: {
167
+ readonly markerHash: string | undefined;
168
+ readonly targetHash: string;
169
+ readonly explicitTarget: boolean;
170
+ readonly refName: string | undefined;
171
+ }): string {
172
+ const markerPart =
173
+ args.markerHash !== undefined
174
+ ? `the database state (${shortDisplayHash(args.markerHash)})`
175
+ : 'the database state';
176
+ const targetShort = shortDisplayHash(args.targetHash);
177
+ if (!args.explicitTarget) {
178
+ return `No migration path from ${markerPart} to the application's contract (${targetShort}). Run \`prisma-next migration plan --name <name>\` to author one.`;
179
+ }
180
+ const targetLabel =
181
+ args.refName !== undefined
182
+ ? `the target (${targetShort} via \`${args.refName}\`)`
183
+ : `the target (${targetShort})`;
184
+ return `No migration path from ${markerPart} to ${targetLabel}. Run \`prisma-next migration plan --name <name>\` to author one, or pass \`--to <contract>\` to pick a reachable target.`;
185
+ }
290
186
 
291
- // Pending edges beyond the target: target → contract (when target is a ref
292
- // and the contract is reachable from it)
293
- if (
294
- contractHash !== EMPTY_CONTRACT_HASH &&
295
- contractHash !== targetHash &&
296
- graph.nodes.has(contractHash)
297
- ) {
298
- const beyondTarget = findPath(graph, targetHash, contractHash);
299
- if (beyondTarget) {
300
- for (const e of beyondTarget) {
301
- if (!assignedKeys.has(edgeKey(e))) {
302
- assignedKeys.add(edgeKey(e));
303
- statuses.push({ dirName: e.dirName, status: 'pending' });
304
- }
305
- }
306
- }
187
+ export function buildStatusHeadline(args: {
188
+ readonly pendingCount: number;
189
+ readonly targetHash: string;
190
+ readonly markerDiverged: boolean;
191
+ readonly markerHash: string | undefined;
192
+ }): string {
193
+ if (args.markerDiverged && args.markerHash !== undefined) {
194
+ return `Database marker ${shortDisplayHash(args.markerHash)} is not in the on-disk migration graph`;
307
195
  }
308
-
309
- // Unreachable edges: on the path from root to the target but neither applied
310
- // nor pending. This covers two cases:
311
- // 1. Marker can't reach target at all (different branch entirely)
312
- // 2. Marker reaches target via a different route, leaving some root→target
313
- // edges orphaned (e.g. a fork where one branch was applied and apply
314
- // will continue through the other)
315
- if (targetPath) {
316
- for (const e of targetPath) {
317
- if (!assignedKeys.has(edgeKey(e))) {
318
- statuses.push({ dirName: e.dirName, status: 'unreachable' });
319
- }
320
- }
196
+ if (args.pendingCount === 0) {
197
+ return 'Up to date';
321
198
  }
322
-
323
- return statuses;
199
+ return `${args.pendingCount} pending — run \`prisma-next migrate --to ${shortDisplayHash(args.targetHash)}\``;
324
200
  }
325
201
 
326
- /**
327
- * @param mode — 'online' if we connected to the database, 'offline' otherwise
328
- * @param markerHash — the marker hash from the database, or undefined if no marker row / offline
329
- */
330
- function buildMigrationEntries(
331
- chain: readonly MigrationEdge[],
332
- packages: readonly OnDiskMigrationPackage[],
333
- mode: 'online' | 'offline',
334
- markerHash: string | undefined,
335
- edgeStatuses?: readonly EdgeStatus[],
336
- ): MigrationStatusEntry[] {
337
- const pkgByDirName = new Map(packages.map((p) => [p.dirName, p]));
338
- const statusByDirName = edgeStatuses
339
- ? new Map(edgeStatuses.map((e) => [e.dirName, e.status]))
340
- : undefined;
341
-
342
- const markerInChain = markerHash === undefined || chain.some((e) => e.to === markerHash);
343
-
344
- const entries: MigrationStatusEntry[] = [];
345
- let reachedMarker = mode === 'online' && markerHash === undefined;
346
-
347
- for (const migration of chain) {
348
- const pkg = pkgByDirName.get(migration.dirName);
349
- const ops = (pkg?.ops ?? []) as readonly MigrationPlanOperation[];
350
- const { summary, hasDestructive } = summarizeOps(ops);
351
-
352
- let status: EdgeStatusKind | 'unknown';
353
- const edgeStatus = statusByDirName?.get(migration.dirName);
354
- if (edgeStatus) {
355
- status = edgeStatus;
356
- } else if (mode === 'offline' || !markerInChain) {
357
- status = 'unknown';
358
- } else if (reachedMarker) {
359
- status = 'pending';
360
- } else {
361
- status = 'applied';
362
- }
363
-
364
- entries.push({
365
- dirName: migration.dirName,
366
- from: migration.from,
367
- to: migration.to,
368
- migrationHash: migration.migrationHash,
369
- operationCount: ops.length,
370
- operationSummary: summary,
371
- hasDestructive,
372
- status,
373
- });
374
-
375
- if (!reachedMarker && migration.to === markerHash) {
376
- reachedMarker = true;
377
- }
202
+ export function formatStatusSummary(result: MigrationStatusResult, colorize: boolean): string {
203
+ const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);
204
+ const lines: string[] = [];
205
+ const pendingTotal = result.spaces.reduce(
206
+ (sum, space) => sum + countPending(space.migrations),
207
+ 0,
208
+ );
209
+ const hasDivergence = result.diagnostics.some(
210
+ (d) => d.code === 'MIGRATION.MARKER_NOT_IN_HISTORY',
211
+ );
212
+ if (hasDivergence || pendingTotal > 0) {
213
+ lines.push(c(yellow, result.summary));
214
+ } else {
215
+ lines.push(result.summary);
378
216
  }
379
-
380
- return entries;
381
- }
382
-
383
- /**
384
- * Resolve the migration chain to display in status output.
385
- *
386
- * When offline or the marker is at EMPTY, the chain is simply the shortest
387
- * path from EMPTY to the target — all structural paths are equivalent per
388
- * the spec, so the deterministic shortest path is the canonical display.
389
- *
390
- * When online with a non-empty marker, the chain routes *through* the marker:
391
- * EMPTY→marker (applied history) + marker→target (pending edges). This ensures
392
- * the displayed chain includes the marker node so applied/pending status is
393
- * correct. Without this, BFS from EMPTY to target could pick a shortest path
394
- * that bypasses the marker entirely (e.g. in a diamond graph), causing the
395
- * marker to appear "diverged" when it isn't.
396
- */
397
- function resolveDisplayChain(
398
- graph: MigrationGraph,
399
- targetHash: string,
400
- markerHash: string | undefined,
401
- ): readonly MigrationEdge[] | null {
402
- if (markerHash === undefined) {
403
- return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);
217
+ if (result.missingInvariantsLine !== undefined) {
218
+ lines.push(c(dim, result.missingInvariantsLine));
404
219
  }
405
-
406
- const toMarker = findPath(graph, EMPTY_CONTRACT_HASH, markerHash);
407
- // Marker unreachable from EMPTY — show the target chain anyway.
408
- // The caller detects this via markerInChain and emits a divergence diagnostic.
409
- if (!toMarker) return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);
410
-
411
- if (markerHash === targetHash) return toMarker;
412
-
413
- const fromMarker = findPath(graph, markerHash, targetHash);
414
- if (fromMarker) return [...toMarker, ...fromMarker];
415
-
416
- // Marker is ahead of target (or on a disconnected branch).
417
- // Try the inverse: target→marker. If it succeeds, the marker is ahead —
418
- // show the full chain from EMPTY through the target and on to the marker.
419
- const toTarget = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);
420
- if (!toTarget) return null;
421
-
422
- const targetToMarker = findPath(graph, targetHash, markerHash);
423
- if (targetToMarker) return [...toTarget, ...targetToMarker];
424
-
425
- // Genuinely disconnected — show EMPTY→target; caller handles divergence diagnostic.
426
- return toTarget;
220
+ return lines.join('\n');
427
221
  }
428
222
 
429
- /**
430
- * Build the aggregate enumeration of contract spaces for the status
431
- * output. Loads the aggregate from disk (lossy on failure extension
432
- * spaces are simply omitted, the app member's output keeps working),
433
- * reads per-space marker rows when online, and uses
434
- * {@link graphWalkStrategy} to compute each space's pending count.
435
- *
436
- * The aggregate-walking status reports per-space marker + pending
437
- * state alongside the cross-space totals.
438
- */
439
- export async function loadAggregateStatusSpaces(args: {
440
- readonly aggregate: ContractSpaceAggregate;
441
- readonly extensionPacks: ReadonlyArray<unknown>;
442
- readonly markersBySpace: ReadonlyMap<string, ContractMarkerRecordLike> | null;
443
- }): Promise<readonly MigrationStatusSpaceEntry[]> {
444
- const declaredExtensions = toDeclaredExtensionsFromRaw(args.extensionPacks);
445
- if (
446
- refuseContractSpaceIntegrity(args.aggregate, {
447
- declaredExtensions,
448
- checkContracts: true,
449
- })
450
- ) {
451
- // Full integrity refusal (drift, layout violation, etc.) — surfacing
452
- // it as a status diagnostic would duplicate `migration plan`'s job.
453
- // The app pipeline still runs; extensions are simply not enumerated.
454
- return [];
455
- }
456
- const aggregate = args.aggregate;
457
-
458
- const orderedMembers = [...aggregate.extensions, aggregate.app];
459
- const rows: MigrationStatusSpaceEntry[] = [];
460
- for (const member of orderedMembers) {
461
- const liveMarker = args.markersBySpace?.get(member.spaceId) ?? null;
462
- const isApp = member.spaceId === aggregate.app.spaceId;
463
- // The aggregate passed the integrity gate above, so every member has
464
- // a resolved head ref (a missing one would have refused the load).
465
- const headRef = requireHeadRef(member);
466
-
467
- if (member.graph().nodes.size === 0) {
468
- rows.push({
469
- spaceId: member.spaceId,
470
- kind: isApp ? 'app' : 'extension',
471
- headHash: headRef.hash,
472
- ...(args.markersBySpace !== null
473
- ? {
474
- markerHash: liveMarker?.storageHash ?? null,
475
- status: headRef.hash === EMPTY_CONTRACT_HASH ? 'up-to-date' : 'never-planned',
476
- pendingCount: 0,
477
- }
478
- : {}),
479
- });
480
- continue;
481
- }
482
-
483
- if (args.markersBySpace === null) {
484
- rows.push({
485
- spaceId: member.spaceId,
486
- kind: isApp ? 'app' : 'extension',
487
- headHash: headRef.hash,
488
- });
489
- continue;
223
+ export function formatStatusHumanOutput(result: MigrationStatusResult, colorize: boolean): string {
224
+ const sections: string[] = [];
225
+ for (const section of result.treeSections) {
226
+ if (section.showHeading) {
227
+ sections.push(`${section.spaceId}:`);
490
228
  }
491
-
492
- const walked = graphWalkStrategy({
493
- aggregateTargetId: aggregate.targetId,
494
- member,
495
- currentMarker: liveMarker,
496
- });
497
- let pendingCount = 0;
498
- let status: MigrationStatusSpaceEntry['status'];
499
- if (walked.kind === 'ok') {
500
- // Count pending *migrations* (graph edges), not operations: a
501
- // single authored migration that lowers to N ops or zero ops
502
- // both count as exactly one pending unit of work for the user.
503
- pendingCount = walked.result.migrationEdges?.length ?? 0;
504
- if (liveMarker === null) {
505
- status = pendingCount === 0 ? 'no-marker' : 'pending';
506
- } else {
507
- status = pendingCount === 0 ? 'up-to-date' : 'pending';
508
- }
229
+ if (section.tree.length > 0) {
230
+ sections.push(section.tree);
509
231
  } else {
510
- status = 'unreachable';
232
+ sections.push('(no migrations)');
511
233
  }
512
-
513
- rows.push({
514
- spaceId: member.spaceId,
515
- kind: isApp ? 'app' : 'extension',
516
- headHash: headRef.hash,
517
- markerHash: liveMarker?.storageHash ?? null,
518
- pendingCount,
519
- ...(status ? { status } : {}),
520
- });
234
+ sections.push('');
521
235
  }
522
- return rows;
236
+ sections.push(formatStatusSummary(result, colorize));
237
+ return sections.join('\n').trimEnd();
523
238
  }
524
239
 
525
- /**
526
- * Read the raw contract.json bytes from disk for the aggregate
527
- * loader. Returns `null` if the file is missing or unparseable —
528
- * the existing `readContractEnvelope` path will report the same
529
- * problem via a status diagnostic, no need to double-surface.
530
- */
531
-
532
- async function validateOnlineMarkerRead(
533
- config: Awaited<ReturnType<typeof loadConfig>>,
534
- dbConnection: unknown,
535
- ): Promise<Result<void, CliStructuredError>> {
536
- const driver = config.driver;
537
- if (!driver) {
538
- return ok(undefined);
539
- }
540
-
541
- const client = createControlClient({
542
- family: config.family,
543
- target: config.target,
544
- adapter: config.adapter,
545
- driver,
546
- extensionPacks: config.extensionPacks ?? [],
547
- });
548
- try {
549
- await client.connect(dbConnection);
550
- await client.readMarker();
551
- return ok(undefined);
552
- } catch (error) {
553
- if (CliStructuredError.is(error)) {
554
- return notOk(error);
555
- }
556
- return notOk(
557
- errorUnexpected(error instanceof Error ? error.message : String(error), {
558
- why: `Failed to read database marker: ${error instanceof Error ? error.message : String(error)}`,
559
- }),
560
- );
561
- } finally {
562
- await client.close();
563
- }
240
+ async function readMarkersAndLedgers(args: {
241
+ readonly client: ReturnType<typeof createControlClient>;
242
+ readonly spaceIds: readonly string[];
243
+ }): Promise<{
244
+ readonly markersBySpace: ReadonlyMap<string, ContractMarkerRecordLike>;
245
+ readonly ledgersBySpace: ReadonlyMap<string, readonly LedgerEntryRecord[]>;
246
+ }> {
247
+ const markersBySpace = new Map<string, ContractMarkerRecordLike>();
248
+ const all = await args.client.readAllMarkers();
249
+ for (const [spaceId, marker] of all) {
250
+ markersBySpace.set(spaceId, marker);
251
+ }
252
+ const ledgersBySpace = new Map<string, readonly LedgerEntryRecord[]>();
253
+ for (const spaceId of args.spaceIds) {
254
+ ledgersBySpace.set(spaceId, await args.client.readLedger(spaceId));
255
+ }
256
+ return { markersBySpace, ledgersBySpace };
564
257
  }
565
258
 
566
259
  async function executeMigrationStatusCommand(
@@ -569,17 +262,24 @@ async function executeMigrationStatusCommand(
569
262
  ui: TerminalUI,
570
263
  ): Promise<Result<MigrationStatusResult, CliStructuredError>> {
571
264
  const config = await loadConfig(options.config);
572
- const { configPath, appMigrationsRelative, migrationsDir, refsDir } = resolveMigrationPaths(
265
+ const { configPath, migrationsDir, migrationsRelative, refsDir } = resolveMigrationPaths(
573
266
  options.config,
574
267
  config,
575
268
  );
576
269
 
577
270
  const dbConnection = options.db ?? config.db?.connection;
578
271
  const hasDriver = !!config.driver;
272
+ const usingFromOverride = options.from !== undefined;
273
+
274
+ if (!usingFromOverride && (!dbConnection || !hasDriver)) {
275
+ return notOk(
276
+ errorDatabaseConnectionRequired({
277
+ why: 'migration status needs a database connection to read the marker and ledger (or pass --from for offline path preview)',
278
+ retryCommand: 'prisma-next migration status --from <contract>',
279
+ }),
280
+ );
281
+ }
579
282
 
580
- let activeRefName: string | undefined;
581
- let activeRefHash: string | undefined;
582
- let activeRefEntry: RefEntry | undefined;
583
283
  let allRefs: Refs = {};
584
284
  try {
585
285
  allRefs = await readRefs(refsDir);
@@ -604,93 +304,52 @@ async function executeMigrationStatusCommand(
604
304
  });
605
305
  }
606
306
 
607
- const contractRawForAggregate = await loadContractRawSafely(config);
608
- const stack = createControlStack(config);
609
- const familyInstance = config.family.create(stack);
610
- const deserializeContract = (json: unknown): Contract => familyInstance.deserializeContract(json);
611
- const appContractStandIn = appContractStandInFromIdentity({
612
- contractHash,
613
- targetId: config.target.id,
614
- targetFamily: config.target.familyId,
615
- });
616
- let appContractForLoad: Contract = appContractStandIn;
617
- if (contractRawForAggregate !== null) {
618
- try {
619
- appContractForLoad = deserializeContract(contractRawForAggregate);
620
- } catch (error) {
621
- diagnostics.push({
622
- code: 'CONTRACT.UNREADABLE',
623
- severity: 'warn',
624
- message: `Could not deserialize contract: ${error instanceof Error ? error.message : 'unknown error'}`,
625
- hints: ["Run 'prisma-next contract emit' to generate a valid contract"],
626
- });
627
- }
628
- }
629
-
630
- let aggregate: ContractSpaceAggregate;
631
- try {
632
- aggregate = await loadContractSpaceAggregate({
633
- migrationsDir,
634
- deserializeContract,
635
- appContract: appContractForLoad,
636
- });
637
- } catch (error) {
638
- if (MigrationToolsError.is(error)) {
639
- return notOk(mapMigrationToolsError(error));
640
- }
641
- return notOk(
642
- errorUnexpected(error instanceof Error ? error.message : String(error), {
643
- why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}`,
644
- }),
645
- );
307
+ const loaded = await buildReadAggregate(config, { migrationsDir });
308
+ if (!loaded.ok) {
309
+ return notOk(loaded.failure);
646
310
  }
647
311
 
312
+ const { aggregate } = loaded.value;
313
+ const contractRawForAggregate = await loadContractRawSafely(config);
648
314
  if (contractRawForAggregate !== null) {
649
315
  const corruptionFailure = refusePackageCorruptionOnAggregate(aggregate);
650
316
  if (corruptionFailure) {
651
317
  return notOk(corruptionFailure);
652
318
  }
653
319
  }
654
-
655
320
  const appGraph = aggregate.app.graph();
656
321
 
322
+ let activeRefHash: string | undefined;
323
+ let activeRefName: string | undefined;
324
+ let activeRefEntry: RefEntry | undefined;
657
325
  let fromOverrideHash: string | undefined;
658
326
 
659
- if (options.to || options.from) {
660
- if (options.to) {
661
- const refResult = parseContractRef(options.to, { graph: appGraph, refs: allRefs });
662
- if (!refResult.ok) {
663
- return notOk(mapRefResolutionError(refResult.failure));
664
- }
665
- activeRefHash = refResult.value.hash;
666
- if (refResult.value.provenance.kind === 'ref') {
667
- const resolvedRefName = refResult.value.provenance.refName;
668
- activeRefName = resolvedRefName;
669
- activeRefEntry = allRefs[resolvedRefName];
670
- }
327
+ if (options.to) {
328
+ const refResult = parseContractRef(options.to, { graph: appGraph, refs: allRefs });
329
+ if (!refResult.ok) {
330
+ return notOk(mapRefResolutionError(refResult.failure));
671
331
  }
332
+ activeRefHash = refResult.value.hash;
333
+ if (refResult.value.provenance.kind === 'ref') {
334
+ activeRefName = refResult.value.provenance.refName;
335
+ activeRefEntry = allRefs[activeRefName];
336
+ }
337
+ }
672
338
 
673
- if (options.from) {
674
- const fromResult = parseContractRef(options.from, { graph: appGraph, refs: allRefs });
675
- if (!fromResult.ok) {
676
- return notOk(mapRefResolutionError(fromResult.failure));
677
- }
678
- fromOverrideHash = fromResult.value.hash;
339
+ if (options.from) {
340
+ const fromResult = parseContractRef(options.from, { graph: appGraph, refs: allRefs });
341
+ if (!fromResult.ok) {
342
+ return notOk(mapRefResolutionError(fromResult.failure));
679
343
  }
344
+ fromOverrideHash = fromResult.value.hash;
680
345
  }
681
346
 
682
347
  const requiredInvariants: readonly string[] = [...(activeRefEntry?.invariants ?? [])].sort();
683
348
 
684
- const statusRefs: StatusRef[] = Object.entries(allRefs).map(([name, entry]) => ({
685
- name,
686
- hash: entry.hash,
687
- active: name === activeRefName,
688
- }));
689
-
690
349
  if (!flags.json && !flags.quiet) {
691
350
  const details: Array<{ label: string; value: string }> = [
692
351
  { label: 'config', value: configPath },
693
- { label: 'migrations', value: appMigrationsRelative },
352
+ { label: 'migrations', value: migrationsRelative },
694
353
  ];
695
354
  if (dbConnection && hasDriver) {
696
355
  details.push({ label: 'database', value: maskConnectionUrl(String(dbConnection)) });
@@ -701,11 +360,8 @@ async function executeMigrationStatusCommand(
701
360
  if (options.from) {
702
361
  details.push({ label: 'from', value: options.from });
703
362
  }
704
- if (activeRefEntry && activeRefEntry.invariants.length > 0) {
705
- details.push({
706
- label: 'required',
707
- value: formatInvariantList(activeRefEntry.invariants),
708
- });
363
+ if (options.space) {
364
+ details.push({ label: 'space', value: options.space });
709
365
  }
710
366
  const header = formatStyledHeader({
711
367
  command: 'migration status',
@@ -714,69 +370,34 @@ async function executeMigrationStatusCommand(
714
370
  flags,
715
371
  });
716
372
  ui.stderr(header);
717
- }
718
-
719
- const bundles = aggregate.app.packages;
720
- const graph = appGraph;
721
-
722
- if (bundles.length === 0) {
723
- if (dbConnection && hasDriver) {
724
- const markerProbe = await validateOnlineMarkerRead(config, dbConnection);
725
- if (!markerProbe.ok) {
726
- return markerProbe;
727
- }
728
- }
729
- if (contractHash !== EMPTY_CONTRACT_HASH) {
730
- diagnostics.push({
731
- code: 'CONTRACT.AHEAD',
732
- severity: 'warn',
733
- message: 'No migration exists for the current contract',
734
- hints: [
735
- "Run 'prisma-next migration plan' to generate a migration for the current contract",
736
- ],
737
- });
373
+ if (shouldShowLegend(options, flags)) {
374
+ ui.stderr(
375
+ renderMigrationGraphLegend({
376
+ colorize: flags.color !== false,
377
+ glyphMode: ui.resolveGlyphMode(false),
378
+ }),
379
+ );
380
+ ui.stderr('');
738
381
  }
739
- return ok({
740
- ok: true,
741
- mode: dbConnection && hasDriver ? 'online' : 'offline',
742
- migrations: [],
743
- targetHash: EMPTY_CONTRACT_HASH,
744
- contractHash,
745
- summary: 'No migrations found',
746
- diagnostics,
747
- requiredInvariants,
748
- });
749
382
  }
750
383
 
751
- let targetHash: string | undefined;
752
-
753
- if (activeRefHash) {
754
- targetHash = activeRefHash;
755
- } else if (graph.nodes.has(contractHash)) {
756
- targetHash = contractHash;
757
- } else {
758
- const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);
759
- if (leaves.length === 1) {
760
- targetHash = leaves[0];
761
- } else {
762
- diagnostics.push({
763
- code: 'MIGRATION.DIVERGED',
764
- severity: 'warn',
765
- message: 'There are multiple valid migration paths — you must select a target',
766
- hints: [
767
- "Use '--to <contract>' to select a target",
768
- "Or 'prisma-next ref set <name> <hash>' to create one",
769
- ],
770
- });
771
- }
384
+ const listSpaces = await migrationSpaceListEntriesFromAggregate(aggregate, migrationsDir);
385
+ const listResult = runMigrationList({
386
+ spaces: listSpaces,
387
+ ...ifDefined('spaceFilter', options.space),
388
+ });
389
+ if (!listResult.ok) {
390
+ return listResult;
772
391
  }
773
392
 
774
- let markerHash: string | undefined;
775
- let markerInvariants: readonly string[] = [];
776
- let mode: 'online' | 'offline' = 'offline';
777
- let allMarkers: ReadonlyMap<string, ContractMarkerRecordLike> | null = null;
393
+ const scopedSpaces = listResult.value.spaces;
394
+ const showSpaceHeadings = scopedSpaces.length > 1;
778
395
 
779
- if (dbConnection && hasDriver) {
396
+ let markersBySpace = new Map<string, ContractMarkerRecordLike>();
397
+ let ledgersBySpace = new Map<string, readonly LedgerEntryRecord[]>();
398
+ let connected = false;
399
+
400
+ if (dbConnection && hasDriver && !usingFromOverride) {
780
401
  const client = createControlClient({
781
402
  family: config.family,
782
403
  target: config.target,
@@ -786,74 +407,32 @@ async function executeMigrationStatusCommand(
786
407
  });
787
408
  try {
788
409
  await client.connect(dbConnection);
789
- const marker = await client.readMarker();
790
- markerHash = marker?.storageHash;
791
- markerInvariants = marker?.invariants ?? [];
792
- mode = 'online';
793
- // Read every space's marker so the aggregate enumeration can
794
- // surface per-space marker state. `readAllMarkers` mirrors what
795
- // `db init` / `db update` already use to drive the planner;
796
- // here it powers the aggregate status output.
797
- //
798
- // Probe for the method first so we only swallow the
799
- // unsupported-method case: older family instances may not
800
- // implement `readAllMarkers` (per-space enumeration then falls
801
- // back to "marker unknown"). Real query / runtime errors from
802
- // an instance that *does* expose the method must propagate up
803
- // — otherwise transient DB failures would silently degrade
804
- // status to "markers unknown".
805
- if (typeof client.readAllMarkers === 'function') {
806
- allMarkers = await client.readAllMarkers();
807
- } else {
808
- // Leaving `allMarkers` as `null` signals "unknown" to the
809
- // aggregate loader (an empty `Map` would instead mean "every
810
- // space has no marker", which is a different condition).
811
- allMarkers = null;
812
- }
410
+ connected = true;
411
+ const read = await readMarkersAndLedgers({
412
+ client,
413
+ spaceIds: scopedSpaces.map((s) => s.spaceId),
414
+ });
415
+ markersBySpace = new Map(read.markersBySpace);
416
+ ledgersBySpace = new Map(read.ledgersBySpace);
813
417
  } catch (error) {
814
418
  if (CliStructuredError.is(error)) {
815
419
  return notOk(error);
816
420
  }
817
- if (!flags.json && !flags.quiet) {
818
- ui.warn('Could not connect to database showing offline status');
819
- }
421
+ return notOk(
422
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
423
+ why: `Failed to read database state: ${error instanceof Error ? error.message : String(error)}`,
424
+ }),
425
+ );
820
426
  } finally {
821
427
  await client.close();
822
428
  }
823
429
  }
824
430
 
825
- if (fromOverrideHash !== undefined) {
826
- markerHash = fromOverrideHash;
827
- mode = 'offline';
828
- allMarkers = null;
829
- }
830
-
831
- let aggregateSpaces: readonly MigrationStatusSpaceEntry[] = [];
832
- if (contractRawForAggregate !== null) {
833
- try {
834
- aggregateSpaces = await loadAggregateStatusSpaces({
835
- aggregate,
836
- extensionPacks: config.extensionPacks ?? [],
837
- markersBySpace: allMarkers,
838
- });
839
- } catch {
840
- aggregateSpaces = [];
841
- }
842
- }
843
- const totalPendingAcrossSpaces = computeTotalPendingAcrossSpaces(aggregateSpaces);
844
-
845
- // Pre-check unknown invariants. Online: union the graph's declared
846
- // invariants with the marker's recorded set so a retired-but-applied
847
- // invariant doesn't surface as MIGRATION.UNKNOWN_INVARIANT — apply would
848
- // route fine because marker subtraction empties `effectiveRequired`.
849
- // Offline: keep the check graph-strict (the marker is unknown, and a
850
- // missing declarer is the dominant signal we can offer).
851
- if (activeRefEntry && activeRefEntry.invariants.length > 0) {
852
- const declared = collectDeclaredInvariants(graph);
431
+ if (activeRefEntry && activeRefEntry.invariants.length > 0 && connected) {
432
+ const declared = collectDeclaredInvariants(appGraph);
433
+ const markerInvariants = markersBySpace.get(aggregate.app.spaceId)?.invariants ?? [];
853
434
  const known = new Set<string>(declared);
854
- if (mode === 'online') {
855
- for (const id of markerInvariants) known.add(id);
856
- }
435
+ for (const id of markerInvariants) known.add(id);
857
436
  const unknown = activeRefEntry.invariants.filter((id) => !known.has(id));
858
437
  if (unknown.length > 0) {
859
438
  return notOk(
@@ -868,247 +447,181 @@ async function executeMigrationStatusCommand(
868
447
  }
869
448
  }
870
449
 
871
- // Marker exists but is not in the migration graph and doesn't match the
872
- // contract hash. The DB is at an unknown state relative to the graph.
873
- // Bail out early with a clear diagnostic instead of rendering a confusing
874
- // graph with no statuses.
875
- //
876
- // When marker === contract (both off-graph), the DB matches the current
877
- // contract proceed normally; the detached contract node will carry both
878
- // the db and contract markers.
879
- if (
880
- mode === 'online' &&
881
- markerHash !== undefined &&
882
- !graph.nodes.has(markerHash) &&
883
- markerHash !== contractHash
884
- ) {
885
- const hints: string[] = [];
886
- if (graph.nodes.has(contractHash)) {
887
- hints.push(
888
- "Run 'prisma-next db sign' to overwrite the marker if the database already matches the contract",
889
- "Run 'prisma-next db update' to push the current contract to the database",
890
- "Run 'prisma-next contract infer' to make your contract match the database",
891
- "Run 'prisma-next db verify' to inspect the database state",
892
- );
893
- } else {
894
- hints.push(
895
- "Run 'prisma-next db update' to push the current contract to the database",
896
- "Run 'prisma-next contract infer' to make your contract match the database",
897
- "Run 'prisma-next db verify' to inspect the database state",
898
- );
450
+ const showAppliedOverlay = connected && !usingFromOverride;
451
+ const showDbMarker = connected && !usingFromOverride;
452
+ const glyphMode = ui.resolveGlyphMode(false);
453
+ const colorize = flags.color !== false;
454
+
455
+ const statusSpaces: MigrationStatusSpaceResult[] = [];
456
+ const treeSections: MigrationStatusTreeSection[] = [];
457
+ let markerDiverged = false;
458
+ let markerCannotReachTarget = false;
459
+ let headlineTargetHash = activeRefHash ?? contractHash;
460
+ let totalPending = 0;
461
+
462
+ const globalLayoutInputs = showSpaceHeadings
463
+ ? scopedSpaces
464
+ .filter((spaceEntry) => spaceEntry.migrations.length > 0)
465
+ .map((spaceEntry) => ({
466
+ graph: aggregate.space(spaceEntry.spaceId)!.graph(),
467
+ liveContractHash: contractHash,
468
+ }))
469
+ : [];
470
+ const globalMaxEdgeTreePrefixWidth =
471
+ globalLayoutInputs.length > 0
472
+ ? computeGlobalMaxEdgeTreePrefixWidth(globalLayoutInputs)
473
+ : undefined;
474
+ const globalMaxDirNameWidth =
475
+ globalLayoutInputs.length > 0 ? computeGlobalMaxDirNameWidth(globalLayoutInputs) : undefined;
476
+
477
+ for (const spaceEntry of scopedSpaces) {
478
+ const member = aggregate.space(spaceEntry.spaceId);
479
+ if (member === undefined) {
480
+ continue;
481
+ }
482
+ const graph = member.graph();
483
+ const spaceContractHash = member.contract().storage.storageHash;
484
+ const targetHash = resolveTarget(spaceContractHash, activeRefHash);
485
+ if (spaceEntry.spaceId === aggregate.app.spaceId) {
486
+ headlineTargetHash = targetHash;
899
487
  }
900
- diagnostics.push({
901
- code: 'MIGRATION.MARKER_NOT_IN_HISTORY',
902
- severity: 'warn',
903
- message:
904
- 'Database was updated outside the migration system (marker does not match any migration)',
905
- hints,
906
- });
907
- return ok({
908
- ok: true,
909
- mode,
910
- migrations: [],
911
- targetHash: EMPTY_CONTRACT_HASH,
912
- contractHash,
913
- summary: `${bundles.length} migration(s) on disk`,
914
- diagnostics,
915
- markerHash,
916
- requiredInvariants,
917
- ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),
918
- });
919
- }
920
488
 
921
- if (mode === 'online' && markerHash === undefined) {
922
- diagnostics.push({
923
- code: 'MIGRATION.NO_MARKER',
924
- severity: 'warn',
925
- message: 'Database has not been initialized — no migration marker found',
926
- hints: ["Run 'prisma-next migrate' to apply pending migrations"],
927
- });
928
- }
489
+ const markerRecord = markersBySpace.get(spaceEntry.spaceId);
490
+ const markerHash = usingFromOverride
491
+ ? fromOverrideHash
492
+ : (markerRecord?.storageHash ?? undefined);
493
+ const originHash = markerHash ?? EMPTY_CONTRACT_HASH;
494
+ const markerInGraph =
495
+ markerHash === undefined || graph.nodes.has(markerHash) || markerHash === spaceContractHash;
496
+ if (
497
+ connected &&
498
+ !usingFromOverride &&
499
+ markerInGraph &&
500
+ originHash !== targetHash &&
501
+ findPath(graph, originHash, targetHash) === null
502
+ ) {
503
+ markerCannotReachTarget = true;
504
+ }
505
+
506
+ if (connected && !usingFromOverride && markerHash !== undefined && !markerInGraph) {
507
+ markerDiverged = true;
508
+ diagnostics.push({
509
+ code: 'MIGRATION.MARKER_NOT_IN_HISTORY',
510
+ severity: 'warn',
511
+ message:
512
+ 'Database was updated outside the migration system (marker does not match any migration)',
513
+ hints: [
514
+ "Run 'prisma-next db sign' to overwrite the marker if the database already matches the contract",
515
+ "Run 'prisma-next db update' to push the current contract to the database",
516
+ ],
517
+ });
518
+ }
929
519
 
930
- // Contract diagnostic fires when no migration produces the current contract hash.
931
- // Suppressed when: (a) graph is diverged (MIGRATION.DIVERGED already guides the user),
932
- // (b) marker === contract and both off-graph (marker-not-in-graph diagnostic covers it).
933
- if (
934
- targetHash &&
935
- contractHash !== EMPTY_CONTRACT_HASH &&
936
- !graph.nodes.has(contractHash) &&
937
- markerHash !== contractHash
938
- ) {
939
- diagnostics.push({
940
- code: 'CONTRACT.AHEAD',
941
- severity: 'warn',
942
- message: 'Contract has changed since the last migration was planned',
943
- hints: ["Run 'prisma-next migration plan' to generate a migration for the current contract"],
944
- });
945
- }
520
+ const ledger = ledgersBySpace.get(spaceEntry.spaceId) ?? [];
521
+ const appliedHashes = showAppliedOverlay ? appliedHashesFromLedger(ledger) : new Set<string>();
946
522
 
947
- if (!targetHash) {
948
- return ok({
949
- ok: true,
950
- mode,
951
- migrations: [],
952
- targetHash: EMPTY_CONTRACT_HASH,
953
- contractHash,
954
- summary: `${bundles.length} migration(s) on disk`,
955
- diagnostics,
956
- ...ifDefined('markerHash', markerHash),
957
- requiredInvariants,
958
- ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),
523
+ const annotations = deriveStatusEdgeAnnotations({
959
524
  graph,
960
- bundles,
961
- diverged: true,
525
+ targetHash,
526
+ originHash,
527
+ appliedMigrationHashes: appliedHashes,
528
+ showAppliedOverlay,
529
+ });
530
+ const tree = renderSpaceTree({
531
+ member,
532
+ liveContractHash: contractHash,
533
+ migrations: spaceEntry.migrations,
534
+ markerHash,
535
+ showDbMarker,
536
+ statusOverlay: annotations,
537
+ colorize,
538
+ glyphMode,
539
+ ...(globalMaxEdgeTreePrefixWidth !== undefined ? { globalMaxEdgeTreePrefixWidth } : {}),
540
+ ...(globalMaxDirNameWidth !== undefined ? { globalMaxDirNameWidth } : {}),
541
+ });
542
+ const migrations = buildStatusMigrations(spaceEntry.migrations, annotations);
543
+ const pending = countPending(migrations);
544
+ totalPending += pending;
545
+
546
+ statusSpaces.push({
547
+ spaceId: spaceEntry.spaceId,
548
+ markerHash: markerHash ?? null,
549
+ targetHash,
550
+ migrations,
551
+ });
552
+ const displayTree =
553
+ showSpaceHeadings && tree.length > 0 ? indentMigrationGraphTreeBlock(tree, ' ') : tree;
554
+ treeSections.push({
555
+ spaceId: spaceEntry.spaceId,
556
+ tree: displayTree,
557
+ showHeading: showSpaceHeadings,
962
558
  });
963
559
  }
964
560
 
965
- const chain = resolveDisplayChain(graph, targetHash, markerHash);
966
-
967
- if (!chain) {
968
- return notOk(
969
- errorRuntime('Cannot reconstruct migration history', {
970
- why: `No path from ${EMPTY_CONTRACT_HASH} to target ${targetHash}`,
971
- fix: 'The migration history may have gaps. Check the migrations directory for missing or corrupted packages.',
972
- }),
973
- );
974
- }
975
-
976
- const edgeStatuses = deriveEdgeStatuses(graph, targetHash, contractHash, markerHash, mode);
977
- const entries = buildMigrationEntries(chain, bundles, mode, markerHash, edgeStatuses);
978
-
979
- const pendingCount = edgeStatuses.filter((e) => e.status === 'pending').length;
980
- const appliedCount = edgeStatuses.filter((e) => e.status === 'applied').length;
981
-
982
- let appliedInvariants: readonly string[] | undefined;
983
- let missingInvariants: readonly string[] | undefined;
984
- let effectiveRequired = new Set<string>();
985
- if (mode === 'online') {
986
- // Mirrors `migrate.ts`: compute `effectiveRequired = required −
987
- // marker.invariants` directly, then derive the display fields from it.
988
- // `appliedInvariants` is the intersection (`required ∩ marker`), which
989
- // is what JSON consumers see for the active ref; the unfiltered set
990
- // lives on `marker.invariants`.
561
+ let missingInvariantsLine: string | undefined;
562
+ if (connected && requiredInvariants.length > 0) {
563
+ const markerInvariants = markersBySpace.get(aggregate.app.spaceId)?.invariants ?? [];
991
564
  const markerSet = new Set(markerInvariants);
992
- effectiveRequired = new Set(requiredInvariants.filter((id) => !markerSet.has(id)));
993
- appliedInvariants = requiredInvariants.filter((id) => markerSet.has(id));
994
- missingInvariants = [...effectiveRequired].sort();
995
- }
996
-
997
- // The marker can match the structural target while still missing required
998
- // invariants for example, a self-edge that provides X, applied via a ref
999
- // declaring X. `pendingCount` (structural) says zero in that case but
1000
- // `effectiveRequired` is non-empty, so up-to-date messaging would mislead.
1001
- const hasInvariantWork = effectiveRequired.size > 0;
1002
- const missingList = [...effectiveRequired].sort().join(', ');
1003
-
1004
- let summary: string;
1005
- if (mode === 'online') {
1006
- if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {
1007
- summary = `${bundles.length} migration(s) on disk`;
1008
- } else if (activeRefHash && activeRefName && markerHash !== undefined) {
1009
- const distance = summarizeRefDistance(graph, markerHash, activeRefHash, activeRefName);
1010
- summary = hasInvariantWork ? `${distance} — missing invariant(s): ${missingList}` : distance;
1011
- } else if (pendingCount === 0 && !hasInvariantWork) {
1012
- summary = `Database is up to date (${appliedCount} migration${appliedCount !== 1 ? 's' : ''} applied)`;
1013
- } else if (pendingCount === 0 && hasInvariantWork) {
1014
- summary = `Missing invariant(s): ${missingList} — run 'prisma-next migrate --to ${activeRefName ?? '<ref>'}' to apply`;
1015
- } else if (markerHash === undefined) {
1016
- summary = `${pendingCount} pending migration(s) — database has no marker`;
1017
- } else {
1018
- summary = `${pendingCount} pending migration(s) — run 'prisma-next migrate' to apply`;
1019
- }
1020
- } else {
1021
- summary = `${entries.length} migration(s) on disk`;
1022
- }
1023
-
1024
- let pathDecision: MigrationStatusResult['pathDecision'];
1025
- let routingUnreachable = false;
1026
- if (mode === 'online') {
1027
- const originHash = markerHash ?? EMPTY_CONTRACT_HASH;
1028
- const outcome = findPathWithDecision(graph, originHash, targetHash, {
1029
- ...ifDefined('refName', activeRefName),
1030
- required: effectiveRequired,
1031
- });
1032
- if (outcome.kind === 'ok') {
1033
- pathDecision = toPathDecisionResult(outcome.decision);
1034
- } else if (outcome.kind === 'unsatisfiable') {
1035
- return notOk(
1036
- mapMigrationToolsError(
1037
- errorNoInvariantPath({
1038
- ...ifDefined('refName', activeRefName),
1039
- required: [...effectiveRequired].sort(),
1040
- missing: outcome.missing,
1041
- structuralPath: outcome.structuralPath.map(toStructuralEdge),
1042
- }),
1043
- ),
1044
- );
1045
- } else {
1046
- // outcome.kind === 'unreachable' — origin (marker) has no structural
1047
- // path to the active target. `pendingCount` and `hasInvariantWork`
1048
- // both report zero in this case, but emitting MIGRATION.UP_TO_DATE
1049
- // would be wrong: the database simply cannot reach the requested
1050
- // ref/contract from its current state. Suppress UP_TO_DATE below.
1051
- routingUnreachable = true;
565
+ const missing = requiredInvariants.filter((id) => !markerSet.has(id));
566
+ if (missing.length > 0) {
567
+ missingInvariantsLine = `missing invariant(s): ${missing.join(', ')}`;
568
+ if (activeRefHash !== undefined) {
569
+ const originHash =
570
+ markersBySpace.get(aggregate.app.spaceId)?.storageHash ?? EMPTY_CONTRACT_HASH;
571
+ const outcome = findPathWithDecision(appGraph, originHash, activeRefHash, {
572
+ ...ifDefined('refName', activeRefName),
573
+ required: new Set(missing),
574
+ });
575
+ if (outcome.kind === 'unsatisfiable') {
576
+ return notOk(
577
+ mapMigrationToolsError(
578
+ errorNoInvariantPath({
579
+ ...ifDefined('refName', activeRefName),
580
+ required: [...missing].sort(),
581
+ missing: outcome.missing,
582
+ structuralPath: outcome.structuralPath.map(toStructuralEdge),
583
+ }),
584
+ ),
585
+ );
586
+ }
587
+ }
1052
588
  }
1053
589
  }
1054
590
 
1055
- if (mode === 'online') {
1056
- if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {
1057
- diagnostics.push({
1058
- code: 'MIGRATION.MARKER_NOT_IN_HISTORY',
1059
- severity: 'warn',
1060
- message: 'Database matches the current contract but was updated directly (not via migrate)',
1061
- hints: ["Run 'prisma-next migration plan' to plan a migration to your current contract"],
1062
- });
1063
- } else if (pendingCount > 0) {
1064
- diagnostics.push({
1065
- code: 'MIGRATION.DATABASE_BEHIND',
1066
- severity: 'info',
1067
- message: `${pendingCount} migration(s) pending`,
1068
- hints: ["Run 'prisma-next migrate' to apply pending migrations"],
591
+ const appMarkerHash = markersBySpace.get(aggregate.app.spaceId)?.storageHash;
592
+ const summary = markerCannotReachTarget
593
+ ? buildNoPathSummary({
594
+ markerHash: appMarkerHash,
595
+ targetHash: headlineTargetHash,
596
+ explicitTarget: options.to !== undefined,
597
+ refName: activeRefName,
598
+ })
599
+ : buildStatusHeadline({
600
+ pendingCount: totalPending,
601
+ targetHash: headlineTargetHash,
602
+ markerDiverged,
603
+ markerHash: appMarkerHash,
1069
604
  });
1070
- } else if (hasInvariantWork) {
1071
- diagnostics.push({
1072
- code: 'MIGRATION.INVARIANTS_PENDING',
1073
- severity: 'info',
1074
- message: `Missing required invariant(s): ${missingList}`,
1075
- hints: [
1076
- `Run 'prisma-next migrate --to ${activeRefName ?? '<ref>'}' to apply a path that covers the required invariants`,
1077
- ],
1078
- });
1079
- } else if (!routingUnreachable) {
1080
- diagnostics.push({
1081
- code: 'MIGRATION.UP_TO_DATE',
1082
- severity: 'info',
1083
- message: 'Database is up to date',
1084
- hints: [],
1085
- });
1086
- }
605
+
606
+ if (scopedSpaces.every((s) => s.migrations.length === 0)) {
607
+ return ok({
608
+ ok: true,
609
+ spaces: statusSpaces,
610
+ summary: 'No migrations found',
611
+ diagnostics,
612
+ treeSections,
613
+ ...ifDefined('missingInvariantsLine', missingInvariantsLine),
614
+ });
1087
615
  }
1088
616
 
1089
- const result: MigrationStatusResult = {
617
+ return ok({
1090
618
  ok: true,
1091
- mode,
1092
- migrations: entries,
1093
- targetHash,
1094
- contractHash,
619
+ spaces: statusSpaces,
1095
620
  summary,
1096
621
  diagnostics,
1097
- ...ifDefined('markerHash', markerHash),
1098
- requiredInvariants,
1099
- ...ifDefined('appliedInvariants', appliedInvariants),
1100
- ...ifDefined('missingInvariants', missingInvariants),
1101
- ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),
1102
- ...ifDefined('pathDecision', pathDecision),
1103
- graph,
1104
- bundles,
1105
- edgeStatuses,
1106
- ...ifDefined('activeRefHash', activeRefHash),
1107
- ...ifDefined('activeRefName', activeRefName),
1108
- spaces: aggregateSpaces,
1109
- ...ifDefined('totalPendingAcrossSpaces', totalPendingAcrossSpaces),
1110
- };
1111
- return ok(result);
622
+ treeSections,
623
+ ...ifDefined('missingInvariantsLine', missingInvariantsLine),
624
+ });
1112
625
  }
1113
626
 
1114
627
  export function createMigrationStatusCommand(): Command {
@@ -1124,6 +637,8 @@ export function createMigrationStatusCommand(): Command {
1124
637
  setCommandExamples(command, [
1125
638
  'prisma-next migration status --db $DATABASE_URL',
1126
639
  'prisma-next migration status --to production --db $DATABASE_URL',
640
+ 'prisma-next migration status --from sha256:abc --to production',
641
+ 'prisma-next migration status --legend --from sha256:abc --to production',
1127
642
  ]);
1128
643
  setCommandSeeAlso(command, [
1129
644
  { verb: 'migration log', oneLiner: 'Show executed migration history' },
@@ -1134,6 +649,7 @@ export function createMigrationStatusCommand(): Command {
1134
649
  addGlobalOptions(command)
1135
650
  .option('--db <url>', 'Database connection string')
1136
651
  .option('--config <path>', 'Path to prisma-next.config.ts')
652
+ .option('--space <id>', 'Narrow output to a single contract space')
1137
653
  .option(
1138
654
  '--to <contract>',
1139
655
  'Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)',
@@ -1142,56 +658,39 @@ export function createMigrationStatusCommand(): Command {
1142
658
  '--from <contract>',
1143
659
  'Origin contract reference; same grammar as --to. Supplying --from switches to offline path computation.',
1144
660
  )
661
+ .option('--legend', 'Print a key for the tree glyphs and lane colors')
1145
662
  .action(async (options: MigrationStatusOptions) => {
1146
663
  const flags = parseGlobalFlagsOrExit(options);
1147
664
  const ui = createTerminalUI(flags);
1148
665
 
666
+ const legendValidation = validateLegendOptions(options, flags);
667
+ if (!legendValidation.ok) {
668
+ process.exit(handleResult(legendValidation, flags, ui));
669
+ }
670
+
1149
671
  const result = await executeMigrationStatusCommand(options, flags, ui);
1150
672
 
1151
673
  const exitCode = handleResult(result, flags, ui, (statusResult) => {
1152
674
  if (flags.json) {
1153
- const {
1154
- graph: _graph,
1155
- bundles: _bundles,
1156
- edgeStatuses: _edgeStatuses,
1157
- activeRefHash: _activeRefHash,
1158
- activeRefName: _activeRefName,
1159
- diverged: _diverged,
1160
- ...jsonResult
1161
- } = statusResult;
1162
- ui.output(JSON.stringify(jsonResult, null, 2));
675
+ ui.output(
676
+ JSON.stringify(
677
+ {
678
+ ok: true,
679
+ spaces: statusResult.spaces,
680
+ summary: statusResult.summary,
681
+ ...(statusResult.diagnostics.length > 0
682
+ ? { diagnostics: statusResult.diagnostics }
683
+ : {}),
684
+ ...(statusResult.missingInvariantsLine
685
+ ? { missingInvariants: statusResult.missingInvariantsLine }
686
+ : {}),
687
+ },
688
+ null,
689
+ 2,
690
+ ),
691
+ );
1163
692
  } else if (!flags.quiet) {
1164
- const colorize = flags.color !== false;
1165
-
1166
- if (statusResult.graph) {
1167
- const renderInput = migrationGraphToRenderInput({
1168
- graph: statusResult.graph,
1169
- mode: statusResult.mode,
1170
- markerHash: statusResult.markerHash,
1171
- contractHash: statusResult.contractHash,
1172
- refs: statusResult.refs,
1173
- activeRefHash: statusResult.activeRefHash,
1174
- activeRefName: statusResult.activeRefName,
1175
- edgeStatuses: statusResult.edgeStatuses,
1176
- });
1177
-
1178
- const graphToRender = statusResult.diverged
1179
- ? renderInput.graph
1180
- : extractRelevantSubgraph(renderInput.graph, renderInput.relevantPaths);
1181
- const dagreOptions = isLinearGraph(graphToRender) ? { ranksep: 1 } : undefined;
1182
- const renderOptions = {
1183
- ...renderInput.options,
1184
- colorize,
1185
- ...ifDefined('dagreOptions', dagreOptions),
1186
- };
1187
- const graphOutput = graphRenderer.render(graphToRender, renderOptions);
1188
- ui.log(graphOutput);
1189
- if (statusResult.mode === 'online') {
1190
- ui.log(formatLegend(colorize));
1191
- }
1192
- }
1193
- ui.log('');
1194
- ui.log(formatStatusSummary(statusResult, colorize));
693
+ ui.output(formatStatusHumanOutput(statusResult, flags.color !== false));
1195
694
  }
1196
695
  });
1197
696
 
@@ -1200,126 +699,3 @@ export function createMigrationStatusCommand(): Command {
1200
699
 
1201
700
  return command;
1202
701
  }
1203
-
1204
- function formatLegend(colorize: boolean): string {
1205
- const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);
1206
- const parts = [
1207
- `${c(cyan, '✓')} applied`,
1208
- `${c(yellow, '⧗')} pending`,
1209
- `${c(magenta, '✗')} unreachable`,
1210
- ];
1211
- return c(dim, parts.join(' '));
1212
- }
1213
-
1214
- export function formatStatusSummary(result: MigrationStatusResult, colorize: boolean): string {
1215
- const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);
1216
- const lines: string[] = [];
1217
-
1218
- const hasUnknown = result.migrations.some((e) => e.status === 'unknown');
1219
- const pendingCount = result.migrations.filter((e) => e.status === 'pending').length;
1220
-
1221
- const hasWarnings = result.diagnostics?.some((d) => d.severity === 'warn') ?? false;
1222
- // INVARIANTS_PENDING is filed at severity 'info' (per ADR 208) so the
1223
- // warn-severity check above doesn't see it. It still represents pending
1224
- // work, so it must promote the summary off the success icon.
1225
- const hasInvariantPending =
1226
- result.diagnostics?.some((d) => d.code === 'MIGRATION.INVARIANTS_PENDING') ?? false;
1227
-
1228
- if (result.mode === 'online') {
1229
- if (hasUnknown || hasWarnings) {
1230
- lines.push(`${c(yellow, '⚠')} ${result.summary}`);
1231
- } else if (pendingCount === 0 && !hasInvariantPending) {
1232
- lines.push(`${c(cyan, '✔')} ${result.summary}`);
1233
- } else {
1234
- lines.push(`${c(yellow, '⧗')} ${result.summary}`);
1235
- }
1236
- } else {
1237
- lines.push(result.summary);
1238
- }
1239
-
1240
- if (result.requiredInvariants.length > 0) {
1241
- if (result.appliedInvariants !== undefined && result.missingInvariants !== undefined) {
1242
- lines.push(`${c(dim, 'applied ')}${formatInvariantList(result.appliedInvariants)}`);
1243
- lines.push(`${c(dim, 'missing ')}${formatInvariantList(result.missingInvariants)}`);
1244
- } else {
1245
- lines.push(`${c(dim, 'applied ')}(unknown — connect a database to evaluate)`);
1246
- }
1247
- }
1248
-
1249
- const warnings = result.diagnostics?.filter((d) => d.severity === 'warn') ?? [];
1250
- for (const diag of warnings) {
1251
- lines.push(`${c(yellow, '⚠')} ${diag.message}`);
1252
- for (const hint of diag.hints) {
1253
- lines.push(` ${c(dim, hint)}`);
1254
- }
1255
- }
1256
-
1257
- // Per-space section. Suppressed when there's no extension space —
1258
- // the top-level output already covers the app member.
1259
- // When extensions exist, render every space (including the app)
1260
- // for consistency, plus a cross-space pending total + apply hint.
1261
- if (result.spaces?.some((s) => s.kind === 'extension')) {
1262
- const total = result.totalPendingAcrossSpaces ?? 0;
1263
- lines.push('');
1264
- lines.push(c(dim, 'spaces'));
1265
- for (const space of result.spaces) {
1266
- lines.push(formatSpaceLine(space, c));
1267
- }
1268
- if (total > 0) {
1269
- lines.push('');
1270
- lines.push(
1271
- `${c(yellow, '⧗')} ${total} pending migration(s) across ${result.spaces.length} space(s) — run 'prisma-next migrate' to apply`,
1272
- );
1273
- }
1274
- }
1275
-
1276
- return lines.join('\n');
1277
- }
1278
-
1279
- function formatSpaceLine(
1280
- space: MigrationStatusSpaceEntry,
1281
- c: (fn: (s: string) => string, s: string) => string,
1282
- ): string {
1283
- const glyph = (() => {
1284
- if (space.status === 'up-to-date' || space.status === 'no-marker') return c(cyan, '✓');
1285
- if (space.status === 'pending') return c(yellow, '⧗');
1286
- if (space.status === 'unreachable' || space.status === 'never-planned') return c(magenta, '✗');
1287
- return ' ';
1288
- })();
1289
- const tag = space.kind === 'app' ? '[app]' : '[ext]';
1290
- const head = space.headHash.slice(0, 8);
1291
- const marker =
1292
- space.markerHash === undefined
1293
- ? '(unknown)'
1294
- : space.markerHash === null
1295
- ? '(no marker)'
1296
- : space.markerHash.slice(0, 8);
1297
- const pending =
1298
- space.pendingCount === undefined
1299
- ? ''
1300
- : space.pendingCount === 0
1301
- ? c(dim, ' (up to date)')
1302
- : c(yellow, ` (${space.pendingCount} pending)`);
1303
- return ` ${glyph} ${c(dim, tag)} ${space.spaceId} → head ${c(dim, head)}, marker ${c(dim, marker)}${pending}`;
1304
- }
1305
-
1306
- function formatInvariantList(ids: readonly string[]): string {
1307
- return ids.length === 0 ? '(none)' : ids.join(', ');
1308
- }
1309
-
1310
- function summarizeRefDistance(
1311
- graph: MigrationGraph,
1312
- markerHash: string,
1313
- refHash: string,
1314
- refName: string,
1315
- ): string {
1316
- if (markerHash === refHash) return `At ref "${refName}" target`;
1317
-
1318
- const pathToRef = findPath(graph, markerHash, refHash);
1319
- if (pathToRef) return `${pathToRef.length} migration(s) behind ref "${refName}"`;
1320
-
1321
- const pathFromRef = findPath(graph, refHash, markerHash);
1322
- if (pathFromRef) return `${pathFromRef.length} migration(s) ahead of ref "${refName}"`;
1323
-
1324
- return `No path between database marker and ref "${refName}" target`;
1325
- }