@prisma/orm-toolchain 8.0.0-rc.18-dev.33 → 8.0.0-rc.18-dev.34

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 (58) hide show
  1. package/dist/{aggregate-C0qscKli.mjs → aggregate-B9HIfbq6.mjs} +7 -7
  2. package/dist/{aggregate-C0qscKli.mjs.map → aggregate-B9HIfbq6.mjs.map} +1 -1
  3. package/dist/{caught-errors-BJYT1ZZW-CJZWDvwc.mjs → caught-errors-VVhfmaAC-B-4FGHb0.mjs} +20 -25
  4. package/dist/caught-errors-VVhfmaAC-B-4FGHb0.mjs.map +1 -0
  5. package/dist/cli.mjs +55 -331
  6. package/dist/cli.mjs.map +1 -1
  7. package/dist/cli__control-api.d.mts +8 -4
  8. package/dist/cli__control-api.d.mts.map +1 -1
  9. package/dist/cli__control-api.mjs +2 -2
  10. package/dist/cli__control-api__testing.d.mts +1 -1
  11. package/dist/cli__migration-cli.mjs +3 -3
  12. package/dist/cli__migration-cli.mjs.map +1 -1
  13. package/dist/{contract-snapshot-store-DwEs5EOp-3qAvnEf3.mjs → contract-snapshot-store-6gIBcUeb-DJK3OM0j.mjs} +3 -3
  14. package/dist/{contract-snapshot-store-DwEs5EOp-3qAvnEf3.mjs.map → contract-snapshot-store-6gIBcUeb-DJK3OM0j.mjs.map} +1 -1
  15. package/dist/{db-sign-WZXfmxmZ-BVlM-YTL.d.mts → db-sign-DyugidHS-DGvMQ558.d.mts} +34 -140
  16. package/dist/db-sign-DyugidHS-DGvMQ558.d.mts.map +1 -0
  17. package/dist/{errors-GnmirXRU.d.mts → errors-CLwhWJiz.d.mts} +10 -2
  18. package/dist/errors-CLwhWJiz.d.mts.map +1 -0
  19. package/dist/{errors-nnIQQvmN-oeANP4Yi.mjs → errors-DXha_4l--relAaiI4.mjs} +9 -6
  20. package/dist/errors-DXha_4l--relAaiI4.mjs.map +1 -0
  21. package/dist/{graph-membership-ul46Kb0W-B8HahKEu.mjs → graph-membership-DxpNgxfZ-BfqA-H7V.mjs} +3 -3
  22. package/dist/{graph-membership-ul46Kb0W-B8HahKEu.mjs.map → graph-membership-DxpNgxfZ-BfqA-H7V.mjs.map} +1 -1
  23. package/dist/{invariants-Jgsl_-rJ-0ieZ1n7L.mjs → invariants-DrF9p5Gd-BF70vGl1.mjs} +3 -3
  24. package/dist/{invariants-Jgsl_-rJ-0ieZ1n7L.mjs.map → invariants-DrF9p5Gd-BF70vGl1.mjs.map} +1 -1
  25. package/dist/{io-QeCr3NPS-Bk-Rfef2.mjs → io-BJ-LXfIc-BDm7pWEw.mjs} +5 -5
  26. package/dist/{io-QeCr3NPS-Bk-Rfef2.mjs.map → io-BJ-LXfIc-BDm7pWEw.mjs.map} +1 -1
  27. package/dist/migration-tools.d.mts +2 -2
  28. package/dist/migration-tools.mjs +12 -12
  29. package/dist/migration-tools__aggregate.mjs +1 -1
  30. package/dist/migration-tools__contract-snapshot-store.mjs +1 -1
  31. package/dist/migration-tools__errors.d.mts +2 -2
  32. package/dist/migration-tools__errors.mjs +1 -1
  33. package/dist/migration-tools__invariants.mjs +1 -1
  34. package/dist/migration-tools__io.mjs +1 -1
  35. package/dist/migration-tools__migration-graph.mjs +1 -1
  36. package/dist/migration-tools__migration.mjs +1 -1
  37. package/dist/migration-tools__ref-resolution.mjs +1 -1
  38. package/dist/migration-tools__refs.mjs +1 -1
  39. package/dist/migration-tools__spaces.mjs +2 -2
  40. package/dist/{migration-Cp6vkFMP.mjs → migration-wBxEFdXP.mjs} +3 -3
  41. package/dist/{migration-Cp6vkFMP.mjs.map → migration-wBxEFdXP.mjs.map} +1 -1
  42. package/dist/{ref-Bn3SzQ9Z-DHi9xcRa.mjs → ref-DLqjHXyn-CsLViutC.mjs} +403 -154
  43. package/dist/ref-DLqjHXyn-CsLViutC.mjs.map +1 -0
  44. package/dist/{ref-resolution-CCIgrFwK.mjs → ref-resolution-Eo0QHp4f.mjs} +2 -2
  45. package/dist/{ref-resolution-CCIgrFwK.mjs.map → ref-resolution-Eo0QHp4f.mjs.map} +1 -1
  46. package/dist/{refs-BIzM-guE-qMvITMOL.mjs → refs-DM3q3IZC-BC6H6P0X.mjs} +3 -3
  47. package/dist/{refs-BIzM-guE-qMvITMOL.mjs.map → refs-DM3q3IZC-BC6H6P0X.mjs.map} +1 -1
  48. package/dist/{spaces-BoFEHLeH.mjs → spaces-COXaiv-z.mjs} +5 -5
  49. package/dist/{spaces-BoFEHLeH.mjs.map → spaces-COXaiv-z.mjs.map} +1 -1
  50. package/dist/{verify-contract-spaces-BFH2o5RL-CI6uhB5B.mjs → verify-contract-spaces-DkXWDLa0-R1nU6Hq1.mjs} +4 -4
  51. package/dist/{verify-contract-spaces-BFH2o5RL-CI6uhB5B.mjs.map → verify-contract-spaces-DkXWDLa0-R1nU6Hq1.mjs.map} +1 -1
  52. package/dist/vite-plugin-contract-emit.mjs +1 -1
  53. package/package.json +12 -12
  54. package/dist/caught-errors-BJYT1ZZW-CJZWDvwc.mjs.map +0 -1
  55. package/dist/db-sign-WZXfmxmZ-BVlM-YTL.d.mts.map +0 -1
  56. package/dist/errors-GnmirXRU.d.mts.map +0 -1
  57. package/dist/errors-nnIQQvmN-oeANP4Yi.mjs.map +0 -1
  58. package/dist/ref-Bn3SzQ9Z-DHi9xcRa.mjs.map +0 -1
@@ -1,27 +1,27 @@
1
1
  import { a as expandContractInputs } from "./exports-BlYTE3-J.mjs";
2
- import { D as errorNoInvariantPath, M as errorUnknownInvariant, b as errorInvalidRefName, r as errorContractDeserializationFailed, t as MigrationToolsError } from "./errors-nnIQQvmN-oeANP4Yi.mjs";
3
- import { r as verifyMigrationHash, t as computeMigrationHash } from "./hash-BAZVWU4a-BQovI7hF.mjs";
4
- import { a as snapshotsImportPathFrom, n as createSnapshotContentVerifier, o as writeContractSnapshot, r as readContractSnapshotJson, t as contractSnapshotDir } from "./contract-snapshot-store-DwEs5EOp-3qAvnEf3.mjs";
5
- import { t as deriveProvidedInvariants } from "./invariants-Jgsl_-rJ-0ieZ1n7L.mjs";
6
- import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigrationDirName, u as writeMigrationPackage } from "./io-QeCr3NPS-Bk-Rfef2.mjs";
7
2
  import { t as EMPTY_CONTRACT_HASH } from "./constants-CM-w38DQ-Cz_EXbOc.mjs";
3
+ import { D as errorNoInvariantPath, M as errorUnknownInvariant, b as errorInvalidRefName, r as errorContractDeserializationFailed, t as MigrationToolsError } from "./errors-DXha_4l--relAaiI4.mjs";
4
+ import { r as verifyMigrationHash, t as computeMigrationHash } from "./hash-BAZVWU4a-BQovI7hF.mjs";
5
+ import { a as snapshotsImportPathFrom, n as createSnapshotContentVerifier, o as writeContractSnapshot, r as readContractSnapshotJson, t as contractSnapshotDir } from "./contract-snapshot-store-6gIBcUeb-DJK3OM0j.mjs";
6
+ import { t as deriveProvidedInvariants } from "./invariants-DrF9p5Gd-BF70vGl1.mjs";
7
+ import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigrationDirName, u as writeMigrationPackage } from "./io-BJ-LXfIc-BDm7pWEw.mjs";
8
8
  import { i as findPathWithDecision, r as findPath } from "./migration-graph-BoiiZAaU-DLht12k7.mjs";
