@prisma-next/cli 0.11.0-dev.46 → 0.11.0-dev.47

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 (105) hide show
  1. package/dist/cli.mjs +9 -9
  2. package/dist/{client-a5NJce0-.mjs → client-5uvDppD8.mjs} +20 -18
  3. package/dist/client-5uvDppD8.mjs.map +1 -0
  4. package/dist/{command-helpers-yLuA78TP.mjs → command-helpers-CI8P5Xyd.mjs} +4 -4
  5. package/dist/{command-helpers-yLuA78TP.mjs.map → command-helpers-CI8P5Xyd.mjs.map} +1 -1
  6. package/dist/commands/contract-emit.mjs +1 -1
  7. package/dist/commands/contract-infer.mjs +1 -1
  8. package/dist/commands/db-init.mjs +5 -5
  9. package/dist/commands/db-schema.mjs +3 -3
  10. package/dist/commands/db-sign.mjs +3 -3
  11. package/dist/commands/db-update.mjs +5 -5
  12. package/dist/commands/db-verify.mjs +1 -1
  13. package/dist/commands/migrate.d.mts +1 -1
  14. package/dist/commands/migrate.d.mts.map +1 -1
  15. package/dist/commands/migrate.mjs +42 -37
  16. package/dist/commands/migrate.mjs.map +1 -1
  17. package/dist/commands/migration-check.d.mts +4 -3
  18. package/dist/commands/migration-check.d.mts.map +1 -1
  19. package/dist/commands/migration-check.mjs +1 -279
  20. package/dist/commands/migration-graph.d.mts +1 -1
  21. package/dist/commands/migration-graph.mjs +2 -2
  22. package/dist/commands/migration-list.d.mts +2 -2
  23. package/dist/commands/migration-list.mjs +1 -1
  24. package/dist/commands/migration-log.mjs +2 -2
  25. package/dist/commands/migration-new.d.mts.map +1 -1
  26. package/dist/commands/migration-new.mjs +32 -30
  27. package/dist/commands/migration-new.mjs.map +1 -1
  28. package/dist/commands/migration-plan.d.mts +1 -1
  29. package/dist/commands/migration-plan.mjs +1 -1
  30. package/dist/commands/migration-show.d.mts +4 -55
  31. package/dist/commands/migration-show.d.mts.map +1 -1
  32. package/dist/commands/migration-show.mjs +62 -152
  33. package/dist/commands/migration-show.mjs.map +1 -1
  34. package/dist/commands/migration-status.d.mts +5 -40
  35. package/dist/commands/migration-status.d.mts.map +1 -1
  36. package/dist/commands/migration-status.mjs +91 -64
  37. package/dist/commands/migration-status.mjs.map +1 -1
  38. package/dist/commands/ref.d.mts +1 -1
  39. package/dist/commands/ref.mjs +2 -2
  40. package/dist/{contract-emit-FtDVFs2Q.mjs → contract-emit-DmBG2Nnc.mjs} +2 -2
  41. package/dist/{contract-emit-FtDVFs2Q.mjs.map → contract-emit-DmBG2Nnc.mjs.map} +1 -1
  42. package/dist/{contract-infer-CVMuoJKk.mjs → contract-infer-BSWFKgI1.mjs} +3 -3
  43. package/dist/{contract-infer-CVMuoJKk.mjs.map → contract-infer-BSWFKgI1.mjs.map} +1 -1
  44. package/dist/contract-space-aggregate-loader-CVHGuA35.mjs +170 -0
  45. package/dist/contract-space-aggregate-loader-CVHGuA35.mjs.map +1 -0
  46. package/dist/{db-verify-B00o3LuC.mjs → db-verify-BzpwFyLg.mjs} +4 -4
  47. package/dist/{db-verify-B00o3LuC.mjs.map → db-verify-BzpwFyLg.mjs.map} +1 -1
  48. package/dist/exports/control-api.d.mts +1 -1
  49. package/dist/exports/control-api.mjs +1 -1
  50. package/dist/exports/index.mjs +1 -1
  51. package/dist/exports/init-output.mjs +1 -1
  52. package/dist/extension-pack-inputs-BiY86HbQ.mjs +62 -0
  53. package/dist/extension-pack-inputs-BiY86HbQ.mjs.map +1 -0
  54. package/dist/{global-flags-Dvibm2yu.d.mts → global-flags-DWsQ6SSI.d.mts} +1 -1
  55. package/dist/{global-flags-Dvibm2yu.d.mts.map → global-flags-DWsQ6SSI.d.mts.map} +1 -1
  56. package/dist/{graph-render-DJVv0_uf.mjs → graph-render-D2FnLpuK.mjs} +1 -1
  57. package/dist/{graph-render-DJVv0_uf.mjs.map → graph-render-D2FnLpuK.mjs.map} +1 -1
  58. package/dist/{init-BKgB6EKw.mjs → init-DEssiJ8j.mjs} +3 -3
  59. package/dist/{init-BKgB6EKw.mjs.map → init-DEssiJ8j.mjs.map} +1 -1
  60. package/dist/{inspect-live-schema-BXUd6RfS.mjs → inspect-live-schema-DlBM84nh.mjs} +3 -3
  61. package/dist/{inspect-live-schema-BXUd6RfS.mjs.map → inspect-live-schema-DlBM84nh.mjs.map} +1 -1
  62. package/dist/migration-check-CzLbAqIQ.mjs +341 -0
  63. package/dist/migration-check-CzLbAqIQ.mjs.map +1 -0
  64. package/dist/{migration-command-scaffold-3l3EdmSD.mjs → migration-command-scaffold-Bp8UHnvJ.mjs} +3 -3
  65. package/dist/{migration-command-scaffold-3l3EdmSD.mjs.map → migration-command-scaffold-Bp8UHnvJ.mjs.map} +1 -1
  66. package/dist/{migration-list-DopkAG7L.mjs → migration-list-C2xnaYsT.mjs} +2 -2
  67. package/dist/{migration-list-DopkAG7L.mjs.map → migration-list-C2xnaYsT.mjs.map} +1 -1
  68. package/dist/{migration-list-graph-render-C-daUZLU.d.mts → migration-list-graph-render-DKw1AT-e.d.mts} +1 -1
  69. package/dist/migration-list-graph-render-DKw1AT-e.d.mts.map +1 -0
  70. package/dist/{migration-plan-BHoeET4O.mjs → migration-plan-BLvOmNCu.mjs} +6 -5
  71. package/dist/{migration-plan-BHoeET4O.mjs.map → migration-plan-BLvOmNCu.mjs.map} +1 -1
  72. package/dist/{migration-types-BXWvz12q.d.mts → migration-types-q64xAI_J.d.mts} +1 -1
  73. package/dist/{migration-types-BXWvz12q.d.mts.map → migration-types-q64xAI_J.d.mts.map} +1 -1
  74. package/dist/{migrations-D-UCOGtk.mjs → migrations-vzQt9LI2.mjs} +3 -13
  75. package/dist/migrations-vzQt9LI2.mjs.map +1 -0
  76. package/dist/{output-CUIdfYo5.mjs → output-B60Gw5fu.mjs} +1 -1
  77. package/dist/{output-CUIdfYo5.mjs.map → output-B60Gw5fu.mjs.map} +1 -1
  78. package/dist/{ref-advancement-CHJ_8HxQ.mjs → ref-advancement-DRh5Nquq.mjs} +1 -1
  79. package/dist/{ref-advancement-CHJ_8HxQ.mjs.map → ref-advancement-DRh5Nquq.mjs.map} +1 -1
  80. package/dist/{types-UWB2-rrw.d.mts → types-CEtm6v6a.d.mts} +1 -8
  81. package/dist/types-CEtm6v6a.d.mts.map +1 -0
  82. package/dist/{verify-9gDJz6cm.mjs → verify-ktSRQvIS.mjs} +2 -2
  83. package/dist/{verify-9gDJz6cm.mjs.map → verify-ktSRQvIS.mjs.map} +1 -1
  84. package/package.json +18 -18
  85. package/src/commands/migrate.ts +52 -42
  86. package/src/commands/migration-check.ts +43 -83
  87. package/src/commands/migration-new.ts +44 -42
  88. package/src/commands/migration-plan.ts +2 -2
  89. package/src/commands/migration-show.ts +65 -284
  90. package/src/commands/migration-status.ts +131 -99
  91. package/src/control-api/client.ts +0 -1
  92. package/src/control-api/operations/db-verify.ts +9 -5
  93. package/src/control-api/operations/migration-apply.ts +11 -19
  94. package/src/control-api/types.ts +0 -7
  95. package/src/utils/command-helpers.ts +8 -3
  96. package/src/utils/contract-space-aggregate-loader.ts +221 -117
  97. package/src/utils/formatters/migrations.ts +4 -38
  98. package/src/utils/integrity-violation-to-check-failure.ts +130 -0
  99. package/dist/client-a5NJce0-.mjs.map +0 -1
  100. package/dist/commands/migration-check.mjs.map +0 -1
  101. package/dist/contract-space-aggregate-loader-EVU3n9YE.mjs +0 -160
  102. package/dist/contract-space-aggregate-loader-EVU3n9YE.mjs.map +0 -1
  103. package/dist/migration-list-graph-render-C-daUZLU.d.mts.map +0 -1
  104. package/dist/migrations-D-UCOGtk.mjs.map +0 -1
  105. package/dist/types-UWB2-rrw.d.mts.map +0 -1
