@prisma-next/migration-tools 0.11.0-dev.46 → 0.11.0-dev.48

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 (81) hide show
  1. package/dist/{errors-CoEN114u.mjs → errors-4YabujxZ.mjs} +3 -21
  2. package/dist/{errors-CoEN114u.mjs.map → errors-4YabujxZ.mjs.map} +1 -1
  3. package/dist/exports/aggregate.d.mts +273 -177
  4. package/dist/exports/aggregate.d.mts.map +1 -1
  5. package/dist/exports/aggregate.mjs +363 -185
  6. package/dist/exports/aggregate.mjs.map +1 -1
  7. package/dist/exports/enumerate-migration-spaces.d.mts +1 -1
  8. package/dist/exports/enumerate-migration-spaces.mjs +4 -4
  9. package/dist/exports/enumerate-migration-spaces.mjs.map +1 -1
  10. package/dist/exports/errors.mjs +1 -1
  11. package/dist/exports/graph.d.mts +1 -1
  12. package/dist/exports/hash.d.mts +1 -1
  13. package/dist/exports/invariants.mjs +1 -1
  14. package/dist/exports/io.d.mts +2 -83
  15. package/dist/exports/io.mjs +1 -1
  16. package/dist/exports/metadata.d.mts +1 -1
  17. package/dist/exports/migration-graph.d.mts +2 -2
  18. package/dist/exports/migration-graph.mjs +2 -2
  19. package/dist/exports/migration-list-graph-layout.d.mts +2 -2
  20. package/dist/exports/migration-list-graph-topology.d.mts +1 -1
  21. package/dist/exports/migration-list-types.d.mts +1 -1
  22. package/dist/exports/migration.d.mts +1 -1
  23. package/dist/exports/migration.mjs +2 -2
  24. package/dist/exports/ref-resolution.d.mts +2 -2
  25. package/dist/exports/ref-resolution.mjs +1 -1
  26. package/dist/exports/refs.d.mts +1 -1
  27. package/dist/exports/refs.mjs +2 -2
  28. package/dist/exports/spaces.d.mts +1 -130
  29. package/dist/exports/spaces.d.mts.map +1 -1
  30. package/dist/exports/spaces.mjs +6 -6
  31. package/dist/exports/spaces.mjs.map +1 -1
  32. package/dist/{graph-B0LIIjIu.d.mts → graph-3dLMZp5l.d.mts} +1 -1
  33. package/dist/{graph-B0LIIjIu.d.mts.map → graph-3dLMZp5l.d.mts.map} +1 -1
  34. package/dist/{invariants-lbJddL-S.mjs → invariants-CCOAyg6c.mjs} +2 -2
  35. package/dist/{invariants-lbJddL-S.mjs.map → invariants-CCOAyg6c.mjs.map} +1 -1
  36. package/dist/io-BH4G3F-i.d.mts +124 -0
  37. package/dist/io-BH4G3F-i.d.mts.map +1 -0
  38. package/dist/{io-Dc64lvaL.mjs → io-BHl0amF0.mjs} +99 -6
  39. package/dist/io-BHl0amF0.mjs.map +1 -0
  40. package/dist/{migration-graph-fl5ChjXE.d.mts → migration-graph-CWEM2SLR.d.mts} +2 -2
  41. package/dist/{migration-graph-fl5ChjXE.d.mts.map → migration-graph-CWEM2SLR.d.mts.map} +1 -1
  42. package/dist/{migration-graph-D5JeadSE.mjs → migration-graph-kGBkIZDa.mjs} +3 -7
  43. package/dist/migration-graph-kGBkIZDa.mjs.map +1 -0
  44. package/dist/{migration-list-graph-topology-CafEnhPT.d.mts → migration-list-graph-topology-Be1d8Y89.d.mts} +2 -2
  45. package/dist/{migration-list-graph-topology-CafEnhPT.d.mts.map → migration-list-graph-topology-Be1d8Y89.d.mts.map} +1 -1
  46. package/dist/{migration-list-types-wLyb3E-p.d.mts → migration-list-types-0YjFETIv.d.mts} +1 -1
  47. package/dist/{migration-list-types-wLyb3E-p.d.mts.map → migration-list-types-0YjFETIv.d.mts.map} +1 -1
  48. package/dist/{read-contract-space-contract-C4fEdoXO.mjs → read-contract-space-contract-7-OB-ykY.mjs} +3 -3
  49. package/dist/{read-contract-space-contract-C4fEdoXO.mjs.map → read-contract-space-contract-7-OB-ykY.mjs.map} +1 -1
  50. package/dist/{refs-D8xBNqs7.d.mts → refs-B33AsTjk.d.mts} +12 -2
  51. package/dist/refs-B33AsTjk.d.mts.map +1 -0
  52. package/dist/{refs-HhOkD8BT.mjs → refs-BBKNL45K.mjs} +75 -3
  53. package/dist/refs-BBKNL45K.mjs.map +1 -0
  54. package/dist/{verify-contract-spaces-DIdQLGo7.mjs → verify-contract-spaces-BJX5gqtD.mjs} +3 -3
  55. package/dist/{verify-contract-spaces-DIdQLGo7.mjs.map → verify-contract-spaces-BJX5gqtD.mjs.map} +1 -1
  56. package/dist/verify-contract-spaces-BdysZdQk.d.mts +132 -0
  57. package/dist/verify-contract-spaces-BdysZdQk.d.mts.map +1 -0
  58. package/package.json +6 -6
  59. package/src/aggregate/aggregate.ts +90 -0
  60. package/src/aggregate/check-integrity.ts +243 -0
  61. package/src/aggregate/loader.ts +156 -334
  62. package/src/aggregate/planner.ts +8 -6
  63. package/src/aggregate/project-schema-to-space.ts +1 -1
  64. package/src/aggregate/strategies/graph-walk.ts +12 -7
  65. package/src/aggregate/strategies/synth.ts +2 -2
  66. package/src/aggregate/types.ts +56 -64
  67. package/src/aggregate/verifier.ts +6 -4
  68. package/src/compute-extension-space-apply-path.ts +1 -1
  69. package/src/enumerate-migration-spaces.ts +1 -1
  70. package/src/exports/aggregate.ts +17 -12
  71. package/src/exports/io.ts +2 -0
  72. package/src/integrity-violation.ts +114 -0
  73. package/src/io.ts +139 -6
  74. package/src/migration-graph.ts +3 -17
  75. package/src/refs.ts +94 -0
  76. package/dist/exports/io.d.mts.map +0 -1
  77. package/dist/io-Dc64lvaL.mjs.map +0 -1
  78. package/dist/migration-graph-D5JeadSE.mjs.map +0 -1
  79. package/dist/refs-D8xBNqs7.d.mts.map +0 -1
  80. package/dist/refs-HhOkD8BT.mjs.map +0 -1
  81. /package/dist/{metadata-COhIQCiH.d.mts → metadata-CGkJF4L6.d.mts} +0 -0