9
- import { a as isValidSpaceId, c as spaceMigrationDirectory, l as spaceRefsDirectory, o as listContractSpaceDirectories, s as readContractSpaceHeadRef, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-BFH2o5RL-CI6uhB5B.mjs";
10
- import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-BoFEHLeH.mjs";
11
- import { B as errorRefSetHashNotInGraph, D as errorInvalidSpaceId, F as errorPlanForgotTheFlag, G as errorSpaceNotFound, H as errorRuntime, I as errorPlanOriginUnknown, J as errorStatementInvalid, K as errorStatementAnswersNoQuestion, L as errorPlanProducedNoOperations, M as errorMigrationPlanningFailed, P as errorPathUnreachable, Q as errorTargetMigrationNotSupported, R as errorRefSetBundleNotFound, T as errorFromCaught, W as errorSnapshotMissing, X as errorStatementOriginUnknown, Y as errorStatementNeedsMigrationFile, Z as errorStatementUnresolved, _ as errorConfigValidation$1, _t as toStructuralEdge, b as errorContractValidationFailed, d as closeQuietly, dt as resolveMigrationPaths, et as errorUnexpected, f as collectDeclaredInvariants, ft as runCommandAction, g as errorAmbiguousMigrationRef, ht as statementFlag, k as errorMarkerMismatch, l as cliErrorFromStructured, lt as requireLiveDatabase, n as CliStructuredError$1, nt as mapRefResolutionError, pt as selfEmitCommand, q as errorStatementDidNotResolveLoss, r as STORE_ORIGIN_SNAPSHOT_STEPS, s as chooseAction, st as readContractEnvelope, tt as getTargetMigrations, ut as resolveContractPath, w as errorFileNotFound, y as errorContractConfigMissing, z as errorRefSetEmptySentinel } from "./caught-errors-BJYT1ZZW-CJZWDvwc.mjs";
9
+ import { a as isValidSpaceId, c as spaceMigrationDirectory, l as spaceRefsDirectory, o as listContractSpaceDirectories, s as readContractSpaceHeadRef, t as APP_SPACE_ID$1 } from "./verify-contract-spaces-DkXWDLa0-R1nU6Hq1.mjs";
10
+ import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-COXaiv-z.mjs";
11
+ import { $ as errorUnexpected, B as errorRefSetHashNotInGraph, D as errorInvalidSpaceId, F as errorPlanForgotTheFlag, G as errorStatementAnswersNoQuestion, I as errorPlanOriginUnknown, J as errorStatementNeedsMigrationFile, K as errorStatementDidNotResolveLoss, L as errorPlanProducedNoOperations, M as errorMigrationPlanningFailed, P as errorPathUnreachable, R as errorRefSetBundleNotFound, T as errorFromCaught, U as errorSnapshotMissing, V as errorRuntime, W as errorSpaceNotFound, X as errorStatementUnresolved, Y as errorStatementOriginUnknown, Z as errorTargetMigrationNotSupported, _ as errorConfigValidation$1, at as printedPlanCommand, b as errorContractValidationFailed, c as cliCommand, ct as requireLiveDatabase, d as closeQuietly, dt as runCommandAction, et as getTargetMigrations, f as collectDeclaredInvariants, ft as selfEmitCommand, g as errorAmbiguousMigrationRef, gt as toStructuralEdge, it as printedPath, k as errorMarkerMismatch, l as cliErrorFromStructured, lt as resolveContractPath, mt as statementFlag, n as CliStructuredError$1, ot as readContractEnvelope, q as errorStatementInvalid, r as STORE_ORIGIN_SNAPSHOT_STEPS, s as chooseAction, t as ActionableCliError, tt as mapRefResolutionError, ut as resolveMigrationPaths, w as errorFileNotFound, y as errorContractConfigMissing, z as errorRefSetEmptySentinel } from "./caught-errors-VVhfmaAC-B-4FGHb0.mjs";
12
12
  import { r as getEmittedArtifactPaths, t as emit } from "./exports-BCIlMjIW-DkUBVDzl.mjs";
13
- import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-ul46Kb0W-B8HahKEu.mjs";
14
- import { d as writeRef, i as readRefs, l as validateRefName, n as deleteRef, o as refsByContractHash, t as HEAD_REF_NAME, u as validateRefValue } from "./refs-BIzM-guE-qMvITMOL.mjs";
15
- import { a as contractHashAtMarker, c as loadContractSpaceAggregate, d as requireHeadRef, f as resolveRecordedPath, m as verifyMigration, n as buildFabricatedMigrationEdge, p as spacesInApplyOrder, r as collectAggregateNamespaces, t as allStorageElementsExternal, u as planMigration } from "./aggregate-C0qscKli.mjs";
13
+ import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-DxpNgxfZ-BfqA-H7V.mjs";
14
+ import { d as writeRef, i as readRefs, l as validateRefName, n as deleteRef, o as refsByContractHash, t as HEAD_REF_NAME, u as validateRefValue } from "./refs-DM3q3IZC-BC6H6P0X.mjs";
15
+ import { a as contractHashAtMarker, c as loadContractSpaceAggregate, d as requireHeadRef, f as resolveRecordedPath, m as verifyMigration, n as buildFabricatedMigrationEdge, p as spacesInApplyOrder, r as collectAggregateNamespaces, t as allStorageElementsExternal, u as planMigration } from "./aggregate-B9HIfbq6.mjs";
16
16
  import { c as internalImportRoot, o as importRootForDependencies, r as createImportSpecifierResolver, t as ImportRootError } from "./import-roots-DXD7fung.mjs";
17
- import { c as parseContractRef, l as parseMigrationRef, o as isLiveMarkerRef, r as RESERVED_CONTRACT_REFS, s as isReservedContractRef, t as EMPTY_CONTRACT_REF } from "./ref-resolution-CCIgrFwK.mjs";
17
+ import { c as parseContractRef, l as parseMigrationRef, o as isLiveMarkerRef, r as RESERVED_CONTRACT_REFS, s as isReservedContractRef, t as EMPTY_CONTRACT_REF } from "./ref-resolution-Eo0QHp4f.mjs";
18
18
  import { a as writeMigrationTs } from "./migration-ts-DDgjsR1O.mjs";
19
19
  import { createRequire } from "node:module";
20
20
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
21
21
  import { CliStructuredError } from "@prisma/orm-framework/errors/control";
22
22
  import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, describeMigrationStatement, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, planOriginOf } from "@prisma/orm-framework/components/control";
23
23
  import { InternalError } from "@prisma/orm-framework/utils/internal-error";
24
- import { isStructuredError, isStructuredErrorCode, structuredError } from "@prisma/orm-framework/utils/structured-error";
24
+ import { docsUrlFor, isStructuredError, isStructuredErrorCode, structuredError } from "@prisma/orm-framework/utils/structured-error";
25
25
  import { basename, dirname, isAbsolute, join, relative, resolve } from "pathe";
26
26
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
27
27
  import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
@@ -34,7 +34,7 @@ import { asNamespaceId } from "@prisma/orm-framework/contract/types";
34
34
  import { isDeepStrictEqual } from "node:util";
35
35
  import { abortable } from "@prisma/orm-framework/utils/abortable";
36
36
  import { resolve as resolve$1 } from "node:path";
37
- //#region ../../../1-framework/3-tooling/cli/dist/ref-Bn3SzQ9Z.mjs
37
+ //#region ../../../1-framework/3-tooling/cli/dist/ref-DLqjHXyn.mjs
38
38
  /**
39
39
  * The meta of a contract that failed to load because the family refused it, such as the columns whose defaults it refused, for the command to report: the refusal's own meta, or the `refusedDefaults` a migration-tools error kept from it.
40
40
  */
@@ -176,6 +176,274 @@ function enrichContract(ir, components) {
176
176
  extensions: sortDeepTyped(extensions)
177
177
  };
178
178
  }
