@prisma-next/migration-tools 0.5.0-dev.9 → 0.5.1

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 (130) hide show
  1. package/README.md +34 -22
  2. package/dist/{constants-BRi0X7B_.mjs → constants-DWV9_o2Z.mjs} +2 -2
  3. package/dist/{constants-BRi0X7B_.mjs.map → constants-DWV9_o2Z.mjs.map} +1 -1
  4. package/dist/errors-EPL_9p9f.mjs +297 -0
  5. package/dist/errors-EPL_9p9f.mjs.map +1 -0
  6. package/dist/exports/aggregate.d.mts +599 -0
  7. package/dist/exports/aggregate.d.mts.map +1 -0
  8. package/dist/exports/aggregate.mjs +599 -0
  9. package/dist/exports/aggregate.mjs.map +1 -0
  10. package/dist/exports/constants.d.mts.map +1 -1
  11. package/dist/exports/constants.mjs +2 -3
  12. package/dist/exports/errors.d.mts +68 -0
  13. package/dist/exports/errors.d.mts.map +1 -0
  14. package/dist/exports/errors.mjs +2 -0
  15. package/dist/exports/graph.d.mts +2 -0
  16. package/dist/exports/graph.mjs +1 -0
  17. package/dist/exports/hash.d.mts +52 -0
  18. package/dist/exports/hash.d.mts.map +1 -0
  19. package/dist/exports/hash.mjs +2 -0
  20. package/dist/exports/invariants.d.mts +39 -0
  21. package/dist/exports/invariants.d.mts.map +1 -0
  22. package/dist/exports/invariants.mjs +2 -0
  23. package/dist/exports/io.d.mts +66 -6
  24. package/dist/exports/io.d.mts.map +1 -1
  25. package/dist/exports/io.mjs +2 -3
  26. package/dist/exports/metadata.d.mts +2 -0
  27. package/dist/exports/metadata.mjs +1 -0
  28. package/dist/exports/migration-graph.d.mts +2 -0
  29. package/dist/exports/migration-graph.mjs +2 -0
  30. package/dist/exports/migration-ts.d.mts.map +1 -1
  31. package/dist/exports/migration-ts.mjs +2 -4
  32. package/dist/exports/migration-ts.mjs.map +1 -1
  33. package/dist/exports/migration.d.mts +15 -14
  34. package/dist/exports/migration.d.mts.map +1 -1
  35. package/dist/exports/migration.mjs +70 -43
  36. package/dist/exports/migration.mjs.map +1 -1
  37. package/dist/exports/package.d.mts +3 -0
  38. package/dist/exports/package.mjs +1 -0
  39. package/dist/exports/refs.d.mts.map +1 -1
  40. package/dist/exports/refs.mjs +3 -4
  41. package/dist/exports/refs.mjs.map +1 -1
  42. package/dist/exports/spaces.d.mts +526 -0
  43. package/dist/exports/spaces.d.mts.map +1 -0
  44. package/dist/exports/spaces.mjs +266 -0
  45. package/dist/exports/spaces.mjs.map +1 -0
  46. package/dist/graph-HMWAldoR.d.mts +28 -0
  47. package/dist/graph-HMWAldoR.d.mts.map +1 -0
  48. package/dist/hash-By50zM_E.mjs +74 -0
  49. package/dist/hash-By50zM_E.mjs.map +1 -0
  50. package/dist/invariants-qgQGlsrV.mjs +57 -0
  51. package/dist/invariants-qgQGlsrV.mjs.map +1 -0
  52. package/dist/io-D5YYptRO.mjs +239 -0
  53. package/dist/io-D5YYptRO.mjs.map +1 -0
  54. package/dist/metadata-CFvm3ayn.d.mts +2 -0
  55. package/dist/migration-graph-DGNnKDY5.mjs +523 -0
  56. package/dist/migration-graph-DGNnKDY5.mjs.map +1 -0
  57. package/dist/migration-graph-DulOITvG.d.mts +124 -0
  58. package/dist/migration-graph-DulOITvG.d.mts.map +1 -0
  59. package/dist/op-schema-D5qkXfEf.mjs +13 -0
  60. package/dist/op-schema-D5qkXfEf.mjs.map +1 -0
  61. package/dist/package-BjiZ7KDy.d.mts +21 -0
  62. package/dist/package-BjiZ7KDy.d.mts.map +1 -0
  63. package/dist/read-contract-space-contract-Cme8KZk_.mjs +259 -0
  64. package/dist/read-contract-space-contract-Cme8KZk_.mjs.map +1 -0
  65. package/package.json +42 -17
  66. package/src/aggregate/loader.ts +379 -0
  67. package/src/aggregate/marker-types.ts +16 -0
  68. package/src/aggregate/planner-types.ts +171 -0
  69. package/src/aggregate/planner.ts +159 -0
  70. package/src/aggregate/project-schema-to-space.ts +64 -0
  71. package/src/aggregate/strategies/graph-walk.ts +118 -0
  72. package/src/aggregate/strategies/synth.ts +122 -0
  73. package/src/aggregate/types.ts +89 -0
  74. package/src/aggregate/verifier.ts +230 -0
  75. package/src/assert-descriptor-self-consistency.ts +70 -0
  76. package/src/compute-extension-space-apply-path.ts +152 -0
  77. package/src/concatenate-space-apply-inputs.ts +90 -0
  78. package/src/contract-space-from-json.ts +63 -0
  79. package/src/emit-contract-space-artefacts.ts +70 -0
  80. package/src/errors.ts +251 -17
  81. package/src/exports/aggregate.ts +42 -0
  82. package/src/exports/errors.ts +8 -0
  83. package/src/exports/graph.ts +1 -0
  84. package/src/exports/hash.ts +2 -0
  85. package/src/exports/invariants.ts +1 -0
  86. package/src/exports/io.ts +3 -1
  87. package/src/exports/metadata.ts +1 -0
  88. package/src/exports/{dag.ts → migration-graph.ts} +3 -2
  89. package/src/exports/migration.ts +0 -1
  90. package/src/exports/package.ts +2 -0
  91. package/src/exports/spaces.ts +45 -0
  92. package/src/gather-disk-contract-space-state.ts +62 -0
  93. package/src/graph-ops.ts +57 -30
  94. package/src/graph.ts +25 -0
  95. package/src/hash.ts +91 -0
  96. package/src/invariants.ts +61 -0
  97. package/src/io.ts +163 -40
  98. package/src/metadata.ts +1 -0
  99. package/src/migration-base.ts +97 -56
  100. package/src/migration-graph.ts +676 -0
  101. package/src/op-schema.ts +11 -0
  102. package/src/package.ts +21 -0
  103. package/src/plan-all-spaces.ts +76 -0
  104. package/src/read-contract-space-contract.ts +44 -0
  105. package/src/read-contract-space-head-ref.ts +63 -0
  106. package/src/space-layout.ts +48 -0
  107. package/src/verify-contract-spaces.ts +272 -0
  108. package/dist/attestation-BnzTb0Qp.mjs +0 -65
  109. package/dist/attestation-BnzTb0Qp.mjs.map +0 -1
  110. package/dist/errors-BmiSgz1j.mjs +0 -160
  111. package/dist/errors-BmiSgz1j.mjs.map +0 -1
  112. package/dist/exports/attestation.d.mts +0 -37
  113. package/dist/exports/attestation.d.mts.map +0 -1
  114. package/dist/exports/attestation.mjs +0 -4
  115. package/dist/exports/dag.d.mts +0 -51
  116. package/dist/exports/dag.d.mts.map +0 -1
  117. package/dist/exports/dag.mjs +0 -386
  118. package/dist/exports/dag.mjs.map +0 -1
  119. package/dist/exports/types.d.mts +0 -35
  120. package/dist/exports/types.d.mts.map +0 -1
  121. package/dist/exports/types.mjs +0 -3
  122. package/dist/io-Cd6GLyjK.mjs +0 -153
  123. package/dist/io-Cd6GLyjK.mjs.map +0 -1
  124. package/dist/types-DyGXcWWp.d.mts +0 -71
  125. package/dist/types-DyGXcWWp.d.mts.map +0 -1
  126. package/src/attestation.ts +0 -81
  127. package/src/dag.ts +0 -426
  128. package/src/exports/attestation.ts +0 -2
  129. package/src/exports/types.ts +0 -10
  130. package/src/types.ts +0 -66