@@ -1,10 +1,77 @@
1
- import { t as MigrationToolsError } from "../errors-CoEN114u.mjs";
2
- import { s as readMigrationsDir } from "../io-Dc64lvaL.mjs";
3
- import "../constants-DWV9_o2Z.mjs";
4
- import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-D5JeadSE.mjs";
5
- import { c as spaceMigrationDirectory, r as APP_SPACE_ID, t as listContractSpaceDirectories } from "../verify-contract-spaces-DIdQLGo7.mjs";
6
- import { n as readContractSpaceHeadRef, t as readContractSpaceContract } from "../read-contract-space-contract-C4fEdoXO.mjs";
1
+ import { t as MigrationToolsError } from "../errors-4YabujxZ.mjs";
2
+ import { s as readMigrationsDir } from "../io-BHl0amF0.mjs";
3
+ import { t as EMPTY_CONTRACT_HASH } from "../constants-DWV9_o2Z.mjs";
4
+ import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-kGBkIZDa.mjs";
5
+ import { a as readRefsTolerant, t as HEAD_REF_NAME } from "../refs-BBKNL45K.mjs";
6
+ import { c as spaceMigrationDirectory, i as RESERVED_SPACE_SUBDIR_NAMES, l as spaceRefsDirectory, r as APP_SPACE_ID, s as isValidSpaceId, t as listContractSpaceDirectories } from "../verify-contract-spaces-BJX5gqtD.mjs";
7
+ import { n as readContractSpaceHeadRef, t as readContractSpaceContract } from "../read-contract-space-contract-7-OB-ykY.mjs";
7
8
  import { notOk, ok } from "@prisma-next/utils/result";
9
+ //#region src/aggregate/aggregate.ts
10
+ /**
11
+ * Resolve a member's head ref, asserting it is present. The apply/verify
12
+ * engine only runs after `checkIntegrity` has refused on `headRefMissing`,
13
+ * so a member reaching the planner / verifier without a head ref is a
14
+ * programming error (the integrity gate was skipped), not a user-facing
15
+ * state. The app member's head ref is always synthesised, so this only
16
+ * ever guards an ungated extension space.
17
+ */
18
+ function requireHeadRef(member) {
19
+ if (member.headRef === null) throw new Error(`Contract space "${member.spaceId}" has no head ref; the integrity gate must refuse a missing head ref before planning or verifying.`);
20
+ return member.headRef;
21
+ }
22
+ /**
23
+ * Build a {@link ContractSpaceMember} with lazily-memoised `graph()` and
24
+ * `contract()` facets.
25
+ *
26
+ * `graph()` reconstructs the migration graph from `packages` on first
27
+ * call and caches it. `contract()` calls `resolveContract` on first call
28
+ * and caches the result; a throwing `resolveContract` (e.g. a missing or
29
+ * undeserializable on-disk contract) re-throws on each call rather than
30
+ * caching a value — `checkIntegrity` surfaces that as `contractUnreadable`.
31
+ */
32
+ function createContractSpaceMember(args) {
33
+ const { spaceId, packages, refs, headRef, resolveContract } = args;
34
+ let graphMemo;
35
+ let contractMemo;
36
+ return {
37
+ spaceId,
38
+ packages,
39
+ refs,
40
+ headRef,
41
+ graph() {
42
+ graphMemo ??= reconstructGraph(packages);
43
+ return graphMemo;
44
+ },
45
+ contract() {
46
+ contractMemo ??= resolveContract();
47
+ return contractMemo;
48
+ }
49
+ };
50
+ }
51
+ /**
52
+ * Assemble a {@link ContractSpaceAggregate} value from its members and a
53
+ * `checkIntegrity` implementation. The query methods (`listSpaces` /
54
+ * `hasSpace` / `space` / `spaces`) are derived here so every aggregate —
55
+ * loader-built or test-built — shares one query surface: `app` first,
56
+ * then `extensions` in the order supplied (the loader sorts them
57
+ * lex-ascending by `spaceId`).
58
+ */
59
+ function createContractSpaceAggregate(args) {
60
+ const { targetId, app, extensions, checkIntegrity } = args;
61
+ const ordered = [app, ...extensions];
62
+ const byId = new Map(ordered.map((m) => [m.spaceId, m]));
63
+ return {
64
+ targetId,
65
+ app,
66
+ extensions,
67
+ listSpaces: () => ordered.map((m) => m.spaceId),
68
+ hasSpace: (id) => byId.has(id),
69
+ space: (id) => byId.get(id),
70
+ spaces: () => ordered,
71
+ checkIntegrity
72
+ };
73
+ }
74
+ //#endregion
8
75
  //#region src/aggregate/extract-storage-element-names.ts