179
+ /** The operation classes `db update` applies. */
180
+ const DB_UPDATE_POLICY = { allowedOperationClasses: [
181
+ "additive",
182
+ "widening",
183
+ "destructive"
184
+ ] };
185
+ /** The way out of a failed check before an operation of `db migrate`. */
186
+ function migrateFailedPrecheckFix(report, invocation) {
187
+ const migrate = `\`${cliCommand(invocation, "db migrate")}\``;
188
+ return report.planStartsFromMarker ? `The database has drifted from its migration history: it is not in the state the migrations before this one leave. See how it differs from the contract with \`${cliCommand(invocation, "db verify")}\`, change the database or the migration so they agree, and run ${migrate} again.` : `The database has no migration marker, so ${migrate} applies every migration from the first, and the database may already be ahead of this one. If its schema already matches the contract, adopt it with \`${cliCommand(invocation, "db sign")}\` instead.`;
189
+ }
190
+ /** The way out of a failed check before an operation of `db init`, which runs only on a database with no marker. */
191
+ function dbInitFailedPrecheckFix(invocation) {
192
+ return `The database already holds part of the schema \`${cliCommand(invocation, "db init")}\` would create. If its schema already matches the contract, adopt it with \`${cliCommand(invocation, "db sign")}\` instead.`;
193
+ }
194
+ /** The issues a failed schema check after apply reported; a check that reported none counts as none. */
195
+ function schemaCheckIssues(failure) {
196
+ const issues = failure.meta.schemaIssues;
197
+ return issues === void 0 || issues.length === 0 ? void 0 : issues;
198
+ }
199
+ /** What a runner failure says of a type change that failed: who converted the values, and how it failed. */
200
+ function failedTypeChangeText(change) {
201
+ if (change.by === "cast") return change.reason === "noCast" ? `The database has no cast from the old type of field "${change.field}" to its new type.` : `A value of field "${change.field}" cannot be converted to its new type by the database's cast.`;
202
+ switch (change.reason) {
203
+ case "value": return `The conversion of field "${change.field}" failed on a value its new type cannot hold.`;
204
+ case "invalidResult": return `The conversion of field "${change.field}" left a value its new type cannot hold.`;
205
+ case "expressionError": return `The conversion of field "${change.field}" failed with an error in its expression.`;
206
+ }
207
+ }
208
+ function migrationPlanCommand(invocation, flags, from) {
209
+ return `\`${printedPlanCommand(invocation, from, flags)}\``;
210
+ }
211
+ /** A `db migrate` command as advice prints it. */
212
+ function dbMigrateCommand(invocation) {
213
+ return `\`${cliCommand(invocation, "db migrate")}\``;
214
+ }
215
+ /** The step between filling a planned migration.ts and applying it, which writes its operations. */
216
+ const RUN_PLANNED_FILE = "run that migration.ts with the `node` command `migration plan` prints";
217
+ function backfillFlags(reports) {
218
+ return [...new Set(reports.flatMap(({ field }) => field === void 0 ? [] : [statementFlag({
219
+ verb: "backfill",
220
+ text: field
221
+ })]))];
222
+ }
223
+ /** The way out of a failed cast for `db update`, which plans and applies in one step. */
224
+ function dbUpdateFailedTypeChangeFix(change, databaseStorageHash, invocation) {
225
+ const plan = migrationPlanCommand(invocation, [statementFlag({
226
+ verb: "convert",
227
+ text: change.field
228
+ })], databaseStorageHash);
229
+ return `${failedTypeChangeText(change)} Plan the change with ${plan}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}.`;
230
+ }
231
+ /** The way out of rows without a value for `db update`, which plans and applies in one step. */
232
+ function dbUpdateRowsWithoutValueFix(reports, databaseStorageHash, invocation) {
233
+ const flags = backfillFlags(reports);
234
+ const plan = flags.length === 0 ? void 0 : `${migrationPlanCommand(invocation, flags, databaseStorageHash)}, fill the backfill steps in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`;
235
+ if (reports[0]?.reason === "nullValues") {
236
+ const keep = "Set a value in those rows, or keep the field optional.";
237
+ return plan === void 0 ? keep : `${keep} Or plan it with ${plan}.`;
238
+ }
239
+ return plan === void 0 ? "Make the field optional." : `Plan it with ${plan}. Or make the field optional.`;
240
+ }
241
+ /**
242
+ * The way out of rows without a value for `db init`: a migration plan needs an origin contract,
243
+ * which a database that `db init` never initialized does not have.
244
+ */
245
+ function dbInitRowsWithoutValueFix(reports, invocation) {
246
+ const field = reports[0]?.field;
247
+ const subject = field === void 0 ? "it" : `field "${field}"`;
248
+ return `Run \`${cliCommand(invocation, "db init")}\` with ${subject} optional. Then make it required with \`${cliCommand(invocation, "db update")}\`, which says how to give the rows a value.`;
249
+ }
250
+ function failedMigrationText(failed, invocation) {
251
+ const dirName = basename(failed.directory);
252
+ return {
253
+ directory: printedPath(invocation, failed.directory),
254
+ name: dirName.slice(dirName.indexOf("_") + 1),
255
+ from: failed.from === "empty" ? void 0 : failed.from,
256
+ nodeCommand: selfEmitCommand(invocation, join(failed.directory, "migration.ts")),
257
+ invocation
258
+ };
259
+ }
260
+ function replan(flags, failed, except = void 0) {
261
+ const others = except === void 0 ? "its other statements" : `its other statements except any ${except}`;
262
+ const plan = migrationPlanCommand(failed.invocation, [
263
+ "--name",
264
+ failed.name,
265
+ ...flags
266
+ ], failed.from);
267
+ return `delete \`${failed.directory}\` (copy any code you wrote in its migration.ts first), plan it again with ${plan} and ${others}, fill in the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(failed.invocation)}`;
268
+ }
269
+ /**
270
+ * Where to fix code written in the failed migration's `migration.ts`, and the command that runs the
271
+ * file again.
272
+ */
273
+ function failedMigrationFile(failedMigration) {
274
+ if (failedMigration === void 0) return {
275
+ file: "the migration.ts of the failed migration",
276
+ run: "run that file with node"
277
+ };
278
+ return {
279
+ file: `\`${failedMigration.directory}/migration.ts\``,
280
+ run: `run \`${failedMigration.nodeCommand}\``
281
+ };
282
+ }
283
+ function migrateFailedTypeChangeFix(change, failedMigration, invocation) {
284
+ if (change.by === "conversion") {
285
+ const { file, run } = failedMigrationFile(failedMigration);
286
+ return `${failedTypeChangeText(change)} The failed apply changed nothing. Fix the conversion in ${file}, ${run}, and re-run ${dbMigrateCommand(invocation)}.`;
287
+ }
288
+ const convert = statementFlag({
289
+ verb: "convert",
290
+ text: change.field
291
+ });
292
+ if (failedMigration === void 0) return `${failedTypeChangeText(change)} Plan the type change again with ${migrationPlanCommand(invocation, [convert], void 0)}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}.`;
293
+ const deleted = `\`${statementFlag({
294
+ verb: "delete",
295
+ text: change.field
296
+ })}\``;
297
+ const { file, run } = failedMigrationFile(failedMigration);
298
+ return `${failedTypeChangeText(change)} The failed apply changed nothing. ${file} has no conversion for field "${change.field}": write one there, ${run}, and re-run ${dbMigrateCommand(invocation)}. Or ${replan([convert], failedMigration, deleted)}.`;
299
+ }
300
+ function migrateRowsWithoutValueFix(reports, failedMigration, invocation) {
301
+ const [first] = reports;
302
+ if (first?.reason === "backfillMissedRows") {
303
+ const { file, run } = failedMigrationFile(failedMigration);
304
+ return `${first.field === void 0 ? "The backfill step" : `The backfill step of field "${first.field}"`} left those rows without a value, and the failed apply changed nothing. Make its run fill every row in ${file}, ${run}, and re-run ${dbMigrateCommand(invocation)}.`;
305
+ }
306
+ const flags = backfillFlags(reports);
307
+ const again = flags.length === 0 || failedMigration === void 0 ? void 0 : replan(flags, failedMigration);
308
+ if (reports.every(({ reason }) => reason === "nullValues")) {
309
+ const rerun = reports.length === 1 ? `Set a value in those rows and re-run ${dbMigrateCommand(invocation)}.` : `Set a value in the rows that hold NULL in each of ${fieldList(reports)} and re-run ${dbMigrateCommand(invocation)}.`;
310
+ const keep = failedMigration === void 0 ? `Or keep ${reports.length === 1 ? "the field" : "those fields"} optional, and plan the migration again.` : `Or keep ${reports.length === 1 ? "the field" : "those fields"} optional: make ${reports.length === 1 ? "it" : "them"} optional in the contract again, delete \`${failedMigration.directory}\` (copy any code you wrote in its migration.ts first), and plan it again with ${migrationPlanCommand(invocation, ["--name", failedMigration.name], failedMigration.from)} and its other statements, put back any code you copied, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}.`;
311
+ return [
312
+ rerun,
313
+ ...again === void 0 ? [] : [`Or ${again}.`],
314
+ keep
315
+ ].join(" ");
316
+ }
317
+ if (reports[0]?.reason === "nullValues") return again === void 0 ? "The migration also adds a required field the existing rows have no value for, so setting values is not enough: make the new fields optional, and plan the migration again." : `The migration also adds a required field the existing rows have no value for, so setting values is not enough. The failed apply changed nothing: ${again}.`;
318
+ return again === void 0 ? "Make the field optional, and plan the migration again." : `The failed apply changed nothing. To keep the field required, ${again}. Or make the field optional, and plan it again.`;
319
+ }
320
+ function fieldList(reports) {
321
+ return reports.map(({ field }) => field === void 0 ? void 0 : `"${field}"`).filter((field) => field !== void 0).join(", ");
322
+ }
323
+ function migrateSchemaCheckFix(failedMigration, invocation) {
324
+ const emit = `\`${cliCommand(invocation, "contract emit")}\``;
325
+ if (failedMigration === void 0) return `The failed apply changed nothing. Change the contract source to resolve the issues listed, re-run ${emit}, delete the failed migration's directory (copy any code you wrote in its migration.ts first), plan it again with ${migrationPlanCommand(invocation, [], void 0)}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(invocation)}.`;
326
+ const plan = migrationPlanCommand(invocation, ["--name", failedMigration.name], failedMigration.from);
327
+ return `The failed apply changed nothing. Change the contract source to resolve the issues listed, re-run ${emit}, delete \`${failedMigration.directory}\` (copy any code you wrote in its migration.ts first), plan it again with ${plan}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(invocation)}.`;
328
+ }
329
+ /**
330
+ * The way out of a failed `db migrate` apply: every path and command it prints works from where the
331
+ * CLI ran, with the `--config` it was given.
332
+ */
333
+ function migrateFix(failure, facts, failedOnDisk, invocation) {
334
+ const failedMigration = failedOnDisk === void 0 ? void 0 : failedMigrationText(failedOnDisk, invocation);
335
+ if (facts.failedTypeChange !== void 0) return migrateFailedTypeChangeFix(facts.failedTypeChange, failedMigration, invocation);
336
+ if (facts.rowsWithoutValue !== void 0) return migrateRowsWithoutValueFix(facts.rowsWithoutValue, failedMigration, invocation);
337
+ if (schemaCheckIssues(failure) !== void 0) return migrateSchemaCheckFix(failedMigration, invocation);
338
+ if (facts.failedPrecheck !== void 0) return migrateFailedPrecheckFix(facts.failedPrecheck, invocation);
339
+ return `Fix the issue and re-run \`${cliCommand(invocation, "db migrate", ["--to", "<contract>"])}\` — previously applied migrations are preserved.`;
340
+ }
341
+ /**
342
+ * A runner failure as the CLI reports it: the runner's code, message, why and meta, and the failure
343
+ * itself as `cause`, with the CLI's `fix`.
344
+ */
345
+ function runnerFailureError(failure, advice) {
346
+ return new CliStructuredError$1(failure.code, failure.message, {
347
+ ...ifDefined("why", failure.why),
348
+ fix: advice.fix,
349
+ meta: failure.meta,
350
+ docsUrl: docsUrlFor(failure.code),
351
+ cause: failure
352
+ });
353
+ }
354
+ const DB_INIT_ADDITIVE_ONLY_FIX = "`db init` applies only additive changes. Run `{bin} db update`, which also applies widening and destructive ones once you answer what each operation that would lose data means, with `--delete` or `--rename`.";
355
+ const DB_INIT_NEEDS_MIGRATION_FIX = "`db init` applies only additive changes, and `db update` does not apply data operations. Plan a migration with `{bin} migration plan`, which can include them, and apply it with `{bin} db migrate`.";
356
+ /**
357
+ * What to do instead of `db init` when its additive-only policy refused operations of the given classes: `db update` when its policy allows all of them, otherwise a planned migration.
358
+ */
359
+ function adviceForRefusedClasses(refused) {
360
+ const allowedByDbUpdate = new Set(DB_UPDATE_POLICY.allowedOperationClasses);
361
+ if (![...refused].every((operationClass) => allowedByDbUpdate.has(operationClass))) return {
362
+ fix: DB_INIT_NEEDS_MIGRATION_FIX,
363
+ nextAction: runCommandAction("Plan a migration, since db update does not apply data operations", "{bin} migration plan")
364
+ };
365
+ return {
366
+ fix: DB_INIT_ADDITIVE_ONLY_FIX,
367
+ nextAction: runCommandAction(refused.has("destructive") ? "Apply the change with db update, which asks what each operation that would lose data means" : "Apply the change with db update", "{bin} db update")
368
+ };
369
+ }
370
+ /**
371
+ * `db init`'s planning failure: when its additive-only policy refused operations, it says to use
372
+ * `db update` or a planned migration instead.
373
+ */
374
+ function dbInitPlanningFailedError(conflicts) {
375
+ const planningFailed = errorMigrationPlanningFailed({ conflicts });
376
+ const refused = new Set(conflicts.flatMap((conflict) => conflict.refusedOperationClass === void 0 ? [] : [conflict.refusedOperationClass]));
377
+ if (refused.size === 0) return planningFailed;
378
+ const { fix, nextAction } = adviceForRefusedClasses(refused);
379
+ return new ActionableCliError(planningFailed.code, planningFailed.message, {
380
+ why: planningFailed.why,
381
+ fix,
382
+ nextActions: [nextAction],
383
+ ...ifDefined("meta", planningFailed.meta),
384
+ ...ifDefined("docsUrl", planningFailed.docsUrl)
385
+ });
386
+ }
387
+ /** A failed `db init` apply as the CLI reports it. */
388
+ function dbInitRunnerFailureError(failure, facts, invocation) {
389
+ return runnerFailureError(failure, { fix: facts.rowsWithoutValue !== void 0 ? dbInitRowsWithoutValueFix(facts.rowsWithoutValue, invocation) : schemaCheckIssues(failure) !== void 0 ? `Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${cliCommand(invocation, "db init")}\`.` : facts.failedPrecheck !== void 0 ? dbInitFailedPrecheckFix(invocation) : `Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run \`${cliCommand(invocation, "db init")}\`` });
390
+ }
391
+ /**
392
+ * A failed `db update` apply as the CLI reports it. `databaseStorageHash` is the contract the
393
+ * database is at when a migration of the graph ends at it: the origin a `migration plan` for this
394
+ * database starts from.
395
+ */
396
+ function dbUpdateRunnerFailureError(failure, facts, context) {
397
+ const { databaseStorageHash, invocation } = context;
398
+ return runnerFailureError(failure, { fix: facts.failedTypeChange !== void 0 ? dbUpdateFailedTypeChangeFix(facts.failedTypeChange, databaseStorageHash, invocation) : facts.rowsWithoutValue !== void 0 ? dbUpdateRowsWithoutValueFix(facts.rowsWithoutValue, databaseStorageHash, invocation) : schemaCheckIssues(failure) !== void 0 ? `Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${cliCommand(invocation, "db update")}\`.` : `Inspect the reported conflict, reconcile schema drift if needed, then re-run \`${cliCommand(invocation, "db update")}\`` });
399
+ }
400
+ function startText(fromHash) {
401
+ return fromHash === "empty" ? "the empty contract (the space has no marker)" : `the contract its marker names ("${fromHash}")`;
402
+ }
403
+ const INSTALL_MATCHING = "Install a version of the extension whose migrations start from the contract the database is at";
404
+ /** The way out for an extension space: only another version of the extension changes its migrations. */
405
+ function extensionAdvice(space) {
406
+ const rerun = cliCommand(space.invocation, space.command);
407
+ const list = cliCommand(space.invocation, "migration list", ["--space", space.spaceId]);
408
+ return {
409
+ fix: `The migrations of extension space "${space.spaceId}" come with the extension. ${INSTALL_MATCHING}, then run \`${rerun}\` again. List the space's migrations with \`${list}\`.`,
410
+ nextActions: [
411
+ chooseAction(INSTALL_MATCHING),
412
+ runCommandAction(`List the migrations of extension space "${space.spaceId}"`, list),
413
+ runCommandAction(`Run ${space.command} again`, rerun)
414
+ ]
415
+ };
416
+ }
417
+ /** `MIGRATION.PATH_UNREACHABLE` for an extension space whose migrations do not lead from where the database is to the extension's head. */
418
+ function errorExtensionPathUnreachable(space) {
419
+ return errorPathUnreachable({
420
+ summary: `Cannot resolve apply path for extension space "${space.spaceId}"`,
421
+ why: `No path in the on-disk migration graph for extension space "${space.spaceId}" leads from ${startText(space.fromHash)} to the on-disk head ref hash "${space.targetHash}".`,
422
+ meta: {
423
+ kind: "pathUnreachable",
424
+ spaceId: space.spaceId,
425
+ fromHash: space.fromHash,
426
+ targetHash: space.targetHash
427
+ }
428
+ }, extensionAdvice(space));
429
+ }
430
+ /**
431
+ * `MIGRATION.NO_INVARIANT_PATH` for an extension space whose migrations reach the extension's head
432
+ * from where the database is, but not through the ones that provide the invariants its head requires.
433
+ */
434
+ function errorExtensionNoInvariantPath(space) {
435
+ const missing = space.missing.map((id) => JSON.stringify(id)).join(", ");
436
+ return errorNoInvariantPath({
437
+ required: space.required,
438
+ missing: space.missing,
439
+ structuralPath: space.structuralPath,
440
+ extensionSpace: {
441
+ spaceId: space.spaceId,
442
+ why: `The head of extension space "${space.spaceId}" requires invariants that no path of its migrations from ${startText(space.fromHash)} provides: ${missing}.`,
443
+ ...extensionAdvice(space)
444
+ }
445
+ });
446
+ }
179
447
  function formsFix$1(verb) {
180
448
  return verb === "delete" ? "Write the statement as --delete <name>, where the name is Model, namespace.Model, Model.field or namespace.Model.field, or the storage name the refusal gave, for example --delete Legacy or --delete User.nickname." : "Write the statement as --allow <name>, where the name is the model the refusal gave, for example --allow User.";
181
449
  }
