@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,599 @@
1
+ import { n as OnDiskMigrationPackage } from "../package-BjiZ7KDy.mjs";
2
+ import { n as MigrationGraph } from "../graph-HMWAldoR.mjs";
3
+ import { t as PathDecision } from "../migration-graph-DulOITvG.mjs";
4
+ import { ControlFamilyInstance, MigrationOperationPolicy, MigrationPlan, MigrationPlanOperation, MigrationPlannerConflict, TargetMigrationsCapability } from "@prisma-next/framework-components/control";
5
+ import { Result } from "@prisma-next/utils/result";
6
+ import { Contract } from "@prisma-next/contract/types";
7
+ import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";
8
+
9
+ //#region src/aggregate/types.d.ts
10
+ /**
11
+ * Hydrated migration graph for a single contract space.
12
+ *
13
+ * `graph` is the structural shortest-path graph (forward / reverse chain,
14
+ * deterministic tie-break order) reconstructed from a set of on-disk
15
+ * migration packages. `packagesByMigrationHash` is the lookup table the
16
+ * graph-walk strategy uses to resolve a path's edge sequence back to the
17
+ * concrete `OnDiskMigrationPackage` (and therefore the operation list) for
18
+ * apply.
19
+ *
20
+ * Eagerly hydrated by the loader. Once a `ContractSpaceAggregate` exists,
21
+ * downstream consumers do **not** touch the filesystem to walk graphs or
22
+ * resolve packages — the aggregate is the boundary.
23
+ */
24
+ interface HydratedMigrationGraph {
25
+ readonly graph: MigrationGraph;
26
+ readonly packagesByMigrationHash: ReadonlyMap<string, OnDiskMigrationPackage>;
27
+ }
28
+ /**
29
+ * One contract space — app or extension — as a member of a
30
+ * {@link ContractSpaceAggregate}. Every member has the same shape.
31
+ *
32
+ * - `spaceId`: `'app'` for the application, otherwise the extension's
33
+ * id (validated against `[a-z][a-z0-9_-]{0,63}`).
34
+ * - `contract`: the validated contract value for this member. For the
35
+ * app, the user's authored contract; for an extension, the on-disk
36
+ * `migrations/<spaceId>/contract.json`. Both have already passed the
37
+ * family's `validateContract` at the loader boundary.
38
+ * - `headRef.hash`: the storage hash this member is targeting. For the
39
+ * app, equals `contract.storage.storageHash`. For extensions, the
40
+ * on-disk `refs/head.json.hash`.
41
+ * - `headRef.invariants`: alphabetically sorted, deduplicated invariant
42
+ * ids declared on the head ref. Empty for the app member (the app's
43
+ * plan is synthesised from the contract IR, no invariants required).
44
+ * - `migrations`: the hydrated migration graph for this space. Possibly
45
+ * empty (an extension whose on-disk head ref points at the
46
+ * empty-contract sentinel and ships no migrations yet, or the app
47
+ * when the user hasn't authored any).
48
+ */
49
+ interface ContractSpaceMember {
50
+ readonly spaceId: string;
51
+ readonly contract: Contract;
52
+ readonly headRef: {
53
+ readonly hash: string;
54
+ readonly invariants: readonly string[];
55
+ };
56
+ readonly migrations: HydratedMigrationGraph;
57
+ }
58
+ /**
59
+ * Typed value carrying the user's app contract plus every loaded
60
+ * extension contract space, fully hydrated and internally consistent.
61
+ *
62
+ * Produced once per CLI invocation by `loadContractSpaceAggregate`.
63
+ * Every downstream component (planner, verifier, runner adapter)
64
+ * consumes this value rather than rebuilding state from disk.
65
+ *
66
+ * Invariants the loader enforces at construction:
67
+ *
68
+ * 1. `targetId` is consistent across every member (`contract.target`
69
+ * matches `aggregate.targetId`). The aggregate's `targetId` is the
70
+ * `Config.adapter.targetId` value the loader was told to use.
71
+ * 2. `aggregate.extensions` is sorted alphabetically by `spaceId`.
72
+ * Mirrors {@link import('../concatenate-space-apply-inputs').concatenateSpaceApplyInputs}'s
73
+ * extension ordering convention so downstream apply order matches
74
+ * today's behaviour byte-for-byte.
75
+ * 3. No two members claim the same storage element (table / type / etc.).
76
+ * 4. For each extension member: `member.headRef.hash` is reachable from
77
+ * the empty-contract sentinel in `member.migrations.graph` (or the
78
+ * graph is empty and `member.headRef.hash === EMPTY_CONTRACT_HASH`).
79
+ * 5. For the app member: `member.headRef.hash` equals
80
+ * `member.contract.storage.storageHash`. The app's `migrations`
81
+ * is hydrated from the user's authored `migrations/` (or empty if
82
+ * none).
83
+ *
84
+ * The aggregate is **type-uniform** post-construction: app/extension
85
+ * distinguishability survives only at the caller-policy layer
86
+ * (`ignoreGraphFor: new Set([appSpaceId])`), not on member shape.
87
+ */
88
+ interface ContractSpaceAggregate {
89
+ readonly targetId: string;
90
+ readonly app: ContractSpaceMember;
91
+ readonly extensions: readonly ContractSpaceMember[];
92
+ }
93
+ //#endregion
94
+ //#region src/aggregate/loader.d.ts
95
+ /**
96
+ * Single declared extension entry the loader needs from `Config.extensionPacks`.
97
+ *
98
+ * Only the subset of fields the loader operates on:
99
+ *
100
+ * - `id` — the space id (also the directory name under `migrations/`).
101
+ * - `targetId` — the configured `Config.adapter.targetId` value the
102
+ * declaring extension declared. The loader rejects mismatches against
103
+ * the aggregate's `targetId` with `targetMismatch`.
104
+ *
105
+ * Whether the descriptor declares a contract space is decided by whether
106
+ * its corresponding `migrations/<id>/` directory exists on disk
107
+ * (materialised by the seed phase before the loader runs); the loader
108
+ * never reads the descriptor's `contractJson` itself. That makes the
109
+ * aggregate's apply / verify paths byte-for-byte independent of the
110
+ * descriptor module — `db verify` succeeds even if the descriptor's
111
+ * `contractJson` is a throwing getter.
112
+ *
113
+ * Typed structurally so the migration-tools layer stays framework-neutral.
114
+ */
115
+ interface DeclaredExtensionEntry {
116
+ readonly id: string;
117
+ readonly targetId: string;
118
+ }
119
+ /**
120
+ * Inputs for {@link loadContractSpaceAggregate}.
121
+ *
122
+ * The loader is the **sole** descriptor-import boundary in the M2.5
123
+ * pipeline: callers gather the descriptor data (already-validated app
124
+ * contract, declared extension entries) and pass it through. Once the
125
+ * loader returns, no descriptor module is imported again for this
126
+ * aggregate's lifetime.
127
+ */
128
+ interface LoadAggregateInput {
129
+ readonly targetId: string;
130
+ readonly migrationsDir: string;
131
+ readonly appContract: Contract;
132
+ readonly declaredExtensions: ReadonlyArray<DeclaredExtensionEntry>;
133
+ readonly validateContract: (contractJson: unknown) => Contract;
134
+ /**
135
+ * Hydrated migration graph for the **app member**.
136
+ *
137
+ * The framework-neutral migration-tools layer doesn't know how to read
138
+ * the user's authored `migrations/` directory (the app member's
139
+ * migration-package layout is family-aware: ops.json shape, manifest
140
+ * keys, etc.). Callers — the SQL family today — read the user's
141
+ * `migrations/` and hand the resulting `OnDiskMigrationPackage[]` through.
142
+ *
143
+ * Passing `[]` is valid (greenfield project, no authored migrations).
144
+ * Equivalent to `migrations/` not existing or being empty.
145
+ */
146
+ readonly appMigrationPackages: ReadonlyArray<OnDiskMigrationPackage>;
147
+ }
148
+ /**
149
+ * Discriminated failure variants the loader emits.
150
+ *
151
+ * Every variant short-circuits at first hit; the loader does not keep
152
+ * collecting after the first violation in any phase except for layout
153
+ * (where every layout offence is bundled into one `layoutViolation`).
154
+ */
155
+ type LoadAggregateError = {
156
+ readonly kind: 'layoutViolation';
157
+ readonly violations: readonly LayoutViolation[];
158
+ } | {
159
+ readonly kind: 'integrityFailure';
160
+ readonly spaceId: string;
161
+ readonly detail: string;
162
+ } | {
163
+ readonly kind: 'validationFailure';
164
+ readonly spaceId: string;
165
+ readonly detail: string;
166
+ } | {
167
+ readonly kind: 'disjointnessViolation';
168
+ readonly element: string;
169
+ readonly claimedBy: readonly string[];
170
+ } | {
171
+ readonly kind: 'targetMismatch';
172
+ readonly spaceId: string;
173
+ readonly expected: string;
174
+ readonly actual: string;
175
+ };
176
+ /**
177
+ * Single layout violation; bundled into a `layoutViolation` error so
178
+ * users see every layout offence at once rather than fixing them one
179
+ * at a time across re-runs.
180
+ *
181
+ * - `declaredButUnmigrated`: extension declared in `extensionPacks` with
182
+ * a `contractSpace` but no contract-space dir on disk. Remediation:
183
+ * `prisma-next migrate`.
184
+ * - `orphanSpaceDir`: contract-space dir under `migrations/` for an extension
185
+ * not in `extensionPacks`. Remediation: remove the directory, or
186
+ * re-add the extension to `extensionPacks`.
187
+ */
188
+ type LayoutViolation = {
189
+ readonly kind: 'declaredButUnmigrated';
190
+ readonly spaceId: string;
191
+ } | {
192
+ readonly kind: 'orphanSpaceDir';
193
+ readonly spaceId: string;
194
+ };
195
+ type LoadAggregateOutput = Result<{
196
+ readonly aggregate: ContractSpaceAggregate;
197
+ }, LoadAggregateError>;
198
+ /**
199
+ * Hydrate a {@link ContractSpaceAggregate} from on-disk state and
200
+ * the app contract value the caller supplies.
201
+ *
202
+ * The loader is the **only** descriptor-import boundary at apply /
203
+ * verify time, but it intentionally does **not** read the extension
204
+ * descriptor's `contractJson` value. Each extension space's contract
205
+ * is read from its on-disk `migrations/<id>/contract.json` mirror; the
206
+ * descriptor's role is exhausted by the seed phase that wrote that
207
+ * mirror in the first place. The loader composes existing
208
+ * migration-tools primitives — layout precheck (via
209
+ * {@link listContractSpaceDirectories}), integrity checks (via
210
+ * {@link readMigrationsDir} / {@link readContractSpaceHeadRef} /
211
+ * {@link readContractSpaceContract} / `validateContract`), and
212
+ * disjointness — into a single typed value.
213
+ *
214
+ * Failure semantics: every failure variant in {@link LoadAggregateError}
215
+ * short-circuits the load.
216
+ */
217
+ declare function loadContractSpaceAggregate(input: LoadAggregateInput): Promise<LoadAggregateOutput>;
218
+ //#endregion
219
+ //#region src/aggregate/marker-types.d.ts
220
+ /**
221
+ * Structural shape the aggregate planner / verifier accept for marker
222
+ * rows. Mirrors `family.readAllMarkers(...)` outputs across SQL and
223
+ * Mongo families: a `(storageHash, invariants)` pair plus an optional
224
+ * `profileHash` the verifier uses to align the marker with the
225
+ * destination contract's profile envelope.
226
+ *
227
+ * Typed structurally so `migration-tools` stays framework-neutral; SQL
228
+ * and Mongo families pass their typed `ContractMarkerRecord` through
229
+ * unchanged.
230
+ */
231
+ interface ContractMarkerRecordLike {
232
+ readonly storageHash: string;
233
+ readonly invariants: readonly string[];
234
+ readonly profileHash?: string;
235
+ }
236
+ //#endregion
237
+ //#region src/aggregate/planner-types.d.ts
238
+ /**
239
+ * Caller-provided policy for {@link planAggregate}. Today this carries
240
+ * just one knob:
241
+ *
242
+ * - `ignoreGraphFor`: `Set<spaceId>`. For listed members, the planner
243
+ * forces the **synth** strategy (synthesise a plan from the contract
244
+ * IR via `familyInstance.createPlanner(...).plan(...)`) regardless of
245
+ * whether a graph is available. The CLI's daily-driver `db init` /
246
+ * `db update` pipelines pass `new Set([aggregate.app.spaceId])` to
247
+ * keep today's app-space behaviour: the user's authored
248
+ * `migrations/` directory is **not** walked for the app member, the
249
+ * plan is synthesised on the fly. Extension members are walked.
250
+ *
251
+ * Listing a member here whose `headRef.invariants` is non-empty is
252
+ * a `policyConflict` — synth cannot satisfy authored invariants.
253
+ */
254
+ interface CallerPolicy {
255
+ readonly ignoreGraphFor: ReadonlySet<string>;
256
+ }
257
+ /**
258
+ * Snapshot of the live database state the planner needs to drive
259
+ * strategy selection.
260
+ *
261
+ * - `markersBySpaceId`: per-space marker rows. Absent entry = no
262
+ * marker yet (greenfield space). The planner treats the marker's
263
+ * `storageHash` as the graph-walk's `from` node, falling back to
264
+ * {@link import('../constants').EMPTY_CONTRACT_HASH} when absent.
265
+ * - `schemaIntrospection`: the family's full live schema IR. Fed into
266
+ * the synth strategy after per-space pre-projection via
267
+ * {@link import('./project-schema-to-space').projectSchemaToSpace}.
268
+ *
269
+ * Callers (CLI commands) gather this via the family's
270
+ * `readAllMarkers` + `introspect` calls before invoking the planner.
271
+ * The planner itself does not touch the database.
272
+ */
273
+ interface AggregateCurrentDBState {
274
+ readonly markersBySpaceId: ReadonlyMap<string, ContractMarkerRecordLike | null>;
275
+ readonly schemaIntrospection: unknown;
276
+ }
277
+ /**
278
+ * Inputs to {@link planAggregate}.
279
+ *
280
+ * The planner is target-agnostic but family-aware: per-member synth
281
+ * delegates to the family's `createPlanner(familyInstance).plan(...)`,
282
+ * which is why `familyInstance`, `migrations` (the
283
+ * `TargetMigrationsCapability`), and `frameworkComponents` are all
284
+ * threaded through. (`frameworkComponents` is passed verbatim into
285
+ * `planner.plan(...)` per ADR 212; the planner does not interpret it.)
286
+ *
287
+ * The aggregate planner does **not** receive a `targetId` separately —
288
+ * it reads `aggregate.targetId` and stamps it onto every emitted
289
+ * `MigrationPlan` from construction. No placeholder, no patch step.
290
+ */
291
+ interface AggregatePlannerInput<TFamilyId extends string, TTargetId extends string> {
292
+ readonly aggregate: ContractSpaceAggregate;
293
+ readonly currentDBState: AggregateCurrentDBState;
294
+ readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;
295
+ readonly migrations: TargetMigrationsCapability<TFamilyId, TTargetId, ControlFamilyInstance<TFamilyId, unknown>>;
296
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;
297
+ readonly callerPolicy: CallerPolicy;
298
+ readonly operationPolicy: MigrationOperationPolicy;
299
+ }
300
+ /**
301
+ * Per-member output of the aggregate planner. The runner ingests this
302
+ * shape directly via a thin `toRunnerInput` adapter at the CLI.
303
+ *
304
+ * - `plan`: ready-to-execute `MigrationPlan` with `targetId` already
305
+ * set from `aggregate.targetId`.
306
+ * - `displayOps`: same operation list, surfaced separately so plan-mode
307
+ * output can render without touching the runner-bound `plan`.
308
+ * - `destinationContract`: the typed contract value the runner uses
309
+ * for post-apply verification. For the app member, the user's
310
+ * contract; for extension members, the on-disk `contract.json`.
311
+ * - `strategy`: which strategy produced this plan (`'graph-walk'` or
312
+ * `'synth'`). Surfaced for diagnostics; not consumed by the runner.
313
+ */
314
+ /**
315
+ * Per-edge metadata for the chain assembled by the graph-walk
316
+ * strategy. Lets `migration apply` surface a per-migration `applied[]`
317
+ * entry (preserving the single-space `migrationsApplied` count
318
+ * semantics) without re-walking the graph.
319
+ *
320
+ * `synth`-produced plans leave this absent — synthesised plans don't
321
+ * have authored edges to surface.
322
+ */
323
+ interface AggregateMigrationEdgeRef {
324
+ readonly migrationHash: string;
325
+ readonly dirName: string;
326
+ readonly from: string;
327
+ readonly to: string;
328
+ readonly operationCount: number;
329
+ }
330
+ interface AggregatePerSpacePlan {
331
+ readonly plan: MigrationPlan;
332
+ readonly displayOps: readonly MigrationPlanOperation[];
333
+ readonly destinationContract: Contract;
334
+ readonly strategy: 'graph-walk' | 'synth';
335
+ /**
336
+ * Per-edge breakdown of the chain. Populated by the graph-walk
337
+ * strategy; absent for synth-produced plans.
338
+ */
339
+ readonly migrationEdges?: readonly AggregateMigrationEdgeRef[];
340
+ /**
341
+ * Path decision data the strategy used to select the chain
342
+ * (alternative count, tie-break reasons, required/satisfied
343
+ * invariants, per-edge invariants). Populated by the graph-walk
344
+ * strategy; absent for synth-produced plans.
345
+ *
346
+ * `migration apply` surfaces this for the app member as
347
+ * `MigrationApplySuccess.pathDecision` (back-compat with single-
348
+ * space callers).
349
+ */
350
+ readonly pathDecision?: PathDecision;
351
+ }
352
+ interface AggregatePlannerSuccess {
353
+ readonly perSpace: ReadonlyMap<string, AggregatePerSpacePlan>;
354
+ /**
355
+ * `applyOrder` is the order the runner must walk per-space inputs.
356
+ * Mirrors the existing `concatenateSpaceApplyInputs` convention:
357
+ * extensions alphabetically by `spaceId`, then the app. Tests assert
358
+ * on `MultiSpaceRunnerFailure.failingSpace`, which is positional in
359
+ * the runner's input array — preserving the literal ordering keeps
360
+ * `failingSpace` attribution byte-for-byte.
361
+ */
362
+ readonly applyOrder: readonly string[];
363
+ }
364
+ /**
365
+ * Discriminated failure variants for {@link planAggregate}. Each
366
+ * variant short-circuits the plan; per-member errors carry the
367
+ * `spaceId` so the CLI can surface a precise envelope.
368
+ */
369
+ type AggregatePlannerError = {
370
+ readonly kind: 'extensionPathUnreachable';
371
+ readonly spaceId: string;
372
+ readonly target: string;
373
+ } | {
374
+ readonly kind: 'extensionPathUnsatisfiable';
375
+ readonly spaceId: string;
376
+ readonly missingInvariants: readonly string[];
377
+ } | {
378
+ readonly kind: 'appSynthFailure';
379
+ readonly spaceId: string;
380
+ readonly conflicts: readonly MigrationPlannerConflict[];
381
+ } | {
382
+ readonly kind: 'policyConflict';
383
+ readonly spaceId: string;
384
+ readonly detail: string;
385
+ };
386
+ type AggregatePlannerOutput = Result<AggregatePlannerSuccess, AggregatePlannerError>;
387
+ //#endregion
388
+ //#region src/aggregate/planner.d.ts
389
+ /**
390
+ * Plan a migration across every member of a {@link ContractSpaceAggregate}.
391
+ *
392
+ * Strategy selection per member, in order; first match wins:
393
+ *
394
+ * 1. If `callerPolicy.ignoreGraphFor.has(member.spaceId)`:
395
+ * - If `member.headRef.invariants` is empty → synth.
396
+ * - Else → `policyConflict` (synth cannot satisfy authored invariants).
397
+ * 2. Else if `member.migrations.graph` is non-empty AND graph-walk
398
+ * succeeds → graph-walk.
399
+ * 3. Else if `member.headRef.invariants` is empty → synth.
400
+ * 4. Else → graph-walk failure → `extensionPathUnreachable` /
401
+ * `extensionPathUnsatisfiable`.
402
+ *
403
+ * Output `applyOrder` is `[...aggregate.extensions.map(spaceId), aggregate.app.spaceId]`
404
+ * — extensions alphabetical, then app — matching today's
405
+ * `concatenateSpaceApplyInputs` ordering. This preserves
406
+ * `MultiSpaceRunnerFailure.failingSpace` attribution byte-for-byte.
407
+ *
408
+ * Every emitted `MigrationPlan` has `targetId = aggregate.targetId`.
409
+ * No placeholder cast; no patch step.
410
+ */
411
+ declare function planAggregate<TFamilyId extends string, TTargetId extends string>(input: AggregatePlannerInput<TFamilyId, TTargetId>): Promise<AggregatePlannerOutput>;
412
+ //#endregion
413
+ //#region src/aggregate/project-schema-to-space.d.ts
414
+ /**
415
+ * Project the introspected live schema to the slice claimed by a single
416
+ * contract-space member.
417
+ *
418
+ * Returns the same `schema` value with every top-level table claimed by
419
+ * **other** members of the aggregate removed. Tables not claimed by any
420
+ * member flow through unchanged — the planner / verifier sees them as
421
+ * orphans (extras in strict mode).
422
+ *
423
+ * Used by:
424
+ *
425
+ * - The aggregate planner's **synth strategy**: when synthesising a
426
+ * plan against a member's contract, the live schema must be projected
427
+ * to that member's slice so the planner doesn't treat tables claimed
428
+ * by other members as "extras" and emit destructive ops to drop
429
+ * them.
430
+ * - The aggregate verifier's **schemaCheck**: projects per member so the
431
+ * single-contract `verifySqlSchema` only sees the slice claimed by
432
+ * the member it is checking. Closes the F23 architectural concern
433
+ * (multi-member deployments where each member's tables look like
434
+ * extras to every other member's verify pass).
435
+ *
436
+ * **Duck-typing semantics**: the helper operates on `unknown` for the
437
+ * schema and falls through structurally if the shape doesn't match.
438
+ * Every family today exposes `storage.tables: Record<string, ...>` and
439
+ * the introspected schema mirrors the same shape; a future family with
440
+ * a different storage shape gets the schema returned unchanged rather
441
+ * than blowing up the aggregate planner.
442
+ */
443
+ declare function projectSchemaToSpace(schema: unknown, member: ContractSpaceMember, otherMembers: ReadonlyArray<ContractSpaceMember>): unknown;
444
+ //#endregion
445
+ //#region src/aggregate/strategies/graph-walk.d.ts
446
+ /**
447
+ * Outcome variants for the graph-walk strategy. Mirrors
448
+ * {@link import('../../compute-extension-space-apply-path').ExtensionSpaceApplyPathOutcome}
449
+ * but operates against the **already-hydrated** `member.migrations.graph`
450
+ * instead of re-reading from disk. The aggregate planner converts
451
+ * these into {@link import('../planner-types').AggregatePlannerError}
452
+ * variants.
453
+ */
454
+ type GraphWalkOutcome = {
455
+ readonly kind: 'ok';
456
+ readonly result: AggregatePerSpacePlan;
457
+ } | {
458
+ readonly kind: 'unreachable';
459
+ } | {
460
+ readonly kind: 'unsatisfiable';
461
+ readonly missing: readonly string[];
462
+ };
463
+ interface GraphWalkStrategyInputs {
464
+ readonly aggregateTargetId: string;
465
+ readonly member: ContractSpaceMember;
466
+ readonly currentMarker: ContractMarkerRecordLike | null;
467
+ /**
468
+ * Optional ref name to decorate the resulting `PathDecision`. Used by
469
+ * `migration apply` to surface the user-supplied `--ref <name>` in
470
+ * structured-progress events and invariant-path error envelopes. The
471
+ * strategy itself does not interpret it.
472
+ */
473
+ readonly refName?: string;
474
+ }
475
+ /**
476
+ * Walk a member's hydrated migration graph from the live marker to
477
+ * `member.headRef.hash`, covering every required invariant.
478
+ *
479
+ * Pure synchronous function — no I/O. The aggregate's loader has
480
+ * already integrity-checked every package and reconstructed the graph;
481
+ * this strategy just looks up ops by `migrationHash` and assembles a
482
+ * `MigrationPlan` with `targetId` set from the aggregate (no
483
+ * placeholder cast).
484
+ *
485
+ * Required invariants are computed as `headRef.invariants \ marker.invariants`
486
+ * — the marker already declares some invariants satisfied; the path
487
+ * only needs to provide the remainder. Mirrors today's
488
+ * `computeExtensionSpaceApplyPath` semantics.
489
+ */
490
+ declare function graphWalkStrategy(input: GraphWalkStrategyInputs): GraphWalkOutcome;
491
+ //#endregion
492
+ //#region src/aggregate/verifier.d.ts
493
+ /**
494
+ * Caller policy for the aggregate verifier. Today's only knob is
495
+ * `mode`: `strict` treats orphan elements (live tables not claimed by
496
+ * any aggregate member) as errors; `lenient` treats them as
497
+ * informational. Maps directly to `db verify --strict`.
498
+ */
499
+ interface AggregateVerifierInput<TSchemaResult> {
500
+ readonly aggregate: ContractSpaceAggregate;
501
+ readonly markersBySpaceId: ReadonlyMap<string, ContractMarkerRecordLike | null>;
502
+ readonly schemaIntrospection: unknown;
503
+ readonly mode: 'strict' | 'lenient';
504
+ /**
505
+ * Caller-supplied per-space schema verifier. The CLI wires this to
506
+ * the family's `verifySqlSchema` (SQL) / equivalent (other
507
+ * families). The aggregate verifier projects the schema to the
508
+ * member's slice via {@link projectSchemaToSpace} before invoking
509
+ * the callback, so single-contract semantics are preserved.
510
+ *
511
+ * Typed structurally with a generic `TSchemaResult` so the
512
+ * migration-tools layer doesn't depend on the SQL family's
513
+ * `VerifySqlSchemaResult`. CLI callers pass the family's type
514
+ * through unchanged.
515
+ */
516
+ readonly verifySchemaForMember: (projectedSchema: unknown, member: ContractSpaceMember, mode: 'strict' | 'lenient') => TSchemaResult;
517
+ }
518
+ /**
519
+ * Marker-check result per member. Mirrors the four cases the
520
+ * `verifyContractSpaces` primitive surfaces today, plus an `'absent'`
521
+ * case for greenfield spaces (no marker row written yet — `db init`
522
+ * not run).
523
+ */
524
+ type MarkerCheckResult = {
525
+ readonly kind: 'ok';
526
+ } | {
527
+ readonly kind: 'absent';
528
+ } | {
529
+ readonly kind: 'hashMismatch';
530
+ readonly markerHash: string;
531
+ readonly expected: string;
532
+ } | {
533
+ readonly kind: 'missingInvariants';
534
+ readonly missing: readonly string[];
535
+ };
536
+ interface MarkerCheckSection {
537
+ readonly perSpace: ReadonlyMap<string, MarkerCheckResult>;
538
+ readonly orphanMarkers: readonly {
539
+ readonly spaceId: string;
540
+ readonly row: ContractMarkerRecordLike;
541
+ }[];
542
+ }
543
+ /**
544
+ * A live storage element (today: a top-level table) not claimed by any
545
+ * member of the aggregate. The aggregate verifier always reports these;
546
+ * the caller decides what to do — `db verify --strict` treats them as
547
+ * errors, the lenient default treats them as informational.
548
+ *
549
+ * Today only `kind: 'table'` exists. The discriminated shape leaves
550
+ * room for orphan columns / indexes / sequences in the future without
551
+ * breaking the type contract.
552
+ */
553
+ type OrphanElement = {
554
+ readonly kind: 'table';
555
+ readonly name: string;
556
+ };
557
+ interface SchemaCheckSection<TSchemaResult> {
558
+ readonly perSpace: ReadonlyMap<string, TSchemaResult>;
559
+ /**
560
+ * Live elements present in the introspected schema that are not
561
+ * claimed by **any** aggregate member. Sorted alphabetically by name.
562
+ */
563
+ readonly orphanElements: readonly OrphanElement[];
564
+ }
565
+ interface AggregateVerifierSuccess<TSchemaResult> {
566
+ readonly markerCheck: MarkerCheckSection;
567
+ readonly schemaCheck: SchemaCheckSection<TSchemaResult>;
568
+ }
569
+ type AggregateVerifierError = {
570
+ readonly kind: 'introspectionFailure';
571
+ readonly detail: string;
572
+ };
573
+ type AggregateVerifierOutput<TSchemaResult> = Result<AggregateVerifierSuccess<TSchemaResult>, AggregateVerifierError>;
574
+ /**
575
+ * Verify a {@link ContractSpaceAggregate} against the live database
576
+ * state. Bundles two checks:
577
+ *
578
+ * - `markerCheck` per member: compare the live marker row against the
579
+ * member's `headRef.hash` + `headRef.invariants`. Absence is a
580
+ * distinct kind, not an error (callers — `db verify` strict vs
581
+ * `db init` precondition — choose how to interpret it).
582
+ * - `schemaCheck` per member: project the live schema to the slice
583
+ * the member claims via {@link projectSchemaToSpace}, then delegate
584
+ * to the caller-supplied `verifySchemaForMember`. The pre-projection
585
+ * means the family's single-contract verifier no longer sees other
586
+ * members' tables as `extras`, so a multi-member deployment never
587
+ * surfaces cross-member tables as orphaned schema elements.
588
+ *
589
+ * `markerCheck.orphanMarkers` lists every marker row whose `space` is
590
+ * not a member of the aggregate. `db verify` callers reject orphans;
591
+ * future tooling may not.
592
+ *
593
+ * Pure synchronous function; no I/O. The caller (CLI) gathers
594
+ * `markersBySpaceId` and `schemaIntrospection` ahead of the call.
595
+ */
596
+ declare function verifyAggregate<TSchemaResult>(input: AggregateVerifierInput<TSchemaResult>): AggregateVerifierOutput<TSchemaResult>;
597
+ //#endregion
598
+ export { type AggregateCurrentDBState, type AggregateMigrationEdgeRef, type AggregatePerSpacePlan, type AggregatePlannerError, type AggregatePlannerInput, type AggregatePlannerOutput, type AggregatePlannerSuccess, type AggregateVerifierError, type AggregateVerifierInput, type AggregateVerifierOutput, type AggregateVerifierSuccess, type CallerPolicy, type ContractMarkerRecordLike, type ContractSpaceAggregate, type ContractSpaceMember, type DeclaredExtensionEntry, type GraphWalkOutcome, type GraphWalkStrategyInputs, type HydratedMigrationGraph, type LayoutViolation, type LoadAggregateError, type LoadAggregateInput, type LoadAggregateOutput, type MarkerCheckResult, type MarkerCheckSection, type OrphanElement, type SchemaCheckSection, graphWalkStrategy, loadContractSpaceAggregate, planAggregate, projectSchemaToSpace, verifyAggregate };
599
+ //# sourceMappingURL=aggregate.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregate.d.mts","names":[],"sources":["../../src/aggregate/types.ts","../../src/aggregate/loader.ts","../../src/aggregate/marker-types.ts","../../src/aggregate/planner-types.ts","../../src/aggregate/planner.ts","../../src/aggregate/project-schema-to-space.ts","../../src/aggregate/strategies/graph-walk.ts","../../src/aggregate/verifier.ts"],"mappings":";;;;;;;;;;;;;;;AAkBA;;;;;;;;UAAiB,sBAAA;EAAA,SACN,KAAA,EAAO,cAAA;EAAA,SACP,uBAAA,EAAyB,WAAA,SAAoB,sBAAA;AAAA;;;;AAwBxD;;;;;;;;;;;;;;AAwCA;;;;UAxCiB,mBAAA;EAAA,SACN,OAAA;EAAA,SACA,QAAA,EAAU,QAAA;EAAA,SACV,OAAA;IAAA,SACE,IAAA;IAAA,SACA,UAAA;EAAA;EAAA,SAEF,UAAA,EAAY,sBAAA;AAAA;;ACnBvB;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;UDsCiB,sBAAA;EAAA,SACN,QAAA;EAAA,SACA,GAAA,EAAK,mBAAA;EAAA,SACL,UAAA,WAAqB,mBAAA;AAAA;;;;;;;;AArEhC;;;;;;;;;;;;;;;UCciB,sBAAA;EAAA,SACN,EAAA;EAAA,SACA,QAAA;AAAA;;;;;;;;;;UAYM,kBAAA;EAAA,SACN,QAAA;EAAA,SACA,aAAA;EAAA,SACA,WAAA,EAAa,QAAA;EAAA,SACb,kBAAA,EAAoB,aAAA,CAAc,sBAAA;EAAA,SAClC,gBAAA,GAAmB,YAAA,cAA0B,QAAA;EDmC7C;;;;;;;;;ACtDX;;;EDsDW,SCtBA,oBAAA,EAAsB,aAAA,CAAc,sBAAA;AAAA;AAlB/C;;;;;;;AAAA,KA4BY,kBAAA;EAAA,SACG,IAAA;EAAA,SAAkC,UAAA,WAAqB,eAAA;AAAA;EAAA,SACvD,IAAA;EAAA,SAAmC,OAAA;EAAA,SAA0B,MAAA;AAAA;EAAA,SAC7D,IAAA;EAAA,SAAoC,OAAA;EAAA,SAA0B,MAAA;A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