@@ -2,109 +2,161 @@ import type { Contract } from '@prisma-next/contract/types';
2
2
  import type { ControlExtensionDescriptor } from '@prisma-next/framework-components/control';
3
3
  import type {
4
4
  ContractSpaceAggregate,
5
- LoadAggregateError,
6
- LoadAggregateInput,
7
- LoadAggregateOutput,
5
+ DeclaredExtensionEntry,
6
+ IntegrityQueryOptions,
7
+ IntegrityViolation,
8
8
  } from '@prisma-next/migration-tools/aggregate';
9
9
  import { loadContractSpaceAggregate } from '@prisma-next/migration-tools/aggregate';
10
- import type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';
11
10
  import { notOk, ok, type Result } from '@prisma-next/utils/result';
12
11
  import { CliStructuredError } from './cli-errors';
13
12
  import { toDeclaredExtensionsFromRaw } from './extension-pack-inputs';
14
13
 
14
+ const CONTRACT_SPACES_DOCS_URL = 'https://pris.ly/contract-spaces';
15
+
16
+ function contractSpaceError5002(
17
+ summary: string,
18
+ options: {
19
+ readonly why: string;
20
+ readonly fix: string;
21
+ readonly violations: readonly IntegrityViolation[];
22
+ },
23
+ ): CliStructuredError {
24
+ return new CliStructuredError('5002', summary, {
25
+ domain: 'MIG',
26
+ why: options.why,
27
+ fix: options.fix,
28
+ docsUrl: CONTRACT_SPACES_DOCS_URL,
29
+ meta: { violations: options.violations },
30
+ });
31
+ }
32
+
33
+ /**
34
+ * Build the `5002` structured-error envelope for a contract-space
35
+ * target mismatch. Shared between the declared-extension precheck (the
36
+ * descriptor's configured target disagrees with the project target) and
37
+ * the on-disk-contract check surfaced by `checkIntegrity`.
38
+ */
39
+ function targetMismatchError(
40
+ spaceId: string,
41
+ expected: string,
42
+ actual: string,
43
+ ): CliStructuredError {
44
+ return contractSpaceError5002(`Contract-space target mismatch for "${spaceId}"`, {
45
+ why: `Space "${spaceId}" targets "${actual}" but the project's adapter targets "${expected}".`,
46
+ fix: 'Update the extension descriptor to target the configured database, or change the project adapter.',
47
+ violations: [{ kind: 'targetMismatch', spaceId, expected, actual }],
48
+ });
49
+ }
50
+
15
51
  /**
16
- * Render a {@link LoadAggregateError} into a CLI structured-error
17
- * envelope. Preserves error codes `5001` (layout) and `5002` (marker /
18
- * disjointness / etc.) so existing integration tests and downstream
19
- * tooling continue to assert on the same `meta.violations[]` shape
20
- * they did under the old precheck/marker-check helpers.
52
+ * Human-readable detail for an integrity violation, used as the `why`
53
+ * of the `integrityFailure` envelope. Mirrors the messages the prior
54
+ * throw-on-load loader produced so downstream consumers see the same
55
+ * text for the same on-disk state.
21
56
  */