@@ -1448,6 +1716,32 @@ function stripOperations(operations) {
1448
1716
  }));
1449
1717
  }
1450
1718
  /**
1719
+ * The path from `fromHash` to `targetHash` when invariants are ignored, or none. A space with no
1720
+ * marker starts from the empty contract's hash, so the path is found even then.
1721
+ */
1722
+ function structuralPathOf(graph, fromHash, targetHash) {
1723
+ const structural = findPathWithDecision(graph, fromHash, targetHash, { required: /* @__PURE__ */ new Set() });
1724
+ return structural.kind === "ok" ? structural.decision.selectedPath.map((edge) => ({
1725
+ dirName: edge.dirName,
1726
+ migrationHash: edge.migrationHash,
1727
+ from: edge.from,
1728
+ to: edge.to,
1729
+ invariants: edge.invariants
1730
+ })) : [];
1731
+ }
1732
+ /**
1733
+ * `MIGRATION.NO_INVARIANT_PATH` for a space whose graph reaches `targetHash` from `fromHash` but
1734
+ * provides none of `missing`, naming the path that ignores invariants.
1735
+ */
1736
+ function noInvariantPathError(input) {
1737
+ return errorNoInvariantPath({
1738
+ ...input.refName !== void 0 ? { refName: input.refName } : {},
1739
+ required: input.required,
1740
+ missing: input.missing,
1741
+ structuralPath: structuralPathOf(input.graph, input.fromHash, input.targetHash)
1742
+ });
1743
+ }
1744
+ /**
1451
1745
  * Span id emitted via `onProgress` for the run phase. Stable
1452
1746
  * identifier consumed by the structured-output renderer and by tests.
1453
1747
  */