9
76
  /**
10
77
  * Extract the set of top-level storage element names a contract claims.
@@ -61,189 +128,296 @@ function addRecordKeys(value, names) {
61
128
  if (typeof value === "object" && value !== null && !Array.isArray(value)) for (const name of Object.keys(value)) names.add(name);
62
129
  }
63
130
  //#endregion
64
- //#region src/aggregate/loader.ts
65
- function integrityDetail(error) {
66
- if (MigrationToolsError.is(error)) return error.why;
67
- if (error instanceof Error) return error.message;
68
- return String(error);
69
- }
131
+ //#region src/aggregate/check-integrity.ts
70
132
  /**
71
- * Hydrate a {@link ContractSpaceAggregate} from on-disk state and
72
- * the app contract value the caller supplies.
73
- *
74
- * The loader is the **only** descriptor-import boundary at apply /
75
- * verify time, but it intentionally does **not** read the extension
76
- * descriptor's `contractJson` value. Each extension space's contract
77
- * is read from its on-disk `migrations/<id>/contract.json` mirror; the
78
- * descriptor's role is exhausted by the seed phase that wrote that
79
- * mirror in the first place. The loader composes existing
80
- * migration-tools primitives — layout precheck (via
81
- * {@link listContractSpaceDirectories}), integrity checks (via
82
- * {@link readMigrationsDir} / {@link readContractSpaceHeadRef} /
83
- * {@link readContractSpaceContract} / `deserializeContract`), and
84
- * disjointness — into a single typed value.
85
- *
86
- * Failure semantics: every failure variant in {@link LoadAggregateError}
87
- * short-circuits the load.
133
+ * Walk the loaded model and return **every** integrity violation — never
134
+ * bailing at the first. Structurally-derivable violations (load-time
135
+ * problems, self-edges, missing / unreachable head refs) are always
136
+ * produced; layout-drift checks require `declaredExtensions`, and
137
+ * contract / target / disjointness checks require `checkContracts`.
88
138
  */