22
- export function mapLoadAggregateError(error: LoadAggregateError): CliStructuredError {
23
- if (error.kind === 'layoutViolation') {
24
- const lines = error.violations.map((v) => `- [${v.kind}] ${v.spaceId}`);
57
+ function describeIntegrityViolation(violation: IntegrityViolation): string {
58
+ switch (violation.kind) {
59
+ case 'hashMismatch':
60
+ return `Migration "${violation.dirName}" stored hash "${violation.stored}" does not match computed hash "${violation.computed}".`;
61
+ case 'providedInvariantsMismatch':
62
+ return `Migration "${violation.dirName}" providedInvariants in migration.json disagrees with ops.json.`;
63
+ case 'packageUnloadable':
64
+ return `Migration "${violation.dirName}" could not be loaded: ${violation.detail}`;
65
+ case 'sameSourceAndTarget':
66
+ return `Migration "${violation.dirName}" has source equal to target (${violation.hash}) with no data invariant — a true no-op self-edge.`;
67
+ case 'headRefMissing':
68
+ return `Head ref \`refs/head.json\` is missing for contract space "${violation.spaceId}".`;
69
+ case 'headRefNotInGraph':
70
+ return `Head ref ${violation.hash} for contract space "${violation.spaceId}" is not present in the migration graph.`;
71
+ case 'refUnreadable':
72
+ return `Ref "${violation.refName}" for contract space "${violation.spaceId}" is unreadable: ${violation.detail}`;
73
+ case 'duplicateMigrationHash':
74
+ return `Multiple migrations in space "${violation.spaceId}" share migrationHash "${violation.migrationHash}" (${violation.dirNames.join(', ')}).`;
75
+ default: {
76
+ const spaceId = 'spaceId' in violation ? violation.spaceId : '*';
77
+ return `Integrity violation "${violation.kind}" for contract space "${spaceId}".`;
78
+ }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Map the integrity violations `checkIntegrity` reports into a single
84
+ * CLI structured-error envelope, preserving the error codes the prior
85
+ * throw-on-load loader emitted: `5001` (layout drift, bundled) and
86
+ * `5002` (target / disjointness / contract-validation / structural
87
+ * integrity). Returns `null` when there is nothing to refuse on.
88
+ *
89
+ * Precedence reproduces the prior loader's first-failure ordering:
90
+ * layout drift first (every offence bundled into one envelope), then
91
+ * target mismatch, then disjointness, then a contract-validation
92
+ * failure, then any remaining structural integrity violation.
93
+ */
94
+ export function mapIntegrityViolations(
95
+ violations: readonly IntegrityViolation[],
96
+ ): CliStructuredError | null {
97
+ if (violations.length === 0) return null;
98
+
99
+ const layout = violations.filter(
100
+ (v): v is Extract<IntegrityViolation, { kind: 'orphanSpaceDir' | 'declaredButUnmigrated' }> =>
101
+ v.kind === 'orphanSpaceDir' || v.kind === 'declaredButUnmigrated',
102
+ );
103
+ if (layout.length > 0) {
104
+ const lines = layout.map((v) => `- [${v.kind}] ${v.spaceId}`);
25
105
  const summary =
26
- error.violations.length === 1
106
+ layout.length === 1
27
107
  ? 'Contract-space layout violation detected'
28
- : `Contract-space layout violations detected (${error.violations.length})`;
108
+ : `Contract-space layout violations detected (${layout.length})`;
29
109
  return new CliStructuredError('5001', summary, {
30
110
  domain: 'MIG',
31
111
  why: `The on-disk \`migrations/\` directory and your \`extensionPacks\` declaration are not in agreement.\n${lines.join('\n')}`,
32
- fix: 'Run `prisma-next migrate` to materialise on-disk artefacts for declared extensions, or remove the orphan directory.',
33
- docsUrl: 'https://pris.ly/contract-spaces',
34
- meta: {
35
- violations: error.violations.map((v) => ({
36
- kind: v.kind,
37
- spaceId: v.spaceId,
38
- })),
39
- },
112
+ fix: 'Declare the extension in `extensionPacks` and re-emit its contract-space artefacts, or remove the orphan `migrations/<space>` directory.',
113
+ docsUrl: CONTRACT_SPACES_DOCS_URL,
114
+ meta: { violations: layout },
40
115
  });
41
116
  }
42
- if (error.kind === 'disjointnessViolation') {
43
- return new CliStructuredError(
44
- '5002',
45
- `Contract-space disjointness violation: storage element "${error.element}" claimed by multiple spaces`,
46
- {
47
- domain: 'MIG',
48
- why: `Spaces ${error.claimedBy.map((s) => `"${s}"`).join(', ')} all claim the storage element "${error.element}". Each storage element must be owned by exactly one contract space.`,
49
- fix: 'Update the conflicting contracts so each storage element is claimed by exactly one space.',
50
- docsUrl: 'https://pris.ly/contract-spaces',
51
- meta: {
52
- violations: [
53
- {
54
- kind: 'disjointness',
55
- spaceId: error.claimedBy.join(','),
56
- element: error.element,
57
- claimedBy: error.claimedBy,
58
- },
59
- ],
60
- },
61
- },
117
+
118
+ const targetMismatch = violations.find((v) => v.kind === 'targetMismatch');
119
+ if (targetMismatch && targetMismatch.kind === 'targetMismatch') {
120
+ return targetMismatchError(
121
+ targetMismatch.spaceId,
122
+ targetMismatch.expected,
123
+ targetMismatch.actual,
62
124
  );
63
125
  }
64
- if (error.kind === 'integrityFailure') {
65
- return new CliStructuredError(
66
- '5002',
67
- `Contract-space integrity failure for "${error.spaceId}"`,
126
+
127
+ const disjointness = violations.find((v) => v.kind === 'disjointness');
128
+ if (disjointness && disjointness.kind === 'disjointness') {
129
+ return contractSpaceError5002(
130
+ `Contract-space disjointness violation: storage element "${disjointness.element}" claimed by multiple spaces`,
68
131
  {
69
- domain: 'MIG',
70
- why: error.detail,
71
- fix: 'Run `prisma-next migrate` to refresh on-disk artefacts, or restore the on-disk `migrations/` directory from version control.',
72
- docsUrl: 'https://pris.ly/contract-spaces',
73
- meta: {
74
- violations: [{ kind: 'integrity', spaceId: error.spaceId, detail: error.detail }],
75
- },
132
+ why: `Spaces ${disjointness.claimedBy.map((s) => `"${s}"`).join(', ')} all claim the storage element "${disjointness.element}". Each storage element must be owned by exactly one contract space.`,
133
+ fix: 'Update the conflicting contracts so each storage element is claimed by exactly one space.',
134
+ violations: [disjointness],
76
135
  },
77
136
  );
78
137
  }
79
- if (error.kind === 'validationFailure') {
80
- return new CliStructuredError(
81
- '5002',
82
- `Contract-space contract validation failed for "${error.spaceId}"`,
138
+
139
+ const contractUnreadable = violations.find((v) => v.kind === 'contractUnreadable');
140
+ if (contractUnreadable && contractUnreadable.kind === 'contractUnreadable') {
141
+ return contractSpaceError5002(
142
+ `Contract-space contract validation failed for "${contractUnreadable.spaceId}"`,
83
143
  {
84
- domain: 'MIG',
85
- why: error.detail,
86
- fix: 'Run `prisma-next migrate` to refresh on-disk artefacts, or fix the extension descriptor producing the invalid contract.',
87
- meta: {
88
- violations: [{ kind: 'validation', spaceId: error.spaceId, detail: error.detail }],
89
- },
144
+ why: contractUnreadable.detail,
145
+ fix: 'Re-emit the extension contract with `prisma-next contract emit`, or fix the extension pack descriptor producing the invalid contract.',
146
+ violations: [contractUnreadable],
90
147
  },
91
148
  );
92
149
  }
93
- // targetMismatch
94
- return new CliStructuredError('5002', `Contract-space target mismatch for "${error.spaceId}"`, {
95
- domain: 'MIG',
96
- why: `Space "${error.spaceId}" targets "${error.actual}" but the project's adapter targets "${error.expected}".`,
97
- fix: 'Update the extension descriptor to target the configured database, or change the project adapter.',
98
- meta: {
99
- violations: [
100
- {
101
- kind: 'targetMismatch',
102
- spaceId: error.spaceId,
103
- expected: error.expected,
104
- actual: error.actual,
105
- },
106
- ],
107
- },
150
+
151
+ // Any remaining recoverable structural violation refuses as an
152
+ // integrity failure, surfacing the first one's detail (every violation
153
+ // is still computed; the gate just renders one envelope).
154
+ const structural = violations[0]!;
155
+ const spaceId = 'spaceId' in structural ? structural.spaceId : '*';
156
+ return contractSpaceError5002(`Contract-space integrity failure for "${spaceId}"`, {
157
+ why: describeIntegrityViolation(structural),
158
+ fix: 'Re-emit the affected migration package(s) or restore the on-disk `migrations/` directory from version control.',
159
+ violations: [structural],
108
160
  });
109
161
  }
110
162
 
@@ -121,57 +173,109 @@ export interface BuildAggregateInputs<TFamilyId extends string, TTargetId extend
121
173
  readonly appContract: Contract;
122
174
  readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;
123
175
  readonly deserializeContract: (contractJson: unknown) => Contract;
124
- /**
125
- * App-space migration packages to hydrate the app member's
126
- * migration graph with. Defaults to `[]` (matches the `db init` /
127
- * `db update` daily-driver behaviour, where the app's authored
128
- * `migrations/` graph is not walked — the planner uses the synth
129
- * strategy for the app member instead).
130
- *
131
- * `migrate` callers thread the user's authored app-space
132
- * packages (loaded via `loadMigrationPackages(appMigrationsDir)`)
133
- * through here so the graph-walk strategy can plot a path through
134
- * them — the prod-time replay path explicitly forbids synth.
135
- */
136
- readonly appMigrationPackages?: ReadonlyArray<OnDiskMigrationPackage>;
176
+ }
177
+
178
+ function declaredExtensionsFromInputs(
179
+ extensionPacks: BuildAggregateInputs<string, string>['extensionPacks'],
180
+ ): readonly DeclaredExtensionEntry[] {
181
+ return toDeclaredExtensionsFromRaw(extensionPacks as ReadonlyArray<unknown>);
137
182
  }
138
183
 
139
184
  /**
140
- * Run the aggregate loader at the CLI surface, mapping any
141
- * {@link LoadAggregateError} into a {@link CliStructuredError} envelope.
142
- *
143
- * App-side migration packages flow through `inputs.appMigrationPackages`
144
- * (defaulting to `[]`). `db init` / `db update` leave it empty: the
145
- * planner's `synth` strategy is used for the app member (driven by
146
- * `callerPolicy.ignoreGraphFor`), so the app's authored `migrations/`
147
- * graph does not need to be walked. `migrate` threads the
148
- * already-loaded app-space packages through so the graph-walk strategy
149
- * can plot a path through them — replay forbids synth.
150
- *
151
- * @see specs/contract-space-aggregate-spec.md § Loader.
185
+ * Reject extension descriptors whose configured target disagrees with
186
+ * the project target before any on-disk read.
152
187
  */
153
- export async function buildContractSpaceAggregate<
188
+ export function refuseDeclaredExtensionTargetMismatch<
189
+ TFamilyId extends string,
190
+ TTargetId extends string,
191
+ >(inputs: BuildAggregateInputs<TFamilyId, TTargetId>): CliStructuredError | null {
192
+ for (const declared of declaredExtensionsFromInputs(inputs.extensionPacks)) {
193
+ if (declared.targetId !== inputs.targetId) {
194
+ return targetMismatchError(declared.id, inputs.targetId, declared.targetId);
195
+ }
196
+ }
197
+ return null;
198
+ }
199
+
200
+ /**
201
+ * Load the tolerant {@link ContractSpaceAggregate} once at the CLI
202
+ * surface. Construction never throws on disk content; callers query
203
+ * {@link ContractSpaceAggregate.app} / extension facets instead of
204
+ * re-reading `migrations/`.
205
+ */
206
+ export async function loadContractSpaceAggregateForCli<
154
207
  TFamilyId extends string,
155
208
  TTargetId extends string,
156
209
  >(
157
210
  inputs: BuildAggregateInputs<TFamilyId, TTargetId>,
158
211
  ): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {
159
- const declaredExtensions = toDeclaredExtensionsFromRaw(
160
- inputs.extensionPacks as ReadonlyArray<unknown>,
161
- );
212
+ const targetFailure = refuseDeclaredExtensionTargetMismatch(inputs);
213
+ if (targetFailure) {
214
+ return notOk(targetFailure);
215
+ }
162
216
 
163
- const loadInput: LoadAggregateInput = {
164
- targetId: inputs.targetId,
217
+ const aggregate = await loadContractSpaceAggregate({
165
218
  migrationsDir: inputs.migrationsDir,
166
- appContract: inputs.appContract,
167
- declaredExtensions,
168
219
  deserializeContract: inputs.deserializeContract,
169
- appMigrationPackages: inputs.appMigrationPackages ?? [],
170
- };
220
+ appContract: inputs.appContract,
221
+ });
222
+ return ok(aggregate);
223
+ }
224
+
225
+ /**
226
+ * Run `checkIntegrity` on a loaded aggregate and map violations into
227
+ * the contract-space refusal envelope, or return `null` when the model
228
+ * is acceptable for the requested check scope.
229
+ */
230
+ export function refuseContractSpaceIntegrity(
231
+ aggregate: ContractSpaceAggregate,
232
+ options: IntegrityQueryOptions,
233
+ ): CliStructuredError | null {
234
+ return mapIntegrityViolations(aggregate.checkIntegrity(options));
235
+ }
171
236
 
172
- const result: LoadAggregateOutput = await loadContractSpaceAggregate(loadInput);
173
- if (!result.ok) {
174
- return notOk(mapLoadAggregateError(result.failure));
237
+ const PACKAGE_CORRUPTION_KINDS = new Set<IntegrityViolation['kind']>([
238
+ 'hashMismatch',
239
+ 'providedInvariantsMismatch',
240
+ 'packageUnloadable',
241
+ ]);
242
+
243
+ /**
244
+ * Reader-subset integrity refusal for `migration status`: package
245
+ * corruptions only (`hashMismatch`, `providedInvariantsMismatch`,
246
+ * `packageUnloadable`).
247
+ */
248
+ export function refusePackageCorruptionOnAggregate(
249
+ aggregate: ContractSpaceAggregate,
250
+ ): CliStructuredError | null {
251
+ const corruption = aggregate.checkIntegrity().filter((v) => PACKAGE_CORRUPTION_KINDS.has(v.kind));
252
+ return mapIntegrityViolations(corruption);
253
+ }
254
+
255
+ /**
256
+ * Construct the tolerant {@link ContractSpaceAggregate} at the CLI
257
+ * surface and apply the explicit integrity refusal.
258
+ *
259
+ * App-space migration packages are read from `migrations/<app>/` by the
260
+ * loader itself; callers no longer thread them through.
261
+ */
262
+ export async function buildContractSpaceAggregate<
263
+ TFamilyId extends string,
264
+ TTargetId extends string,
265
+ >(
266
+ inputs: BuildAggregateInputs<TFamilyId, TTargetId>,
267
+ ): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {
268
+ const declaredExtensions = declaredExtensionsFromInputs(inputs.extensionPacks);
269
+ const loaded = await loadContractSpaceAggregateForCli(inputs);
270
+ if (!loaded.ok) {
271
+ return loaded;
272
+ }
273
+ const failure = refuseContractSpaceIntegrity(loaded.value, {
274
+ declaredExtensions,
275
+ checkContracts: true,
276
+ });
277
+ if (failure) {
278
+ return notOk(failure);
175
279
  }
176
- return ok(result.value.aggregate);
280
+ return ok(loaded.value);
177
281
  }
@@ -314,9 +314,7 @@ export function formatMigrationApplyCommandOutput(
314
314
  return lines.join('\n');
315
315
  }
316
316
 
317
- interface MigrationShowSpacePresent {
318
- readonly kind: 'present';
319
- readonly spaceId: string;
317
+ interface MigrationShowPresent {
320
318
  readonly dirName: string;
321
319
  readonly dirPath: string;
322
320
  readonly from: string | null;
@@ -332,22 +330,11 @@ interface MigrationShowSpacePresent {
332
330
  readonly summary: string;
333
331
  }
334
332
 
335
- interface MigrationShowSpaceMissing {
336
- readonly kind: 'missing';
337
- readonly spaceId: string;
338
- readonly summary: string;
339
- }
340
-
341
- type MigrationShowSpaceResult = MigrationShowSpacePresent | MigrationShowSpaceMissing;
342
-
343
333
  interface MigrationShowResult {
344
- readonly spaces: readonly MigrationShowSpaceResult[];
334
+ readonly migration: MigrationShowPresent;
345
335
  }
346
336
 
347
- function formatSpaceShowBlock(
348
- space: MigrationShowSpacePresent,
349
- useColor: boolean,
350
- ): readonly string[] {
337
+ function formatSpaceShowBlock(space: MigrationShowPresent, useColor: boolean): readonly string[] {
351
338
  const formatGreen = createColorFormatter(useColor, green);
352
339
  const formatYellow = createColorFormatter(useColor, yellow);
353
340
  const formatDimText = (text: string) => formatDim(useColor, text);
@@ -403,28 +390,7 @@ export function formatMigrationShowOutput(result: MigrationShowResult, flags: Gl
403
390
  }
404
391
 
405
392
  const useColor = flags.color !== false;
406
- const formatDimText = (text: string) => formatDim(useColor, text);
407
- const multipleSpaces = result.spaces.length > 1;
408
- const lines: string[] = [];
409
-
410
- for (let i = 0; i < result.spaces.length; i++) {
411
- const space = result.spaces[i]!;
412
- if (multipleSpaces) {
413
- lines.push(formatDimText(`── ${space.spaceId} ──`));
414
- }
415
- if (space.kind === 'missing') {
416
- lines.push(formatDimText(` ${space.summary}`));
417
- } else {
418
- for (const line of formatSpaceShowBlock(space, useColor)) {
419
- lines.push(line);
420
- }
421
- }
422
- if (i < result.spaces.length - 1) {
423
- lines.push('');
424
- }
425
- }
426
-
427
- return lines.join('\n');
393
+ return formatSpaceShowBlock(result.migration, useColor).join('\n');
428
394
  }
429
395
 
430
396
  /**
@@ -0,0 +1,130 @@
1
+ import type { IntegrityViolation } from '@prisma-next/migration-tools/aggregate';
2
+ import { join, relative } from 'pathe';
3
+
4
+ export interface CheckFailure {
5
+ readonly pnCode: string;
6
+ readonly where: string;
7
+ readonly why: string;
8
+ readonly fix: string;
9
+ }
10
+
11
+ function migrationPathRelative(dirPath: string): string {
12
+ return relative(process.cwd(), dirPath);
13
+ }
14
+
15
+ function migrationFileRelative(dirPath: string, fileName: string): string {
16
+ return join(migrationPathRelative(dirPath), fileName);
17
+ }
18
+
19
+ /**
20
+ * Map one {@link IntegrityViolation} onto a `migration check` failure row.
21
+ * Sole catalogue mapping from integrity violations to `PN-MIG-CHECK-*`.
22
+ */
23
+ export function integrityViolationToCheckFailure(
24
+ violation: IntegrityViolation,
25
+ migrationsDir: string,
26
+ ): CheckFailure {
27
+ const spaceRelative = (spaceId: string): string =>
28
+ migrationPathRelative(join(migrationsDir, spaceId));
29
+ const packageRelative = (spaceId: string, dirName: string): string =>
30
+ migrationPathRelative(join(migrationsDir, spaceId, dirName));
31
+ const refRelative = (spaceId: string, refName: string): string =>
32
+ migrationPathRelative(join(migrationsDir, spaceId, 'refs', `${refName}.json`));
33
+
34
+ switch (violation.kind) {
35
+ case 'hashMismatch':
36
+ return {
37
+ pnCode: 'PN-MIG-CHECK-001',
38
+ where: migrationFileRelative(
39
+ join(migrationsDir, violation.spaceId, violation.dirName),
40
+ 'migration.json',
41
+ ),
42
+ why: `Stored hash ${violation.stored} does not match recomputed hash ${violation.computed}`,
43
+ fix: 'Re-emit the migration package or restore from version control.',
44
+ };
45
+ case 'providedInvariantsMismatch':
46
+ return {
47
+ pnCode: 'PN-MIG-CHECK-002',
48
+ where: packageRelative(violation.spaceId, violation.dirName),
49
+ why: `Migration "${violation.dirName}" providedInvariants in migration.json disagrees with ops.json.`,
50
+ fix: 'Re-emit the migration package so migration.json and ops.json agree.',
51
+ };
52
+ case 'packageUnloadable':
53
+ return {
54
+ pnCode: 'PN-MIG-CHECK-002',
55
+ where: packageRelative(violation.spaceId, violation.dirName),
56
+ why: `Migration "${violation.dirName}" could not be loaded: ${violation.detail}`,
57
+ fix: 'Re-emit the migration package or restore from version control.',
58
+ };
59
+ case 'sameSourceAndTarget':
60
+ return {
61
+ pnCode: 'PN-MIG-CHECK-007',
62
+ where: packageRelative(violation.spaceId, violation.dirName),
63
+ why: `Migration "${violation.dirName}" in space "${violation.spaceId}" has source equal to target (${violation.hash}) with no data invariant — a true no-op self-edge.`,
64
+ fix: 'Add a data operation if this self-edge was meant to carry a data invariant, or delete the migration if it is a true no-op.',
65
+ };
66
+ case 'orphanSpaceDir':
67
+ return {
68
+ pnCode: 'PN-MIG-CHECK-008',
69
+ where: spaceRelative(violation.spaceId),
70
+ why: `Contract-space directory "${violation.spaceId}" exists on disk but no extension declares it.`,
71
+ fix: 'Remove the orphan directory, or declare the extension in `extensionPacks`.',
72
+ };
73
+ case 'declaredButUnmigrated':
74
+ return {
75
+ pnCode: 'PN-MIG-CHECK-009',
76
+ where: spaceRelative(violation.spaceId),
77
+ why: `Extension "${violation.spaceId}" is declared in \`extensionPacks\` but has no on-disk migrations directory.`,
78
+ fix: 'Re-emit the extension contract-space artefacts with `prisma-next contract emit` and migration planning, or remove the extension from `extensionPacks` if it is unused.',
79
+ };
80
+ case 'headRefMissing':
81
+ return {
82
+ pnCode: 'PN-MIG-CHECK-010',
83
+ where: refRelative(violation.spaceId, 'head'),
84
+ why: `Head ref \`refs/head.json\` is missing for contract space "${violation.spaceId}".`,
85
+ fix: 'Re-emit the contract-space migrations and head ref artefacts, or restore `refs/head.json` from version control.',
86
+ };
87
+ case 'headRefNotInGraph':
88
+ return {
89
+ pnCode: 'PN-MIG-CHECK-011',
90
+ where: refRelative(violation.spaceId, 'head'),
91
+ why: `Head ref ${violation.hash} for contract space "${violation.spaceId}" is not present in its migration graph.`,
92
+ fix: 'Re-emit the contract space migrations, or restore the missing migration package.',
93
+ };
94
+ case 'refUnreadable':
95
+ return {
96
+ pnCode: 'PN-MIG-CHECK-012',
97
+ where: refRelative(violation.spaceId, violation.refName),
98
+ why: `Ref "${violation.refName}" for contract space "${violation.spaceId}" is unreadable: ${violation.detail}`,
99
+ fix: 'Repair or remove the corrupt ref file.',
100
+ };
101
+ case 'targetMismatch':
102
+ return {
103
+ pnCode: 'PN-MIG-CHECK-013',
104
+ where: spaceRelative(violation.spaceId),
105
+ why: `Contract space "${violation.spaceId}" targets "${violation.actual}" but the project targets "${violation.expected}".`,
106
+ fix: 'Update the extension to target the configured database, or change the project target.',
107
+ };
108
+ case 'disjointness':
109
+ return {
110
+ pnCode: 'PN-MIG-CHECK-014',
111
+ where: migrationPathRelative(migrationsDir),
112
+ why: `Storage element "${violation.element}" is claimed by multiple contract spaces: ${violation.claimedBy.join(', ')}.`,
113
+ fix: 'Update the contracts so each storage element is owned by exactly one contract space.',
114
+ };
115
+ case 'contractUnreadable':
116
+ return {
117
+ pnCode: 'PN-MIG-CHECK-015',
118
+ where: migrationFileRelative(join(migrationsDir, violation.spaceId), 'contract.json'),
119
+ why: `Contract for space "${violation.spaceId}" is unreadable: ${violation.detail}`,
120
+ fix: 'Re-emit the extension contract artefacts, or fix the descriptor producing the invalid contract.',
121
+ };
122
+ case 'duplicateMigrationHash':
123
+ return {
124
+ pnCode: 'PN-MIG-CHECK-016',
125
+ where: spaceRelative(violation.spaceId),
126
+ why: `Multiple migrations in space "${violation.spaceId}" share migrationHash "${violation.migrationHash}" (${violation.dirNames.join(', ')}).`,
127
+ fix: 'Re-emit one of the conflicting packages so each migrationHash is unique.',
128
+ };
129
+ }
130
+ }