@@ -1472,15 +1766,15 @@ function failedTypeChangeReport(change, field) {
1472
1766
  }
1473
1767
  /** What the runner said blocked the failed operation, named as the advice names it. */
1474
1768
  function failureReports(failure, resolutions) {
1475
- const resolution = resolutions.find(({ spaceId }) => spaceId === failure.failingSpace);
1769
+ const resolution = resolutions.find(({ spaceId }) => spaceId === failure.meta.failingSpace);
1476
1770
  if (resolution === void 0) return {};
1477
1771
  const fieldText = (field) => subjectText(field, {
1478
1772
  origin: resolution.entry.destinationContract,
1479
1773
  statements: []
1480
1774
  });
1481
- const { failedTypeChange, rowsWithoutValue } = failure;
1775
+ const { failedTypeChange, rowsWithoutValue } = failure.meta;
1482
1776
  const operationIndex = failedTypeChange?.operationIndex ?? rowsWithoutValue?.[0]?.operationIndex;
1483
- const edge = operationIndex !== void 0 ? edgeOfOperation(resolution.entry.migrationEdges, operationIndex) : schemaIssuesOf(failure) !== void 0 ? resolution.entry.migrationEdges.at(-1) : void 0;
1777
+ const edge = operationIndex !== void 0 ? edgeOfOperation(resolution.entry.migrationEdges, operationIndex) : schemaCheckIssues(failure) !== void 0 ? resolution.entry.migrationEdges.at(-1) : void 0;
1484
1778
  return {
1485
1779
  ...ifDefined("failedTypeChange", failedTypeChange === void 0 ? void 0 : failedTypeChangeReport(failedTypeChange, fieldText(failedTypeChange.field))),
1486
1780
  ...ifDefined("rowsWithoutValue", rowsWithoutValue?.map(({ field, reason }) => ({
@@ -1493,21 +1787,23 @@ function failureReports(failure, resolutions) {
1493
1787
  })
1494
1788
  };
1495
1789
  }
1496
- /** The issues of a failed schema check after apply; a check that reported none counts as no issues. */
1497
- function schemaIssuesOf(failure) {
1498
- const issues = failure.schemaIssues;
1499
- return issues === void 0 || issues.length === 0 ? void 0 : issues;
1500
- }
1501
1790
  function failedPrecheckOf(failure, resolutions) {
1502
- const check = failure.failedCheck;
1503
- if (check === void 0 || check.phase !== "precheck" || failure.why !== void 0) return;
1504
- const resolution = resolutions.find(({ spaceId }) => spaceId === failure.failingSpace);
1791
+ const check = failure.meta.failedCheck;
1792
+ if (check === void 0 || check.phase !== "precheck") return;
1793
+ const resolution = resolutions.find(({ spaceId }) => spaceId === failure.meta.failingSpace);
1505
1794
  return {
1506
1795
  operationId: check.operationId,
1507
1796
  description: check.description,
1508
1797
  planStartsFromMarker: resolution !== void 0 && resolution.entry.plan.origin !== null
1509
1798
  };
1510
1799
  }
1800
+ /** The facts the advice for `failure` names, found in the plans of `resolutions`. */
1801
+ function runnerFailureFacts(failure, resolutions) {
1802
+ return {
1803
+ ...failureReports(failure, resolutions),
1804
+ ...ifDefined("failedPrecheck", failedPrecheckOf(failure, resolutions))
1805
+ };
1806
+ }
1511
1807
  /**
1512
1808
  * Runner-driving tail shared by every run caller — `db init`,
1513
1809
  * `db update`, and `migrate`. Consumes already-resolved per-space
@@ -1555,19 +1851,7 @@ async function runMigration(inputs) {
1555
1851
  spanId: RUN_SPAN_ID,
1556
1852
  outcome: "error"
1557
1853
  });
1558
- return notOk({
1559
- summary: runnerResult.failure.summary,
1560
- ...ifDefined("why", runnerResult.failure.why),
1561
- meta: {
1562
- ...runnerResult.failure.meta ?? {},
1563
- failingSpace: runnerResult.failure.failingSpace,
1564
- runnerErrorCode: runnerResult.failure.code
1565
- },
1566
- ...failureReports(runnerResult.failure, orderedResolutions),
1567
- ...ifDefined("failedPrecheck", failedPrecheckOf(runnerResult.failure, orderedResolutions)),
1568
- ...ifDefined("schemaIssues", schemaIssuesOf(runnerResult.failure)),
1569
- cause: runnerResult.failure
1570
- });
1854
+ return notOk(runnerResult.failure);
1571
1855
  }
1572
1856
  onProgress?.({
1573
1857
  action,
@@ -1758,7 +2042,12 @@ async function executeRun(options) {
1758
2042
  spanId: SPAN_IDS$1.plan,
1759
2043
  outcome: "error"
1760
2044
  });
1761
- return notOk(mapPlannerError(planned.failure));
2045
+ return notOk({ refused: mapPlannerError(planned.failure, {
2046
+ action,
2047
+ aggregate,
2048
+ markerRows,
2049
+ invocation: options.invocation
2050
+ }) });
1762
2051
  }
1763
2052
  onProgress?.({
1764
2053
  action,
@@ -1789,7 +2078,7 @@ async function executeRun(options) {
1789
2078
  });
1790
2079
  };
1791
2080
  const first = await plan(statements);
1792
- if (!first.ok) return first.failure;
2081
+ if (!first.ok) return notOk(first.failure.refused);
1793
2082
  let run = first.value;
1794
2083
  let plannedTexts = statementTexts.filter(isPlannedStatement);
1795
2084
  let consented = [];
@@ -1812,7 +2101,7 @@ async function executeRun(options) {
1812
2101
  });
1813
2102
  if (!answered.ok) {
1814
2103
  if (CliStructuredError$1.is(answered.failure)) throw answered.failure;
1815
- return answered.failure;
2104
+ return notOk(answered.failure.refused);
1816
2105
  }
1817
2106
  run = answered.value.plan;
1818
2107
  plannedTexts = answered.value.statements;
@@ -1832,6 +2121,7 @@ async function executeRun(options) {
1832
2121
  }
1833
2122
  const { planned, orderedResolutions } = run;
1834
2123
  const plannerWarnings = aggregatePlannerWarnings(orderedResolutions);
2124
+ if (plannerWarnings !== void 0) options.onPlannerWarnings?.(plannerWarnings);
1835
2125
  const appResolution = orderedResolutions.find((r) => r.spaceId === aggregate.app.spaceId);
1836
2126
  if (!appResolution) throw new InternalError("Aggregate planner returned no plan for the app space — the planner is supposed to always emit one.");
1837
2127
  const appPlan = appResolution.entry.plan;
@@ -1864,8 +2154,7 @@ async function executeRun(options) {
1864
2154
  summary,
1865
2155
  appliedStatements,
1866
2156
  subjects,
1867
- databaseStorageHash,
1868
- ...ifDefined("warnings", plannerWarnings)
2157
+ databaseStorageHash
1869
2158
  });
1870
2159
  }
1871
2160
  const applied = await runMigration({
@@ -1880,18 +2169,13 @@ async function executeRun(options) {
1880
2169
  action,
1881
2170
  ...ifDefined("onProgress", onProgress)
1882
2171
  });
1883
- if (!applied.ok) return buildRunnerFailure({
1884
- summary: applied.failure.summary,
1885
- ...ifDefined("why", applied.failure.why),
1886
- meta: applied.failure.meta,
1887
- ...ifDefined("warnings", plannerWarnings),
1888
- ...ifDefined("failedTypeChange", applied.failure.failedTypeChange),
1889
- ...ifDefined("rowsWithoutValue", applied.failure.rowsWithoutValue),
1890
- ...ifDefined("failedPrecheck", applied.failure.failedPrecheck),
1891
- ...ifDefined("schemaIssues", applied.failure.schemaIssues),
1892
- ...ifDefined("databaseStorageHash", databaseStorageHash),
1893
- ...ifDefined("cause", applied.failure.cause)
1894
- });
2172
+ if (!applied.ok) {
2173
+ const facts = runnerFailureFacts(applied.failure, orderedResolutions);
2174
+ return notOk(action === "dbInit" ? dbInitRunnerFailureError(applied.failure, facts, options.invocation) : dbUpdateRunnerFailureError(applied.failure, facts, {
2175
+ databaseStorageHash,
2176
+ invocation: options.invocation
2177
+ }));
2178
+ }
1895
2179
  const aggregateOps = applied.value.orderedResolutions.flatMap((r) => r.entry.displayOps);
1896
2180
  const summary = action === "dbInit" ? `Applied ${applied.value.totalOpsExecuted} operation(s) across ${applied.value.orderedResolutions.length} space(s), database signed` : applied.value.totalOpsExecuted === 0 ? `Database already matches contract across ${applied.value.orderedResolutions.length} space(s), signature updated` : `Applied ${applied.value.totalOpsExecuted} operation(s) across ${applied.value.orderedResolutions.length} space(s), signature updated`;
1897
2181
  return wrapApplyResult({
@@ -1903,8 +2187,7 @@ async function executeRun(options) {
1903
2187
  summary,
1904
2188
  appliedStatements,
1905
2189
  subjects,
1906
- databaseStorageHash,
1907
- ...ifDefined("warnings", plannerWarnings)
2190
+ databaseStorageHash
1908
2191
  });
1909
2192
  }
1910
2193
  /** The origin of a database whose marker names no readable contract: no models. */
@@ -2026,34 +2309,25 @@ function detectOrphanMarkers(aggregate, markerRows) {
2026
2309
  })) }
