@prisma/orm-toolchain 8.0.0-rc.20-dev.13 → 8.0.0-rc.20-dev.15

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.
@@ -8,7 +8,7 @@ import { i as materialiseExtensionMigrationPackageIfMissing, r as formatMigratio
8
8
  import { i as findPathWithDecision, r as findPath } from "./migration-graph-BoiiZAaU-DLht12k7.mjs";
9
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-B12R3P5U-CfBKlBjj.mjs";
10
10
  import { i as emitContractSpaceArtifacts, o as planAllSpaces } from "./spaces-B0zxbzdl.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, 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, c as cliCommand, ct as readContractEnvelope, d as closeQuietly, dt as resolveContractPath, f as collectDeclaredInvariants, ft as resolveMigrationPaths, gt as statementFlag, h as editFileAction, j as errorMarkerMismatch, 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-ChEu1-VS-CYbzB68y.mjs";
11
+ import { B as errorRefSetEmptySentinel, D as errorFromCaught, E as errorFileNotFound, F as errorPathUnreachable, G as errorSpaceNotFound, H as errorRuntime, I as errorPlanForgotTheFlag, J as errorStatementInvalid, K as errorStatementAnswersNoQuestion, L as errorPlanOriginUnknown, N as errorMigrationPlanningFailed, Q as errorTargetMigrationNotSupported, R as errorPlanProducedNoOperations, S as errorContractValidationFailed, V as errorRefSetHashNotInGraph, W as errorSnapshotMissing, X as errorStatementOriginUnknown, Y as errorStatementNeedsMigrationFile, Z as errorStatementUnresolved, _ as errorAmbiguousMigrationRef, _t as toStructuralEdge, at as printedPath, c as cliCommand, d as closeQuietly, dt as resolveMigrationPaths, et as errorUnexpected, f as collectDeclaredInvariants, ft as runCommandAction, h as editFileAction, ht as statementFlag, k as errorInvalidSpaceId, l as cliErrorFromStructured, lt as requireLiveDatabase, n as CliStructuredError$1, nt as mapRefResolutionError, ot as printedPlanCommand, pt as selfEmitCommand, q as errorStatementDidNotResolveLoss, r as STORE_ORIGIN_SNAPSHOT_STEPS, s as chooseAction, st as readContractEnvelope, t as ActionableCliError, tt as getTargetMigrations, ut as resolveContractPath, v as errorConfigValidation$1, vt as writtenMigrationRunCommand, x as errorContractConfigMissing, y as errorConsentUnused, z as errorRefSetBundleNotFound } from "./caught-errors-BxdRHTkj-C40Qqf4i.mjs";
12
12
  import { r as getEmittedArtifactPaths, t as emit } from "./exports-BCIlMjIW-DkUBVDzl.mjs";
13
13
  import { n as isGraphNode, t as assertHashIsGraphNode } from "./graph-membership-DxpNgxfZ-BfqA-H7V.mjs";
14
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";
@@ -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-C1IRwZNR.mjs
37
+ //#region ../../../1-framework/3-tooling/cli/dist/ref-D-HCqZAl.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
  */
@@ -478,7 +478,7 @@ function dbInitPlanningFailedError(conflicts) {
478
478
  /** A failed `db init` apply as the CLI reports it. */
479
479
  function dbInitRunnerFailureError(failure, facts, invocation) {
480
480
  const init = cliCommand(invocation, "db init");
481
- return runnerFailureError(failure, facts.rowsWithoutValue !== void 0 ? dbInitRowsWithoutValueAdvice(facts.rowsWithoutValue, invocation) : schemaCheckIssues(failure) !== void 0 ? [editFileAction(`Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${init}\``)] : facts.failedPrecheck !== void 0 ? dbInitFailedPrecheckAdvice(invocation) : [chooseAction(`Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run \`${init}\``)]);
481
+ return runnerFailureError(failure, facts.rowsWithoutValue !== void 0 ? dbInitRowsWithoutValueAdvice(facts.rowsWithoutValue, invocation) : schemaCheckIssues(failure) !== void 0 ? [editFileAction(`Change the contract source to resolve the issues listed, re-run \`${cliCommand(invocation, "contract emit")}\`, then re-run \`${init}\``)] : facts.failedPrecheck !== void 0 ? dbInitFailedPrecheckAdvice(invocation) : [chooseAction(`Fix the schema mismatch (db init is additive-only), or bring the database to the contract with \`${cliCommand(invocation, "db update")}\`, which moves the database without a reset and asks before losing data`)]);
482
482
  }
483
483
  /**
484
484
  * A failed `db update` apply as the CLI reports it. `databaseStorageHash` is the contract the
@@ -496,7 +496,7 @@ function startText(fromHash) {
496
496
  }
497
497
  const INSTALL_MATCHING = "Install a version of the extension whose migrations start from the contract the database is at";
498
498
  /** The way out for an extension space: only another version of the extension changes its migrations. */
499
- function extensionAdvice(space) {
499
+ function extensionAdvice$1(space) {
500
500
  const rerun = cliCommand(space.invocation, space.command);
501
501
  const list = cliCommand(space.invocation, "migration list", ["--space", space.spaceId]);
502
502
  return {
@@ -519,7 +519,7 @@ function errorExtensionPathUnreachable(space) {
519
519
  fromHash: space.fromHash,
520
520
  targetHash: space.targetHash
521
521
  }
522
- }, extensionAdvice(space));
522
+ }, extensionAdvice$1(space));
523
523
  }
