@prisma/orm-toolchain 8.0.0-rc.24-dev.23 → 8.0.0-rc.24-dev.24

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 (74) hide show
  1. package/dist/{aggregate-BmhAhXYL.d.mts → aggregate-C6PGBKyb.d.mts} +7 -3
  2. package/dist/aggregate-C6PGBKyb.d.mts.map +1 -0
  3. package/dist/{aggregate-BIjV2dM9.mjs → aggregate-CRIdmKmq.mjs} +12 -8
  4. package/dist/aggregate-CRIdmKmq.mjs.map +1 -0
  5. package/dist/{caught-errors-Cll-zcA1-MXR0HE1V.mjs → caught-errors-I1l50iPc-D_-F2M3t.mjs} +21 -5
  6. package/dist/caught-errors-I1l50iPc-D_-F2M3t.mjs.map +1 -0
  7. package/dist/cli.d.mts +1 -1
  8. package/dist/cli.mjs +187 -67
  9. package/dist/cli.mjs.map +1 -1
  10. package/dist/cli__control-api.d.mts +17 -5
  11. package/dist/cli__control-api.d.mts.map +1 -1
  12. package/dist/cli__control-api.mjs +2 -2
  13. package/dist/cli__control-api__testing.d.mts +1 -1
  14. package/dist/cli__migration-cli.mjs +3 -3
  15. package/dist/cli__migration-cli.mjs.map +1 -1
  16. package/dist/{contract-snapshot-store-nWnsWPPQ-rJ94UCcE.mjs → contract-snapshot-store-B0fRbVHB-BN2g8BKh.mjs} +3 -3
  17. package/dist/{contract-snapshot-store-nWnsWPPQ-rJ94UCcE.mjs.map → contract-snapshot-store-B0fRbVHB-BN2g8BKh.mjs.map} +1 -1
  18. package/dist/{db-sign-DGSaPRQ--B_9CmDng.d.mts → db-sign-Bv-FZMAD-uQhMNCC7.d.mts} +42 -26
  19. package/dist/db-sign-Bv-FZMAD-uQhMNCC7.d.mts.map +1 -0
  20. package/dist/{errors-DXha_4l--relAaiI4.mjs → errors-BMq40nYH-Cg8PBect.mjs} +33 -4
  21. package/dist/errors-BMq40nYH-Cg8PBect.mjs.map +1 -0
  22. package/dist/{errors-CLwhWJiz.d.mts → errors-oP9FaWWm.d.mts} +5 -2
  23. package/dist/errors-oP9FaWWm.d.mts.map +1 -0
  24. package/dist/{graph-membership-DxpNgxfZ-BfqA-H7V.mjs → graph-membership-D7m41lWA-B68g1CRS.mjs} +3 -3
  25. package/dist/{graph-membership-DxpNgxfZ-BfqA-H7V.mjs.map → graph-membership-D7m41lWA-B68g1CRS.mjs.map} +1 -1
  26. package/dist/{invariants-DrF9p5Gd-BF70vGl1.mjs → invariants-DxCj82g2-DhGkStla.mjs} +3 -3
  27. package/dist/{invariants-DrF9p5Gd-BF70vGl1.mjs.map → invariants-DxCj82g2-DhGkStla.mjs.map} +1 -1
  28. package/dist/{io-4O31S6Ei-DvsFKW_Y.mjs → io-B39zsxMm-D5Wcf6cf.mjs} +5 -5
  29. package/dist/{io-4O31S6Ei-DvsFKW_Y.mjs.map → io-B39zsxMm-D5Wcf6cf.mjs.map} +1 -1
  30. package/dist/{migration-CWyjX9vz.mjs → migration-DTmtOJ0n.mjs} +3 -3
  31. package/dist/{migration-CWyjX9vz.mjs.map → migration-DTmtOJ0n.mjs.map} +1 -1
  32. package/dist/migration-tools.d.mts +6 -5
  33. package/dist/migration-tools.mjs +12 -12
  34. package/dist/migration-tools__aggregate.d.mts +1 -1
  35. package/dist/migration-tools__aggregate.mjs +1 -1
  36. package/dist/migration-tools__contract-snapshot-store.mjs +1 -1
  37. package/dist/migration-tools__errors.d.mts +2 -2
  38. package/dist/migration-tools__errors.mjs +2 -2
  39. package/dist/migration-tools__invariants.mjs +1 -1
  40. package/dist/migration-tools__io.mjs +1 -1
  41. package/dist/migration-tools__migration-graph.mjs +1 -1
  42. package/dist/migration-tools__migration.mjs +1 -1
  43. package/dist/migration-tools__ref-resolution.d.mts +1 -1
  44. package/dist/migration-tools__ref-resolution.mjs +1 -1
  45. package/dist/migration-tools__refs.d.mts +3 -2
  46. package/dist/migration-tools__refs.mjs +2 -2
  47. package/dist/migration-tools__spaces.mjs +2 -2
  48. package/dist/{ref-D4GWEHQU-BOqb4i_E.mjs → ref-DfuqRCA7-CPPoVHY9.mjs} +459 -101
  49. package/dist/ref-DfuqRCA7-CPPoVHY9.mjs.map +1 -0
  50. package/dist/{ref-resolution-Eo0QHp4f.mjs → ref-resolution-C9j2SSb6.mjs} +2 -2
  51. package/dist/{ref-resolution-Eo0QHp4f.mjs.map → ref-resolution-C9j2SSb6.mjs.map} +1 -1
  52. package/dist/{ref-resolution-BPhR-kta.d.mts → ref-resolution-UwnXbc9M.d.mts} +2 -2
  53. package/dist/{ref-resolution-BPhR-kta.d.mts.map → ref-resolution-UwnXbc9M.d.mts.map} +1 -1
  54. package/dist/refs-B5N_vHH7.d.mts +1 -0
  55. package/dist/{refs-BNCUu58Y-BIso5Jfg.d.mts → refs-CkGjbosE-CLkrSkQ4.d.mts} +18 -3
  56. package/dist/refs-CkGjbosE-CLkrSkQ4.d.mts.map +1 -0
  57. package/dist/{refs-DM3q3IZC-BC6H6P0X.mjs → refs-t_JbIjGo-CRpBRRkq.mjs} +79 -20
  58. package/dist/refs-t_JbIjGo-CRpBRRkq.mjs.map +1 -0
  59. package/dist/{spaces-BIABdklg.mjs → spaces-OVZ0QzWJ.mjs} +5 -5
  60. package/dist/{spaces-BIABdklg.mjs.map → spaces-OVZ0QzWJ.mjs.map} +1 -1
  61. package/dist/{verify-contract-spaces-BmnQiKDj-JwT2fAPh.mjs → verify-contract-spaces-BOnqhfQs-BBq5YOKo.mjs} +11 -7
  62. package/dist/verify-contract-spaces-BOnqhfQs-BBq5YOKo.mjs.map +1 -0
  63. package/dist/vite-plugin-contract-emit.mjs +1 -1
  64. package/package.json +12 -12
  65. package/dist/aggregate-BIjV2dM9.mjs.map +0 -1
  66. package/dist/aggregate-BmhAhXYL.d.mts.map +0 -1
  67. package/dist/caught-errors-Cll-zcA1-MXR0HE1V.mjs.map +0 -1
  68. package/dist/db-sign-DGSaPRQ--B_9CmDng.d.mts.map +0 -1
  69. package/dist/errors-CLwhWJiz.d.mts.map +0 -1
  70. package/dist/errors-DXha_4l--relAaiI4.mjs.map +0 -1
  71. package/dist/ref-D4GWEHQU-BOqb4i_E.mjs.map +0 -1
  72. package/dist/refs-BNCUu58Y-BIso5Jfg.d.mts.map +0 -1
  73. package/dist/refs-DM3q3IZC-BC6H6P0X.mjs.map +0 -1
  74. package/dist/verify-contract-spaces-BmnQiKDj-JwT2fAPh.mjs.map +0 -1
@@ -1,28 +1,29 @@
1
1
  import { a as expandContractInputs } from "./exports-CSVHjfwG.mjs";
2
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";
3
+ import { D as errorNoInvariantPath, M as errorUnknownInvariant, b as errorInvalidRefName, r as errorContractDeserializationFailed, t as MigrationToolsError, y as errorInvalidRefFile } from "./errors-BMq40nYH-Cg8PBect.mjs";
4
4
  import { r as verifyMigrationHash, t as computeMigrationHash } from "./hash-BAZVWU4a-BQovI7hF.mjs";