2027
2310
  });
2028
2311
  }
2029
- function mapPlannerError(error) {
2030
- if (error.kind === "planFromDiffFailed") return blindCast(notOk({
2031
- code: "PLANNING_FAILED",
2032
- summary: "Migration planning failed due to conflicts",
2033
- conflicts: error.conflicts,
2034
- why: void 0,
2035
- meta: void 0
2036
- }));
2037
- if (error.kind === "extensionPathUnreachable") return buildRunnerFailure({
2038
- summary: `Cannot resolve apply path for extension space "${error.spaceId}"`,
2039
- why: `No path in the on-disk migration graph for extension space "${error.spaceId}" reaches the on-disk head ref hash "${error.target}".`,
2040
- meta: {
2041
- spaceId: error.spaceId,
2042
- target: error.target
2043
- }
2044
- });
2045
- if (error.kind === "extensionPathUnsatisfiable") return buildRunnerFailure({
2046
- summary: `Cannot resolve apply path for extension space "${error.spaceId}"`,
2047
- why: `On-disk migration graph for extension space "${error.spaceId}" reaches the on-disk head ref but does not cover required invariants: ${error.missingInvariants.join(", ")}.`,
2048
- meta: {
2049
- spaceId: error.spaceId,
2050
- missingInvariants: error.missingInvariants
2051
- }
2052
- });
2053
- return buildRunnerFailure({
2054
- summary: `Aggregate planner policy conflict for space "${error.spaceId}"`,
2055
- why: error.detail,
2056
- meta: { spaceId: error.spaceId }
2312
+ function mapPlannerError(error, context) {
2313
+ if (error.kind === "planFromDiffFailed") return context.action === "dbInit" ? dbInitPlanningFailedError(error.conflicts) : errorMigrationPlanningFailed({ conflicts: error.conflicts });
2314
+ if (error.kind === "policyConflict") throw new InternalError(`The planner refused the planning policy db init and db update give it, which plans the app space from the diff and walks every extension space's graph: ${error.detail}`);
2315
+ const space = context.aggregate.extensions.find(({ spaceId }) => spaceId === error.spaceId);
2316
+ if (space === void 0) throw new InternalError(`The planner named extension space "${error.spaceId}", which the aggregate does not hold.`);
2317
+ const headRef = requireHeadRef(space);
2318
+ const unplannable = {
2319
+ spaceId: error.spaceId,
2320
+ fromHash: context.markerRows.get(error.spaceId)?.storageHash ?? "empty",
2321
+ targetHash: headRef.hash,
2322
+ command: context.action === "dbInit" ? "db init" : "db update",
2323
+ invocation: context.invocation
2324
+ };
2325
+ if (error.kind === "extensionPathUnreachable") return errorExtensionPathUnreachable(unplannable);
2326
+ return errorExtensionNoInvariantPath({
2327
+ ...unplannable,
2328
+ required: headRef.invariants,
2329
+ missing: error.missingInvariants,
2330
+ structuralPath: structuralPathOf(space.graph(), unplannable.fromHash, unplannable.targetHash)
2057
2331
  });
2058
2332
  }
2059
2333
  function wrapPlanResult(args) {
@@ -2071,8 +2345,7 @@ function wrapPlanResult(args) {
2071
2345
  ...ifDefined("profileHash", args.destination.profileHash)
2072
2346
  },
2073
2347
  perSpace: args.perSpace,
2074
- summary: args.summary,
2075
- ...ifDefined("warnings", args.warnings)
2348
+ summary: args.summary
2076
2349
  });
2077
2350
  }
2078
2351
  function wrapApplyResult(args) {
@@ -2095,26 +2368,9 @@ function wrapApplyResult(args) {
2095
2368
  profileHash: args.destination.profileHash
2096
2369
  } : { storageHash: args.destination.storageHash },
2097
2370
  perSpace: args.perSpace,
2098
- summary: args.summary,
2099
- ...ifDefined("warnings", args.warnings)
2371
+ summary: args.summary
2100
2372
  });
2101
2373
  }