@@ -0,0 +1,379 @@
1
+ import type { Contract } from '@prisma-next/contract/types';
2
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
3
+ import { EMPTY_CONTRACT_HASH } from '../constants';
4
+ import { readMigrationsDir } from '../io';
5
+ import { reconstructGraph } from '../migration-graph';
6
+ import type { OnDiskMigrationPackage } from '../package';
7
+ import { readContractSpaceContract } from '../read-contract-space-contract';
8
+ import { readContractSpaceHeadRef } from '../read-contract-space-head-ref';
9
+ import { APP_SPACE_ID, spaceMigrationDirectory } from '../space-layout';
10
+ import { listContractSpaceDirectories } from '../verify-contract-spaces';
11
+ import type { ContractSpaceAggregate, ContractSpaceMember, HydratedMigrationGraph } from './types';
12
+
13
+ /**
14
+ * Single declared extension entry the loader needs from `Config.extensionPacks`.
15
+ *
16
+ * Only the subset of fields the loader operates on:
17
+ *
18
+ * - `id` — the space id (also the directory name under `migrations/`).
19
+ * - `targetId` — the configured `Config.adapter.targetId` value the
20
+ * declaring extension declared. The loader rejects mismatches against
21
+ * the aggregate's `targetId` with `targetMismatch`.
22
+ *
23
+ * Whether the descriptor declares a contract space is decided by whether
24
+ * its corresponding `migrations/<id>/` directory exists on disk
25
+ * (materialised by the seed phase before the loader runs); the loader
26
+ * never reads the descriptor's `contractJson` itself. That makes the
27
+ * aggregate's apply / verify paths byte-for-byte independent of the
28
+ * descriptor module — `db verify` succeeds even if the descriptor's
29
+ * `contractJson` is a throwing getter.
30
+ *
31
+ * Typed structurally so the migration-tools layer stays framework-neutral.
32
+ */
33
+ export interface DeclaredExtensionEntry {
34
+ readonly id: string;
35
+ readonly targetId: string;
36
+ }
37
+
38
+ /**
39
+ * Inputs for {@link loadContractSpaceAggregate}.
40
+ *
41
+ * The loader is the **sole** descriptor-import boundary in the M2.5
42
+ * pipeline: callers gather the descriptor data (already-validated app
43
+ * contract, declared extension entries) and pass it through. Once the
44
+ * loader returns, no descriptor module is imported again for this
45
+ * aggregate's lifetime.
46
+ */
47
+ export interface LoadAggregateInput {
48
+ readonly targetId: string;
49
+ readonly migrationsDir: string;
50
+ readonly appContract: Contract;
51
+ readonly declaredExtensions: ReadonlyArray<DeclaredExtensionEntry>;
52
+ readonly validateContract: (contractJson: unknown) => Contract;
53
+ /**
54
+ * Hydrated migration graph for the **app member**.
55
+ *
56
+ * The framework-neutral migration-tools layer doesn't know how to read
57
+ * the user's authored `migrations/` directory (the app member's
58
+ * migration-package layout is family-aware: ops.json shape, manifest
59
+ * keys, etc.). Callers — the SQL family today — read the user's
60
+ * `migrations/` and hand the resulting `OnDiskMigrationPackage[]` through.
61
+ *
62
+ * Passing `[]` is valid (greenfield project, no authored migrations).
63
+ * Equivalent to `migrations/` not existing or being empty.
64
+ */
65
+ readonly appMigrationPackages: ReadonlyArray<OnDiskMigrationPackage>;
66
+ }
67
+
68
+ /**
69
+ * Discriminated failure variants the loader emits.
70
+ *
71
+ * Every variant short-circuits at first hit; the loader does not keep
72
+ * collecting after the first violation in any phase except for layout
73
+ * (where every layout offence is bundled into one `layoutViolation`).
74
+ */
75
+ export type LoadAggregateError =
76
+ | { readonly kind: 'layoutViolation'; readonly violations: readonly LayoutViolation[] }
77
+ | { readonly kind: 'integrityFailure'; readonly spaceId: string; readonly detail: string }
78
+ | { readonly kind: 'validationFailure'; readonly spaceId: string; readonly detail: string }
79
+ | {
80
+ readonly kind: 'disjointnessViolation';
81
+ readonly element: string;
82
+ readonly claimedBy: readonly string[];
83
+ }
84
+ | {
85
+ readonly kind: 'targetMismatch';
86
+ readonly spaceId: string;
87
+ readonly expected: string;
88
+ readonly actual: string;
89
+ };
90
+
91
+ /**
92
+ * Single layout violation; bundled into a `layoutViolation` error so
93
+ * users see every layout offence at once rather than fixing them one
94
+ * at a time across re-runs.
95
+ *
96
+ * - `declaredButUnmigrated`: extension declared in `extensionPacks` with
97
+ * a `contractSpace` but no contract-space dir on disk. Remediation:
98
+ * `prisma-next migrate`.
99
+ * - `orphanSpaceDir`: contract-space dir under `migrations/` for an extension
100
+ * not in `extensionPacks`. Remediation: remove the directory, or
101
+ * re-add the extension to `extensionPacks`.
102
+ */
103
+ export type LayoutViolation =
104
+ | { readonly kind: 'declaredButUnmigrated'; readonly spaceId: string }
105
+ | { readonly kind: 'orphanSpaceDir'; readonly spaceId: string };
106
+
107
+ export type LoadAggregateOutput = Result<
108
+ { readonly aggregate: ContractSpaceAggregate },
109
+ LoadAggregateError
110
+ >;
111
+
112
+ interface LoadedExtensionState {
113
+ readonly entry: DeclaredExtensionEntry;
114
+ readonly contract: Contract;
115
+ readonly headRefHash: string;
116
+ readonly headRefInvariants: readonly string[];
117
+ readonly migrations: HydratedMigrationGraph;
118
+ }
119
+
120
+ /**
121
+ * Hydrate a {@link ContractSpaceAggregate} from on-disk state and
122
+ * the app contract value the caller supplies.
123
+ *
124
+ * The loader is the **only** descriptor-import boundary at apply /
125
+ * verify time, but it intentionally does **not** read the extension
126
+ * descriptor's `contractJson` value. Each extension space's contract
127
+ * is read from its on-disk `migrations/<id>/contract.json` mirror; the
128
+ * descriptor's role is exhausted by the seed phase that wrote that
129
+ * mirror in the first place. The loader composes existing
130
+ * migration-tools primitives — layout precheck (via
131
+ * {@link listContractSpaceDirectories}), integrity checks (via
132
+ * {@link readMigrationsDir} / {@link readContractSpaceHeadRef} /
133
+ * {@link readContractSpaceContract} / `validateContract`), and
134
+ * disjointness — into a single typed value.
135
+ *
136
+ * Failure semantics: every failure variant in {@link LoadAggregateError}
137
+ * short-circuits the load.
138
+ */
139
+ export async function loadContractSpaceAggregate(
140
+ input: LoadAggregateInput,
141
+ ): Promise<LoadAggregateOutput> {
142
+ // 1. Validate target consistency on the app contract.
143
+ const appContractTarget = input.appContract.target;
144
+ if (appContractTarget !== input.targetId) {
145
+ return notOk({
146
+ kind: 'targetMismatch',
147
+ spaceId: APP_SPACE_ID,
148
+ expected: input.targetId,
149
+ actual: appContractTarget,
150
+ });
151
+ }
152
+
153
+ for (const entry of input.declaredExtensions) {
154
+ if (entry.targetId !== input.targetId) {
155
+ return notOk({
156
+ kind: 'targetMismatch',
157
+ spaceId: entry.id,
158
+ expected: input.targetId,
159
+ actual: entry.targetId,
160
+ });
161
+ }
162
+ }
163
+
164
+ // 2. Layout precheck: bundle every layout offence at once.
165
+ //
166
+ // Every declared extension contributes an entry to the aggregate when
167
+ // a corresponding `migrations/<id>/` directory exists on disk. The
168
+ // loader treats the directory's presence as the membership signal —
169
+ // the descriptor itself is not read — so codec-only extensions (no
170
+ // on-disk dir) and contract-space extensions (dir present) are
171
+ // distinguished structurally.
172
+ const declaredSpaceIds = new Set(input.declaredExtensions.map((e) => e.id));
173
+ const allDirs = await listContractSpaceDirectories(input.migrationsDir);
174
+ // The app member is implicitly declared (it is always part of the
175
+ // aggregate); its `migrations/<APP_SPACE_ID>/` directory may exist or
176
+ // not (greenfield projects start with neither). Filter it out of the
177
+ // orphan / declared-but-unmigrated checks so the layout precheck is
178
+ // about extensions only.
179
+ const extensionDirsOnDisk = allDirs.filter((d) => d !== APP_SPACE_ID);
180
+ const spaceDirSet = new Set(extensionDirsOnDisk);
181
+
182
+ const layoutViolations: LayoutViolation[] = [];
183
+ for (const dir of extensionDirsOnDisk) {
184
+ if (!declaredSpaceIds.has(dir)) {
185
+ layoutViolations.push({ kind: 'orphanSpaceDir', spaceId: dir });
186
+ }
187
+ }
188
+ for (const id of [...declaredSpaceIds].sort()) {
189
+ if (!spaceDirSet.has(id)) {
190
+ layoutViolations.push({ kind: 'declaredButUnmigrated', spaceId: id });
191
+ }
192
+ }
193
+ if (layoutViolations.length > 0) {
194
+ return notOk({ kind: 'layoutViolation', violations: layoutViolations });
195
+ }
196
+
197
+ // 3-5. Per-extension: read + validate + integrity-check.
198
+ const loadedExtensions: LoadedExtensionState[] = [];
199
+ for (const entry of [...input.declaredExtensions].sort((a, b) => a.id.localeCompare(b.id))) {
200
+ const headRef = await readContractSpaceHeadRef(input.migrationsDir, entry.id);
201
+ if (headRef === null) {
202
+ return notOk({
203
+ kind: 'integrityFailure',
204
+ spaceId: entry.id,
205
+ detail: `Head ref \`refs/head.json\` is missing for extension space "${entry.id}".`,
206
+ });
207
+ }
208
+
209
+ let spaceContractRaw: unknown;
210
+ try {
211
+ spaceContractRaw = await readContractSpaceContract(input.migrationsDir, entry.id);
212
+ } catch (error) {
213
+ return notOk({
214
+ kind: 'integrityFailure',
215
+ spaceId: entry.id,
216
+ detail: error instanceof Error ? error.message : String(error),
217
+ });
218
+ }
219
+
220
+ let spaceContract: Contract;
221
+ try {
222
+ spaceContract = input.validateContract(spaceContractRaw);
223
+ } catch (error) {
224
+ return notOk({
225
+ kind: 'validationFailure',
226
+ spaceId: entry.id,
227
+ detail: error instanceof Error ? error.message : String(error),
228
+ });
229
+ }
230
+
231
+ if (spaceContract.target !== input.targetId) {
232
+ return notOk({
233
+ kind: 'targetMismatch',
234
+ spaceId: entry.id,
235
+ expected: input.targetId,
236
+ actual: spaceContract.target,
237
+ });
238
+ }
239
+
240
+ // Read + integrity-check the migration packages. `readMigrationsDir`
241
+ // re-derives `providedInvariants` and verifies migrationHash for
242
+ // every package.
243
+ let packages: readonly OnDiskMigrationPackage[];
244
+ try {
245
+ packages = await readMigrationsDir(spaceMigrationDirectory(input.migrationsDir, entry.id));
246
+ } catch (error) {
247
+ return notOk({
248
+ kind: 'integrityFailure',
249
+ spaceId: entry.id,
250
+ detail: error instanceof Error ? error.message : String(error),
251
+ });
252
+ }
253
+
254
+ let graph: ReturnType<typeof reconstructGraph>;
255
+ try {
256
+ graph = reconstructGraph(packages);
257
+ } catch (error) {
258
+ return notOk({
259
+ kind: 'integrityFailure',
260
+ spaceId: entry.id,
261
+ detail: error instanceof Error ? error.message : String(error),
262
+ });
263
+ }
264
+
265
+ // The on-disk head ref must be reachable in the graph. Empty graphs
266
+ // are tolerated only when the head ref points at the empty-contract
267
+ // sentinel (a never-emitted extension space; not a typical scenario
268
+ // because the layout precheck would have flagged the missing
269
+ // dir, but defensible).
270
+ if (graph.nodes.size === 0) {
271
+ if (headRef.hash !== EMPTY_CONTRACT_HASH) {
272
+ return notOk({
273
+ kind: 'integrityFailure',
274
+ spaceId: entry.id,
275
+ detail: `Head ref "${headRef.hash}" is not present in the (empty) on-disk migration graph.`,
276
+ });
277
+ }
278
+ } else if (!graph.nodes.has(headRef.hash)) {
279
+ return notOk({
280
+ kind: 'integrityFailure',
281
+ spaceId: entry.id,
282
+ detail: `Head ref "${headRef.hash}" is not present in the on-disk migration graph.`,
283
+ });
284
+ }
285
+
286
+ const packagesByMigrationHash = new Map<string, OnDiskMigrationPackage>(
287
+ packages.map((p) => [p.metadata.migrationHash, p]),
288
+ );
289
+
290
+ loadedExtensions.push({
291
+ entry,
292
+ contract: spaceContract,
293
+ headRefHash: headRef.hash,
294
+ headRefInvariants: [...headRef.invariants].sort(),
295
+ migrations: { graph, packagesByMigrationHash },
296
+ });
297
+ }
298
+
299
+ // 6. Build app member with hydrated graph from caller-supplied packages.
300
+ let appGraph: ReturnType<typeof reconstructGraph>;
301
+ try {
302
+ appGraph = reconstructGraph(input.appMigrationPackages);
303
+ } catch (error) {
304
+ return notOk({
305
+ kind: 'integrityFailure',
306
+ spaceId: APP_SPACE_ID,
307
+ detail: error instanceof Error ? error.message : String(error),
308
+ });
309
+ }
310
+ const appPackagesByMigrationHash = new Map<string, OnDiskMigrationPackage>(
311
+ input.appMigrationPackages.map((p) => [p.metadata.migrationHash, p]),
312
+ );
313
+
314
+ const appMember: ContractSpaceMember = {
315
+ spaceId: APP_SPACE_ID,
316
+ contract: input.appContract,
317
+ headRef: {
318
+ hash: input.appContract.storage.storageHash,
319
+ invariants: [],
320
+ },
321
+ migrations: {
322
+ graph: appGraph,
323
+ packagesByMigrationHash: appPackagesByMigrationHash,
324
+ },
325
+ };
326
+
327
+ const extensionMembers: ContractSpaceMember[] = loadedExtensions.map((s) => ({
328
+ spaceId: s.entry.id,
329
+ contract: s.contract,
330
+ headRef: {
331
+ hash: s.headRefHash,
332
+ invariants: s.headRefInvariants,
333
+ },
334
+ migrations: s.migrations,
335
+ }));
336
+
337
+ // 7. Disjointness: no two members claim the same storage element.
338
+ const elementClaimedBy = new Map<string, string[]>();
339
+ for (const member of [appMember, ...extensionMembers]) {
340
+ const tables = extractTableNames(member.contract);
341
+ for (const tableName of tables) {
342
+ const claimers = elementClaimedBy.get(tableName);
343
+ if (claimers) claimers.push(member.spaceId);
344
+ else elementClaimedBy.set(tableName, [member.spaceId]);
345
+ }
346
+ }
347
+ for (const [element, claimedBy] of elementClaimedBy) {
348
+ if (claimedBy.length > 1) {
349
+ return notOk({
350
+ kind: 'disjointnessViolation',
351
+ element,
352
+ claimedBy: [...claimedBy].sort(),
353
+ });
354
+ }
355
+ }
356
+
357
+ return ok({
358
+ aggregate: {
359
+ targetId: input.targetId,
360
+ app: appMember,
361
+ extensions: extensionMembers,
362
+ },
363
+ });
364
+ }
365
+
366
+ /**
367
+ * Extract the set of top-level storage table names from a contract.
368
+ * Duck-typed: returns `[]` if the contract's storage shape doesn't
369
+ * match the canonical `storage.tables: Record<string, ...>` form. A
370
+ * future family with a different storage shape gets disjointness
371
+ * effectively disabled (not enforced) rather than a hard failure.
372
+ */
373
+ function extractTableNames(contract: Contract): readonly string[] {
374
+ const storage = (contract as { readonly storage?: unknown }).storage;
375
+ if (typeof storage !== 'object' || storage === null) return [];
376
+ const tables = (storage as { readonly tables?: unknown }).tables;
377
+ if (typeof tables !== 'object' || tables === null) return [];
378
+ return Object.keys(tables as Record<string, unknown>);
379
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Structural shape the aggregate planner / verifier accept for marker
3
+ * rows. Mirrors `family.readAllMarkers(...)` outputs across SQL and
4
+ * Mongo families: a `(storageHash, invariants)` pair plus an optional
5
+ * `profileHash` the verifier uses to align the marker with the
6
+ * destination contract's profile envelope.
7
+ *
8
+ * Typed structurally so `migration-tools` stays framework-neutral; SQL
9
+ * and Mongo families pass their typed `ContractMarkerRecord` through
10
+ * unchanged.
11
+ */
12
+ export interface ContractMarkerRecordLike {
13
+ readonly storageHash: string;
14
+ readonly invariants: readonly string[];
15
+ readonly profileHash?: string;
16
+ }
@@ -0,0 +1,171 @@
1
+ import type { Contract } from '@prisma-next/contract/types';
2
+ import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';
3
+ import type {
4
+ ControlFamilyInstance,
5
+ MigrationOperationPolicy,
6
+ MigrationPlan,
7
+ MigrationPlannerConflict,
8
+ MigrationPlanOperation,
9
+ TargetMigrationsCapability,
10
+ } from '@prisma-next/framework-components/control';
11
+ import type { Result } from '@prisma-next/utils/result';
12
+ import type { PathDecision } from '../migration-graph';
13
+ import type { ContractMarkerRecordLike } from './marker-types';
14
+ import type { ContractSpaceAggregate } from './types';
15
+
16
+ /**
17
+ * Caller-provided policy for {@link planAggregate}. Today this carries
18
+ * just one knob:
19
+ *
20
+ * - `ignoreGraphFor`: `Set<spaceId>`. For listed members, the planner
21
+ * forces the **synth** strategy (synthesise a plan from the contract
22
+ * IR via `familyInstance.createPlanner(...).plan(...)`) regardless of
23
+ * whether a graph is available. The CLI's daily-driver `db init` /
24
+ * `db update` pipelines pass `new Set([aggregate.app.spaceId])` to
25
+ * keep today's app-space behaviour: the user's authored
26
+ * `migrations/` directory is **not** walked for the app member, the
27
+ * plan is synthesised on the fly. Extension members are walked.
28
+ *
29
+ * Listing a member here whose `headRef.invariants` is non-empty is
30
+ * a `policyConflict` — synth cannot satisfy authored invariants.
31
+ */
32
+ export interface CallerPolicy {
33
+ readonly ignoreGraphFor: ReadonlySet<string>;
34
+ }
35
+
36
+ /**
37
+ * Snapshot of the live database state the planner needs to drive
38
+ * strategy selection.
39
+ *
40
+ * - `markersBySpaceId`: per-space marker rows. Absent entry = no
41
+ * marker yet (greenfield space). The planner treats the marker's
42
+ * `storageHash` as the graph-walk's `from` node, falling back to
43
+ * {@link import('../constants').EMPTY_CONTRACT_HASH} when absent.
44
+ * - `schemaIntrospection`: the family's full live schema IR. Fed into
45
+ * the synth strategy after per-space pre-projection via
46
+ * {@link import('./project-schema-to-space').projectSchemaToSpace}.
47
+ *
48
+ * Callers (CLI commands) gather this via the family's
49
+ * `readAllMarkers` + `introspect` calls before invoking the planner.
50
+ * The planner itself does not touch the database.
51
+ */
52
+ export interface AggregateCurrentDBState {
53
+ readonly markersBySpaceId: ReadonlyMap<string, ContractMarkerRecordLike | null>;
54
+ readonly schemaIntrospection: unknown;
55
+ }
56
+
57
+ /**
58
+ * Inputs to {@link planAggregate}.
59
+ *
60
+ * The planner is target-agnostic but family-aware: per-member synth
61
+ * delegates to the family's `createPlanner(familyInstance).plan(...)`,
62
+ * which is why `familyInstance`, `migrations` (the
63
+ * `TargetMigrationsCapability`), and `frameworkComponents` are all
64
+ * threaded through. (`frameworkComponents` is passed verbatim into
65
+ * `planner.plan(...)` per ADR 212; the planner does not interpret it.)
66
+ *
67
+ * The aggregate planner does **not** receive a `targetId` separately —
68
+ * it reads `aggregate.targetId` and stamps it onto every emitted
69
+ * `MigrationPlan` from construction. No placeholder, no patch step.
70
+ */
71
+ export interface AggregatePlannerInput<TFamilyId extends string, TTargetId extends string> {
72
+ readonly aggregate: ContractSpaceAggregate;
73
+ readonly currentDBState: AggregateCurrentDBState;
74
+ readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;
75
+ readonly migrations: TargetMigrationsCapability<
76
+ TFamilyId,
77
+ TTargetId,
78
+ ControlFamilyInstance<TFamilyId, unknown>
79
+ >;
80
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;
81
+ readonly callerPolicy: CallerPolicy;
82
+ readonly operationPolicy: MigrationOperationPolicy;
83
+ }
84
+
85
+ /**
86
+ * Per-member output of the aggregate planner. The runner ingests this
87
+ * shape directly via a thin `toRunnerInput` adapter at the CLI.
88
+ *
89
+ * - `plan`: ready-to-execute `MigrationPlan` with `targetId` already
90
+ * set from `aggregate.targetId`.
91
+ * - `displayOps`: same operation list, surfaced separately so plan-mode
92
+ * output can render without touching the runner-bound `plan`.
93
+ * - `destinationContract`: the typed contract value the runner uses
94
+ * for post-apply verification. For the app member, the user's
95
+ * contract; for extension members, the on-disk `contract.json`.
96
+ * - `strategy`: which strategy produced this plan (`'graph-walk'` or
97
+ * `'synth'`). Surfaced for diagnostics; not consumed by the runner.
98
+ */
99
+ /**
100
+ * Per-edge metadata for the chain assembled by the graph-walk
101
+ * strategy. Lets `migration apply` surface a per-migration `applied[]`
102
+ * entry (preserving the single-space `migrationsApplied` count
103
+ * semantics) without re-walking the graph.
104
+ *
105
+ * `synth`-produced plans leave this absent — synthesised plans don't
106
+ * have authored edges to surface.
107
+ */
108
+ export interface AggregateMigrationEdgeRef {
109
+ readonly migrationHash: string;
110
+ readonly dirName: string;
111
+ readonly from: string;
112
+ readonly to: string;
113
+ readonly operationCount: number;
114
+ }
115
+
116
+ export interface AggregatePerSpacePlan {
117
+ readonly plan: MigrationPlan;
118
+ readonly displayOps: readonly MigrationPlanOperation[];
119
+ readonly destinationContract: Contract;
120
+ readonly strategy: 'graph-walk' | 'synth';
121
+ /**
122
+ * Per-edge breakdown of the chain. Populated by the graph-walk
123
+ * strategy; absent for synth-produced plans.
124
+ */
125
+ readonly migrationEdges?: readonly AggregateMigrationEdgeRef[];
126
+ /**
127
+ * Path decision data the strategy used to select the chain
128
+ * (alternative count, tie-break reasons, required/satisfied
129
+ * invariants, per-edge invariants). Populated by the graph-walk
130
+ * strategy; absent for synth-produced plans.
131
+ *
132
+ * `migration apply` surfaces this for the app member as
133
+ * `MigrationApplySuccess.pathDecision` (back-compat with single-
134
+ * space callers).
135
+ */
136
+ readonly pathDecision?: PathDecision;
137
+ }
138
+
139
+ export interface AggregatePlannerSuccess {
140
+ readonly perSpace: ReadonlyMap<string, AggregatePerSpacePlan>;
141
+ /**
142
+ * `applyOrder` is the order the runner must walk per-space inputs.
143
+ * Mirrors the existing `concatenateSpaceApplyInputs` convention:
144
+ * extensions alphabetically by `spaceId`, then the app. Tests assert
145
+ * on `MultiSpaceRunnerFailure.failingSpace`, which is positional in
146
+ * the runner's input array — preserving the literal ordering keeps
147
+ * `failingSpace` attribution byte-for-byte.
148
+ */
149
+ readonly applyOrder: readonly string[];
150
+ }
151
+
152
+ /**
153
+ * Discriminated failure variants for {@link planAggregate}. Each
154
+ * variant short-circuits the plan; per-member errors carry the
155
+ * `spaceId` so the CLI can surface a precise envelope.
156
+ */
157
+ export type AggregatePlannerError =
158
+ | { readonly kind: 'extensionPathUnreachable'; readonly spaceId: string; readonly target: string }
159
+ | {
160
+ readonly kind: 'extensionPathUnsatisfiable';
161
+ readonly spaceId: string;
162
+ readonly missingInvariants: readonly string[];
163
+ }
164
+ | {
165
+ readonly kind: 'appSynthFailure';
166
+ readonly spaceId: string;
167
+ readonly conflicts: readonly MigrationPlannerConflict[];
168
+ }
169
+ | { readonly kind: 'policyConflict'; readonly spaceId: string; readonly detail: string };
170
+
171
+ export type AggregatePlannerOutput = Result<AggregatePlannerSuccess, AggregatePlannerError>;