5
- import { c as writeContractSnapshot, i as readContractSnapshotJson, r as createSnapshotContentVerifier, s as snapshotsImportPathFrom, t as contractSnapshotDir } from "./contract-snapshot-store-nWnsWPPQ-rJ94UCcE.mjs";
6
- import { t as deriveProvidedInvariants } from "./invariants-DrF9p5Gd-BF70vGl1.mjs";
7
- import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigrationDirName, u as writeMigrationPackage } from "./io-4O31S6Ei-DvsFKW_Y.mjs";
5
+ import { c as writeContractSnapshot, i as readContractSnapshotJson, r as createSnapshotContentVerifier, s as snapshotsImportPathFrom, t as contractSnapshotDir } from "./contract-snapshot-store-B0fRbVHB-BN2g8BKh.mjs";
6
+ import { t as deriveProvidedInvariants } from "./invariants-DxCj82g2-DhGkStla.mjs";
7
+ import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigrationDirName, u as writeMigrationPackage } from "./io-B39zsxMm-D5Wcf6cf.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-BmnQiKDj-JwT2fAPh.mjs";
10
- import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-BIABdklg.mjs";
11
- import { $ as errorTargetMigrationNotSupported, B as errorRefSetBundleNotFound, D as errorFromCaught, E as errorFileNotFound, G as errorSnapshotMissing, H as errorRefSetHashNotInGraph, I as errorPathUnreachable, J as errorStatementDidNotResolveLoss, K as errorSpaceNotFound, L as errorPlanForgotTheFlag, M as errorMigrationHasUnfilledPlaceholders, P as errorMigrationPlanningFailed, Q as errorStatementUnresolved, R as errorPlanOriginUnknown, S as errorContractValidationFailed, U as errorRuntime, V as errorRefSetEmptySentinel, X as errorStatementNeedsMigrationFile, Y as errorStatementInvalid, Z as errorStatementOriginUnknown, _ as errorAmbiguousMigrationRef, at as migrationsDirFor, c as cliCommand, ct as readContractEnvelope, d as closeQuietly, dt as resolveContractPath, f as collectDeclaredInvariants, ft as resolveMigrationPaths, gt as statementFlag, h as editFileAction, k as errorInvalidSpaceId, l as cliErrorFromStructured, mt as selfEmitCommand, n as CliStructuredError$1, nt as getTargetMigrations, ot as printedPath, pt as runCommandAction, q as errorStatementAnswersNoQuestion, r as STORE_ORIGIN_SNAPSHOT_STEPS, rt as mapRefResolutionError, s as chooseAction, st as printedPlanCommand, t as ActionableCliError, tt as errorUnexpected, ut as requireLiveDatabase, v as errorConfigValidation$1, vt as toStructuralEdge, x as errorContractConfigMissing, y as errorConsentUnused, yt as writtenMigrationRunCommand, z as errorPlanProducedNoOperations } from "./caught-errors-Cll-zcA1-MXR0HE1V.mjs";
9
+ import { c as readContractSpaceHeadRef, l as spaceMigrationDirectory, o as isValidSpaceId, s as listContractSpaceDirectories, t as APP_SPACE_ID$1, u as spaceRefsDirectory } from "./verify-contract-spaces-BOnqhfQs-BBq5YOKo.mjs";
10
+ import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-OVZ0QzWJ.mjs";
11
+ import { $ as errorStatementOriginUnknown, B as errorPlanOriginUnknown, C as errorContractConfigMissing, G as errorRuntime, H as errorRefSetBundleNotFound, I as errorMigrationPlanningFailed, J as errorSpaceNotFound, O as errorFileNotFound, P as errorMigrationHasUnfilledPlaceholders, Q as errorStatementNeedsMigrationFile, R as errorPathUnreachable, St as writtenMigrationRunCommand, U as errorRefSetEmptySentinel, V as errorPlanProducedNoOperations, W as errorRefSetHashNotInGraph, X as errorStatementDidNotResolveLoss, Y as errorStatementAnswersNoQuestion, Z as errorStatementInvalid, _ as editFileAction, _t as selfEmitCommand, at as mapRefResolutionError, b as errorConfigValidation$1, c as cliCommand, ct as printedPath, d as closeQuietly, et as errorStatementUnresolved, f as collectDeclaredInvariants, ft as requireLiveDatabase, gt as runCommandAction, h as dbUpdateRerun, ht as resolveMigrationPaths, it as getTargetMigrations, j as errorInvalidSpaceId, k as errorFromCaught, l as cliErrorFromStructured, lt as printedPlanCommand, m as dbMigrateRerun, mt as resolveContractPath, n as CliStructuredError$1, q as errorSnapshotMissing, r as STORE_ORIGIN_SNAPSHOT_STEPS, rt as errorUnexpected, s as chooseAction, st as migrationsDirFor, t as ActionableCliError, tt as errorTargetMigrationNotSupported, ut as readContractEnvelope, vt as shellQuoted, w as errorContractValidationFailed, x as errorConsentUnused, xt as toStructuralEdge, y as errorAmbiguousMigrationRef, yt as statementFlag, z as errorPlanForgotTheFlag } from "./caught-errors-I1l50iPc-D_-F2M3t.mjs";
12
12
  import { r as getEmittedArtifactPaths, t as emit } from "./exports-CVgs3YWV-BF4rqnxF.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-BIjV2dM9.mjs";
13
+ import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-D7m41lWA-B68g1CRS.mjs";
14
+ import { a as readRefs, d as validateRefValue, n as advanceRef, r as deleteRef, s as refsByContractHash, t as HEAD_REF_NAME, u as validateRefName } from "./refs-t_JbIjGo-CRpBRRkq.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-CRIdmKmq.mjs";
16
16
  import { a as writeMigrationTs, n as formatMigrationTs } from "./migration-ts-DDgjsR1O.mjs";
17
17
  import { c as internalImportRoot, o as importRootForDependencies, r as createImportSpecifierResolver, t as ImportRootError } from "./import-roots-Dqs1_cn4.mjs";
18
- 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
+ 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-C9j2SSb6.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
- import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, describeMigrationStatement, enumValueCoordinateFromJson, enumValueStatementText, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, planOriginOf, valueObjectFieldStatementText } from "@prisma/orm-framework/components/control";
22
+ import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME, createControlStack, databasePoliciesOf, databasePolicyDifferences, databasePolicyValueText, describeMigrationStatement, enumValueCoordinateFromJson, enumValueStatementText, fieldStatementText, hasMigrations, hasOperationPreview, hasPslContractInfer, hasSchemaSubjectClassifier, hasSchemaView, isStorageHashHex, migrationStatementJson, migrationSubjectJson, migrationSubjectKey, modelDisplayName, modelStatementText, movedDatabasePoliciesWhy, planOriginOf, valueObjectFieldStatementText, withDeclaredDatabasePolicies } from "@prisma/orm-framework/components/control";
23
23
  import { InternalError } from "@prisma/orm-framework/utils/internal-error";
24
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
+ import { errorMarkerPoliciesCorrupt } from "@prisma/orm-framework/errors/execution";
26
27
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
27
28
  import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
28
29
  import { type } from "arktype";
@@ -36,7 +37,7 @@ import { isDeepStrictEqual } from "node:util";
36
37
  import { canonicalStringify } from "@prisma/orm-framework/utils/canonical-stringify";
37
38
  import { abortable } from "@prisma/orm-framework/utils/abortable";
38
39
  import { resolve as resolve$1 } from "node:path";
39
- //#region ../../../1-framework/3-tooling/cli/dist/ref-D4GWEHQU.mjs
40
+ //#region ../../../1-framework/3-tooling/cli/dist/ref-DfuqRCA7.mjs
40
41
  /**
41
42
  * 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.
42
43
  */
@@ -215,9 +216,8 @@ const DB_UPDATE_POLICY = { allowedOperationClasses: [
215
216
  ] };
216
217
  /** The way out of a failed check before an operation of `db migrate`. */
217
218
  function migrateFailedPrecheckAdvice(report, invocation) {
218
- const migrate = `\`${cliCommand(invocation, "db migrate")}\``;
219
- if (report.planStartsFromMarker) return [chooseAction(`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`)];
220
- return [runCommandAction(`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 instead`, cliCommand(invocation, "db sign"))];
219
+ if (report.planStartsFromMarker) return [chooseAction(`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 \`${dbMigrateRerun(invocation)}\` again`)];
220
+ return [runCommandAction(`The database has no migration marker, so \`${cliCommand(invocation, "db 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 instead`, cliCommand(invocation, "db sign"))];
221
221
  }
222
222
  /** The way out of a failed check before an operation of `db init`, which runs only on a database with no marker. */
223
223
  function dbInitFailedPrecheckAdvice(invocation) {
@@ -240,10 +240,14 @@ function failedTypeChangeText(change) {
240
240
  function quoted$1(command) {
241
241
  return `\`${command}\``;
242
242
  }
243
- /** A `db migrate` command as advice prints it. */
243
+ /** A `db migrate` command as advice prints it, for a migration that is not the one the user ran. */
244
244
  function dbMigrateCommand(invocation) {
245
245
  return quoted$1(cliCommand(invocation, "db migrate"));
246
246
  }
247
+ /** The `db migrate` the user ran, as advice that repeats it prints it. */
248
+ function dbMigrateAgain(invocation) {
249
+ return quoted$1(dbMigrateRerun(invocation));
250
+ }
247
251
  /** The steps after filling the migration.ts a `migration plan` wrote with no placeholders: run it, which writes its operations, and apply it. */
248
252
  function runWrittenFile(invocation) {
249
253
  return `run ${quoted$1(writtenMigrationRunCommand(invocation))} for the directory it writes, and apply it with ${dbMigrateCommand(invocation)}`;
@@ -268,7 +272,7 @@ function dbUpdateFailedTypeChangeAdvice(change, databaseStorageHash, invocation)
268
272
  verb: "convert",
269
273
  text: change.field
270
274
  })]);
271
- return [chooseAction(`${failedTypeChangeText(change)} Plan the change with ${quoted$1(plan)}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`), ...changeValueAdvice(change, quoted$1(cliCommand(invocation, "db update", invocation.rerunArgs ?? [])))];
275
+ return [chooseAction(`${failedTypeChangeText(change)} Plan the change with ${quoted$1(plan)}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`), ...changeValueAdvice(change, quoted$1(dbUpdateRerun(invocation)))];
272
276
  }
273
277
  /** The way out of rows without a value for `db update`, which plans and applies in one step. */