2102
- function buildRunnerFailure(args) {
2103
- return blindCast(notOk({
2104
- code: "RUNNER_FAILED",
2105
- summary: args.summary,
2106
- why: args.why,
2107
- meta: args.meta,
2108
- conflicts: void 0,
2109
- ...ifDefined("warnings", args.warnings),
2110
- ...ifDefined("failedTypeChange", args.failedTypeChange),
2111
- ...ifDefined("rowsWithoutValue", args.rowsWithoutValue),
2112
- ...ifDefined("failedPrecheck", args.failedPrecheck),
2113
- ...ifDefined("schemaIssues", args.schemaIssues),
2114
- ...ifDefined("databaseStorageHash", args.databaseStorageHash),
2115
- ...ifDefined("cause", args.cause)
2116
- }));
2117
- }
2118
2374
  /**
2119
2375
  * The storage hash of the contract the application space's database is at, when the migration
2120
2376
  * graph has it: `migration plan --from` then resolves it. Without a migration that ends at it,
@@ -2144,8 +2400,10 @@ async function executeDbInit(options) {
2144
2400
  targetId: options.targetId,
2145
2401
  extensions: options.extensions ?? [],
2146
2402
  policy: { allowedOperationClasses: ["additive"] },
2403
+ invocation: options.invocation,
2147
2404
  action: "dbInit",
2148
2405
  ...ifDefined("verifySnapshotContent", options.verifySnapshotContent),
2406
+ ...ifDefined("onPlannerWarnings", options.onPlannerWarnings),
2149
2407
  ...ifDefined("onProgress", options.onProgress)
2150
2408
  });
2151
2409
  }
@@ -2457,11 +2715,6 @@ async function signContractSpaces(options) {
2457
2715
  };
2458
2716
  }) });
2459
2717
  }
2460
- const DB_UPDATE_POLICY = { allowedOperationClasses: [
2461
- "additive",
2462
- "widening",
2463
- "destructive"
2464
- ] };
2465
2718
  /** Execute `db update` against the configured contract. */
2466
2719
  async function executeDbUpdate(options) {
2467
2720
  const statements = options.statements ?? [];
@@ -2477,6 +2730,7 @@ async function executeDbUpdate(options) {
2477
2730
  targetId: options.targetId,
2478
2731
  extensions: options.extensions ?? [],
2479
2732
  policy: DB_UPDATE_POLICY,
2733
+ invocation: options.invocation,
2480
2734
  action: "dbUpdate",
2481
2735
  mode: options.mode,
2482
2736
  statements: options.statements ?? [],
@@ -2484,6 +2738,7 @@ async function executeDbUpdate(options) {
2484
2738
  acceptDataLoss: options.acceptDataLoss ?? false,
2485
2739
  acceptAccessWidening: options.acceptAccessWidening ?? false,
2486
2740
  ...ifDefined("verifySnapshotContent", options.verifySnapshotContent),
2741
+ ...ifDefined("onPlannerWarnings", options.onPlannerWarnings),
2487
2742
  ...ifDefined("onProgress", options.onProgress)
2488
2743
  });
2489
2744
  }
@@ -2705,6 +2960,13 @@ async function loadContractSource(config, options = {}) {
2705
2960
  });
2706
2961
  }
2707
2962
  /**
2963
+ * A failed `db migrate` apply as the CLI reports it; its advice prints paths and commands that work
2964
+ * from where the CLI ran, with the `--config` it was given.
2965
+ */
2966
+ function migrateRunnerFailureError(failure, facts, failedMigration, invocation) {
2967
+ return runnerFailureError(failure, { fix: migrateFix(failure, facts, failedMigration, invocation) });
2968
+ }
2969
+ /**
2708
2970
  * Apply pending migrations across every contract space (app +
2709
2971
  * extensions). Replay-only: graph-walk against the on-disk graph for
2710
2972
  * every contract space; no synth, no introspection.
@@ -2764,22 +3026,14 @@ async function executeMigrate(options) {
2764
3026
  }
2765
3027
  if (outcome.kind === "never-planned") return notOk(buildNeverPlannedFailure(outcome.spaceId, outcome.targetHash, migrationsDir));
2766
3028
  if (outcome.kind === "unreachable") return notOk(buildPathNotFoundFailure(outcome.spaceId, outcome.liveMarker, outcome.targetHash));
2767
- if (outcome.kind === "unsatisfiable") {
2768
- const structural = findPathWithDecision(outcome.targetSpace.graph(), outcome.liveHash, spaceTargetHash, { required: /* @__PURE__ */ new Set() });
2769
- const structuralPath = structural.kind === "ok" ? structural.decision.selectedPath.map((edge) => ({
2770
- dirName: edge.dirName,
2771
- migrationHash: edge.migrationHash,
2772
- from: edge.from,
2773
- to: edge.to,
2774
- invariants: edge.invariants
2775
- })) : [];
2776
- throw errorNoInvariantPath({
2777
- ...outcome.refName !== void 0 ? { refName: outcome.refName } : {},
2778
- required: outcome.targetInvariants,
2779
- missing: outcome.missing,
2780
- structuralPath
2781
- });
2782
- }
3029
+ if (outcome.kind === "unsatisfiable") throw noInvariantPathError({
3030
+ graph: outcome.targetSpace.graph(),
3031
+ fromHash: outcome.liveHash,
3032
+ targetHash: spaceTargetHash,
3033
+ required: outcome.targetInvariants,
3034
+ missing: outcome.missing,
3035
+ ...outcome.refName !== void 0 ? { refName: outcome.refName } : {}
3036
+ });
2783
3037
  if (leavesUnmarkedSpaceUntouched(outcome.plan)) plansKeptFromRunner.set(space.spaceId, outcome.plan);
2784
3038
  else perSpacePlans.set(space.spaceId, outcome.plan);
2785
3039
  }
@@ -2824,18 +3078,10 @@ async function executeMigrate(options) {
2824
3078
  action: "migrate",
2825
3079
  ...ifDefined("onProgress", onProgress)
2826
3080
  });