524
524
  /**
525
525
  * `MIGRATION.NO_INVARIANT_PATH` for an extension space whose migrations reach the extension's head
@@ -534,7 +534,7 @@ function errorExtensionNoInvariantPath(space) {
534
534
  extensionSpace: {
535
535
  spaceId: space.spaceId,
536
536
  why: `The head of extension space "${space.spaceId}" requires invariants that no path of its migrations from ${startText(space.fromHash)} provides: ${missing}.`,
537
- ...extensionAdvice(space)
537
+ ...extensionAdvice$1(space)
538
538
  }
539
539
  });
540
540
  }
@@ -3715,6 +3715,122 @@ async function loadContractSource(config, options = {}) {
3715
3715
  warnings
3716
3716
  });
3717
3717
  }
3718
+ /** The ledger as `read` gives it, or undefined when the read fails: the error it explains must not fail with it. */
3719
+ async function readLedgerQuietly(read) {
3720
+ try {
3721
+ return await read();
3722
+ } catch {
3723
+ return;
3724
+ }
3725
+ }
3726
+ function ledgerAfterGraph(ledger, graph) {
3727
+ const lastOnGraph = ledger.findLastIndex((applied) => isGraphNode(applied.to, graph));
3728
+ const last = ledger[lastOnGraph];
3729
+ if (last === void 0) return;
3730
+ const after = ledger.slice(lastOnGraph + 1);
3731
+ const named = after.flatMap((applied) => applied.migrationName === "" ? [] : [applied.migrationName]);
3732
+ const onDisk = new Set([...graph.migrationByHash.values()].map((edge) => edge.dirName));
3733
+ return {
3734
+ lastGraphHash: last.to,
3735
+ missingMigrations: named.filter((name) => !onDisk.has(name)),
3736
+ replannedMigrations: named.filter((name) => onDisk.has(name)),
3737
+ movedWithoutMigration: after.some((applied) => applied.migrationName === "")
3738
+ };
3739
+ }
3740
+ const NAMES_IN_WHY = 5;
3741
+ function nameList(names) {
3742
+ const shown = names.slice(0, NAMES_IN_WHY).join(", ");
3743
+ const hidden = names.length - NAMES_IN_WHY;
3744
+ return hidden > 0 ? `${shown}, and ${hidden} more` : shown;
3745
+ }
3746
+ const MOVED_BY_DB_UPDATE = "`db update` or `db init` moved it outside the migration graph.";
3747
+ function whichIs(names, singular, plural) {
3748
+ return `${nameList(names)}, which ${names.length === 1 ? singular : plural}`;
3749
+ }
3750
+ function historySentence(history) {
3751
+ const { lastGraphHash, missingMigrations, replannedMigrations, movedWithoutMigration } = history;
3752
+ const migrations = [...missingMigrations.length === 0 ? [] : [whichIs(missingMigrations, "is no longer on disk", "are no longer on disk")], ...replannedMigrations.length === 0 ? [] : [whichIs(replannedMigrations, "has since been planned again with different content", "have since been planned again with different content")]];
3753
+ const opening = `After ${lastGraphHash}, the last graph contract it reached,`;
3754
+ if (migrations.length === 0) return movedWithoutMigration ? `${opening} ${MOVED_BY_DB_UPDATE}` : `${opening} its marker was moved without a migration, for example by \`db sign\`.`;
3755
+ const applied = `${opening} it applied ${migrations.join(", and ")}.`;
3756
+ return movedWithoutMigration ? `${applied} After that, ${MOVED_BY_DB_UPDATE}` : applied;
3757
+ }
3758
+ const CAUSE_UNKNOWN = "A migration it applied was planned again or deleted, or `db update` moved it to a contract no migration ends at.";
3759
+ function extensionCause(spaceId) {
3760
+ return `The migrations of extension space "${spaceId}" come with the extension; it was changed to a version whose migrations do not include that contract.`;
3761
+ }
3762
+ const MOVE_WITH_DB_UPDATE = "Unless this database changes only through migrations, as production does, move it with db update; its data stays:";
3763
+ /** The `db update` arguments that name the target, or undefined when no `--to` names it. */
3764
+ function reconcileArgs(found, owner) {
3765
+ if (found.graph.reverseChain.has(found.targetHash)) return ["--to", found.targetHash];
3766
+ return found.targetHash === owner.emittedContractHash ? [] : void 0;
3767
+ }
3768
+ function applicationAdvice(found, owner, history) {
3769
+ const from = history?.lastGraphHash ?? (found.graph.nodes.size === 0 ? "the empty contract" : "the nearest contract in the migration graph");
3770
+ if (found.markerHash === found.targetHash) {
3771
+ const authorOne = `The database is already at the target, but no migration ends there: author a migration from ${from} to ${found.targetHash}, commit it, and deploy again.`;
3772
+ return {
3773
+ fix: authorOne,
3774
+ nextActions: [chooseAction(authorOne)]
3775
+ };
3776
+ }
3777
+ const toTarget = reconcileArgs(found, owner);
3778
+ if (toTarget === void 0) {
3779
+ const migrationsOnly = `Plan a migration from ${from} to the database's current contract, then one to ${found.targetHash}, commit them, and deploy again.`;
3780
+ return {
3781
+ fix: migrationsOnly,
3782
+ nextActions: [chooseAction(migrationsOnly)]
3783
+ };
3784
+ }
3785
+ const dryRun = cliCommand(found.invocation, "db update", [...toTarget, "--dry-run"]);
3786
+ const reconcile = cliCommand(found.invocation, "db update", toTarget);
3787
+ const otherwise = `Otherwise plan a migration from ${from} to its current contract, then one to ${found.targetHash}, and deploy again.`;
3788
+ return {
3789
+ fix: [
3790
+ MOVE_WITH_DB_UPDATE,
3791
+ ` ${dryRun}`,
3792
+ ` ${reconcile}`,
3793
+ otherwise
3794
+ ].join("\n"),
3795
+ nextActions: [
3796
+ chooseAction(MOVE_WITH_DB_UPDATE),
3797
+ runCommandAction("Preview the changes", dryRun),
3798
+ runCommandAction("Reconcile the database", reconcile),
3799
+ chooseAction(otherwise)
3800
+ ]
3801
+ };
3802
+ }
3803
+ function extensionAdvice(found) {
3804
+ const install = `Install a version of the extension whose migrations include the contract the database is at (${found.markerHash}), or ask the extension's maintainers for one.`;
3805
+ const list = cliCommand(found.invocation, "migration list", ["--space", found.spaceId]);
3806
+ return {
3807
+ fix: [install, `List the space's migrations with \`${list}\`.`].join("\n"),
3808
+ nextActions: [chooseAction(install), runCommandAction(`List the migrations of extension space "${found.spaceId}"`, list)]
3809
+ };
3810
+ }
3811
+ /**
3812
+ * `MIGRATION.MARKER_MISMATCH`: the database's marker names a contract no migration of the space
3813
+ * starts or ends at. It explains the cause from the ledger and gives the ways back onto the graph,
3814
+ * none of which resets the database.
3815
+ */
3816
+ function errorMarkerMismatch(found) {
3817
+ const { spaceId, markerHash, targetHash, invocation, owner } = found;
3818
+ const history = found.ledger === void 0 ? void 0 : ledgerAfterGraph(found.ledger, found.graph);
3819
+ const why = `The database's marker names ${markerHash}, which no migration in ${printedPath(invocation, join(found.migrationsDir, spaceId))} starts or ends at. ${owner.kind === "extension" ? extensionCause(spaceId) : history === void 0 ? CAUSE_UNKNOWN : historySentence(history)}`;
3820
+ const advice = owner.kind === "extension" ? extensionAdvice(found) : applicationAdvice(found, owner, history);
3821
+ return new ActionableCliError("MIGRATION.MARKER_MISMATCH", "The database is at a contract that is not in the migration graph", {
3822
+ why,
3823
+ fix: advice.fix,
3824
+ nextActions: [...advice.nextActions],
3825
+ meta: {
3826
+ spaceId,
3827
+ markerHash,
3828
+ targetHash,
3829
+ ...ifDefined("lastGraphHash", history?.lastGraphHash),
3830
+ ...found.ledger === void 0 ? {} : { missingMigrations: [...history?.missingMigrations ?? []] }
3831
+ }
3832
+ });
3833
+ }
3718
3834
  /**
3719
3835
  * A failed `db migrate` apply as the CLI reports it; its advice prints paths and commands that work
3720
3836
  * from where the CLI ran, with the `--config` it was given.
@@ -3759,23 +3875,29 @@ async function executeMigrate(options) {
3759
3875
  });
3760
3876
  if (!loaded.ok) throw loaded.failure;
3761
3877
  const aggregate = loaded.value;
3762
- const markerRows = await familyInstance.readAllMarkers({ driver });
3878
+ const planned = await planEverySpace({
3879
+ aggregate,
3880
+ markers: await familyInstance.readAllMarkers({ driver }),
3881
+ appTarget: {
3882
+ hash: refHash ?? requireHeadRef(aggregate.app).hash,
3883
+ invariants: refHash === void 0 ? void 0 : refInvariants,
3884
+ refName
3885
+ },
3886
+ storageNameOf: (operation) => familyInstance.storageNameOf(operation),
3887
+ migrationsDir,
3888
+ invocation: options.invocation,
3889
+ readLedger: (spaceId) => familyInstance.readLedger({
3890
+ driver,
3891
+ space: spaceId
3892
+ })
3893
+ });
3894
+ if (!planned.ok) return notOk(planned.failure);
3763
3895
  const allSpaces = [aggregate.app, ...aggregate.extensions];
3764
3896
  const perSpacePlans = /* @__PURE__ */ new Map();