89
- async function loadContractSpaceAggregate(input) {
90
- const appContractTarget = input.appContract.target;
91
- if (appContractTarget !== input.targetId) return notOk({
92
- kind: "targetMismatch",
93
- spaceId: APP_SPACE_ID,
94
- expected: input.targetId,
95
- actual: appContractTarget
96
- });
97
- for (const entry of input.declaredExtensions) if (entry.targetId !== input.targetId) return notOk({
98
- kind: "targetMismatch",
99
- spaceId: entry.id,
100
- expected: input.targetId,
101
- actual: entry.targetId
139
+ function computeIntegrityViolations(input, opts) {
140
+ const violations = [];
141
+ for (const { member, problems, refProblems, headRefProblem, isApp } of input.spaces) {
142
+ const { spaceId } = member;
143
+ for (const problem of problems) violations.push(loadProblemToViolation(spaceId, problem));
144
+ for (const refProblem of refProblems) violations.push({
145
+ kind: "refUnreadable",
146
+ spaceId,
147
+ refName: refProblem.refName,
148
+ detail: refProblem.detail
149
+ });
150
+ if (headRefProblem !== null) violations.push({
151
+ kind: "refUnreadable",
152
+ spaceId,
153
+ refName: headRefProblem.refName,
154
+ detail: headRefProblem.detail
155
+ });
156
+ for (const pkg of member.packages) {
157
+ const from = pkg.metadata.from ?? "sha256:empty";
158
+ const isSelfEdge = from === pkg.metadata.to;
159
+ const hasDataOp = pkg.ops.some((op) => op.operationClass === "data");
160
+ if (isSelfEdge && !hasDataOp) violations.push({
161
+ kind: "sameSourceAndTarget",
162
+ spaceId,
163
+ dirName: pkg.dirName,
164
+ hash: from
165
+ });
166
+ }
167
+ violations.push(...duplicateMigrationHashViolations(spaceId, member.packages));
168
+ if (!isApp && headRefProblem === null) {
169
+ if (member.headRef === null) violations.push({
170
+ kind: "headRefMissing",
171
+ spaceId
172
+ });
173
+ else if (!headRefPresentInGraph(member, member.headRef.hash)) violations.push({
174
+ kind: "headRefNotInGraph",
175
+ spaceId,
176
+ hash: member.headRef.hash
177
+ });
178
+ }
179
+ }
180
+ if (opts?.declaredExtensions !== void 0) violations.push(...layoutViolations(input.spaces, opts.declaredExtensions));
181
+ if (opts?.checkContracts === true) violations.push(...contractViolations(input));
182
+ return violations;
183
+ }
184
+ function loadProblemToViolation(spaceId, problem) {
185
+ switch (problem.kind) {
186
+ case "hashMismatch": return {
187
+ kind: "hashMismatch",
188
+ spaceId,
189
+ dirName: problem.dirName,
190
+ stored: problem.stored,
191
+ computed: problem.computed
192
+ };
193
+ case "providedInvariantsMismatch": return {
194
+ kind: "providedInvariantsMismatch",
195
+ spaceId,
196
+ dirName: problem.dirName
197
+ };
198
+ case "packageUnloadable": return {
199
+ kind: "packageUnloadable",
200
+ spaceId,
201
+ dirName: problem.dirName,
202
+ detail: problem.detail
203
+ };
204
+ }
205
+ }
206
+ function duplicateMigrationHashViolations(spaceId, packages) {
207
+ const dirNamesByHash = /* @__PURE__ */ new Map();
208
+ for (const pkg of packages) {
209
+ const hash = pkg.metadata.migrationHash;
210
+ const dirNames = dirNamesByHash.get(hash);
211
+ if (dirNames) dirNames.push(pkg.dirName);
212
+ else dirNamesByHash.set(hash, [pkg.dirName]);
213
+ }
214
+ const out = [];
215
+ for (const [migrationHash, dirNames] of dirNamesByHash) if (dirNames.length > 1) out.push({
216
+ kind: "duplicateMigrationHash",
217
+ spaceId,
218
+ migrationHash,
219
+ dirNames: [...dirNames].sort()
102
220
  });
103
- const declaredSpaceIds = new Set(input.declaredExtensions.map((e) => e.id));
104
- const extensionDirsOnDisk = (await listContractSpaceDirectories(input.migrationsDir)).filter((d) => d !== APP_SPACE_ID);
105
- const spaceDirSet = new Set(extensionDirsOnDisk);
106
- const layoutViolations = [];
107
- for (const dir of extensionDirsOnDisk) if (!declaredSpaceIds.has(dir)) layoutViolations.push({
221
+ return out;
222
+ }
223
+ /**
224
+ * Whether a space's head-ref hash is present in its reconstructed graph.
225
+ * An empty graph is reachable only by the empty-contract sentinel.
226
+ */
227
+ function headRefPresentInGraph(member, headHash) {
228
+ const graph = member.graph();
229
+ if (graph.nodes.size === 0) return headHash === EMPTY_CONTRACT_HASH;
230
+ return graph.nodes.has(headHash);
231
+ }
232
+ function layoutViolations(spaces, declaredExtensions) {
233
+ const out = [];
234
+ const extensionSpaceIds = new Set(spaces.filter((s) => !s.isApp).map((s) => s.member.spaceId));
235
+ const declaredIds = new Set(declaredExtensions.map((d) => d.id));
236
+ for (const id of [...extensionSpaceIds].sort()) if (!declaredIds.has(id)) out.push({
108
237
  kind: "orphanSpaceDir",
109
- spaceId: dir
238
+ spaceId: id
110
239
  });
111
- for (const id of [...declaredSpaceIds].sort()) if (!spaceDirSet.has(id)) layoutViolations.push({
240
+ for (const id of [...declaredIds].sort()) if (!extensionSpaceIds.has(id)) out.push({
112
241
  kind: "declaredButUnmigrated",
113
242
  spaceId: id
114
243
  });
115
- if (layoutViolations.length > 0) return notOk({
116
- kind: "layoutViolation",
117
- violations: layoutViolations
118
- });
119
- const loadedExtensions = [];
120
- for (const entry of [...input.declaredExtensions].sort((a, b) => a.id.localeCompare(b.id))) {
121
- const headRef = await readContractSpaceHeadRef(input.migrationsDir, entry.id);
122
- if (headRef === null) return notOk({
123
- kind: "integrityFailure",
124
- spaceId: entry.id,
125
- detail: `Head ref \`refs/head.json\` is missing for extension space "${entry.id}".`
126
- });
127
- let spaceContractRaw;
128
- try {
129
- spaceContractRaw = await readContractSpaceContract(input.migrationsDir, entry.id);
130
- } catch (error) {
131
- return notOk({
132
- kind: "integrityFailure",
133
- spaceId: entry.id,
134
- detail: integrityDetail(error)
135
- });
136
- }
137
- let spaceContract;
244
+ return out;
245
+ }
246
+ function contractViolations(input) {
247
+ const out = [];
248
+ const elementClaimedBy = /* @__PURE__ */ new Map();
249
+ for (const { member } of input.spaces) {
250
+ let contract;
138
251
  try {
139
- spaceContract = input.deserializeContract(spaceContractRaw);
252
+ contract = member.contract();
140
253
  } catch (error) {
141
- return notOk({
142
- kind: "validationFailure",
143
- spaceId: entry.id,
144
- detail: integrityDetail(error)
254
+ out.push({
255
+ kind: "contractUnreadable",
256
+ spaceId: member.spaceId,
257
+ detail: detailOf$1(error)
145
258
  });
259
+ continue;
146
260
  }
147
- if (spaceContract.target !== input.targetId) return notOk({
261
+ if (contract.target !== input.targetId) out.push({
148
262
  kind: "targetMismatch",
149
- spaceId: entry.id,
263
+ spaceId: member.spaceId,
150
264
  expected: input.targetId,
151
- actual: spaceContract.target
152
- });
153
- let packages;
154
- try {
155
- packages = await readMigrationsDir(spaceMigrationDirectory(input.migrationsDir, entry.id));
156
- } catch (error) {
157
- return notOk({
158
- kind: "integrityFailure",
159
- spaceId: entry.id,
160
- detail: integrityDetail(error)
161
- });
162
- }
163
- let graph;
164
- try {
165
- graph = reconstructGraph(packages);
166
- } catch (error) {
167
- return notOk({
168
- kind: "integrityFailure",
169
- spaceId: entry.id,
170
- detail: integrityDetail(error)
171
- });
172
- }
173
- if (graph.nodes.size === 0) {
174
- if (headRef.hash !== "sha256:empty") return notOk({
175
- kind: "integrityFailure",
176
- spaceId: entry.id,
177
- detail: `Head ref "${headRef.hash}" is not present in the (empty) on-disk migration graph.`
178
- });
179
- } else if (!graph.nodes.has(headRef.hash)) return notOk({
180
- kind: "integrityFailure",
181
- spaceId: entry.id,
182
- detail: `Head ref "${headRef.hash}" is not present in the on-disk migration graph.`
183
- });
184
- const packagesByMigrationHash = new Map(packages.map((p) => [p.metadata.migrationHash, p]));
185
- loadedExtensions.push({
186
- entry,
187
- contract: spaceContract,
188
- headRefHash: headRef.hash,
189
- headRefInvariants: [...headRef.invariants].sort(),
190
- migrations: {
191
- graph,
192
- packagesByMigrationHash
193
- }
265
+ actual: contract.target
194
266
  });
195
- }
196
- let appGraph;
197
- try {
198
- appGraph = reconstructGraph(input.appMigrationPackages);
199
- } catch (error) {
200
- return notOk({
201
- kind: "integrityFailure",
202
- spaceId: APP_SPACE_ID,
203
- detail: error instanceof Error ? error.message : String(error)
204
- });
205
- }
206
- const appPackagesByMigrationHash = new Map(input.appMigrationPackages.map((p) => [p.metadata.migrationHash, p]));
207
- const appMember = {
208
- spaceId: APP_SPACE_ID,
209
- contract: input.appContract,
210
- headRef: {
211
- hash: input.appContract.storage.storageHash,
212
- invariants: []
213
- },
214
- migrations: {
215
- graph: appGraph,
216
- packagesByMigrationHash: appPackagesByMigrationHash
217
- }
218
- };
219
- const extensionMembers = loadedExtensions.map((s) => ({
220
- spaceId: s.entry.id,
221
- contract: s.contract,
222
- headRef: {
223
- hash: s.headRefHash,
224
- invariants: s.headRefInvariants
225
- },
226
- migrations: s.migrations
227
- }));
228
- const elementClaimedBy = /* @__PURE__ */ new Map();
229
- for (const member of [appMember, ...extensionMembers]) {
230
- const elements = extractStorageElementNames(member.contract);
231
- for (const elementName of elements) {
267
+ for (const elementName of extractStorageElementNames(contract)) {
232
268
  const claimers = elementClaimedBy.get(elementName);
233
269
  if (claimers) claimers.push(member.spaceId);
234
270
  else elementClaimedBy.set(elementName, [member.spaceId]);
235
271
  }
236
272
  }
237
- for (const [element, claimedBy] of elementClaimedBy) if (claimedBy.length > 1) return notOk({
238
- kind: "disjointnessViolation",
273
+ const disjointness = [];
274
+ for (const [element, claimedBy] of elementClaimedBy) if (claimedBy.length > 1) disjointness.push({
275
+ kind: "disjointness",
239
276
  element,
240
277
  claimedBy: [...claimedBy].sort()
241
278
  });
242
- return ok({ aggregate: {
243
- targetId: input.targetId,
244
- app: appMember,
245
- extensions: extensionMembers
246
- } });
279
+ disjointness.sort((a, b) => a.kind === "disjointness" && b.kind === "disjointness" ? a.element.localeCompare(b.element) : 0);
280
+ out.push(...disjointness);
281
+ return out;
282
+ }
283
+ function detailOf$1(error) {
284
+ if (MigrationToolsError.is(error)) return error.why;
285
+ if (error instanceof Error) return error.message;
286
+ return String(error);
287
+ }
288
+ //#endregion
289
+ //#region src/aggregate/loader.ts
290
+ /**
291
+ * Build a tolerant, queryable {@link ContractSpaceAggregate} from on-disk
292
+ * migration state plus the caller's live app contract.
293
+ *
294
+ * Building **never throws on disk content**: a hash- or
295
+ * invariants-mismatched package is retained, an unparseable package is
296
+ * omitted, a missing extension head ref leaves `headRef: null`, and an
297
+ * unreadable on-disk contract defers its failure to `member.contract()`.
298
+ * Every such problem is judged by {@link ContractSpaceAggregate.checkIntegrity}
299
+ * rather than aborting the load. The only rejections are catastrophic I/O
300
+ * (a `migrations/` that exists but is unreadable for reasons other than
301
+ * absence).
302
+ *
303
+ * The app space's head ref is synthesised from the live contract's
304
+ * storage hash (the app contract is authored independently of the
305
+ * migration graph), and `app.contract()` returns the supplied contract.
306
+ * Extension spaces read their contract, refs, and head ref from disk.
307
+ */
308
+ async function loadContractSpaceAggregate(input) {
309
+ const { migrationsDir, deserializeContract, appContract } = input;
310
+ const targetId = appContract.target;
311
+ const appState = await loadAppSpace(migrationsDir, appContract);
312
+ const extensionStates = await loadExtensionSpaces(migrationsDir, deserializeContract);
313
+ const spaces = [appState, ...extensionStates];
314
+ return createContractSpaceAggregate({
315
+ targetId,
316
+ app: appState.member,
317
+ extensions: extensionStates.map((state) => state.member),
318
+ checkIntegrity: (opts) => computeIntegrityViolations({
319
+ targetId,
320
+ spaces
321
+ }, opts)
322
+ });
323
+ }
324
+ async function loadAppSpace(migrationsDir, appContract) {
325
+ const spaceDir = spaceMigrationDirectory(migrationsDir, APP_SPACE_ID);
326
+ const { packages, problems } = await readMigrationsDir(spaceDir);
327
+ const { refs, problems: refProblems } = await readRefsTolerant(spaceRefsDirectory(spaceDir));
328
+ return {
329
+ member: createContractSpaceMember({
330
+ spaceId: APP_SPACE_ID,
331
+ packages,
332
+ refs,
333
+ headRef: {
334
+ hash: appContract.storage.storageHash,
335
+ invariants: []
336
+ },
337
+ resolveContract: () => appContract
338
+ }),
339
+ problems,
340
+ refProblems,
341
+ headRefProblem: null,
342
+ isApp: true
343
+ };
344
+ }
345
+ async function loadExtensionSpaces(migrationsDir, deserializeContract) {
346
+ const extensionIds = (await listContractSpaceDirectories(migrationsDir)).filter((name) => name !== APP_SPACE_ID).filter((name) => !RESERVED_SPACE_SUBDIR_NAMES.has(name)).filter(isValidSpaceId).sort();
347
+ const states = [];
348
+ for (const spaceId of extensionIds) states.push(await loadExtensionSpace(migrationsDir, spaceId, deserializeContract));
349
+ return states;
350
+ }
351
+ async function loadExtensionSpace(migrationsDir, spaceId, deserializeContract) {
352
+ const spaceDir = spaceMigrationDirectory(migrationsDir, spaceId);
353
+ const { packages, problems } = await readMigrationsDir(spaceDir);
354
+ const { refs, problems: refProblems } = await readRefsTolerant(spaceRefsDirectory(spaceDir));
355
+ const { headRef, problem: headRefProblem } = await readHeadRefTolerant(migrationsDir, spaceId);
356
+ const rawContract = await readRawContractDeferred(migrationsDir, spaceId);
357
+ return {
358
+ member: createContractSpaceMember({
359
+ spaceId,
360
+ packages,
361
+ refs,
362
+ headRef,
363
+ resolveContract: () => deserializeContract(rawContract())
364
+ }),
365
+ problems,
366
+ refProblems,
367
+ headRefProblem,
368
+ isApp: false
369
+ };
370
+ }
371
+ /**
372
+ * Read an extension's head ref, distinguishing a *genuinely absent*
373
+ * `head.json` (`headRef: null`, no problem — judged `headRefMissing`)
374
+ * from one that *exists but cannot be parsed* (`headRef: null` plus a
375
+ * problem — judged `refUnreadable`, not `headRefMissing`).
376
+ * `readContractSpaceHeadRef` already returns `null` only for ENOENT and
377
+ * throws for unparseable / schema-invalid content, so the throw is the
378
+ * corruption signal. Construction never throws on disk content.
379
+ */
380
+ function isToleratedRefHeadReadError(error) {
381
+ if (MigrationToolsError.is(error)) return true;
382
+ if (!(error instanceof Error)) return false;
383
+ const code = error.code;
384
+ return code === "ENOENT" || code === "EISDIR";
385
+ }
386
+ async function readHeadRefTolerant(migrationsDir, spaceId) {
387
+ try {
388
+ return {
389
+ headRef: await readContractSpaceHeadRef(migrationsDir, spaceId),
390
+ problem: null
391
+ };
392
+ } catch (error) {
393
+ if (!isToleratedRefHeadReadError(error)) throw error;
394
+ return {
395
+ headRef: null,
396
+ problem: {
397
+ refName: HEAD_REF_NAME,
398
+ detail: detailOf(error)
399
+ }
400
+ };
401
+ }
402
+ }
403
+ function detailOf(error) {
404
+ return error instanceof Error ? error.message : String(error);
405
+ }
406
+ /**
407
+ * Read the raw on-disk contract eagerly (cheap I/O) but defer its
408
+ * (throwing) failure to call time, so a missing or unparseable
409
+ * `contract.json` becomes a `contract()` throw — surfaced as
410
+ * `contractUnreadable` — rather than a construction failure.
411
+ */
412
+ async function readRawContractDeferred(migrationsDir, spaceId) {
413
+ try {
414
+ const raw = await readContractSpaceContract(migrationsDir, spaceId);
415
+ return () => raw;
416
+ } catch (error) {
417
+ return () => {
418
+ throw error;
419
+ };
420
+ }
247
421
  }
248
422
  //#endregion
249
423
  //#region src/aggregate/strategies/graph-walk.ts
@@ -264,11 +438,13 @@ async function loadContractSpaceAggregate(input) {
264
438
  */
265
439
  function graphWalkStrategy(input) {
266
440
  const { aggregateTargetId, member, currentMarker, refName } = input;
267
- const { graph, packagesByMigrationHash } = member.migrations;
441
+ const headRef = requireHeadRef(member);
442
+ const graph = member.graph();
443
+ const packagesByMigrationHash = new Map(member.packages.map((pkg) => [pkg.metadata.migrationHash, pkg]));
268
444
  const fromHash = currentMarker?.storageHash ?? "sha256:empty";
269
445
  const markerInvariants = new Set(currentMarker?.invariants ?? []);
270
- const required = new Set(member.headRef.invariants.filter((id) => !markerInvariants.has(id)));
271
- const outcome = findPathWithDecision(graph, fromHash, member.headRef.hash, {
446
+ const required = new Set(headRef.invariants.filter((id) => !markerInvariants.has(id)));
447
+ const outcome = findPathWithDecision(graph, fromHash, headRef.hash, {
272
448
  required,
273
449
  ...refName !== void 0 ? { refName } : {}
274
450
  });
@@ -300,12 +476,12 @@ function graphWalkStrategy(input) {
300
476
  targetId: aggregateTargetId,
301
477
  spaceId: member.spaceId,
302
478
  origin: currentMarker === null ? null : { storageHash: currentMarker.storageHash },
303
- destination: { storageHash: member.headRef.hash },
479
+ destination: { storageHash: headRef.hash },
304
480
  operations: pathOps,
305
481
  providedInvariants: [...providedInvariantsSet].sort()
306
482
  },
307
483
  displayOps: pathOps,
308
- destinationContract: member.contract,
484
+ destinationContract: member.contract(),
309
485
  strategy: "graph-walk",
310
486
  migrationEdges: edgeRefs,
311
487
  pathDecision: outcome.decision
@@ -387,7 +563,7 @@ function collectOwnedNames(member, otherMembers) {
387
563
  const owned = /* @__PURE__ */ new Set();
388
564
  for (const other of otherMembers) {
389
565
  if (other.spaceId === member.spaceId) continue;
390
- for (const name of extractStorageElementNames(other.contract)) owned.add(name);
566
+ for (const name of extractStorageElementNames(other.contract())) owned.add(name);
391
567
  }
392
568
  return owned;
393
569
  }
@@ -451,7 +627,7 @@ function pruneCollectionsArray(schemaObj, ownedByOthers) {
451
627
  async function synthStrategy(input) {
452
628
  const projectedSchema = projectSchemaToSpace(input.schemaIntrospection, input.member, input.otherMembers);
453
629
  const plannerResult = await input.migrations.createPlanner(input.familyInstance).plan({
454
- contract: input.member.contract,
630
+ contract: input.member.contract(),
455
631
  schema: projectedSchema,
456
632
  policy: input.operationPolicy,
457
633
  fromContract: null,
@@ -477,7 +653,7 @@ async function synthStrategy(input) {
477
653
  }
478
654
  }),
479
655
  displayOps: synthedPlan.operations,
480
- destinationContract: input.member.contract,
656
+ destinationContract: input.member.contract(),
481
657
  strategy: "synth"
482
658
  }
483
659
  };
@@ -492,7 +668,7 @@ async function synthStrategy(input) {
492
668
  * 1. If `callerPolicy.ignoreGraphFor.has(member.spaceId)`:
493
669
  * - If `member.headRef.invariants` is empty → synth.
494
670
  * - Else → `policyConflict` (synth cannot satisfy authored invariants).
495
- * 2. Else if `member.migrations.graph` is non-empty AND graph-walk
671
+ * 2. Else if `member.graph()` is non-empty AND graph-walk
496
672
  * succeeds → graph-walk.
497
673
  * 3. Else if `member.headRef.invariants` is empty → synth.
498
674
  * 4. Else → graph-walk failure → `extensionPathUnreachable` /
@@ -514,12 +690,13 @@ async function planAggregate(input) {
514
690
  for (const member of orderedMembers) {
515
691
  const otherMembers = allMembers.filter((m) => m.spaceId !== member.spaceId);
516
692
  const currentMarker = currentDBState.markersBySpaceId.get(member.spaceId) ?? null;
693
+ const headRef = requireHeadRef(member);
517
694
  const ignoreGraph = callerPolicy.ignoreGraphFor.has(member.spaceId);
518
- const invariantsRequired = member.headRef.invariants.length > 0;
695
+ const invariantsRequired = headRef.invariants.length > 0;
519
696
  if (ignoreGraph && invariantsRequired) return notOk({
520
697
  kind: "policyConflict",
521
698
  spaceId: member.spaceId,
522
- detail: `\`callerPolicy.ignoreGraphFor\` requested for space "${member.spaceId}", but the member declares non-empty head-ref invariants (${member.headRef.invariants.join(", ")}). Synthesising a plan from the contract IR cannot satisfy authored invariants — the graph must be walked. Either remove "${member.spaceId}" from \`ignoreGraphFor\` or amend the on-disk head ref to declare zero invariants.`
699
+ detail: `\`callerPolicy.ignoreGraphFor\` requested for space "${member.spaceId}", but the member declares non-empty head-ref invariants (${headRef.invariants.join(", ")}). Synthesising a plan from the contract IR cannot satisfy authored invariants — the graph must be walked. Either remove "${member.spaceId}" from \`ignoreGraphFor\` or amend the on-disk head ref to declare zero invariants.`
523
700
  });
524
701
  if (ignoreGraph) {
525
702
  const synthOutcome = await synthStrategy({
@@ -540,7 +717,7 @@ async function planAggregate(input) {
540
717
  perSpace.set(member.spaceId, synthOutcome.result);
541
718
  continue;
542
719
  }
543
- if (member.migrations.graph.nodes.size > 0) {
720
+ if (member.graph().nodes.size > 0) {
544
721
  const walked = graphWalkStrategy({
545
722
  aggregateTargetId: aggregate.targetId,
546
723
  member,
@@ -553,7 +730,7 @@ async function planAggregate(input) {
553
730
  if (walked.kind === "unreachable") return notOk({
554
731
  kind: "extensionPathUnreachable",
555
732
  spaceId: member.spaceId,
556
- target: member.headRef.hash
733
+ target: headRef.hash
557
734
  });
558
735
  return notOk({
559
736
  kind: "extensionPathUnsatisfiable",
@@ -564,7 +741,7 @@ async function planAggregate(input) {
564
741
  if (invariantsRequired) return notOk({
565
742
  kind: "extensionPathUnsatisfiable",
566
743
  spaceId: member.spaceId,
567
- missingInvariants: [...member.headRef.invariants].sort()
744
+ missingInvariants: [...headRef.invariants].sort()
568
745
  });
569
746
  const synthOutcome = await synthStrategy({
570
747
  aggregateTargetId: aggregate.targetId,
@@ -633,16 +810,17 @@ function runVerifyAggregate(input) {
633
810
  markerPerSpace.set(member.spaceId, { kind: "absent" });
634
811
  continue;
635
812
  }
636
- if (marker.storageHash !== member.headRef.hash) {
813
+ const headRef = requireHeadRef(member);
814
+ if (marker.storageHash !== headRef.hash) {
637
815
  markerPerSpace.set(member.spaceId, {
638
816
  kind: "hashMismatch",
639
817
  markerHash: marker.storageHash,
640
- expected: member.headRef.hash
818
+ expected: headRef.hash
641
819
  });
642
820
  continue;
643
821
  }
644
822
  const markerInvariants = new Set(marker.invariants);
645
- const missing = member.headRef.invariants.filter((id) => !markerInvariants.has(id));
823
+ const missing = headRef.invariants.filter((id) => !markerInvariants.has(id));
646
824
  if (missing.length > 0) {
647
825
  markerPerSpace.set(member.spaceId, {
648
826
  kind: "missingInvariants",
@@ -685,7 +863,7 @@ function detectOrphanElements(schemaIntrospection, members) {
685
863
  const liveTables = schemaIntrospection.tables;
686
864
  if (typeof liveTables !== "object" || liveTables === null) return [];
687
865
  const claimedTables = /* @__PURE__ */ new Set();
688
- for (const member of members) for (const name of extractStorageElementNames(member.contract)) claimedTables.add(name);
866
+ for (const member of members) for (const name of extractStorageElementNames(member.contract())) claimedTables.add(name);
689
867
  const orphans = [];
690
868
  for (const tableName of Object.keys(liveTables)) if (!claimedTables.has(tableName)) orphans.push({
691
869
  kind: "table",
@@ -695,6 +873,6 @@ function detectOrphanElements(schemaIntrospection, members) {
695
873
  return orphans;
696
874
  }
697
875
  //#endregion
698
- export { graphWalkStrategy, loadContractSpaceAggregate, planAggregate, projectSchemaToSpace, verifyAggregate };
876
+ export { computeIntegrityViolations, createContractSpaceAggregate, createContractSpaceMember, graphWalkStrategy, loadContractSpaceAggregate, loadProblemToViolation, planAggregate, projectSchemaToSpace, requireHeadRef, verifyAggregate };
699
877
 
700
878
  //# sourceMappingURL=aggregate.mjs.map