274
278
  function dbUpdateRowsWithoutValueAdvice(reports, databaseStorageHash, invocation) {
@@ -353,7 +357,7 @@ function dbUpdateRowsHoldingValueAdvice(reports, databaseStorageHash, invocation
353
357
  const others = otherStatements$1(invocation, reports);
354
358
  const deletes = deleteFlags(reports);
355
359
  const rename = chooseAction(`${newMember(reports, invocation)}, then run ${quoted$1(cliCommand(invocation, "db update", [...others, ...renameFlags(reports)]))}`);
356
- if (databaseStorageHash === void 0) return [rename, chooseAction(`To keep that data under another stored value, change ${storedValuesText(reports)} in the database yourself, then re-run ${quoted$1(cliCommand(invocation, "db update", [...others, ...deletes]))}`)];
360
+ if (databaseStorageHash === void 0) return [rename, chooseAction(`To keep that data under another stored value, change ${storedValuesText(reports)} in the database yourself, then re-run ${quoted$1(dbUpdateRerun(invocation, [...others, ...deletes]))}`)];
357
361
  const swaps = swapCalls(reports);
358
362
  if (swaps === void 0) return [rename];
359
363
  return [rename, chooseAction(`To keep that data by hand, plan the change with ${quoted$1(printedPlanCommand(invocation, databaseStorageHash, [...others, ...deletes]))}, make the edits below in the migration.ts it writes, ${KEPT_VALUE}, ${runWrittenFile(invocation)}.\n${swaps}`)];
@@ -361,7 +365,7 @@ function dbUpdateRowsHoldingValueAdvice(reports, databaseStorageHash, invocation
361
365
  function migrateRowsHoldingValueAdvice(reports, failedMigration, invocation) {
362
366
  const { file, run } = failedMigrationFile(failedMigration);
363
367
  const swaps = swapCalls(reports);
364
- const byHand = swaps === void 0 ? [] : [editFileAction(`To keep that data by hand, make the edits below in ${file}, ${KEPT_VALUE}, ${run}, and re-run ${dbMigrateCommand(invocation)}.\n${swaps}`)];
368
+ const byHand = swaps === void 0 ? [] : [editFileAction(`To keep that data by hand, make the edits below in ${file}, ${KEPT_VALUE}, ${run}, and re-run ${dbMigrateAgain(invocation)}.\n${swaps}`)];
365
369
  if (failedMigration === void 0) return byHand;
366
370
  return [replan(`${newMember(reports, invocation)}, delete`, renameFlags(reports), failedMigration, deleteFlags(reports).map((flag) => `\`${flag}\``).join(" or "), `put any code you copied into the migration.ts it writes, ${runWrittenFile(invocation)}`), ...byHand];
367
371
  }
@@ -377,7 +381,7 @@ function fixRowsFirst(report, rerun) {
377
381
  }
378
382
  /** The way out when existing rows fail a check `db update` adds: it cannot keep the data while the check it replaces holds. */
379
383
  function dbUpdateRowsFailingCheckAdvice(report, databaseStorageHash, invocation) {
380
- const update = cliCommand(invocation, "db update", invocation.rerunArgs ?? []);
384
+ const update = dbUpdateRerun(invocation);
381
385
  const { replacedCheck } = report;
382
386
  if (replacedCheck === void 0) return [fixRowsFirst(report, update)];
383
387
  const cannotKeep = `${quoted$1(cliCommand(invocation, "db update"))} cannot keep this data`;
@@ -386,9 +390,9 @@ function dbUpdateRowsFailingCheckAdvice(report, databaseStorageHash, invocation)
386
390
  }
387
391
  function migrateRowsFailingCheckAdvice(report, failedMigration, invocation) {
388
392
  const { replacedCheck } = report;
389
- if (replacedCheck === void 0) return [fixRowsFirst(report, cliCommand(invocation, "db migrate", invocation.rerunArgs ?? []))];
393
+ if (replacedCheck === void 0) return [fixRowsFirst(report, dbMigrateRerun(invocation))];
390
394
  const { file, run } = failedMigrationFile(failedMigration);
391
- return [editFileAction(`To keep the data, add ${updateOperation(report)} to ${file}, ${betweenTheChecks(report, replacedCheck)}, ${run}, and re-run ${dbMigrateCommand(invocation)}`)];
395
+ return [editFileAction(`To keep the data, add ${updateOperation(report)} to ${file}, ${betweenTheChecks(report, replacedCheck)}, ${run}, and re-run ${dbMigrateAgain(invocation)}`)];
392
396
  }
393
397
  /**
394
398
  * The way out of rows without a value for `db init`: a migration plan needs an origin contract,
@@ -412,7 +416,7 @@ function failedMigrationText(failed, invocation) {
412
416
  * Planning the failed migration again with `flags`. `opening` is the words before the directory,
413
417
  * so the sentence can start the advice or follow why it is needed.
414
418
  */
415
- function replan(opening, flags, failed, except = void 0, afterPlan = `fill in the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(failed.invocation)}`) {
419
+ function replan(opening, flags, failed, except = void 0, afterPlan = `fill in the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateAgain(failed.invocation)}`) {
416
420
  const others = except === void 0 ? OTHER_STATEMENTS : `${OTHER_STATEMENTS} except any ${except}`;
417
421
  const plan = printedPlanCommand(failed.invocation, failed.from, [
418
422
  "--name",
@@ -438,19 +442,19 @@ function failedMigrationFile(failedMigration) {
438
442
  function migrateFailedTypeChangeAdvice(change, failedMigration, invocation) {
439
443
  const changeText = failedTypeChangeText(change);
440
444
  const { file, run } = failedMigrationFile(failedMigration);
441
- if (change.by === "conversion") return [editFileAction(`${changeText} Fix the conversion in ${file}, ${run}, and re-run ${dbMigrateCommand(invocation)}`)];
445
+ if (change.by === "conversion") return [editFileAction(`${changeText} Fix the conversion in ${file}, ${run}, and re-run ${dbMigrateAgain(invocation)}`)];
442
446
  const convert = statementFlag({
443
447
  verb: "convert",
444
448
  text: change.field
445
449
  });
446
- if (failedMigration === void 0) return [chooseAction(`${changeText} Plan the type change again with ${quoted$1(printedPlanCommand(invocation, void 0, [convert]))}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateCommand(invocation)}`), ...changeValueAdvice(change, dbMigrateCommand(invocation))];
450
+ if (failedMigration === void 0) return [chooseAction(`${changeText} Plan the type change again with ${quoted$1(printedPlanCommand(invocation, void 0, [convert]))}, write the conversion in the migration.ts it writes, ${RUN_PLANNED_FILE}, and apply it with ${dbMigrateAgain(invocation)}`), ...changeValueAdvice(change, dbMigrateAgain(invocation))];
447
451
  const deleted = `\`${statementFlag({
448
452
  verb: "delete",
449
453
  text: change.field
450
454
  })}\``;
451
455
  return [
452
- editFileAction(`${changeText} ${file} changes field "${change.field}" ${change.reason === "noCast" ? "with a cast the database does not have between these types: replace it" : "with the database's cast, which met a value it cannot cast: replace that cast"} with your own conversion of the values there, ${run}, and re-run ${dbMigrateCommand(invocation)}`),
453
- ...changeValueAdvice(change, dbMigrateCommand(invocation)),
456
+ editFileAction(`${changeText} ${file} changes field "${change.field}" ${change.reason === "noCast" ? "with a cast the database does not have between these types: replace it" : "with the database's cast, which met a value it cannot cast: replace that cast"} with your own conversion of the values there, ${run}, and re-run ${dbMigrateAgain(invocation)}`),
457
+ ...changeValueAdvice(change, dbMigrateAgain(invocation)),
454
458
  replan("Delete", [convert], failedMigration, deleted)
455
459
  ];
456
460
  }
@@ -458,13 +462,13 @@ function migrateRowsWithoutValueAdvice(reports, failedMigration, invocation) {
458
462
  const [first] = reports;
459
463
  if (first?.reason === "backfillMissedRows") {
460
464
  const { file, run } = failedMigrationFile(failedMigration);
461
- return [editFileAction(`${first.field === void 0 ? "The backfill step" : `The backfill step of field "${first.field}"`} left those rows without a value. Make its run fill every row in ${file}, ${run}, and re-run ${dbMigrateCommand(invocation)}`)];
465
+ return [editFileAction(`${first.field === void 0 ? "The backfill step" : `The backfill step of field "${first.field}"`} left those rows without a value. Make its run fill every row in ${file}, ${run}, and re-run ${dbMigrateAgain(invocation)}`)];
462
466
  }
463
467
  const flags = backfillFlags(reports);
464
468
  const again = (opening) => flags.length === 0 || failedMigration === void 0 ? void 0 : replan(opening, flags, failedMigration);
465
469
  const one = reports.length === 1;
466
470
  if (reports.every(({ reason }) => reason === "nullValues")) {
467
- const rerun = chooseAction(one ? `Set a value in ${theRows(first?.rows ?? 0)} and re-run ${dbMigrateCommand(invocation)}` : `Set a value in the rows that hold NULL in each of ${fieldList(reports)} and re-run ${dbMigrateCommand(invocation)}`);
471
+ const rerun = chooseAction(one ? `Set a value in ${theRows(first?.rows ?? 0)} and re-run ${dbMigrateAgain(invocation)}` : `Set a value in the rows that hold NULL in each of ${fieldList(reports)} and re-run ${dbMigrateAgain(invocation)}`);
468
472
  const backfill = again("Delete");
469
473
  const fields = optionalFields(reports, one ? "the field" : "those fields");
470
474
  const keep = fields === void 0 ? [] : [failedMigration === void 0 ? editFileAction(`Keep ${fields.text} optional in the contract source, and plan the migration again`) : keepOptional(fields.text, fields.one ? "it" : "them", failedMigration, invocation)];
@@ -488,7 +492,7 @@ function migrateRowsWithoutValueAdvice(reports, failedMigration, invocation) {
488
492
  return [required, ...optional === void 0 ? [] : [editFileAction(`Make ${optional.text} optional in the contract source, and plan it again`)]];
489
493
  }
490
494
  function resolveTheCause(invocation) {
491
- return chooseAction(`Resolve the cause the failure names, then re-run \`${cliCommand(invocation, "db migrate", invocation.rerunArgs ?? [])}\``);
495
+ return chooseAction(`Resolve the cause the failure names, then re-run ${dbMigrateAgain(invocation)}`);
492
496
  }
493
497
  function keepOptional(fields, pronoun, failedMigration, invocation) {
494
498
  const plan = printedPlanCommand(invocation, failedMigration.from, ["--name", failedMigration.name]);
@@ -505,7 +509,7 @@ function migrateSchemaCheckAdvice(failedMigration, invocation) {
505
509
  const plan = printedPlanCommand(invocation, failedMigration?.from, failedMigration === void 0 ? [] : ["--name", failedMigration.name]);
506
510
  const directory = failedMigration === void 0 ? "the failed migration's directory" : `\`${failedMigration.directory}\``;
507
511
  const { file, run } = failedMigrationFile(failedMigration);
508
- return [editFileAction(`If the contract source does not describe the schema you want, change it to resolve the issues listed, re-run ${emit}, delete ${directory} (copy any code you wrote in its migration.ts first), plan it again with ${quoted$1(plan)}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(invocation)}`), editFileAction(`If ${file} does not reach its destination contract, for example after a hand edit, change its operations to resolve the issues listed, ${run}, and run ${dbMigrateCommand(invocation)}`)];
512
+ return [editFileAction(`If the contract source does not describe the schema you want, change it to resolve the issues listed, re-run ${emit}, delete ${directory} (copy any code you wrote in its migration.ts first), plan it again with ${quoted$1(plan)}, put any code you copied into the migration.ts it writes, ${RUN_PLANNED_FILE}, and run ${dbMigrateCommand(invocation)}`), editFileAction(`If ${file} does not reach its destination contract, for example after a hand edit, change its operations to resolve the issues listed, ${run}, and run ${dbMigrateAgain(invocation)}`)];
509
513
  }
510
514
  /** The way out when objects in the database keep an operation from running. */
511
515
  function blockingObjectsAdvice(objects, rerun) {
@@ -519,7 +523,7 @@ function blockingObjectsAdvice(objects, rerun) {
519
523
  function migrateAdvice(failure, facts, failedOnDisk, invocation) {
520
524
  const failedMigration = failedOnDisk === void 0 ? void 0 : failedMigrationText(failedOnDisk, invocation);
521
525
  const { blockingObjects } = failure.meta;
522
- if (blockingObjects !== void 0) return blockingObjectsAdvice(blockingObjects, cliCommand(invocation, "db migrate", invocation.rerunArgs ?? []));
526
+ if (blockingObjects !== void 0) return blockingObjectsAdvice(blockingObjects, dbMigrateRerun(invocation));
523
527
  if (facts.failedTypeChange !== void 0) return migrateFailedTypeChangeAdvice(facts.failedTypeChange, failedMigration, invocation);
524
528
  if (facts.rowsWithoutValue !== void 0) return migrateRowsWithoutValueAdvice(facts.rowsWithoutValue, failedMigration, invocation);
525
529
  if (facts.rowsHoldingValue !== void 0) return migrateRowsHoldingValueAdvice(facts.rowsHoldingValue, failedMigration, invocation);
@@ -599,7 +603,7 @@ function dbInitRunnerFailureError(failure, facts, invocation) {
599
603
  */
600
604
  function dbUpdateRunnerFailureError(failure, facts, context) {
601
605
  const { databaseStorageHash, invocation } = context;
602
- const update = cliCommand(invocation, "db update", invocation.rerunArgs ?? []);
606
+ const update = dbUpdateRerun(invocation);
603
607
  const { blockingObjects } = failure.meta;
604
608
  return runnerFailureError(failure, blockingObjects !== void 0 ? blockingObjectsAdvice(blockingObjects, update) : facts.failedTypeChange !== void 0 ? dbUpdateFailedTypeChangeAdvice(facts.failedTypeChange, databaseStorageHash, invocation) : facts.rowsWithoutValue !== void 0 ? dbUpdateRowsWithoutValueAdvice(facts.rowsWithoutValue, databaseStorageHash, invocation) : facts.rowsHoldingValue !== void 0 ? dbUpdateRowsHoldingValueAdvice(facts.rowsHoldingValue, databaseStorageHash, invocation) : facts.rowsFailingCheck !== void 0 ? dbUpdateRowsFailingCheckAdvice(facts.rowsFailingCheck, databaseStorageHash, invocation) : schemaCheckIssues(failure) !== void 0 ? [editFileAction(`Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${update}\``)] : [chooseAction(`Resolve the cause the failure names, then re-run \`${update}\``)]);
605
609
  }
@@ -761,6 +765,109 @@ function planningRefusedError(conflicts, context) {
761
765
  ...ifDefined("docsUrl", refused.docsUrl)
762
766
  });
763
767
  }
768
+ /** `change: migrate; dataProtection.dataLoss: data-loss-forbidden`: the declared side of each difference. */
769
+ function declaredSettingsText(differences) {
770
+ return differences.map(({ setting, declared }) => `${setting}: ${databasePolicyValueText(declared)}`).join("; ");
771
+ }
772
+ /** `MIGRATION.POLICY_MISMATCH`: the ref declares policies that differ from those the database's marker records. */
773
+ function errorPolicyMismatch(args) {
774
+ const { spaceId, refName, differences } = args;
775
+ const why = differences.map(({ setting, declared, inForce }) => `${refName} declares ${setting}: ${databasePolicyValueText(declared)}; the database has ${setting}: ${databasePolicyValueText(inForce)}.`).join(" ");
776
+ const recovery = "Make the ref match the database, or have whoever owns the database apply the ref's policies.";
777
+ return new ActionableCliError("MIGRATION.POLICY_MISMATCH", "The ref's policies differ from the database's", {
778
+ why,
779
+ fix: recovery,
780
+ nextActions: [chooseAction(recovery)],
781
+ meta: {
782
+ spaceId,
783
+ refName,
784
+ differences
785
+ }
786
+ });
787
+ }
788
+ /** `MIGRATION.CHANGE_POLICY_FORBIDS`: the change policy does not permit the command's way of changing the database. */
789
+ function errorChangePolicyForbids(args) {
790
+ const { spaceId, command, change, invocation, source } = args;
791
+ const holder = source.kind === "ref" ? `${source.refName} declares` : "The marker records";
792
+ const policyHolder = source.kind === "ref" ? `${source.refName} declares a change policy that` : "This database's change policy";
793
+ const refusal = command === "db sign" ? "may not sign it" : "may not move it";
794
+ const why = `${holder} change: ${change.join(", ")}, so ${command} ${refusal}.`;
795
+ const meta = {
796
+ spaceId,
797
+ command,
798
+ change
799
+ };
800
+ const ref = source.kind === "ref" ? {
801
+ name: source.refName,
802
+ permitPolicyChange: true
803
+ } : args.ref;
804
+ const toRef = ref === void 0 ? [] : [
805
+ "--to",
806
+ shellQuoted(ref.name),
807
+ ...ref.permitPolicyChange ? ["--permit-policy-change"] : []
808
+ ];
809
+ if (command === "db migrate") {
810
+ const reconcile = cliCommand(invocation, "db update", ref === void 0 ? ["--to", args.targetHash] : toRef);
811
+ return new ActionableCliError("MIGRATION.CHANGE_POLICY_FORBIDS", `${policyHolder} permits only db update`, {
812
+ why,
813
+ fix: `Reconcile the database: ${reconcile}`,
814
+ nextActions: [runCommandAction("Reconcile the database", reconcile)],
815
+ meta
816
+ });
817
+ }
818
+ const migrate = cliCommand(invocation, "db migrate", toRef);
819
+ const recovery = `Author a migration with ${cliCommand(invocation, "migration plan")}, then apply it with ${migrate}.`;
820
+ return new ActionableCliError("MIGRATION.CHANGE_POLICY_FORBIDS", `${policyHolder} permits only migrations`, {
821
+ why,
822
+ fix: recovery,
823
+ nextActions: [chooseAction(recovery)],
824
+ meta
825
+ });
826
+ }
827
+ /**
828
+ * `CLI.INVALID_ARGUMENTS`: consent to write policies was given without a ref whose policies it could
829
+ * write. `command` names the CLI command that was run, whose flags the error names; without it, the
830
+ * error names the control API option `refOption` (`target` for `migrate`, `ref` for `dbUpdate`).
831
+ */
832
+ function errorPermitPolicyChangeNeedsRef(args) {
833
+ const { to } = args;
834
+ const why = to === void 0 ? "No ref was given, so there are no policies to write." : `${to} is not a ref, so it declares no policies to write.`;
835
+ const toMeta = to === void 0 ? {} : { to };
836
+ if ("command" in args) {
837
+ const recovery = "Name the ref whose policies to write with --to <ref>, or leave out --permit-policy-change.";
838
+ return new ActionableCliError("CLI.INVALID_ARGUMENTS", "--permit-policy-change needs --to <ref>", {
839
+ why,
840
+ fix: recovery,
841
+ nextActions: [chooseAction(recovery)],
842
+ meta: {
843
+ command: args.command,
844
+ ...toMeta
845
+ }
846
+ });
847
+ }
848
+ const [summary, recovery] = args.refOption === "target" ? ["permitPolicyChange needs a target of kind ref", "Pass a target of kind ref whose policies to write, or leave out permitPolicyChange."] : ["permitPolicyChange needs a ref", "Pass the ref whose policies to write, or leave out permitPolicyChange."];
849
+ return new ActionableCliError("CLI.INVALID_ARGUMENTS", summary, {
850
+ why,
851
+ fix: recovery,
852
+ nextActions: [chooseAction(recovery)],
853
+ meta: toMeta
854
+ });
855
+ }
856
+ /** `MIGRATION.MARKER_CAS_FAILURE` for `db sign`: the database's policies changed after it checked them, so it did not sign the application space. */
857
+ function errorDatabasePoliciesMovedDuringSign(args) {
858
+ const rerun = cliCommand(args.invocation, "db sign", args.invocation.rerunArgs ?? []);
859
+ return new ActionableCliError("MIGRATION.MARKER_CAS_FAILURE", "The database's policies changed while db sign ran", {
860
+ why: `${movedDatabasePoliciesWhy("db sign", args.checked, args.found)} db sign did not sign the application space.`,
861
+ fix: `Sign again, which checks the policies anew: ${rerun}`,
862
+ nextActions: [runCommandAction("Sign again", rerun)],
863
+ meta: {
864
+ reason: "databasePolicies",
865
+ space: args.spaceId,
866
+ checkedDatabasePolicies: args.checked,
867
+ foundDatabasePolicies: args.found
868
+ }
869
+ });
870
+ }
764
871
  function formsFix$1(verb) {
765
872
  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.";
766
873
  }
@@ -2973,6 +3080,8 @@ function mapIntegrityViolations(violations, migrationsDir) {
2973
3080
  fix: "Re-emit the extension contract with `{bin} contract emit`, or fix the extension pack descriptor producing the invalid contract.",
2974
3081
  violations: [contractUnreadable]
2975
3082
  });
3083
+ const refUnreadable = violations.find((v) => v.kind === "refUnreadable");
3084
+ if (refUnreadable && refUnreadable.kind === "refUnreadable") return errorInvalidRefFile(refUnreadable.path, refUnreadable.detail, refUnreadable.policyIssues);
2976
3085
  const structural = violations[0];
2977
3086
  return contractSpaceViolationError(`Contract-space integrity failure for "${"spaceId" in structural ? structural.spaceId : "*"}"`, {
2978
3087
  why: describeIntegrityViolation(structural),
@@ -3113,13 +3222,73 @@ async function buildReadAggregate(config, options) {
3113
3222
  return ok({
3114
3223
  aggregate: loaded.value,
3115
3224
  contractHash,
3116
- storageNameOf: (operation) => familyInstance.storageNameOf(operation)
3225
+ storageNameOf: (operation) => familyInstance.storageNameOf(operation),
3226
+ markerLocation: familyInstance.markerLocation
3117
3227
  });
3118
3228
  } catch (error) {
3119
3229
  return notOk(errorFromCaught(error, (message) => `Failed to read migrations directory: ${message}`));
3120
3230
  }
3121
3231
  }
3122
3232
  /**
3233
+ * The database's policies in force: what the application space's marker records, filled from
3234
+ * the defaults. A marker whose recorded policies are not valid is a corrupt marker row.
3235
+ */
3236
+ function databasePoliciesInForce(markers, appSpaceId, markerLocation) {
3237
+ const inForce = databasePoliciesOf(markers.get(appSpaceId));
3238
+ if (!inForce.ok) throw errorMarkerPoliciesCorrupt({
3239
+ why: inForce.failure.why,
3240
+ space: appSpaceId,
3241
+ markerLocation
3242
+ });
3243
+ return inForce.value;
3244
+ }
3245
+ const STRATEGY_OF = {
3246
+ "db migrate": "migrate",
3247
+ "db update": "reconcile",
3248
+ "db sign": "reconcile"
3249
+ };
3250
+ /**
3251
+ * Checks a run against the database's policies, once, before it plans anything. A ref whose
3252
+ * declared policies differ refuses the run unless `permitPolicyChange` consents to recording
3253
+ * them. Then the change policy the run would leave in force must permit the command.
3254
+ */
3255
+ function checkRunPolicies(args) {
3256
+ const { appSpaceId, inForce, ref } = args;
3257
+ const declared = ref?.policies;
3258
+ const differences = declared === void 0 ? [] : databasePolicyDifferences(declared, inForce);
3259
+ if (ref !== void 0 && differences.length > 0 && !args.permitPolicyChange) return notOk(errorPolicyMismatch({
3260
+ spaceId: appSpaceId,
3261
+ refName: ref.name,
3262
+ differences
3263
+ }));
3264
+ const toWrite = declared !== void 0 && differences.length > 0 ? {
3265
+ policies: withDeclaredDatabasePolicies(inForce, declared),
3266
+ differences
3267
+ } : void 0;
3268
+ const required = STRATEGY_OF[args.command];
3269
+ const declaresChange = toWrite !== void 0 && declared?.change !== void 0;
3270
+ const change = toWrite?.policies.change ?? inForce.change;
3271
+ if (!change.includes(required)) return notOk(errorChangePolicyForbids({
3272
+ spaceId: appSpaceId,
3273
+ command: args.command,
3274
+ change,
3275
+ source: declaresChange && ref !== void 0 ? {
3276
+ kind: "ref",
3277
+ refName: ref.name
3278
+ } : { kind: "marker" },
3279
+ targetHash: args.targetHash,
3280
+ ref: ref === void 0 ? void 0 : {
3281
+ name: ref.name,
3282
+ permitPolicyChange: args.permitPolicyChange
3283
+ },
3284
+ invocation: args.invocation
3285
+ }));
3286
+ return ok({
3287
+ inForce,
3288
+ toWrite
3289
+ });
3290
+ }
3291
+ /**
3123
3292
  * Strips operation objects to their public shape (id, label, operationClass).
3124
3293
  * Used at the API boundary to avoid leaking internal fields (precheck, execute, postcheck, etc.).
3125
3294
  */
@@ -3258,7 +3427,7 @@ function runnerFailureFacts(failure, resolutions) {
3258
3427
  * progress event is taken from the caller's `action` argument.
3259
3428
  */
3260
3429
  async function runMigration(inputs) {
3261
- const { aggregate, perSpacePlans, applyOrder, driver, familyInstance, migrations, frameworkComponents, policy, action, onProgress } = inputs;
3430
+ const { aggregate, perSpacePlans, applyOrder, driver, familyInstance, migrations, frameworkComponents, policy, databasePolicies, expectedDatabasePolicies, action, onProgress } = inputs;
3262
3431
  const orderedResolutions = collectOrdered(applyOrder, perSpacePlans);
3263
3432
  const runner = migrations.createRunner(familyInstance);
3264
3433
  onProgress?.({
@@ -3273,13 +3442,15 @@ async function runMigration(inputs) {
3273
3442
  driver,
3274
3443
  destinationContract: r.entry.destinationContract,
3275
3444
  policy,
3445
+ ...r.spaceId === aggregate.app.spaceId ? ifDefined("databasePolicies", databasePolicies) : {},
3276
3446
  frameworkComponents,
3277
3447
  migrationEdges: r.entry.migrationEdges,
3278
3448
  strictVerification: false
3279
3449
  }));
3280
3450
  const runnerResult = await runner.execute({
3281
3451
  driver,
3282
- perSpaceOptions
3452
+ perSpaceOptions,
3453
+ ...ifDefined("expectedDatabasePolicies", expectedDatabasePolicies)
3283
3454
  });
3284
3455
  if (!runnerResult.ok) {
3285
3456
  onProgress?.({
@@ -3409,6 +3580,21 @@ async function executeRun(options) {
3409
3580
  if (!loaded.ok) throw loaded.failure;
3410
3581
  const aggregate = loaded.value;
3411
3582
  const markerRows = await familyInstance.readAllMarkers({ driver });
3583
+ let checkedPolicies;
3584
+ if (options.action === "dbUpdate") {
3585
+ const checked = checkRunPolicies({
3586
+ command: "db update",
3587
+ appSpaceId: aggregate.app.spaceId,
3588
+ inForce: databasePoliciesInForce(markerRows, aggregate.app.spaceId, familyInstance.markerLocation),
3589
+ ref: options.ref,
3590
+ permitPolicyChange: options.permitPolicyChange,
3591
+ targetHash: contract.storage.storageHash,
3592
+ invocation: options.invocation
3593
+ });
3594
+ if (!checked.ok) return notOk(checked.failure);
3595
+ checkedPolicies = checked.value;
3596
+ }
3597
+ const policiesToWrite = checkedPolicies?.toWrite;
3412
3598
  const appOrigin = options.action === "dbUpdate" ? await readAppOrigin({
3413
3599
  marker: markerRows.get(aggregate.app.spaceId) ?? null,
3414
3600
  migrationsDir,
@@ -3631,6 +3817,8 @@ async function executeRun(options) {
3631
3817
  migrations,
3632
3818
  frameworkComponents,
3633
3819
  policy,
3820
+ ...ifDefined("databasePolicies", policiesToWrite?.policies),
3821
+ ...ifDefined("expectedDatabasePolicies", checkedPolicies?.inForce),
3634
3822
  action,
3635
3823
  ...ifDefined("onProgress", onProgress)
3636
3824
  });
@@ -3643,7 +3831,9 @@ async function executeRun(options) {
3643
3831
  }
3644
3832
  const aggregateOps = applied.value.orderedResolutions.flatMap((r) => r.entry.displayOps);
3645
3833
  const signedWithoutOperations = action === "dbUpdate" && applied.value.totalOpsExecuted === 0 && markerRows.get(aggregate.app.spaceId)?.storageHash !== appPlan.destination.storageHash;
3646
- const summary = action === "dbInit" ? `Applied ${applied.value.totalOpsExecuted} operation(s) across ${applied.value.orderedResolutions.length} space(s), database signed` : signedWithoutOperations ? `The storage the contract describes changed, but the database needs no operation for it, so none ran and the database was signed with the new contract. ${whatChangedSentence(fromContract, contract)}` : 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`;
3834
+ const runSummary = action === "dbInit" ? `Applied ${applied.value.totalOpsExecuted} operation(s) across ${applied.value.orderedResolutions.length} space(s), database signed` : signedWithoutOperations ? `The storage the contract describes changed, but the database needs no operation for it, so none ran and the database was signed with the new contract. ${whatChangedSentence(fromContract, contract)}` : 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`;
3835
+ const policiesText = policiesToWrite === void 0 ? void 0 : declaredSettingsText(policiesToWrite.differences);
3836
+ const summary = policiesText === void 0 ? runSummary : signedWithoutOperations ? `${runSummary} Policies updated: ${policiesText}.` : `${runSummary}; policies updated: ${policiesText}`;
3647
3837
  return wrapApplyResult({
3648
3838
  operations: aggregateOps,
3649
3839
  destination: appPlan.destination,
@@ -3654,7 +3844,8 @@ async function executeRun(options) {
3654
3844
  appliedStatements,
3655
3845
  subjects,
3656
3846
  databaseStorageHash,
3657
- changedStorageEntities: signedWithoutOperations ? changedStorageEntities(fromContract, contract) : void 0
3847
+ changedStorageEntities: signedWithoutOperations ? changedStorageEntities(fromContract, contract) : void 0,
3848
+ databasePoliciesUpdated: policiesToWrite?.differences
3658
3849
  });
3659
3850
  }
3660
3851
  /** The origin of a database whose marker names no readable contract: no models. */
@@ -3827,6 +4018,7 @@ function wrapPlanResult(args) {
3827
4018
  function wrapApplyResult(args) {
3828
4019
  return ok({
3829
4020
  mode: "apply",
4021
+ ...ifDefined("databasePoliciesUpdated", args.databasePoliciesUpdated),
3830
4022
  ...ifDefined("databaseStorageHash", args.databaseStorageHash),
3831
4023
  ...ifDefined("changedStorageEntities", args.changedStorageEntities),
3832
4024
  ...ifDefined("appliedStatements", args.appliedStatements),
@@ -4125,6 +4317,7 @@ async function executeDbSign(options) {
4125
4317
  familyInstance,
4126
4318
  aggregate: loaded.value,
4127
4319
  frameworkComponents: options.frameworkComponents,
4320
+ invocation: options.invocation,
4128
4321
  ...ifDefined("onProgress", options.onProgress)
4129
4322
  });
4130
4323
  }
@@ -4153,6 +4346,20 @@ function contractHashes(space) {
4153
4346
  async function signContractSpaces(options) {
4154
4347
  const { driver, familyInstance, aggregate, frameworkComponents, onProgress } = options;
4155
4348
  const markers = await familyInstance.readAllMarkers({ driver });
4349
+ const appSpaceId = aggregate.app.spaceId;
4350
+ const inForce = markers.has(appSpaceId) ? databasePoliciesInForce(markers, appSpaceId, familyInstance.markerLocation) : void 0;
4351
+ if (inForce !== void 0) {
4352
+ const permitted = checkRunPolicies({
4353
+ command: "db sign",
4354
+ appSpaceId,
4355
+ inForce,
4356
+ ref: void 0,
4357
+ permitPolicyChange: false,
4358
+ targetHash: aggregate.app.contract().storage.storageHash,
4359
+ invocation: options.invocation
4360
+ });
4361
+ if (!permitted.ok) return notOk(permitted.failure);
4362
+ }
4156
4363
  const verified = verifyMigration({
4157
4364
  aggregate,
4158
4365
  markersBySpaceId: markers,
@@ -4196,15 +4403,31 @@ async function signContractSpaces(options) {
4196
4403
  });
4197
4404
  const signatures = await familyInstance.signSpaces({
4198
4405
  driver,
4199
- spaces: toSign
4406
+ spaces: toSign,
4407
+ ...ifDefined("expectedDatabasePolicies", inForce)
4200
4408
  });
4409
+ const policiesConflict = signatures.find((signature) => signature.status === "conflict" && signature.reason === "databasePolicies");
4201
4410
  onProgress?.({
4202
4411
  action: "dbSign",
4203
4412
  kind: "spanEnd",
4204
4413
  spanId: "sign",
4205
- outcome: "ok"
4206
- });
4207
- const signatureOf = new Map(signatures.map((signature) => [signature.space, signature]));
4414
+ outcome: policiesConflict === void 0 ? "ok" : "error"
4415
+ });
4416
+ if (policiesConflict !== void 0) {
4417
+ const { comparison } = policiesConflict;
4418
+ if (comparison.kind === "unreadable") throw errorMarkerPoliciesCorrupt({
4419
+ why: comparison.why,
4420
+ space: appSpaceId,
4421
+ markerLocation: familyInstance.markerLocation
4422
+ });
4423
+ return notOk(errorDatabasePoliciesMovedDuringSign({
4424
+ spaceId: appSpaceId,
4425
+ checked: policiesConflict.checked,
4426
+ found: comparison.found,
4427
+ invocation: options.invocation
4428
+ }));
4429
+ }
4430
+ const signatureOf = new Map(signatures.flatMap((signature) => signature.status === "conflict" && signature.reason === "databasePolicies" ? [] : [[signature.space, signature]]));
4208
4431
  return ok({ spaces: allSpaces.map((space) => {
4209
4432
  const signature = signatureOf.get(space.spaceId);
4210
4433
  if (signature !== void 0) return signature;
@@ -4226,6 +4449,24 @@ async function signContractSpaces(options) {
4226
4449
  }
4227
4450
  /** Execute `db update` against the configured contract. */
4228
4451
  async function executeDbUpdate(options) {
4452
+ if (options.permitPolicyChange === true && options.ref === void 0) return notOk(errorPermitPolicyChangeNeedsRef({
4453
+ refOption: "ref",
4454
+ to: void 0
4455
+ }));
4456
+ const contractStorageHash = options.contract.storage.storageHash;
4457
+ if (options.ref !== void 0 && options.ref.hash !== contractStorageHash) {
4458
+ const fix = `Pass the contract the ref names, or a ref whose hash is ${contractStorageHash}.`;
4459
+ return notOk(new ActionableCliError("CLI.INVALID_ARGUMENTS", "The ref names another contract than the one db update reconciles to", {
4460
+ why: `db update was given ref "${options.ref.name}" at ${options.ref.hash}, but the contract it reconciles to is ${contractStorageHash}.`,
4461
+ fix,
4462
+ nextActions: [chooseAction(fix)],
4463
+ meta: {
4464
+ refName: options.ref.name,
4465
+ refHash: options.ref.hash,
4466
+ contractStorageHash
4467
+ }
4468
+ }));
4469
+ }
4229
4470
  return await executeRun({
4230
4471
  driver: options.driver,
4231
4472
  adapter: options.adapter,
@@ -4244,6 +4485,8 @@ async function executeDbUpdate(options) {
4244
4485
  answerQuestions: options.answerQuestions,
4245
4486
  acceptDataLoss: options.acceptDataLoss ?? false,
4246
4487
  acceptAccessChanges: options.acceptAccessChanges ?? false,
4488
+ ...ifDefined("ref", options.ref),
4489
+ permitPolicyChange: options.permitPolicyChange ?? false,
4247
4490
  ...ifDefined("verifySnapshotContent", options.verifySnapshotContent),
4248
4491
  ...ifDefined("onPlannerWarnings", options.onPlannerWarnings),
4249
4492
  ...ifDefined("onProgress", options.onProgress)
@@ -4555,11 +4798,12 @@ const CAUSE_UNKNOWN = "A migration it applied was planned again or deleted, or `
4555
4798
  function extensionCause(spaceId) {
4556
4799
  return `The migrations of extension space "${spaceId}" come with the extension; it was changed to a version whose migrations do not include that contract.`;
4557
4800
  }
4558
- const MOVE_WITH_DB_UPDATE = "Unless this database changes only through migrations, as production does, move it with db update; its data stays:";
4559
- /** The `db update` arguments that name the target, or undefined when no `--to` names it. */
4801
+ const MOVE_WITH_DB_UPDATE = "Move it with db update; its data stays:";
4802
+ /** The `db update` arguments that name the target as the command was given it, or undefined when `db update` cannot reach it. */
4560
4803
  function reconcileArgs(found, owner) {
4561
- if (found.graph.reverseChain.has(found.targetHash)) return ["--to", found.targetHash];
4562
- return found.targetHash === owner.emittedContractHash ? [] : void 0;
4804
+ if (!(found.graph.reverseChain.has(found.targetHash) || found.targetHash === owner.emittedContractHash)) return void 0;
4805
+ if (found.targetRefName !== void 0) return ["--to", found.targetRefName];
4806
+ return found.graph.reverseChain.has(found.targetHash) ? ["--to", found.targetHash] : [];
4563
4807
  }
4564
4808
  function applicationAdvice(found, owner, history) {
4565
4809
  const from = history?.lastGraphHash ?? (found.graph.nodes.size === 0 ? "the empty contract" : "the nearest contract in the migration graph");
@@ -4570,6 +4814,13 @@ function applicationAdvice(found, owner, history) {
4570
4814
  nextActions: [chooseAction(authorOne)]
4571
4815
  };
4572
4816
  }
4817
+ if (!found.change.includes("reconcile")) {
4818
+ const migrationsOnly = `This database's change policy permits only migrations. Author migrations that bring it back onto the graph: one from ${from} to its current contract, then one from there to ${found.targetHash}. Commit them and deploy again.`;
4819
+ return {
4820
+ fix: migrationsOnly,
4821
+ nextActions: [chooseAction(migrationsOnly)]
4822
+ };
4823
+ }
4573
4824
  const toTarget = reconcileArgs(found, owner);
4574
4825
  if (toTarget === void 0) {
4575
4826
  const migrationsOnly = `Plan a migration from ${from} to the database's current contract, then one to ${found.targetHash}, commit them, and deploy again.`;
@@ -4580,20 +4831,13 @@ function applicationAdvice(found, owner, history) {
4580
4831
  }
4581
4832
  const dryRun = cliCommand(found.invocation, "db update", [...toTarget, "--dry-run"]);
4582
4833
  const reconcile = cliCommand(found.invocation, "db update", toTarget);
4583
- const otherwise = `Otherwise plan a migration from ${from} to its current contract, then one to ${found.targetHash}, and deploy again.`;
4584
4834
  return {
4585
4835
  fix: [
4586
4836
  MOVE_WITH_DB_UPDATE,
4587
4837
  ` ${dryRun}`,
4588
- ` ${reconcile}`,
4589
- otherwise
4838
+ ` ${reconcile}`
4590
4839
  ].join("\n"),
4591
- nextActions: [
4592
- chooseAction(MOVE_WITH_DB_UPDATE),
4593
- runCommandAction("Preview the changes", dryRun),
4594
- runCommandAction("Reconcile the database", reconcile),
4595
- chooseAction(otherwise)
4596
- ]
4840
+ nextActions: [runCommandAction("Preview the changes", dryRun), runCommandAction("Reconcile the database", reconcile)]
4597
4841
  };
4598
4842
  }
4599
4843
  function extensionAdvice(found) {
@@ -4622,6 +4866,7 @@ function errorMarkerMismatch(found) {
4622
4866
  spaceId,
4623
4867
  markerHash,
4624
4868
  targetHash,
4869
+ change: found.change,
4625
4870
  ...ifDefined("lastGraphHash", history?.lastGraphHash),
4626
4871
  ...found.ledger === void 0 ? {} : { missingMigrations: [...history?.missingMigrations ?? []] }
4627
4872
  }
@@ -4796,7 +5041,12 @@ function tokenize(source) {
4796
5041
  * authored migration graph on disk before this operation can advance it.
4797
5042
  */
4798
5043
  async function executeMigrate(options) {
4799
- const { driver, familyInstance, contract, migrations, frameworkComponents, migrationsDir, extensions, targetId, refHash, refInvariants, refName, onProgress } = options;
5044
+ const { driver, familyInstance, contract, migrations, frameworkComponents, migrationsDir, extensions, targetId, target, onProgress } = options;
5045
+ const ref = target?.kind === "ref" ? target.ref : void 0;
5046
+ if (options.permitPolicyChange === true && ref === void 0) return notOk(errorPermitPolicyChangeNeedsRef({
5047
+ refOption: "target",
5048
+ to: target?.kind === "hash" ? target.hash : void 0
5049
+ }));
4800
5050
  const loaded = await buildContractSpaceAggregate({
4801
5051
  targetId,
4802
5052
  migrationsDir,
@@ -4807,13 +5057,16 @@ async function executeMigrate(options) {
4807
5057
  });
4808
5058
  if (!loaded.ok) throw loaded.failure;
4809
5059
  const aggregate = loaded.value;
5060
+ const markerRows = await familyInstance.readAllMarkers({ driver });
5061
+ const appTargetHash = target === void 0 ? requireHeadRef(aggregate.app).hash : target.kind === "ref" ? target.ref.hash : target.hash;
5062
+ const inForce = databasePoliciesInForce(markerRows, aggregate.app.spaceId, familyInstance.markerLocation);
4810
5063
  const planned = await planEverySpace({
4811
5064
  aggregate,
4812
- markers: await familyInstance.readAllMarkers({ driver }),
5065
+ markers: markerRows,
4813
5066
  appTarget: {
4814
- hash: refHash ?? requireHeadRef(aggregate.app).hash,
4815
- invariants: refHash === void 0 ? void 0 : refInvariants,
4816
- refName
5067
+ hash: appTargetHash,
5068
+ invariants: ref?.invariants,
5069
+ refName: ref?.name
4817
5070
  },
4818
5071
  storageNameOf: (operation) => familyInstance.storageNameOf(operation),
4819
5072
  migrationsDir,
@@ -4821,9 +5074,21 @@ async function executeMigrate(options) {
4821
5074
  readLedger: (spaceId) => familyInstance.readLedger({
4822
5075
  driver,
4823
5076
  space: spaceId
4824
- })
5077
+ }),
5078
+ change: inForce.change
4825
5079
  });
4826
5080
  if (!planned.ok) return notOk(planned.failure);
5081
+ const checkedPolicies = checkRunPolicies({
5082
+ command: "db migrate",
5083
+ appSpaceId: aggregate.app.spaceId,
5084
+ inForce,
5085
+ ref,
5086
+ permitPolicyChange: options.permitPolicyChange ?? false,
5087
+ targetHash: appTargetHash,
5088
+ invocation: options.invocation
5089
+ });
5090
+ if (!checkedPolicies.ok) return notOk(checkedPolicies.failure);
5091
+ const policiesToWrite = checkedPolicies.value.toWrite;
4827
5092
  const allSpaces = [aggregate.app, ...aggregate.extensions];
4828
5093
  const perSpacePlans = /* @__PURE__ */ new Map();
4829
5094
  const plansKeptFromRunner = /* @__PURE__ */ new Map();
@@ -4849,10 +5114,19 @@ async function executeMigrate(options) {
4849
5114
  }
4850
5115
  const canonicalOrder = spacesInApplyOrder(aggregate).map((space) => space.spaceId);
4851
5116
  const applyOrder = canonicalOrder.filter((spaceId) => perSpacePlans.has(spaceId));
4852
- if (!applyOrder.some((spaceId) => {
5117
+ const hasPendingWork = applyOrder.some((spaceId) => {
4853
5118
  const entry = perSpacePlans.get(spaceId);
4854
5119
  return entry !== void 0 && planRequiresExecution(entry);
4855
- })) {
5120
+ });
5121
+ if (!hasPendingWork && policiesToWrite !== void 0) return runPolicyOnly({
5122
+ ...options,
5123
+ aggregate,
5124
+ plans: new Map([...plansKeptFromRunner, ...perSpacePlans]),
5125
+ canonicalOrder,
5126
+ policiesToWrite,
5127
+ inForce
5128
+ });
5129
+ if (!hasPendingWork) {
4856
5130
  const ordered = canonicalOrder.filter((spaceId) => perSpacePlans.has(spaceId) || plansKeptFromRunner.has(spaceId)).map((spaceId) => {
4857
5131
  const entry = perSpacePlans.get(spaceId) ?? plansKeptFromRunner.get(spaceId);
4858
5132
  if (entry === void 0) throw new InternalError(`Unreachable: missing per-space plan for "${spaceId}"`);
@@ -4881,12 +5155,9 @@ async function executeMigrate(options) {
4881
5155
  familyInstance,
4882
5156
  migrations,
4883
5157
  frameworkComponents,
4884
- policy: { allowedOperationClasses: [
4885
- "additive",
4886
- "widening",
4887
- "destructive",
4888
- "data"
4889
- ] },
5158
+ policy: MIGRATE_POLICY,
5159
+ ...ifDefined("databasePolicies", policiesToWrite?.policies),
5160
+ expectedDatabasePolicies: inForce,
4890
5161
  action: "migrate",
4891
5162
  ...ifDefined("onProgress", onProgress)
4892
5163
  });
@@ -4907,19 +5178,76 @@ async function executeMigrate(options) {
4907
5178
  };
4908
5179
  });
4909
5180
  const perSpaceAll = buildPerSpaceBreakdown(orderedAll, aggregate.app.spaceId, { includeMarkers: true });
4910
- const summary = appliedSummary({
5181
+ const applySummary = appliedSummary({
4911
5182
  migrations: applied.value.orderedResolutions.reduce((sum, r) => sum + r.entry.migrationEdges.length, 0),
4912
5183
  planned: applied.value.totalOpsPlanned,
4913
5184
  executed: applied.value.totalOpsExecuted,
4914
5185
  spaces: orderedAll.length
4915
5186
  });
4916
- return ok(buildSuccess({
5187
+ const summary = policiesToWrite === void 0 ? applySummary : `${applySummary}; policies updated: ${declaredSettingsText(policiesToWrite.differences)}`;
5188
+ return ok({
5189
+ ...buildSuccess({
5190
+ aggregate,
5191
+ orderedResolutions: orderedAll,
5192
+ perSpace: perSpaceAll,
5193
+ totalOpsExecuted: applied.value.totalOpsExecuted,
5194
+ summary
5195
+ }),
5196
+ ...ifDefined("databasePoliciesUpdated", policiesToWrite?.differences)
5197
+ });
5198
+ }
5199
+ const MIGRATE_POLICY = { allowedOperationClasses: [
5200
+ "additive",
5201
+ "widening",
5202
+ "destructive",
5203
+ "data"
5204
+ ] };
5205
+ /**
5206
+ * Nothing is pending, but the run has policies to record: the runner applies the application
5207
+ * space's plan, which runs no migration, so that its marker update records them.
5208
+ */
5209
+ async function runPolicyOnly(args) {
5210
+ const { aggregate, plans, policiesToWrite } = args;
5211
+ const appSpaceId = aggregate.app.spaceId;
5212
+ const appPlan = plans.get(appSpaceId);
5213
+ if (appPlan === void 0) throw new InternalError(`Unreachable: no plan for the application space "${appSpaceId}"`);
5214
+ const perSpacePlans = /* @__PURE__ */ new Map([[appSpaceId, appPlan]]);
5215
+ const applied = await runMigration({
4917
5216
  aggregate,
4918
- orderedResolutions: orderedAll,
4919
- perSpace: perSpaceAll,
4920
- totalOpsExecuted: applied.value.totalOpsExecuted,
4921
- summary
4922
- }));
5217
+ perSpacePlans,
5218
+ applyOrder: [appSpaceId],
5219
+ driver: args.driver,
5220
+ familyInstance: args.familyInstance,
5221
+ migrations: args.migrations,
5222
+ frameworkComponents: args.frameworkComponents,
5223
+ policy: MIGRATE_POLICY,
5224
+ databasePolicies: policiesToWrite.policies,
5225
+ expectedDatabasePolicies: args.inForce,
5226
+ action: "migrate",
5227
+ ...ifDefined("onProgress", args.onProgress)
5228
+ });
5229
+ if (!applied.ok) {
5230
+ const facts = runnerFailureFacts(applied.failure, collectOrdered([appSpaceId], perSpacePlans));
5231
+ return notOk(migrateRunnerFailureError(applied.failure, facts, void 0, args.invocation));
5232
+ }
5233
+ const orderedAll = args.canonicalOrder.flatMap((spaceId) => {
5234
+ const entry = plans.get(spaceId);
5235
+ if (entry === void 0) return [];
5236
+ return [applied.value.orderedResolutions.find((r) => r.spaceId === spaceId) ?? {
5237
+ spaceId,
5238
+ entry
5239
+ }];
5240
+ });
5241
+ return ok({
5242
+ ...buildSuccess({
5243
+ aggregate,
5244
+ orderedResolutions: orderedAll,
5245
+ perSpace: buildPerSpaceBreakdown(orderedAll, appSpaceId, { includeMarkers: true }),
5246
+ totalOpsExecuted: 0,
5247
+ summary: `Policies updated: ${declaredSettingsText(policiesToWrite.differences)}`
5248
+ }),
5249
+ databasePoliciesUpdated: policiesToWrite.differences
5250
+ });
4923
5251
  }
4924
5252
  /**
4925
5253
  * Compute the graph-walk path for one contract space.
@@ -5072,7 +5400,9 @@ async function planEverySpace(args) {
5072
5400
  graph: space.graph(),
5073
5401
  migrationsDir: args.migrationsDir,
5074
5402
  ledger: await readLedgerQuietly(() => args.readLedger(space.spaceId)),
5075
- invocation: args.invocation
5403
+ invocation: args.invocation,
5404
+ change: args.change,
5405
+ targetRefName: space.spaceId === aggregate.app.spaceId ? args.appTarget.refName : void 0
5076
5406
  }));
5077
5407
  }
5078
5408
  return ok(continuing);
@@ -5481,6 +5811,8 @@ var ControlClientImpl = class {
5481
5811
  extensions: this.options.extensions ?? [],
5482
5812
  ...ifDefined("acceptDataLoss", options.acceptDataLoss),
5483
5813
  ...ifDefined("acceptAccessChanges", options.acceptAccessChanges),
5814
+ ...ifDefined("ref", options.ref),
5815
+ ...ifDefined("permitPolicyChange", options.permitPolicyChange),
5484
5816
  ...ifDefined("statements", options.statements),
5485
5817
  answerQuestions: options.answerQuestions,
5486
5818
  ...ifDefined("verifySnapshotContent", this.snapshotVerifier),
@@ -5518,6 +5850,7 @@ var ControlClientImpl = class {
5518
5850
  targetId: this.options.target.targetId,
5519
5851
  extensions: this.options.extensions ?? [],
5520
5852
  frameworkComponents,
5853
+ invocation: options.invocation,
5521
5854
  ...ifDefined("verifySnapshotContent", this.snapshotVerifier),
5522
5855
  ...ifDefined("onProgress", onProgress)
5523
5856
  });
@@ -5565,9 +5898,8 @@ var ControlClientImpl = class {
5565
5898
  migrationsDir: options.migrationsDir,
5566
5899
  extensions: this.options.extensions ?? [],
5567
5900
  targetId: this.options.target.targetId,
5568
- ...ifDefined("refHash", options.refHash),
5569
- ...ifDefined("refInvariants", options.refInvariants),
5570
- ...ifDefined("refName", options.refName),
5901
+ ...ifDefined("target", options.target),
5902
+ ...ifDefined("permitPolicyChange", options.permitPolicyChange),
5571
5903
  ...ifDefined("verifySnapshotContent", this.snapshotVerifier),
5572
5904
  ...ifDefined("onProgress", onProgress)
5573
5905
  });
@@ -6303,10 +6635,7 @@ async function executeRefAdvancement(refsDir, migrationsDir, name, hash, contrac
6303
6635
  contractJson: contractIR.contract,
6304
6636
  contractDts: contractIR.contractDts
6305
6637
  });
6306
- await writeRef(refsDir, name, {
6307
- hash,
6308
- invariants: []
6309
- });
6638
+ await advanceRef(refsDir, name, hash);
6310
6639
  return {
6311
6640
  name,
6312
6641
  hash
@@ -6397,11 +6726,18 @@ async function resolveContractRefToSnapshot(options) {
6397
6726
  });
6398
6727
  if (!refResult.ok) return notOk(mapRefResolutionError(refResult.failure));
6399
6728
  const targetHash = refResult.value.hash;
6729
+ const { provenance } = refResult.value;
6730
+ const refEntry = provenance.kind === "ref" ? refs[provenance.refName] : void 0;
6731
+ const namedRef = provenance.kind === "ref" && refEntry !== void 0 ? {
6732
+ name: provenance.refName,
6733
+ ...refEntry
6734
+ } : void 0;
6400
6735
  if (bundles.find((p) => p.metadata.to === targetHash)) return ok({
6401
6736
  hash: targetHash,
6402
6737
  contractJson: blindCast(await readContractSnapshotJson(options.migrationsDir, targetHash, snapshotVerifierFor(options.config))),
6403
6738
  contractJsonPath: join(contractSnapshotDir(options.migrationsDir, targetHash), "contract.json"),
6404
- source: "snapshot"
6739
+ source: "snapshot",
6740
+ ...ifDefined("ref", namedRef)
6405
6741
  });
6406
6742
  if (!options.fallbackToEmitted) return notOk(errorUnexpected(`No migration bundle found for ${options.argument} "${options.refInput}" (resolved hash: ${targetHash})`, {
6407
6743
  why: `The ref resolved successfully but no on-disk migration package has a destination (\`to\`) hash matching ${targetHash}.`,
@@ -6431,7 +6767,8 @@ async function resolveContractRefToSnapshot(options) {
6431
6767
  hash: targetHash,
6432
6768
  contractJson: defaultContract,
6433
6769
  contractJsonPath: options.contractPathAbsolute,
6434
- source: "emitted"
6770
+ source: "emitted",
6771
+ ...ifDefined("ref", namedRef)
6435
6772
  });
6436
6773
  return notOk(errorRuntime("MIGRATION.SNAPSHOT_MISSING", `No contract file found for hash "${targetHash}"`, {
6437
6774
  why: `Resolved contract reference "${options.refInput}" to hash "${targetHash}" but no migration produces that hash and the emitted contract does not match.`,
@@ -6471,8 +6808,7 @@ function retryCommandFor(args) {
6471
6808
  ...args.from === void 0 ? [] : [`--from ${args.from}`],
6472
6809
  ...suggestsOffline ? ["--from <contract>"] : [],
6473
6810
  ...args.to === void 0 ? [] : [`--to ${args.to}`],
6474
- ...args.advanceRef === void 0 ? [] : [`--advance-ref ${args.advanceRef}`],
6475
- ...(args.statements ?? []).map(statementFlag),
6811
+ ...args.rerunArgs ?? [],
6476
6812
  ...needsConnection ? ["--db $DATABASE_URL"] : []
6477
6813
  ].join(" ");
6478
6814
  }
@@ -6597,10 +6933,11 @@ async function executeMigrateShowPlan(options) {
6597
6933
  }
6598
6934
  const loaded = await buildReadAggregate(config, { migrationsDir });
6599
6935
  if (!loaded.ok) return notOk(loaded.failure);
6600
- const { aggregate, contractHash, storageNameOf } = loaded.value;
6936
+ const { aggregate, contractHash, storageNameOf, markerLocation } = loaded.value;
6601
6937
  const appGraph = aggregate.app.graph();
6602
6938
  let targetHash = contractHash;
6603
6939
  let refInvariants;
6940
+ let namedRef;
6604
6941
  const refContext = {
6605
6942
  graph: appGraph,
6606
6943
  refs: allRefs,
@@ -6611,10 +6948,21 @@ async function executeMigrateShowPlan(options) {
6611
6948
  if (!toResult.ok) return notOk(toResult.failure);
6612
6949
  targetHash = toResult.value.hash;
6613
6950
  if (toResult.value.provenance.kind === "ref") {
6614
- const refEntry = allRefs[toResult.value.provenance.refName];
6615
- if (refEntry) refInvariants = refEntry.invariants;
6951
+ const refName = toResult.value.provenance.refName;
6952
+ const refEntry = allRefs[refName];
6953
+ if (refEntry) {
6954
+ refInvariants = refEntry.invariants;
6955
+ namedRef = {
6956
+ name: refName,
6957
+ ...refEntry
6958
+ };
6959
+ }
6616
6960
  }
6617
6961
  }
6962
+ if (options.permitPolicyChange === true && namedRef === void 0) return notOk(errorPermitPolicyChangeNeedsRef({
6963
+ command: "db migrate",
6964
+ to: options.to
6965
+ }));
6618
6966
  options.onPreflightComplete?.({
6619
6967
  configPath,
6620
6968
  migrationsRelative,
@@ -6663,14 +7011,26 @@ async function executeMigrateShowPlan(options) {
6663
7011
  markerBySpace.set(space.spaceId, marker ?? null);
6664
7012
  }
6665
7013
  if (liveTarget) targetHash = contractHashAtMarker(appMarker);
7014
+ const inForce = databasePoliciesInForce(allMarkers, aggregate.app.spaceId, markerLocation);
6666
7015
  const checked = await planEverySpace({
6667
7016
  ...planInputs(),
6668
7017
  markers: allMarkers,
6669
7018
  migrationsDir,
6670
7019
  invocation: options.invocation,
6671
- readLedger: (spaceId) => client.readLedger(spaceId)
7020
+ readLedger: (spaceId) => client.readLedger(spaceId),
7021
+ change: inForce.change
6672
7022
  });
6673
7023
  if (!checked.ok) return notOk(checked.failure);
7024
+ const permitted = checkRunPolicies({
7025
+ command: "db migrate",
7026
+ appSpaceId: aggregate.app.spaceId,
7027
+ inForce,
7028
+ ref: namedRef,
7029
+ permitPolicyChange: options.permitPolicyChange ?? false,
7030
+ targetHash,
7031
+ invocation: options.invocation
7032
+ });
7033
+ if (!permitted.ok) return notOk(permitted.failure);
6674
7034
  if (liveOrigin) outcomes = checked.value;
6675
7035
  } catch (error) {
6676
7036
  return notOk(errorFromCaught(error, (message) => `Failed to read live DB marker: ${message}`, { connection: typeof dbConnection === "string" ? dbConnection : void 0 }));
@@ -8294,15 +8654,13 @@ async function executeRefSetCommand(name, contractInput, options) {
8294
8654
  }));
8295
8655
  throw readError;
8296
8656
  }
8297
- await writeRef(refsDir, name, {
8298
- hash: resolvedHash,
8299
- invariants: []
8300
- });
8657
+ const written = await advanceRef(refsDir, name, resolvedHash);
8301
8658
  return ok({
8302
8659
  ok: true,
8303
8660
  ref: name,
8304
- hash: resolvedHash,
8305
- invariants: []
8661
+ hash: written.hash,
8662
+ invariants: written.invariants,
8663
+ ...ifDefined("policies", written.policies)
8306
8664
  });
8307
8665
  } catch (error) {
8308
8666
  return notOk(errorFromCaught(error, (message) => message));
@@ -8333,6 +8691,6 @@ async function executeRefListCommand(options) {
8333
8691
  }
8334
8692
  }
8335
8693
  //#endregion
8336
- export { refuseContractSpaceIntegrity as $, executeRefDeleteCommand as A, loadAggregateIntegrityViolations as B, executeDbSign as C, withWarningFindings as Ct, executeMigrationNewCommand as D, executeMigrateShowPlan as E, hasMigrationPath as F, looksLikePath as G, loadContractSource as H, isStatementVerb as I, matchConsents as J, mapContractAtError as K, labelsText as L, executeRefSetCommand as M, findPackageByDirPath as N, executeMigrationPlanCommand as O, formatSourceDiagnostic as P, readMigrationRefs as Q, listRefsByContractHash as R, executeDbInit as S, validateLoadedContract as St, executeDbVerify as T, loadContractSourceWithStack as U, loadContractRawSafely as V, loadContractSpaceAggregateForCli as W, planEverySpace as X, migrationSpaceListEntriesFromAggregate as Y, preflightRefAdvancement as Z, deriveStatusEdgeAnnotations as _, skippedOperationsText as _t, advanceRefSafely as a, requireDatabaseForLiveMarkerUse as at, enumerateCheckSpaces as b, statusForMigrationHash as bt, buildContractSpaceAggregate as c, resolveContractRefToSnapshot as ct, buildRefAdvancementFields as d, resolveStatements as dt, refuseDeclaredExtensionTargetMismatch as et, checkSingleTarget as f, resolveToForPlan as ft, createControlClient as g, runMigrationList as gt, convertAndDelete as h, runMigrationCheck as ht, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as i, renamedAndDeleted as it, executeRefListCommand as j, executeRefAdvancement as k, buildMigrationSpaceGraphEntries as l, resolveFromForPlan as lt, contractValidationMeta as m, runContractSpaceSeedPhase as mt, NO_REF_ADVANCEMENT as n, refusePackageCorruptionOnAggregate as nt, appContractStandInFromIdentity as o, resolveAppTargetPath as ot, computeRefAdvancementName as p, retryCommandFor as pt, mapIntegrityViolations as q, RECORDED_CONTRACT_REF_FORMS as r, refuseUnknownInvariants as rt, appliedHashesFromLedger as s, resolveContractRef$1 as st, ALL_CONTRACT_REF_FORMS as t, refuseMissingInvariantPath as tt, buildReadAggregate as u, resolveMigrationRef as ut, disposeEmitQueue as v, snapshotVerifierFor as vt, executeDbUpdate as w, executeContractEmit as x, toDeclaredExtensionsFromRaw as xt, enrichContract as y, sourceWarningDiagnostic as yt, liveMarkerUse as z };
8694
+ export { planEverySpace as $, executeMigrationNewCommand as A, labelsText as B, errorPermitPolicyChangeNeedsRef as C, statusForMigrationHash as Ct, executeDbUpdate as D, executeDbSign as E, withWarningFindings as Et, executeRefSetCommand as F, loadContractSource as G, liveMarkerUse as H, findPackageByDirPath as I, looksLikePath as J, loadContractSourceWithStack as K, formatSourceDiagnostic as L, executeRefAdvancement as M, executeRefDeleteCommand as N, executeDbVerify as O, executeRefListCommand as P, migrationSpaceListEntriesFromAggregate as Q, hasMigrationPath as R, enumerateCheckSpaces as S, sourceWarningDiagnostic as St, executeDbInit as T, validateLoadedContract as Tt, loadAggregateIntegrityViolations as U, listRefsByContractHash as V, loadContractRawSafely as W, mapIntegrityViolations as X, mapContractAtError as Y, matchConsents as Z, databasePoliciesInForce as _, runContractSpaceSeedPhase as _t, advanceRefSafely as a, refusePackageCorruptionOnAggregate as at, disposeEmitQueue as b, skippedOperationsText as bt, buildContractSpaceAggregate as c, requireDatabaseForLiveMarkerUse as ct, buildRefAdvancementFields as d, resolveContractRefToSnapshot as dt, preflightRefAdvancement as et, checkSingleTarget as f, resolveFromForPlan as ft, createControlClient as g, retryCommandFor as gt, convertAndDelete as h, resolveToForPlan as ht, RECORDED_OR_EMPTY_CONTRACT_REF_FORMS as i, refuseMissingInvariantPath as it, executeMigrationPlanCommand as j, executeMigrateShowPlan as k, buildMigrationSpaceGraphEntries as l, resolveAppTargetPath as lt, contractValidationMeta as m, resolveStatements as mt, NO_REF_ADVANCEMENT as n, refuseContractSpaceIntegrity as nt, appContractStandInFromIdentity as o, refuseUnknownInvariants as ot, computeRefAdvancementName as p, resolveMigrationRef as pt, loadContractSpaceAggregateForCli as q, RECORDED_CONTRACT_REF_FORMS as r, refuseDeclaredExtensionTargetMismatch as rt, appliedHashesFromLedger as s, renamedAndDeleted as st, ALL_CONTRACT_REF_FORMS as t, readMigrationRefs as tt, buildReadAggregate as u, resolveContractRef$1 as ut, declaredSettingsText as v, runMigrationCheck as vt, executeContractEmit as w, toDeclaredExtensionsFromRaw as wt, enrichContract as x, snapshotVerifierFor as xt, deriveStatusEdgeAnnotations as y, runMigrationList as yt, isStatementVerb as z };
8337
8695
 
8338
- //# sourceMappingURL=ref-D4GWEHQU-BOqb4i_E.mjs.map
8696
+ //# sourceMappingURL=ref-DfuqRCA7-CPPoVHY9.mjs.map