2827
- if (!applied.ok) return notOk({
2828
- code: "RUNNER_FAILED",
2829
- summary: applied.failure.summary,
2830
- why: applied.failure.why,
2831
- meta: applied.failure.meta,
2832
- ...ifDefined("failedTypeChange", applied.failure.failedTypeChange),
2833
- ...ifDefined("rowsWithoutValue", applied.failure.rowsWithoutValue),
2834
- ...ifDefined("failedPrecheck", applied.failure.failedPrecheck),
2835
- ...ifDefined("schemaIssues", applied.failure.schemaIssues),
2836
- ...ifDefined("failedMigration", applied.failure.failedMigration === void 0 ? void 0 : failedMigrationOnDisk(applied.failure.failedMigration, migrationsDir)),
2837
- ...ifDefined("cause", applied.failure.cause)
2838
- });
3081
+ if (!applied.ok) {
3082
+ const facts = runnerFailureFacts(applied.failure, collectOrdered(applyOrder, perSpacePlans));
3083
+ return notOk(migrateRunnerFailureError(applied.failure, facts, facts.failedMigration === void 0 ? void 0 : failedMigrationOnDisk(facts.failedMigration, migrationsDir), options.invocation));
3084
+ }
2839
3085
  const orderedAll = canonicalOrder.filter((spaceId) => perSpacePlans.has(spaceId) || plansKeptFromRunner.has(spaceId)).map((spaceId) => {
2840
3086
  if (perSpacePlans.has(spaceId)) {
2841
3087
  const fromRunner = applied.value.orderedResolutions.find((r) => r.spaceId === spaceId);
@@ -3050,16 +3296,15 @@ function buildSuccess(args) {
3050
3296
  * @internal Exported for testing only.
3051
3297
  */
3052
3298
  function buildNeverPlannedFailure(spaceId, targetHash, migrationsDir) {
3053
- return {
3054
- code: "MIGRATION_PATH_NOT_FOUND",
3299
+ return errorPathUnreachable({
3055
3300
  summary: `No on-disk migrations for contract space "${spaceId}"`,
3056
3301
  why: `migrate is replay-only: a contract space that declares managed storage elements must have an authored migration graph on disk. Space "${spaceId}" has no migrations under \`${migrationsDir}/${spaceId}/\` but its head ref targets "${targetHash}".`,
3057
3302
  meta: {
3058
3303
  spaceId,
3059
- target: targetHash,
3304
+ targetHash,
3060
3305
  kind: "neverPlanned"
3061
3306
  }
3062
- };
3307
+ });
3063
3308
  }
3064
3309
  /**
3065
3310
  * Build the `pathUnreachable` failure raised when an emitted contract has no
@@ -3072,18 +3317,18 @@ function buildNeverPlannedFailure(spaceId, targetHash, migrationsDir) {
3072
3317
  * @internal Exported for testing only.
3073
3318
  */
3074
3319
  function buildPathNotFoundFailure(spaceId, marker, targetHash) {
3075
- const fromHash = marker?.storageHash ?? "<empty>";
3076
- return {
3077
- code: "MIGRATION_PATH_NOT_FOUND",
3320
+ const fromHash = marker?.storageHash ?? "empty";
3321
+ const fromText = marker === null ? "the empty contract" : `the current state "${fromHash}"`;
3322
+ return errorPathUnreachable({
3078
3323
  summary: spaceId === "app" ? "Current contract has no planned migration path" : `Current contract has no planned migration path for contract space "${spaceId}"`,
3079
- why: `No migration edge connects the current state "${fromHash}" to the target "${targetHash}" in contract space "${spaceId}". The on-disk migration graph does not join the two, and migrate replays existing edges — it never invents one.`,
3324
+ why: `No migration edge connects ${fromText} to the target "${targetHash}" in contract space "${spaceId}". The on-disk migration graph does not join the two, and migrate replays existing edges — it never invents one.`,
3080
3325
  meta: {
3081
3326
  spaceId,
3082
3327
  fromHash,
3083
3328
  targetHash,
3084
3329
  kind: "pathUnreachable"
3085
3330
  }
3086
- };
3331
+ });
3087
3332
  }
3088
3333
  function failedMigrationOnDisk(failed, migrationsDir) {
3089
3334
  return {
@@ -3310,6 +3555,8 @@ var ControlClientImpl = class {
3310
3555
  }
3311
3556
  return executeDbInit({
3312
3557
  driver,
3558
+ invocation: options.invocation,
3559
+ ...ifDefined("onPlannerWarnings", options.onPlannerWarnings),
3313
3560
  adapter,
3314
3561
  familyInstance,
3315
3562
  contract,
@@ -3340,6 +3587,8 @@ var ControlClientImpl = class {
3340
3587
  }
3341
3588
  return executeDbUpdate({
3342
3589
  driver,
3590
+ invocation: options.invocation,
3591
+ ...ifDefined("onPlannerWarnings", options.onPlannerWarnings),
3343
3592
  adapter,
3344
3593
  familyInstance,
3345
3594
  contract,
@@ -3427,6 +3676,7 @@ var ControlClientImpl = class {
3427
3676
  }
3428
3677
  return executeMigrate({
3429
3678
  driver,
3679
+ invocation: options.invocation,
3430
3680
  familyInstance,
3431
3681
  contract,
3432
3682
  migrations: this.options.target.migrations,
@@ -4453,25 +4703,24 @@ async function executeMigrateShowPlan(options) {
4453
4703
  });
4454
4704
  if (outcome.kind === "at-head") continue;
4455
4705
  if (outcome.kind === "never-planned") return notOk(errorPathUnreachable({
4456
- code: "MIGRATION_PATH_NOT_FOUND",
4457
4706
  summary: `No on-disk migrations for contract space "${outcome.spaceId}"`,
4458
4707
  why: `migrate is replay-only: space "${outcome.spaceId}" has no on-disk migrations but its head ref targets "${outcome.targetHash}".`,
4459
4708
  meta: {
4460
4709
  spaceId: outcome.spaceId,
4461
- target: outcome.targetHash,
4710
+ targetHash: outcome.targetHash,
4462
4711
  kind: "neverPlanned"
4463
4712
  }
4464
4713
  }));
4465
4714
  if (outcome.kind === "unreachable") {
4466
4715
  const fromHash = outcome.liveMarker?.storageHash ?? "empty";
4467
4716
  return notOk(errorPathUnreachable({
4468
- code: "MIGRATION_PATH_NOT_FOUND",
4469
4717
  summary: `No migration path from ${fromHash.slice(0, 14)} to ${outcome.targetHash.slice(0, 14)} in space "${outcome.spaceId}".`,
4470
4718
  why: `The migration graph has no path from the from-state to the target in space "${outcome.spaceId}".`,
4471
4719
  meta: {
4472
4720
  spaceId: outcome.spaceId,
4473
- from: fromHash,
4474
- to: outcome.targetHash
4721
+ fromHash,
4722
+ targetHash: outcome.targetHash,
4723
+ kind: "pathUnreachable"
4475
4724
  }
4476
4725
  }));
4477
4726
  }
@@ -6131,6 +6380,6 @@ async function executeRefListCommand(options) {
6131
6380
  }
6132
6381
  }
6133
6382
  //#endregion
6134
- export { refuseMarkerOutsideGraph as $, executeRefAdvancement as A, loadAggregateIntegrityViolations as B, executeDbInit as C, executeMigrateShowPlan as D, executeDbVerify as E, formatSourceDiagnostic as F, looksLikePath as G, loadContractSource as H, hasMigrationPath as I, migrationSpaceListEntriesFromAggregate as J, mapContractAtError as K, isStatementVerb as L, executeRefListCommand as M, executeRefSetCommand as N, executeMigrationNewCommand as O, findPackageByDirPath as P, refuseDeclaredExtensionTargetMismatch as Q, listRefsByContractHash as R, executeContractEmit as S, executeDbUpdate as T, loadContractSourceWithStack as U, loadContractRawSafely as V, loadContractSpaceAggregateForCli as W, readMigrationRefs as X, preflightRefAdvancement as Y, refuseContractSpaceIntegrity as Z, createControlClient as _, statusForMigrationHash as _t, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as a, resolveContractRef$1 as at, enrichContract as b, appliedHashesFromLedger as c, resolveMigrationRef as ct, buildReadAggregate as d, retryCommandFor as dt, refuseMissingInvariantPath as et, buildRefAdvancementFields as f, runContractSpaceSeedPhase as ft, convertAndDelete as g, sourceWarningDiagnostic as gt, contractValidationMeta as h, snapshotVerifierFor as ht, RECORDED_CONTRACT_REF_FORMS as i, resolveAppTargetPath as it, executeRefDeleteCommand as j, executeMigrationPlanCommand as k, buildContractSpaceAggregate as l, resolveStatements as lt, computeRefAdvancementName as m, runMigrationList as mt, DB_UPDATE_POLICY as n, refuseUnknownInvariants as nt, advanceRefSafely as o, resolveContractRefToSnapshot as ot, checkSingleTarget as p, runMigrationCheck as pt, mapIntegrityViolations as q, NO_REF_ADVANCEMENT as r, requireDatabaseForLiveMarkerUse as rt, appContractStandInFromIdentity as s, resolveFromForPlan as st, ALL_CONTRACT_REF_FORMS as t, refusePackageCorruptionOnAggregate as tt, buildMigrationSpaceGraphEntries as u, resolveToForPlan as ut, deriveStatusEdgeAnnotations as v, toDeclaredExtensionsFromRaw as vt, executeDbSign as w, enumerateCheckSpaces as x, disposeEmitQueue as y, validateLoadedContract as yt, liveMarkerUse as z };
6383
+ export { refuseMissingInvariantPath as $, executeRefDeleteCommand as A, loadContractRawSafely as B, executeDbSign as C, executeMigrationNewCommand as D, executeMigrateShowPlan as E, hasMigrationPath as F, mapContractAtError as G, loadContractSourceWithStack as H, isStatementVerb as I, preflightRefAdvancement as J, mapIntegrityViolations as K, listRefsByContractHash as L, executeRefSetCommand as M, findPackageByDirPath as N, executeMigrationPlanCommand as O, formatSourceDiagnostic as P, refuseMarkerOutsideGraph as Q, liveMarkerUse as R, executeDbInit as S, executeDbVerify as T, loadContractSpaceAggregateForCli as U, loadContractSource as V, looksLikePath as W, refuseContractSpaceIntegrity as X, readMigrationRefs as Y, refuseDeclaredExtensionTargetMismatch as Z, deriveStatusEdgeAnnotations as _, toDeclaredExtensionsFromRaw as _t, advanceRefSafely as a, resolveContractRefToSnapshot as at, enumerateCheckSpaces as b, buildContractSpaceAggregate as c, resolveStatements as ct, buildRefAdvancementFields as d, runContractSpaceSeedPhase as dt, refusePackageCorruptionOnAggregate as et, checkSingleTarget as f, runMigrationCheck as ft, createControlClient as g, statusForMigrationHash as gt, convertAndDelete as h, sourceWarningDiagnostic as ht, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as i, resolveContractRef$1 as it, executeRefListCommand as j, executeRefAdvancement as k, buildMigrationSpaceGraphEntries as l, resolveToForPlan as lt, contractValidationMeta as m, snapshotVerifierFor as mt, NO_REF_ADVANCEMENT as n, requireDatabaseForLiveMarkerUse as nt, appContractStandInFromIdentity as o, resolveFromForPlan as ot, computeRefAdvancementName as p, runMigrationList as pt, migrationSpaceListEntriesFromAggregate as q, RECORDED_CONTRACT_REF_FORMS as r, resolveAppTargetPath as rt, appliedHashesFromLedger as s, resolveMigrationRef as st, ALL_CONTRACT_REF_FORMS as t, refuseUnknownInvariants as tt, buildReadAggregate as u, retryCommandFor as ut, disposeEmitQueue as v, validateLoadedContract as vt, executeDbUpdate as w, executeContractEmit as x, enrichContract as y, loadAggregateIntegrityViolations as z };
6135
6384
 
6136
- //# sourceMappingURL=ref-Bn3SzQ9Z-DHi9xcRa.mjs.map
6385
+ //# sourceMappingURL=ref-DLqjHXyn-CsLViutC.mjs.map