3765
3897
  const plansKeptFromRunner = /* @__PURE__ */ new Map();
3766
3898
  for (const space of allSpaces) {
3767
- const isAppSpace = space.spaceId === aggregate.app.spaceId;
3768
- const headRef = requireHeadRef(space);
3769
- const spaceTargetHash = isAppSpace && refHash !== void 0 ? refHash : headRef.hash;
3770
- const outcome = planSpacePath({
3771
- space,
3772
- aggregate,
3773
- targetHash: spaceTargetHash,
3774
- refInvariants: isAppSpace && refHash !== void 0 ? refInvariants : void 0,
3775
- liveMarker: markerRows.get(space.spaceId) ?? null,
3776
- ...isAppSpace ? { refName } : {},
3777
- storageNameOf: (operation) => familyInstance.storageNameOf(operation)
3778
- });
3899
+ const outcome = planned.value.get(space.spaceId);
3900
+ if (outcome === void 0) throw new InternalError(`Unreachable: no planned outcome for space "${space.spaceId}"`);
3779
3901
  if (outcome.kind === "at-head") {
3780
3902
  plansKeptFromRunner.set(space.spaceId, outcome.plan);
3781
3903
  continue;
@@ -3785,7 +3907,7 @@ async function executeMigrate(options) {
3785
3907
  if (outcome.kind === "unsatisfiable") throw noInvariantPathError({
3786
3908
  graph: outcome.targetSpace.graph(),
3787
3909
  fromHash: outcome.liveHash,
3788
- targetHash: spaceTargetHash,
3910
+ targetHash: outcome.targetHash,
3789
3911
  required: outcome.targetInvariants,
3790
3912
  missing: outcome.missing,
3791
3913
  ...outcome.refName !== void 0 ? { refName: outcome.refName } : {}
@@ -3878,7 +4000,15 @@ async function executeMigrate(options) {
3878
4000
  function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker, refName, storageNameOf }) {
3879
4001
  const isAppSpace = space.spaceId === aggregate.app.spaceId;
3880
4002
  const headRef = requireHeadRef(space);
3881
- if (space.graph().nodes.size === 0) {
4003
+ const graph = space.graph();
4004
+ const extensionShipsNoMigrations = !isAppSpace && graph.nodes.size === 0;
4005
+ if (liveMarker !== null && !extensionShipsNoMigrations && !isGraphNode(liveMarker.storageHash, graph)) return {
4006
+ kind: "marker-outside-graph",
4007
+ spaceId: space.spaceId,
4008
+ markerHash: liveMarker.storageHash,
4009
+ targetHash
4010
+ };
4011
+ if (graph.nodes.size === 0) {
3882
4012
  const liveHash = liveMarker?.storageHash;
3883
4013
  if (targetHash === liveHash || liveHash === void 0 && targetHash === "empty") return {
3884
4014
  kind: "at-head",
@@ -3894,6 +4024,7 @@ function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker
3894
4024
  kind: "unsatisfiable",
3895
4025
  spaceId: space.spaceId,
3896
4026
  isAppSpace,
4027
+ targetHash,
3897
4028
  missing: [...headRef.invariants].sort(),
3898
4029
  targetInvariants: headRef.invariants,
3899
4030
  targetSpace: space,
@@ -3943,6 +4074,7 @@ function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker
3943
4074
  kind: "unsatisfiable",
3944
4075
  spaceId: space.spaceId,
3945
4076
  isAppSpace,
4077
+ targetHash,
3946
4078
  missing: walked.missing,
3947
4079
  targetInvariants,
3948
4080
  targetSpace,
@@ -3955,6 +4087,57 @@ function planSpacePath({ space, aggregate, targetHash, refInvariants, liveMarker
3955
4087
  plan: walked.result
3956
4088
  };
3957
4089
  }
4090
+ /** Every contract space's outcome, keyed by space, the application space first. */
4091
+ function planSpaces(args) {
4092
+ const { aggregate, appTarget } = args;
4093
+ return new Map([aggregate.app, ...aggregate.extensions].map((space) => {
4094
+ const isAppSpace = space.spaceId === aggregate.app.spaceId;
4095
+ const outcome = planSpacePath({
4096
+ space,
4097
+ aggregate,
4098
+ targetHash: isAppSpace ? appTarget.hash : requireHeadRef(space).hash,
4099
+ refInvariants: isAppSpace ? appTarget.invariants : void 0,
4100
+ liveMarker: args.markers.get(space.spaceId) ?? null,
4101
+ ...isAppSpace ? ifDefined("refName", appTarget.refName) : {},
4102
+ storageNameOf: args.storageNameOf
4103
+ });
4104
+ return [space.spaceId, outcome];
4105
+ }));
4106
+ }
4107
+ /**
4108
+ * Plans every contract space from the database's markers and refuses with
4109
+ * `MIGRATION.MARKER_MISMATCH` for the first space, the application space first, whose marker is
4110
+ * outside its graph, before any other failure a space reports. `db migrate`, `db migrate --show`
4111
+ * and the control API's `migrate` all decide it here, so they refuse the same database with the
4112
+ * same envelope.
4113
+ */
4114
+ async function planEverySpace(args) {
4115
+ const { aggregate } = args;
4116
+ const planned = planSpaces(args);
4117
+ const continuing = /* @__PURE__ */ new Map();
4118
+ for (const space of [aggregate.app, ...aggregate.extensions]) {
4119
+ const outcome = planned.get(space.spaceId);
4120
+ if (outcome === void 0) throw new InternalError(`Unreachable: no planned outcome for space "${space.spaceId}"`);
4121
+ if (outcome.kind !== "marker-outside-graph") {
4122
+ continuing.set(space.spaceId, outcome);
4123
+ continue;
4124
+ }
4125
+ return notOk(errorMarkerMismatch({
4126
+ spaceId: space.spaceId,
4127
+ owner: space.spaceId === aggregate.app.spaceId ? {
4128
+ kind: "application",
4129
+ emittedContractHash: requireHeadRef(space).hash
4130
+ } : { kind: "extension" },
4131
+ markerHash: outcome.markerHash,
4132
+ targetHash: outcome.targetHash,
4133
+ graph: space.graph(),
4134
+ migrationsDir: args.migrationsDir,
4135
+ ledger: await readLedgerQuietly(() => args.readLedger(space.spaceId)),
4136
+ invocation: args.invocation
4137
+ }));
4138
+ }
4139
+ return ok(continuing);
4140
+ }
3958
4141
  /**
3959
4142
  * Build a zero-op {@link PerSpacePlan} for an empty-graph space —
3960
4143
  * either one whose live marker already matches the target (at-head), or
@@ -5297,18 +5480,6 @@ function mapContractAtError(error, options) {
5297
5480
  if (CliStructuredError$1.is(error)) return notOk(error);
5298
5481
  throw error;
5299
5482
  }
5300
- /** True when the on-disk graph contains a path fromHash → toHash. */
5301
- function hasMigrationPath(graph, fromHash, toHash) {
5302
- return findPath(graph, fromHash, toHash) !== null;
5303
- }
5304
- /**
5305
- * Refusal for a live marker hash that is not a node of the on-disk app graph.
5306
- * Same errorMarkerMismatch envelope migrate raises today, or null when the marker is a node.
5307
- */
5308
- function refuseMarkerOutsideGraph(args) {
5309
- if (isGraphNode(args.markerHash, args.graph)) return null;
5310
- return errorMarkerMismatch(args.markerHash, [...args.graph.nodes].sort());
5311
- }
5312
5483
  /**
5313
5484
  * Invariant refusals shared by migrate and migration status: unknown ref invariants and unsatisfiable invariant paths.
5314
5485
  */
@@ -5404,6 +5575,17 @@ async function executeMigrateShowPlan(options) {
5404
5575
  const markerBySpace = /* @__PURE__ */ new Map();
5405
5576
  let databaseMarkers;
5406
5577
  const allSpaces = [aggregate.app, ...aggregate.extensions];
5578
+ const planInputs = () => ({
5579
+ aggregate,
5580
+ markers: markerBySpace,
5581
+ appTarget: {
5582
+ hash: targetHash,
5583
+ invariants: refInvariants,
5584
+ refName: void 0
5585
+ },
5586
+ storageNameOf
5587
+ });
5588
+ let outcomes;
5407
5589
  if (options.from !== void 0 && !liveOrigin) {
5408
5590
  const fromResult = resolveContractRef$1(options.from, refContext);
5409
5591
  if (!fromResult.ok) return notOk(fromResult.failure);
@@ -5427,36 +5609,31 @@ async function executeMigrateShowPlan(options) {
5427
5609
  const allMarkers = await client.readAllMarkers();
5428
5610
  databaseMarkers = allMarkers;
5429
5611
  const appMarker = allMarkers.get(aggregate.app.spaceId);
5430
- if (appMarker !== void 0) {
5431
- const refusal = refuseMarkerOutsideGraph({
5432
- markerHash: appMarker.storageHash,
5433
- graph: appGraph
5434
- });
5435
- if (refusal) return notOk(refusal);
5436
- }
5437
5612
  if (liveOrigin) for (const space of allSpaces) {
5438
5613
  const marker = allMarkers.get(space.spaceId);
5439
5614
  markerBySpace.set(space.spaceId, marker ?? null);
5440
5615
  }
5441
5616
  if (liveTarget) targetHash = contractHashAtMarker(appMarker);
5617
+ const checked = await planEverySpace({
5618
+ ...planInputs(),
5619
+ markers: allMarkers,
5620
+ migrationsDir,
5621
+ invocation: options.invocation,
5622
+ readLedger: (spaceId) => client.readLedger(spaceId)
5623
+ });
5624
+ if (!checked.ok) return notOk(checked.failure);
5625
+ if (liveOrigin) outcomes = checked.value;
5442
5626
  } catch (error) {
5443
5627
  return notOk(errorFromCaught(error, (message) => `Failed to read live DB marker: ${message}`, { connection: typeof dbConnection === "string" ? dbConnection : void 0 }));
5444
5628
  } finally {
5445
5629
  await closeQuietly(client);
5446
5630
  }
5447
5631
  }
5632
+ const planned = outcomes ?? planSpaces(planInputs());
5448
5633
  const orderedMigrations = [];
5449
5634
  for (const space of spacesInApplyOrder(aggregate)) {
5450
- const isAppSpace = space.spaceId === aggregate.app.spaceId;
5451
- const headRef = requireHeadRef(space);
5452
- const outcome = planSpacePath({
5453
- space,
5454
- aggregate,
5455
- targetHash: isAppSpace ? targetHash : headRef.hash,
5456
- refInvariants: isAppSpace ? refInvariants : void 0,
5457
- liveMarker: markerBySpace.get(space.spaceId) ?? null,
5458
- storageNameOf
5459
- });
5635
+ const outcome = planned.get(space.spaceId);
5636
+ if (outcome === void 0) throw new InternalError(`Unreachable: no planned outcome for space "${space.spaceId}"`);
5460
5637
  if (outcome.kind === "at-head") continue;
5461
5638
  if (outcome.kind === "never-planned") return notOk(errorPathUnreachable({
5462
5639
  summary: `No on-disk migrations for contract space "${outcome.spaceId}"`,
@@ -5467,8 +5644,8 @@ async function executeMigrateShowPlan(options) {
5467
5644
  kind: "neverPlanned"
5468
5645
  }
5469
5646
  }));
5470
- if (outcome.kind === "unreachable") {
5471
- const fromHash = outcome.liveMarker?.storageHash ?? "empty";
5647
+ if (outcome.kind === "unreachable" || outcome.kind === "marker-outside-graph") {
5648
+ const fromHash = outcome.kind === "marker-outside-graph" ? outcome.markerHash : outcome.liveMarker?.storageHash ?? "empty";
5472
5649
  return notOk(errorPathUnreachable({
5473
5650
  summary: `No migration path from ${fromHash.slice(0, 14)} to ${outcome.targetHash.slice(0, 14)} in space "${outcome.spaceId}".`,
5474
5651
  why: `The migration graph has no path from the from-state to the target in space "${outcome.spaceId}".`,
@@ -7038,6 +7215,10 @@ function buildAutoBaselinePlanSummary(baselineOpsCount, deltaOpsCount, emittedEx
7038
7215
  if (emittedExtensionDirsCount === 0) return base;
7039
7216
  return `${base}; materialised ${emittedExtensionDirsCount} ${emittedExtensionDirsCount === 1 ? "extension-space migration" : "extension-space migrations"}`;
7040
7217
  }
7218
+ /** True when the on-disk graph contains a path fromHash → toHash. */
7219
+ function hasMigrationPath(graph, fromHash, toHash) {
7220
+ return findPath(graph, fromHash, toHash) !== null;
7221
+ }
7041
7222
  function deriveStatusEdgeAnnotations(input) {
7042
7223
  const annotations = /* @__PURE__ */ new Map();
7043
7224
  if (input.showAppliedOverlay) {
@@ -7149,6 +7330,6 @@ async function executeRefListCommand(options) {
7149
7330
  }
7150
7331
  }
7151
7332
  //#endregion
7152
- export { refuseDeclaredExtensionTargetMismatch as $, executeRefDeleteCommand as A, loadAggregateIntegrityViolations as B, executeDbSign as C, 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, refuseContractSpaceIntegrity as Q, listRefsByContractHash as R, executeDbInit as S, withWarningFindings as St, executeDbVerify as T, loadContractSourceWithStack as U, loadContractRawSafely as V, loadContractSpaceAggregateForCli as W, preflightRefAdvancement as X, migrationSpaceListEntriesFromAggregate as Y, readMigrationRefs as Z, deriveStatusEdgeAnnotations as _, snapshotVerifierFor as _t, advanceRefSafely as a, requireDatabaseForLiveMarkerUse as at, enumerateCheckSpaces as b, toDeclaredExtensionsFromRaw as bt, buildContractSpaceAggregate as c, resolveContractRefToSnapshot as ct, buildRefAdvancementFields as d, resolveStatements as dt, refuseMarkerOutsideGraph 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, sourceWarningDiagnostic as vt, executeDbUpdate as w, executeContractEmit as x, validateLoadedContract as xt, enrichContract as y, statusForMigrationHash as yt, liveMarkerUse as z };
7333
+ export { refuseContractSpaceIntegrity as $, executeRefDeleteCommand as A, loadAggregateIntegrityViolations as B, executeDbSign as C, 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, withWarningFindings 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 _, snapshotVerifierFor as _t, advanceRefSafely as a, requireDatabaseForLiveMarkerUse as at, enumerateCheckSpaces as b, toDeclaredExtensionsFromRaw 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, sourceWarningDiagnostic as vt, executeDbUpdate as w, executeContractEmit as x, validateLoadedContract as xt, enrichContract as y, statusForMigrationHash as yt, liveMarkerUse as z };
7153
7334
 
7154
- //# sourceMappingURL=ref-C1IRwZNR-CW8ayjUw.mjs.map
7335
+ //# sourceMappingURL=ref-D-HCqZAl-DZcqYpTO.mjs.map