deltafold 0.0.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +274 -4
  2. package/dist/changelog.d.ts +116 -0
  3. package/dist/changelog.d.ts.map +1 -0
  4. package/dist/changelog.js +304 -0
  5. package/dist/changelog.js.map +1 -0
  6. package/dist/document-BZcZo9nr.js +171 -0
  7. package/dist/document-BZcZo9nr.js.map +1 -0
  8. package/dist/document-DWHsgywm.d.ts +257 -0
  9. package/dist/document-DWHsgywm.d.ts.map +1 -0
  10. package/dist/html.d.ts +8 -0
  11. package/dist/html.d.ts.map +1 -0
  12. package/dist/html.js +13 -0
  13. package/dist/html.js.map +1 -0
  14. package/dist/index.d.ts +378 -1
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +2058 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/markdown.d.ts +8 -0
  19. package/dist/markdown.d.ts.map +1 -0
  20. package/dist/markdown.js +16 -0
  21. package/dist/markdown.js.map +1 -0
  22. package/dist/mdast-DiRsYwPU.js +108 -0
  23. package/dist/mdast-DiRsYwPU.js.map +1 -0
  24. package/dist/package-BfBYnaCz.d.ts +1125 -0
  25. package/dist/package-BfBYnaCz.d.ts.map +1 -0
  26. package/dist/rolldown-runtime-D8jQpDG7.js +12 -0
  27. package/package.json +13 -1
  28. package/src/features/documents/changelog.ts +450 -0
  29. package/src/features/documents/document.ts +357 -0
  30. package/src/features/documents/index.ts +4 -0
  31. package/src/features/documents/public-document.ts +31 -0
  32. package/src/features/documents/sections.ts +44 -0
  33. package/src/features/execution/executor.ts +826 -0
  34. package/src/features/execution/handler.ts +257 -0
  35. package/src/features/execution/settlement.ts +49 -0
  36. package/src/features/package.ts +32 -0
  37. package/src/features/planning/guide.ts +56 -0
  38. package/src/features/planning/history.ts +174 -0
  39. package/src/features/planning/identifiers.ts +43 -0
  40. package/src/features/planning/resolve-error.ts +201 -0
  41. package/src/features/planning/resolve.ts +724 -0
  42. package/src/features/planning/rewrite.ts +331 -0
  43. package/src/features/planning/validate.ts +388 -0
  44. package/src/foundation/action.ts +188 -0
  45. package/src/foundation/change.ts +147 -0
  46. package/src/foundation/instruction.ts +110 -0
  47. package/src/foundation/migration.ts +236 -0
  48. package/src/foundation/plan.ts +245 -0
  49. package/src/foundation/rule.ts +74 -0
  50. package/src/foundation/shortcut.ts +79 -0
  51. package/src/foundation/template.ts +28 -0
  52. package/src/foundation/version.ts +78 -0
  53. package/src/index.ts +22 -11
  54. package/src/renderers/html.ts +12 -0
  55. package/src/renderers/markdown.ts +12 -0
  56. package/src/renderers/mdast.ts +120 -0
  57. package/src/types.ts +2 -0
package/dist/index.js CHANGED
@@ -0,0 +1,2058 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { Array as Array$1, Cause, Context, Data, Deferred, Duration, Effect, Equal, Exit, Graph, Option, Order, Predicate, Result, Schema, SemVer } from "effect";
3
+ import dedentText from "dedent";
4
+ // src/foundation/action.ts
5
+ var action_exports = /* @__PURE__ */ __exportAll({
6
+ define: () => define$1,
7
+ isAction: () => isAction,
8
+ isParallel: () => isParallel,
9
+ isRef: () => isRef,
10
+ isSequence: () => isSequence,
11
+ parallel: () => parallel,
12
+ ref: () => ref,
13
+ sequence: () => sequence
14
+ });
15
+ /**
16
+ * Defines an action kind.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const RenameKey = Action.define<{ target: string; from: string; to: string }>(
21
+ * "config.rename",
22
+ * { describe: ({ target, from, to }) => `In ${target}, rename "${from}" to "${to}"` },
23
+ * );
24
+ * const renameExportA = RenameKey.make("rename-export-a-timeout", {
25
+ * target: "export-a",
26
+ * from: "timeout",
27
+ * to: "requestTimeout",
28
+ * });
29
+ * ```
30
+ *
31
+ * @since @next
32
+ */
33
+ const define$1 = (kind, options = {}) => {
34
+ const describe = options.describe ?? (() => kind);
35
+ return {
36
+ _tag: "ActionKind",
37
+ kind,
38
+ describe,
39
+ make: (id, payload) => ({
40
+ _tag: "Action",
41
+ id,
42
+ kind,
43
+ payload,
44
+ description: describe(payload)
45
+ })
46
+ };
47
+ };
48
+ /**
49
+ * Mentions an action in prose without declaring another occurrence.
50
+ *
51
+ * @since @next
52
+ */
53
+ const ref = (action) => ({
54
+ _tag: "ActionRef",
55
+ action
56
+ });
57
+ /**
58
+ * Declares steps that run one after another.
59
+ *
60
+ * @since @next
61
+ */
62
+ const sequence = (children) => ({
63
+ _tag: "Sequence",
64
+ children
65
+ });
66
+ /**
67
+ * Declares independent branches that may run concurrently. Each branch can be a single
68
+ * step or a sequence.
69
+ *
70
+ * @since @next
71
+ */
72
+ const parallel = (branches, options = {}) => ({
73
+ _tag: "Parallel",
74
+ branches,
75
+ concurrency: options.concurrency ?? "unbounded"
76
+ });
77
+ /** @since @next */
78
+ const isAction = (value) => Predicate.isTagged(value, "Action") && Predicate.hasProperty(value, "id");
79
+ /** @since @next */
80
+ const isRef = (value) => Predicate.isTagged(value, "ActionRef");
81
+ /** @since @next */
82
+ const isSequence = (value) => Predicate.isTagged(value, "Sequence");
83
+ /** @since @next */
84
+ const isParallel = (value) => Predicate.isTagged(value, "Parallel");
85
+ // src/foundation/template.ts
86
+ const placeholder = "\0";
87
+ /**
88
+ * Removes the common indentation of a tagged template and its surrounding whitespace.
89
+ *
90
+ * Returns one literal string per original literal, so interpolated values stay at their
91
+ * positions and are never stringified or re-indented.
92
+ */
93
+ const dedent = (strings) => dedentText(strings.join(placeholder)).split(placeholder);
94
+ const isScalar = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint";
95
+ const describeValue = (value) => {
96
+ if (value === null) return "null";
97
+ if (Array.isArray(value)) return "an array";
98
+ return typeof value === "object" ? "an object" : typeof value;
99
+ };
100
+ // src/foundation/change.ts
101
+ var change_exports = /* @__PURE__ */ __exportAll({
102
+ define: () => define,
103
+ isChange: () => isChange,
104
+ make: () => make$5
105
+ });
106
+ const describe = (id, metadata, relations) => (strings, ...values) => {
107
+ const literals = dedent(strings);
108
+ let description = "";
109
+ for (const [index, literal] of literals.entries()) {
110
+ description += literal;
111
+ if (index >= values.length) continue;
112
+ const value = values[index];
113
+ if (!isScalar(value)) throw new TypeError(`Change "${id}": cannot interpolate ${describeValue(value)}.`);
114
+ description += String(value);
115
+ }
116
+ return {
117
+ _tag: "Change",
118
+ id,
119
+ metadata,
120
+ description,
121
+ reverts: relations.reverts ?? [],
122
+ backportOf: relations.backportOf
123
+ };
124
+ };
125
+ function make$5(id, metadata = {}, relations = {}) {
126
+ return describe(id, metadata, relations);
127
+ }
128
+ /**
129
+ * Defines a reusable change factory whose metadata must have the type `M`.
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * const ConfigChange = Change.define<{
134
+ * readonly kind: "added" | "changed" | "fixed";
135
+ * readonly breaking: boolean;
136
+ * }>();
137
+ * const timeoutRenamed = ConfigChange.make("2026-11-06.rename-timeout", {
138
+ * kind: "changed",
139
+ * breaking: true,
140
+ * })`
141
+ * Rename the timeout configuration option to requestTimeout.
142
+ * `;
143
+ * ```
144
+ *
145
+ * @since @next
146
+ */
147
+ const define = () => ({ make: make$5 });
148
+ /** @since @next */
149
+ const isChange = (value) => Predicate.isTagged(value, "Change");
150
+ // src/features/execution/settlement.ts
151
+ const SettlementReference = Context.Reference("deltafold/Settlement", { defaultValue: () => ({
152
+ grace: Duration.zero,
153
+ record: () => {}
154
+ }) });
155
+ /**
156
+ * Runs a Promise-producing effect. If it is interrupted after the Promise started,
157
+ * waits up to the settlement grace period and records whether the Promise settled.
158
+ */
159
+ const trackPromise = (start) => Effect.suspend(() => {
160
+ let pending;
161
+ const capture = (promise) => {
162
+ pending = promise;
163
+ return promise;
164
+ };
165
+ return start(capture).pipe(Effect.onInterrupt(() => Effect.gen(function* () {
166
+ const started = pending;
167
+ if (started === void 0) return;
168
+ const settlement = yield* SettlementReference;
169
+ const settled = yield* Effect.promise(() => started.then(() => void 0, () => void 0)).pipe(Effect.timeoutOption(settlement.grace));
170
+ settlement.record(Option.isSome(settled));
171
+ })));
172
+ });
173
+ // src/features/execution/handler.ts
174
+ var handler_exports = /* @__PURE__ */ __exportAll({
175
+ UnexpectedHandlerError: () => UnexpectedHandlerError,
176
+ effect: () => effect$1,
177
+ isHandler: () => isHandler,
178
+ promise: () => promise
179
+ });
180
+ /**
181
+ * A Promise handler rejected or threw a value that none of its declared error guards
182
+ * recognized.
183
+ *
184
+ * @since @next
185
+ */
186
+ var UnexpectedHandlerError = class extends Data.TaggedError("UnexpectedHandlerError") {
187
+ get message() {
188
+ return `Handler for action "${this.actionId}" failed unexpectedly in its ${this.phase}`;
189
+ }
190
+ };
191
+ const TypeId = "~deltafold/Handler";
192
+ /** @since @next */
193
+ const isHandler = (value) => Predicate.hasProperty(value, TypeId);
194
+ const skipReasonOf = (action, reason) => {
195
+ if (reason === void 0) return "Precondition returned false";
196
+ return typeof reason === "string" ? reason : reason(action.payload);
197
+ };
198
+ const declaredError = (guards) => (cause) => guards.some((guard) => Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause));
199
+ /**
200
+ * Implements an action with Promise callbacks. The callbacks run lazily through
201
+ * `Effect.tryPromise`, and receive its `AbortSignal` and the declared services in
202
+ * their second argument.
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * Handler.promise(
207
+ * updateRemoteConfig,
208
+ * async (payload, { signal, services: { editor } }) => {
209
+ * await editor.update(payload, { signal });
210
+ * },
211
+ * { services: { editor: ConfigEditor } },
212
+ * );
213
+ * ```
214
+ *
215
+ * @since @next
216
+ */
217
+ const promise = (action, run, options) => {
218
+ const isDeclared = declaredError(options?.errors ?? []);
219
+ const services = options?.services ?? {};
220
+ const resolve = Effect.map(Effect.context(), (context) => Object.fromEntries(Reflect.ownKeys(services).map((name) => [name, Context.get(context, services[name])])));
221
+ const adapt = (phase, callback) => Effect.flatMap(resolve, (resolved) => trackPromise((capture) => Effect.tryPromise({
222
+ try: (signal) => capture(Promise.resolve(callback({
223
+ signal,
224
+ services: resolved
225
+ }))),
226
+ catch: (cause) => isDeclared(cause) ? cause : new UnexpectedHandlerError({
227
+ actionId: action.id,
228
+ kind: action.kind,
229
+ phase,
230
+ cause
231
+ })
232
+ })));
233
+ const when = options?.when;
234
+ return {
235
+ [TypeId]: TypeId,
236
+ action,
237
+ body: Effect.asVoid(adapt("body", (context) => run(action.payload, context))),
238
+ precondition: when === void 0 ? void 0 : adapt("precondition", (context) => when(action.payload, context)),
239
+ skipReason: skipReasonOf(action, options?.skipReason)
240
+ };
241
+ };
242
+ /**
243
+ * Implements an action with an Effect. The body keeps its own errors and services, and
244
+ * stops through native Effect interruption.
245
+ *
246
+ * @since @next
247
+ */
248
+ const effect$1 = (action, run, options = {}) => {
249
+ const when = options.when;
250
+ return {
251
+ [TypeId]: TypeId,
252
+ action,
253
+ body: Effect.asVoid(Effect.suspend(() => run(action.payload))),
254
+ precondition: when === void 0 ? void 0 : Effect.suspend(() => when(action.payload)),
255
+ skipReason: skipReasonOf(action, options.skipReason)
256
+ };
257
+ };
258
+ // src/features/execution/executor.ts
259
+ var executor_exports = /* @__PURE__ */ __exportAll({
260
+ ExecutionFailed: () => ExecutionFailed,
261
+ ExecutionInterrupted: () => ExecutionInterrupted,
262
+ HandlerCoverageError: () => HandlerCoverageError,
263
+ effect: () => effect,
264
+ runPromise: () => runPromise
265
+ });
266
+ const HandlerCoverageBase = Data.TaggedError("HandlerCoverageError");
267
+ /**
268
+ * Handler coverage failed before any precondition or body ran. Every occurrence needs
269
+ * exactly one handler, for the same action definition: the same identifier, kind, and
270
+ * payload. For an occurrence that a rule produced, the issue names the rule and the
271
+ * occurrences it replaced.
272
+ *
273
+ * @since @next
274
+ */
275
+ var HandlerCoverageError = class extends HandlerCoverageBase {
276
+ get message() {
277
+ return `Handler coverage failed for ${this.issues.length} occurrence(s): ${this.issues.map((issue) => `${issue._tag.toLowerCase()} handler for "${issue.actionId}" (${issue.description})`).join("; ")}.`;
278
+ }
279
+ };
280
+ const ExecutionFailedBase = Data.TaggedError("ExecutionFailed");
281
+ /**
282
+ * An occurrence failed. Execution stopped admitting new actions; started ones settled.
283
+ *
284
+ * @since @next
285
+ */
286
+ var ExecutionFailed = class extends ExecutionFailedBase {
287
+ get message() {
288
+ return `Execution failed at ${this.failures.map((failure) => `"${failure.occurrence.id}"`).join(", ")}. Completed actions were not rolled back.`;
289
+ }
290
+ };
291
+ const ExecutionInterruptedBase = Data.TaggedError("ExecutionInterrupted");
292
+ const interruptedBy = {
293
+ cancelled: "cancelled",
294
+ timeout: "stopped by a timeout",
295
+ handler: "interrupted by a handler"
296
+ };
297
+ /**
298
+ * Explicit cancellation, a configured timeout, or a handler's own interruption stopped
299
+ * execution.
300
+ *
301
+ * @since @next
302
+ */
303
+ var ExecutionInterrupted = class extends ExecutionInterruptedBase {
304
+ get message() {
305
+ const pending = this.report.occurrences.filter((entry) => entry.outcome._tag === "Interrupted" && !entry.outcome.settled);
306
+ const suffix = pending.length === 0 ? "" : ` ${pending.length} interrupted action(s) had not settled and may still be running.`;
307
+ return `Execution was ${interruptedBy[this.reason]}.${suffix}`;
308
+ }
309
+ };
310
+ const describeReplaces = (occurrence) => occurrence.origin._tag === "Replacement" ? occurrence.origin.replaces.map((replaced) => ({
311
+ occurrenceId: replaced.id,
312
+ description: replaced.action.description
313
+ })) : [];
314
+ const coverage = (plan, handlers) => {
315
+ const byAction = /* @__PURE__ */ new Map();
316
+ for (const handler of handlers) {
317
+ const list = byAction.get(handler.action.id) ?? [];
318
+ list.push(handler);
319
+ byAction.set(handler.action.id, list);
320
+ }
321
+ const resolved = /* @__PURE__ */ new Map();
322
+ const issues = [];
323
+ for (const occurrence of plan.occurrences) {
324
+ const issue = (tag) => issues.push({
325
+ _tag: tag,
326
+ occurrenceId: occurrence.id,
327
+ actionId: occurrence.action.id,
328
+ description: occurrence.action.description,
329
+ migrationId: occurrence.migration.id,
330
+ rule: occurrence.origin._tag === "Replacement" ? occurrence.origin.rule.id : void 0,
331
+ replaces: describeReplaces(occurrence)
332
+ });
333
+ const candidates = byAction.get(occurrence.action.id) ?? [];
334
+ const [selected] = candidates;
335
+ if (candidates.length > 1) issue("Duplicate");
336
+ else if (selected === void 0) issue("Missing");
337
+ else if (selected.action.kind !== occurrence.action.kind || !Equal.equals(selected.action.payload, occurrence.action.payload)) issue("Mismatched");
338
+ else resolved.set(occurrence.id, selected);
339
+ }
340
+ return {
341
+ resolved,
342
+ issues
343
+ };
344
+ };
345
+ const report = (plan, mode, status, outcomes, bodiesStarted) => ({
346
+ _tag: "Report",
347
+ mode,
348
+ status,
349
+ from: plan.from.id,
350
+ to: plan.to.id,
351
+ route: plan.route.id,
352
+ occurrences: plan.occurrences.map((occurrence) => ({
353
+ occurrence,
354
+ outcome: outcomes.get(occurrence.id) ?? { _tag: "Unattempted" }
355
+ })),
356
+ bodiesStarted,
357
+ persistence: "none"
358
+ });
359
+ const failureOf = (cause) => ({
360
+ error: Option.getOrUndefined(Cause.findErrorOption(cause)),
361
+ cause
362
+ });
363
+ const forEachBranch = (branches, concurrency, run) => Effect.forEach(branches, run, {
364
+ concurrency,
365
+ discard: true
366
+ });
367
+ /** Admission state, cancellation, and timeouts shared by real and dry runs. */
368
+ const makeControl = (options, subscribe) => Effect.gen(function* () {
369
+ const halt = { reason: void 0 };
370
+ const cancelled = yield* Deferred.make();
371
+ const settleTimeout = options.settleTimeout ?? Duration.seconds(5);
372
+ const stop = (reason) => {
373
+ halt.reason ??= reason;
374
+ };
375
+ subscribe?.(() => {
376
+ stop("cancelled");
377
+ Deferred.doneUnsafe(cancelled, Exit.succeed("cancelled"));
378
+ });
379
+ /** Runs one precondition or body, racing it against cancellation and the timeout. */
380
+ const runPhase = (work) => Effect.gen(function* () {
381
+ let settled = true;
382
+ const tracked = work.pipe(Effect.provideService(SettlementReference, {
383
+ grace: settleTimeout,
384
+ record: (value) => {
385
+ settled = value;
386
+ }
387
+ }));
388
+ const stopSignals = [Deferred.await(cancelled)];
389
+ if (options.timeout !== void 0) stopSignals.push(Effect.as(Effect.sleep(options.timeout), "timeout"));
390
+ const result = yield* Effect.raceFirst(Effect.map(Effect.exit(tracked), (exit) => ({
391
+ _tag: "Done",
392
+ exit
393
+ })), Effect.raceAll(stopSignals).pipe(Effect.tap((reason) => Effect.sync(() => stop(reason))), Effect.map((reason) => ({
394
+ _tag: "Stop",
395
+ reason
396
+ }))));
397
+ if (result._tag === "Done") return result;
398
+ return {
399
+ _tag: "Interrupted",
400
+ reason: result.reason,
401
+ settled
402
+ };
403
+ });
404
+ return {
405
+ halt,
406
+ stop,
407
+ runPhase
408
+ };
409
+ });
410
+ const interrupted = (plan, mode, reason, outcomes, bodiesStarted) => new ExecutionInterrupted({
411
+ reason,
412
+ report: report(plan, mode, "interrupted", outcomes, bodiesStarted)
413
+ });
414
+ const execute = (plan, resolved, options, subscribe) => Effect.gen(function* () {
415
+ const outcomes = /* @__PURE__ */ new Map();
416
+ const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
417
+ let bodiesStarted = false;
418
+ const runOccurrence = (occurrence) => Effect.gen(function* () {
419
+ if (halt.reason !== void 0) return;
420
+ const handler = resolved.get(occurrence.id);
421
+ if (handler === void 0) return;
422
+ if (handler.precondition !== void 0) {
423
+ const checked = yield* runPhase(handler.precondition);
424
+ if (checked._tag === "Interrupted") {
425
+ outcomes.set(occurrence.id, {
426
+ _tag: "Interrupted",
427
+ phase: "precondition",
428
+ reason: checked.reason,
429
+ settled: checked.settled
430
+ });
431
+ return;
432
+ }
433
+ if (Exit.isFailure(checked.exit) && Cause.hasInterruptsOnly(checked.exit.cause)) {
434
+ stop("handler");
435
+ outcomes.set(occurrence.id, {
436
+ _tag: "Interrupted",
437
+ phase: "precondition",
438
+ reason: "handler",
439
+ settled: true
440
+ });
441
+ return;
442
+ }
443
+ if (Exit.isFailure(checked.exit)) {
444
+ stop("failure");
445
+ outcomes.set(occurrence.id, {
446
+ _tag: "Failed",
447
+ phase: "precondition",
448
+ ...failureOf(checked.exit.cause)
449
+ });
450
+ return;
451
+ }
452
+ if (!checked.exit.value) {
453
+ outcomes.set(occurrence.id, {
454
+ _tag: "Skipped",
455
+ reason: handler.skipReason
456
+ });
457
+ return;
458
+ }
459
+ if (halt.reason === "cancelled") return;
460
+ }
461
+ bodiesStarted = true;
462
+ const ran = yield* runPhase(handler.body);
463
+ if (ran._tag === "Interrupted") {
464
+ outcomes.set(occurrence.id, {
465
+ _tag: "Interrupted",
466
+ phase: "body",
467
+ reason: ran.reason,
468
+ settled: ran.settled
469
+ });
470
+ return;
471
+ }
472
+ if (Exit.isFailure(ran.exit) && Cause.hasInterruptsOnly(ran.exit.cause)) {
473
+ stop("handler");
474
+ outcomes.set(occurrence.id, {
475
+ _tag: "Interrupted",
476
+ phase: "body",
477
+ reason: "handler",
478
+ settled: true
479
+ });
480
+ return;
481
+ }
482
+ if (Exit.isFailure(ran.exit)) {
483
+ stop("failure");
484
+ outcomes.set(occurrence.id, {
485
+ _tag: "Failed",
486
+ phase: "body",
487
+ ...failureOf(ran.exit.cause)
488
+ });
489
+ return;
490
+ }
491
+ outcomes.set(occurrence.id, { _tag: "Completed" });
492
+ });
493
+ const runNode = (node) => {
494
+ switch (node._tag) {
495
+ case "Occurrence": return runOccurrence(node);
496
+ case "Sequence": return Effect.forEach(node.children, runNode, { discard: true });
497
+ }
498
+ return forEachBranch(node.branches, node.concurrency, runNode);
499
+ };
500
+ for (const step of plan.steps) {
501
+ if (halt.reason !== void 0) break;
502
+ yield* runNode(step.node);
503
+ }
504
+ if (halt.reason === void 0) return report(plan, "execute", "completed", outcomes, bodiesStarted);
505
+ if (halt.reason === "failure") {
506
+ const result = report(plan, "execute", "failed", outcomes, bodiesStarted);
507
+ return yield* new ExecutionFailed({
508
+ failures: result.occurrences.filter((entry) => entry.outcome._tag === "Failed"),
509
+ report: result
510
+ });
511
+ }
512
+ return yield* interrupted(plan, "execute", halt.reason, outcomes, bodiesStarted);
513
+ });
514
+ const dryRun = (plan, resolved, options, subscribe) => Effect.gen(function* () {
515
+ const outcomes = /* @__PURE__ */ new Map();
516
+ const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
517
+ let failedAt;
518
+ /** Returns whether the node would or might change state. */
519
+ const visit = (node, dirty) => Effect.gen(function* () {
520
+ if (node._tag === "Sequence") {
521
+ let current = dirty;
522
+ for (const child of node.children) current = yield* visit(child, current);
523
+ return current;
524
+ }
525
+ if (node._tag === "Parallel") {
526
+ let changed = dirty;
527
+ for (const branch of node.branches) changed = (yield* visit(branch, dirty)) || changed;
528
+ return changed;
529
+ }
530
+ const handler = resolved.get(node.id);
531
+ if (handler === void 0 || halt.reason !== void 0) return dirty;
532
+ if (failedAt !== void 0) {
533
+ outcomes.set(node.id, {
534
+ _tag: "Undetermined",
535
+ reason: `Execution would stop at the failed precondition of "${failedAt}".`
536
+ });
537
+ return true;
538
+ }
539
+ if (handler.precondition === void 0) {
540
+ outcomes.set(node.id, {
541
+ _tag: "WouldExecute",
542
+ evaluated: false
543
+ });
544
+ return true;
545
+ }
546
+ if (dirty) {
547
+ outcomes.set(node.id, {
548
+ _tag: "Undetermined",
549
+ reason: "The precondition depends on earlier actions that a dry run does not apply."
550
+ });
551
+ return true;
552
+ }
553
+ const checked = yield* runPhase(handler.precondition);
554
+ if (checked._tag === "Interrupted") {
555
+ outcomes.set(node.id, {
556
+ _tag: "Interrupted",
557
+ phase: "precondition",
558
+ reason: checked.reason,
559
+ settled: checked.settled
560
+ });
561
+ return true;
562
+ }
563
+ if (Exit.isFailure(checked.exit) && Cause.hasInterruptsOnly(checked.exit.cause)) {
564
+ stop("handler");
565
+ outcomes.set(node.id, {
566
+ _tag: "Interrupted",
567
+ phase: "precondition",
568
+ reason: "handler",
569
+ settled: true
570
+ });
571
+ return true;
572
+ }
573
+ if (Exit.isFailure(checked.exit)) {
574
+ failedAt = node.id;
575
+ outcomes.set(node.id, {
576
+ _tag: "PreconditionFailed",
577
+ ...failureOf(checked.exit.cause)
578
+ });
579
+ return true;
580
+ }
581
+ if (!checked.exit.value) {
582
+ outcomes.set(node.id, {
583
+ _tag: "WouldSkip",
584
+ reason: handler.skipReason
585
+ });
586
+ return false;
587
+ }
588
+ outcomes.set(node.id, {
589
+ _tag: "WouldExecute",
590
+ evaluated: true
591
+ });
592
+ return true;
593
+ });
594
+ let dirty = false;
595
+ for (const step of plan.steps) dirty = yield* visit(step.node, dirty);
596
+ if (halt.reason !== void 0 && halt.reason !== "failure") return yield* interrupted(plan, "dry-run", halt.reason, outcomes, false);
597
+ return report(plan, "dry-run", failedAt === void 0 ? "would-complete" : "would-fail", outcomes, false);
598
+ });
599
+ const run = (plan, options, subscribe) => {
600
+ const handlers = options.handlers ?? [];
601
+ return Effect.gen(function* () {
602
+ const checked = coverage(plan, handlers);
603
+ if (checked.issues.length > 0) return yield* new HandlerCoverageError({
604
+ issues: checked.issues,
605
+ report: report(plan, options.dryRun === true ? "dry-run" : "execute", "not-started", /* @__PURE__ */ new Map(), false)
606
+ });
607
+ return options.dryRun === true ? yield* dryRun(plan, checked.resolved, options, subscribe) : yield* execute(plan, checked.resolved, options, subscribe);
608
+ });
609
+ };
610
+ /**
611
+ * Runs a plan as an Effect. Coverage is checked before any precondition or body runs.
612
+ * Steps are sequential barriers; parallel groups run their branches concurrently. On
613
+ * failure, no new action starts, and actions already running settle before the effect
614
+ * fails with the partial report.
615
+ *
616
+ * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the
617
+ * signal passed to Promise callbacks. The effect then ends as interrupted, without a
618
+ * report.
619
+ *
620
+ * @since @next
621
+ */
622
+ const effect = (plan, options) => run(plan, options, void 0);
623
+ /**
624
+ * Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,
625
+ * `ExecutionFailed`, or `ExecutionInterrupted`, each carrying the partial report.
626
+ * Building a supplied services layer can also reject with the layer's own error,
627
+ * without a report.
628
+ *
629
+ * A services layer is built for this run and finalized when the run ends. A services
630
+ * context stays owned by the caller. A Promise callback that ignores its signal can keep
631
+ * running after cancellation or a timeout, beyond `settleTimeout`, and so after the
632
+ * run's layer resources are finalized; the report marks it as possibly still running.
633
+ *
634
+ * @since @next
635
+ */
636
+ const runPromise = (plan, options) => {
637
+ const { signal } = options;
638
+ const notStarted = () => new ExecutionInterrupted({
639
+ reason: "cancelled",
640
+ report: report(plan, options.dryRun === true ? "dry-run" : "execute", "interrupted", /* @__PURE__ */ new Map(), false)
641
+ });
642
+ if (signal?.aborted === true) return Promise.reject(notStarted());
643
+ const abortedBeforeRun = Deferred.makeUnsafe();
644
+ let cancelRun;
645
+ const onAbort = () => {
646
+ if (cancelRun === void 0) Deferred.doneUnsafe(abortedBeforeRun, Effect.void);
647
+ else cancelRun();
648
+ };
649
+ signal?.addEventListener("abort", onAbort, { once: true });
650
+ const program = run(plan, options, signal === void 0 ? void 0 : (cancel) => {
651
+ cancelRun = cancel;
652
+ if (signal.aborted) cancel();
653
+ });
654
+ const services = options.services;
655
+ const provided = services === void 0 ? program : Context.isContext(services) ? Effect.provideContext(program, services) : Effect.provide(program, services);
656
+ const cancellable = signal === void 0 ? provided : Effect.raceFirst(provided, Effect.andThen(Deferred.await(abortedBeforeRun), Effect.fail(notStarted())));
657
+ return Effect.runPromiseExit(cancellable).finally(() => signal?.removeEventListener("abort", onAbort)).then((exit) => {
658
+ if (Exit.isSuccess(exit)) return exit.value;
659
+ throw Cause.squash(exit.cause);
660
+ });
661
+ };
662
+ // src/features/planning/resolve-error.ts
663
+ /**
664
+ * The history's declarations are invalid. Resolution needs a valid history.
665
+ *
666
+ * @since @next
667
+ */
668
+ var InvalidHistory = class extends Data.TaggedError("InvalidHistory") {
669
+ get message() {
670
+ return `The history has ${this.issues.length} declaration issue(s): ${this.issues.map((issue) => issue.message).join(" ")}`;
671
+ }
672
+ };
673
+ /** @since @next */
674
+ var UnknownVersion = class extends Data.TaggedError("UnknownVersion") {
675
+ get message() {
676
+ return `Version "${this.version}" is not registered in the history.`;
677
+ }
678
+ };
679
+ /**
680
+ * No declared route connects the versions. This never means that no work is needed:
681
+ * declare `Migration.noop` for a supported zero-work transition.
682
+ *
683
+ * @since @next
684
+ */
685
+ var UnsupportedRoute = class extends Data.TaggedError("UnsupportedRoute") {
686
+ get message() {
687
+ const closest = this.closest.length === 0 ? "" : ` Closest reachable: ${this.closest.join(", ")}.`;
688
+ return `No declared ${this.direction} route from "${this.from}" to "${this.to}".${closest}`;
689
+ }
690
+ };
691
+ /**
692
+ * Several routes connect the versions and no selection or policy chose one.
693
+ *
694
+ * @since @next
695
+ */
696
+ var AmbiguousRoute = class extends Data.TaggedError("AmbiguousRoute") {
697
+ get message() {
698
+ const ids = this.candidates.map((candidate) => `"${candidate.id}"`).join(", ");
699
+ const reason = this.policy === void 0 ? "" : ` after applying the "${this.policy}" policy`;
700
+ return `${this.candidates.length} routes connect "${this.from}" and "${this.to}"${reason}: ${ids}. Select one with the \`route\` option, or choose a route policy.`;
701
+ }
702
+ };
703
+ /**
704
+ * The `route` option names no candidate route.
705
+ *
706
+ * @since @next
707
+ */
708
+ var UnknownRoute = class extends Data.TaggedError("UnknownRoute") {
709
+ get message() {
710
+ return `No candidate route has the identifier "${this.route}". Candidates: ${this.candidates.map((candidate) => `"${candidate.id}"`).join(", ")}.`;
711
+ }
712
+ };
713
+ /**
714
+ * Rules rewrite a sequence back into itself.
715
+ *
716
+ * @since @next
717
+ */
718
+ var RewriteCycle = class extends Data.TaggedError("RewriteCycle") {
719
+ get message() {
720
+ return `Rules ${this.rules.map((rule) => `"${rule}"`).join(", ")} rewrite a sequence back into itself on route "${this.route}".`;
721
+ }
722
+ };
723
+ /**
724
+ * Rules can produce different results depending on which applies first.
725
+ *
726
+ * @since @next
727
+ */
728
+ var ConflictingRewrites = class extends Data.TaggedError("ConflictingRewrites") {
729
+ get message() {
730
+ return `Rules produce ${this.outcomes.length} different results on route "${this.route}", depending on the order they apply in.`;
731
+ }
732
+ };
733
+ /**
734
+ * Optimization explored too many states or chained too many rule applications, for
735
+ * example because a rule keeps growing the sequence.
736
+ *
737
+ * @since @next
738
+ */
739
+ var RewriteLimitExceeded = class extends Data.TaggedError("RewriteLimitExceeded") {
740
+ get message() {
741
+ return this.limit === "states" ? `Optimizing route "${this.route}" explored more than ${this.value} states.` : `Optimizing route "${this.route}" chained more than ${this.value} rule applications.`;
742
+ }
743
+ };
744
+ /**
745
+ * More candidate routes exist than the resolver enumerates.
746
+ *
747
+ * @since @next
748
+ */
749
+ var TooManyRoutes = class extends Data.TaggedError("TooManyRoutes") {
750
+ get message() {
751
+ return `More than ${this.limit} routes connect "${this.from}" and "${this.to}".`;
752
+ }
753
+ };
754
+ // src/features/planning/guide.ts
755
+ /** The declared occurrence a retained occurrence is rendered at. */
756
+ const anchorOf = (occurrence) => {
757
+ if (occurrence.origin._tag === "Declared") return occurrence;
758
+ const first = occurrence.origin.replaces[0];
759
+ return first === void 0 ? occurrence : anchorOf(first);
760
+ };
761
+ /**
762
+ * Resolves a migration's content against the occurrences that survived optimization.
763
+ * Removed occurrences disappear with their instruction blocks. Replacements render at
764
+ * the position of the first occurrence they replaced, using their own instruction or
765
+ * description. Unassociated prose stays.
766
+ */
767
+ const resolveGuide = (content, retained, declaredId) => {
768
+ const byAnchor = /* @__PURE__ */ new Map();
769
+ for (const occurrence of retained) {
770
+ const anchor = anchorOf(occurrence).id;
771
+ const list = byAnchor.get(anchor) ?? [];
772
+ list.push(occurrence);
773
+ byAnchor.set(anchor, list);
774
+ }
775
+ const renderStep = (step) => {
776
+ if (step._tag === "Action" || step._tag === "Instruction") {
777
+ const action = step._tag === "Action" ? step : step.action;
778
+ return (byAnchor.get(declaredId(action)) ?? []).map((occurrence) => ({
779
+ _tag: "Occurrence",
780
+ occurrence
781
+ }));
782
+ }
783
+ const children = (step._tag === "Sequence" ? step.children : step.branches).map((child) => renderStep(child)).filter((items) => items.length > 0);
784
+ if (children.length === 0) return [];
785
+ return [{
786
+ _tag: "Group",
787
+ kind: step._tag,
788
+ children
789
+ }];
790
+ };
791
+ return content.flatMap((fragment) => {
792
+ if (fragment._tag === "Text" || fragment._tag === "ActionRef") return [fragment];
793
+ return renderStep(fragment);
794
+ });
795
+ };
796
+ // src/features/planning/identifiers.ts
797
+ const escape = (value, separators) => value.replace(separators, "\\$&");
798
+ const occurrencePart = (id) => escape(id, /[\\/()+]/g);
799
+ const routePart = (id) => escape(id, /[\\>[\]]/g);
800
+ /** `<migration>/<action>` forward, `<migration>/revert/<action>` in reverse. */
801
+ const declaredOccurrenceId = (migration, direction, action) => direction === "forward" ? `${occurrencePart(migration.id)}/${occurrencePart(action.id)}` : `${occurrencePart(migration.id)}/revert/${occurrencePart(action.id)}`;
802
+ /**
803
+ * `<rule>(<replaced>+<replaced>)/<action>`. Replaced identifiers are complete occurrence
804
+ * identifiers, so they nest without further escaping.
805
+ */
806
+ const replacementOccurrenceId = (rule, replaced, action) => `${occurrencePart(rule.id)}(${replaced.map((occurrence) => occurrence.id).join("+")})/${occurrencePart(action.id)}`;
807
+ /** The first version of a route identifier. */
808
+ const routeStart = (version) => routePart(version);
809
+ /** A migration hop: `>` and the target version. */
810
+ const routeHop = (to) => `>${routePart(to)}`;
811
+ /** A shortcut hop: `>[shortcut]>` and the target version. */
812
+ const routeShortcut = (shortcut, to) => `>[${routePart(shortcut)}]>${routePart(to)}`;
813
+ // src/features/planning/rewrite.ts
814
+ var RewriteFailure = class {
815
+ failure;
816
+ constructor(failure) {
817
+ this.failure = failure;
818
+ }
819
+ };
820
+ /** The largest number of distinct states explored while normalizing one sequence. */
821
+ const stateLimit = 1e4;
822
+ const occurrencesOf = (items) => items.flatMap((item) => {
823
+ if (item._tag === "Occ") return [item.occurrence];
824
+ if (item._tag === "Par") return item.branches.flatMap(occurrencesOf);
825
+ return [];
826
+ });
827
+ const groupKey = (branches) => `{${Array$1.sort(branches.map((branch) => `[${branch}]`), Order.String).join("|")}}`;
828
+ /** A key that identifies a sequence by its action structure. Branch order is ignored. */
829
+ const keyOf = (items) => items.map((item) => {
830
+ if (item._tag === "Occ") return JSON.stringify(item.occurrence.action.id);
831
+ if (item._tag === "Barrier") return "#";
832
+ return groupKey(item.branches.map(keyOf));
833
+ }).join(",");
834
+ /** A key that identifies declared steps by their action structure. Branch order is ignored. */
835
+ const stepKey = (steps) => steps.map((step) => {
836
+ switch (step._tag) {
837
+ case "Action": return JSON.stringify(step.id);
838
+ case "Instruction": return JSON.stringify(step.action.id);
839
+ case "Sequence": return stepKey(step.children);
840
+ }
841
+ const branches = step.branches.map((branch) => stepKey([branch]));
842
+ if (branches.length === 1) return branches[0];
843
+ return groupKey(branches);
844
+ }).filter((key) => key !== "").join(",");
845
+ /** Converts declared steps to items. Sequences flatten; single-branch groups flatten. */
846
+ const itemsOf = (steps, make, step) => steps.flatMap((declared) => {
847
+ switch (declared._tag) {
848
+ case "Action": return [{
849
+ _tag: "Occ",
850
+ occurrence: make(declared, void 0),
851
+ step
852
+ }];
853
+ case "Instruction": return [{
854
+ _tag: "Occ",
855
+ occurrence: make(declared.action, declared),
856
+ step
857
+ }];
858
+ case "Sequence": return itemsOf(declared.children, make, step);
859
+ }
860
+ return parallelOf(declared.branches.map((branch) => itemsOf([branch], make, step)), declared.concurrency, step);
861
+ });
862
+ /** Drops empty branches and flattens a group that has a single branch left. */
863
+ const parallelOf = (branches, concurrency, step) => {
864
+ const nonEmpty = branches.filter((branch) => branch.length > 0);
865
+ if (nonEmpty.length === 0) return [];
866
+ if (nonEmpty.length === 1) return nonEmpty[0] ?? [];
867
+ return [{
868
+ _tag: "Par",
869
+ branches: nonEmpty,
870
+ concurrency,
871
+ step
872
+ }];
873
+ };
874
+ const matchesAt = (pattern, items, position) => pattern.every((expected, offset) => {
875
+ const item = items[position + offset];
876
+ if (item === void 0) return false;
877
+ if (expected._tag === "Action") return item._tag === "Occ" && item.occurrence.action.id === expected.id;
878
+ return item._tag === "Par" && keyOf([item]) === stepKey([expected]);
879
+ });
880
+ /** Replaces the match of a rule at a position with occurrences that record their provenance. */
881
+ const replace$1 = (rule, items, position) => {
882
+ const matched = items.slice(position, position + rule.match.length);
883
+ const removed = occurrencesOf(matched);
884
+ const first = removed[0];
885
+ if (first === void 0) throw new Error(`Rule "${rule.id}" matched no occurrences`);
886
+ const step = matched[0]?.step ?? 0;
887
+ const produced = [];
888
+ const make = (action, instruction) => {
889
+ const occurrence = {
890
+ _tag: "Occurrence",
891
+ id: replacementOccurrenceId(rule, removed, action),
892
+ action,
893
+ migration: first.migration,
894
+ direction: first.direction,
895
+ instruction,
896
+ origin: {
897
+ _tag: "Replacement",
898
+ rule,
899
+ replaces: removed
900
+ }
901
+ };
902
+ produced.push(occurrence);
903
+ return occurrence;
904
+ };
905
+ return {
906
+ next: [
907
+ ...items.slice(0, position),
908
+ ...itemsOf(rule.replacement, make, step),
909
+ ...items.slice(position + rule.match.length)
910
+ ],
911
+ application: {
912
+ rule,
913
+ removed,
914
+ produced
915
+ }
916
+ };
917
+ };
918
+ const makeNormalizer = (rules) => {
919
+ const ordered = Array$1.sort(rules, Order.mapInput(Order.String, (rule) => rule.id));
920
+ /**
921
+ * Every single rule application available in a sequence: at any position of the
922
+ * sequence itself, or inside any branch of its groups. Branch-local and whole-group
923
+ * rewrites compete as transitions from the same state.
924
+ */
925
+ const transitions = (items) => {
926
+ const found = [];
927
+ for (let position = 0; position < items.length; position++) {
928
+ for (const rule of ordered) if (rule.match.length > 0 && matchesAt(rule.match, items, position)) found.push(replace$1(rule, items, position));
929
+ const item = items[position];
930
+ if (item?._tag !== "Par") continue;
931
+ for (const [index, branch] of item.branches.entries()) for (const inner of transitions(branch)) {
932
+ const branches = item.branches.map((other, otherIndex) => otherIndex === index ? inner.next : other);
933
+ found.push({
934
+ next: [
935
+ ...items.slice(0, position),
936
+ ...parallelOf(branches, item.concurrency, item.step),
937
+ ...items.slice(position + 1)
938
+ ],
939
+ application: inner.application
940
+ });
941
+ }
942
+ }
943
+ return found;
944
+ };
945
+ /**
946
+ * Explores every rewrite order of the whole sequence, nested groups included, under
947
+ * one shared state and depth budget.
948
+ */
949
+ const normalize = (input) => {
950
+ const seen = /* @__PURE__ */ new Set();
951
+ const onPath = /* @__PURE__ */ new Map();
952
+ const normals = /* @__PURE__ */ new Map();
953
+ const visit = (items, trace) => {
954
+ const key = keyOf(items);
955
+ const entered = onPath.get(key);
956
+ if (entered !== void 0) throw new RewriteFailure({
957
+ _tag: "RewriteCycle",
958
+ rules: trace.slice(entered).map((application) => application.rule.id),
959
+ actions: key
960
+ });
961
+ if (seen.has(key)) return;
962
+ seen.add(key);
963
+ if (seen.size > 1e4) throw new RewriteFailure({
964
+ _tag: "RewriteLimitExceeded",
965
+ limit: "states",
966
+ value: stateLimit
967
+ });
968
+ if (trace.length > 256) throw new RewriteFailure({
969
+ _tag: "RewriteLimitExceeded",
970
+ limit: "depth",
971
+ value: 256
972
+ });
973
+ onPath.set(key, trace.length);
974
+ const available = transitions(items);
975
+ for (const { next, application } of available) visit(next, [...trace, application]);
976
+ if (available.length === 0) normals.set(key, {
977
+ items,
978
+ trace
979
+ });
980
+ onPath.delete(key);
981
+ };
982
+ visit(input, []);
983
+ if (normals.size > 1) throw new RewriteFailure({
984
+ _tag: "ConflictingRewrites",
985
+ outcomes: [...normals.entries()].map(([actions, outcome]) => ({
986
+ actions,
987
+ rules: outcome.trace.map((application) => application.rule.id)
988
+ }))
989
+ });
990
+ const [outcome] = normals.values();
991
+ return outcome ?? {
992
+ items: input,
993
+ trace: []
994
+ };
995
+ };
996
+ return { normalize };
997
+ };
998
+ /** Applies rules to a sequence until no rule matches. */
999
+ const rewrite = (items, rules) => {
1000
+ try {
1001
+ return {
1002
+ _tag: "Success",
1003
+ outcome: makeNormalizer(rules).normalize(items)
1004
+ };
1005
+ } catch (error) {
1006
+ if (error instanceof RewriteFailure) return {
1007
+ _tag: "Failure",
1008
+ failure: error.failure
1009
+ };
1010
+ throw error;
1011
+ }
1012
+ };
1013
+ // src/features/planning/validate.ts
1014
+ const issueOrder = Order.combine(Order.combine(Order.mapInput(Order.String, (issue) => issue._tag), Order.mapInput(Order.String, (issue) => issue.subject)), Order.mapInput(Order.String, (issue) => issue.message));
1015
+ /** Action instances declared by steps, in declaration order. */
1016
+ const actionsOfSteps = (steps) => steps.flatMap((step) => {
1017
+ switch (step._tag) {
1018
+ case "Action": return [step];
1019
+ case "Instruction": return [step.action];
1020
+ case "Sequence": return actionsOfSteps(step.children);
1021
+ }
1022
+ return actionsOfSteps(step.branches);
1023
+ });
1024
+ const stepsOf = (content) => content.flatMap((fragment) => fragment._tag === "Text" || fragment._tag === "ActionRef" ? [] : [fragment]);
1025
+ /** Whether two definitions with the same identifier describe the same change. */
1026
+ const sameDefinition = (self, that) => self === that || self.id === that.id && Equal.equals(self.metadata, that.metadata) && self.description === that.description && self.backportOf?.id === that.backportOf?.id && self.reverts.length === that.reverts.length && self.reverts.every((change, index) => change.id === that.reverts[index]?.id);
1027
+ /** Whether content declares at least one occurrence. Empty groups declare none. */
1028
+ const hasOccurrences = (content) => actionsOfSteps(stepsOf(content)).length > 0;
1029
+ /** Whether content has prose or mentions. */
1030
+ const hasProse = (content) => content.some((fragment) => fragment._tag === "ActionRef" || fragment._tag === "Text" && fragment.text.trim() !== "");
1031
+ const sameAction = (self, that) => self === that || self.kind === that.kind && Equal.equals(self.payload, that.payload);
1032
+ /** Collects every distinct migration: registered ones and those inside shortcuts. */
1033
+ const allMigrations = (declarations) => {
1034
+ const result = [...declarations.migrations];
1035
+ for (const shortcut of declarations.shortcuts) for (const migration of shortcut.migrations) if (!result.includes(migration)) result.push(migration);
1036
+ return result;
1037
+ };
1038
+ const isChain = (migrations, from, to) => {
1039
+ let current = from.id;
1040
+ for (const migration of migrations) {
1041
+ if (migration.from.id !== current) return false;
1042
+ current = migration.to.id;
1043
+ }
1044
+ return migrations.length > 0 && current === to.id;
1045
+ };
1046
+ const validate$1 = (declarations) => {
1047
+ const issues = [];
1048
+ const issue = (tag, subject, message) => issues.push({
1049
+ _tag: tag,
1050
+ subject,
1051
+ message
1052
+ });
1053
+ const versions = /* @__PURE__ */ new Map();
1054
+ for (const version of declarations.versions) {
1055
+ if (versions.has(version.id)) {
1056
+ issue("DuplicateVersion", version.id, `Version "${version.id}" is registered more than once.`);
1057
+ continue;
1058
+ }
1059
+ versions.set(version.id, version);
1060
+ }
1061
+ const unregistered = /* @__PURE__ */ new Map();
1062
+ const requireVersion = (version, referencedBy) => {
1063
+ if (versions.get(version.id) !== void 0) return;
1064
+ const referrers = unregistered.get(version.id) ?? [];
1065
+ if (!referrers.includes(referencedBy)) referrers.push(referencedBy);
1066
+ unregistered.set(version.id, referrers);
1067
+ };
1068
+ for (const version of versions.values()) if (version.previous !== void 0) requireVersion(version.previous, `version "${version.id}"`);
1069
+ const ancestry = Graph.directed((graph) => {
1070
+ const nodes = /* @__PURE__ */ new Map();
1071
+ for (const id of versions.keys()) nodes.set(id, Graph.addNode(graph, id));
1072
+ for (const version of versions.values()) {
1073
+ const source = nodes.get(version.id);
1074
+ const target = version.previous === void 0 ? void 0 : nodes.get(version.previous.id);
1075
+ if (source !== void 0 && target !== void 0) Graph.addEdge(graph, source, target, void 0);
1076
+ }
1077
+ });
1078
+ const cycle = Graph.findCycle(ancestry);
1079
+ if (Option.isSome(cycle)) {
1080
+ const ids = cycle.value.path.flatMap((index) => Option.toArray(Graph.getNode(ancestry, index)));
1081
+ issue("AncestryCycle", ids[0] ?? "", `Release ancestry contains a cycle: ${ids.join(" -> ")}.`);
1082
+ }
1083
+ const changes = /* @__PURE__ */ new Map();
1084
+ const visited = /* @__PURE__ */ new Set();
1085
+ const conflictingChanges = /* @__PURE__ */ new Set();
1086
+ const visitChange = (change) => {
1087
+ if (visited.has(change)) return;
1088
+ visited.add(change);
1089
+ const known = changes.get(change.id);
1090
+ if (known === void 0) changes.set(change.id, change);
1091
+ else if (!sameDefinition(known, change) && !conflictingChanges.has(change.id)) {
1092
+ conflictingChanges.add(change.id);
1093
+ issue("ConflictingChange", change.id, `Change "${change.id}" has conflicting definitions.`);
1094
+ }
1095
+ for (const reverted of change.reverts) visitChange(reverted);
1096
+ if (change.backportOf !== void 0) visitChange(change.backportOf);
1097
+ };
1098
+ for (const version of declarations.versions) for (const change of version.changes) visitChange(change);
1099
+ const actions = /* @__PURE__ */ new Map();
1100
+ const conflicting = /* @__PURE__ */ new Set();
1101
+ const visitAction = (action) => {
1102
+ const known = actions.get(action.id);
1103
+ if (known === void 0) {
1104
+ actions.set(action.id, action);
1105
+ return;
1106
+ }
1107
+ if (!sameAction(known, action) && !conflicting.has(action.id)) {
1108
+ conflicting.add(action.id);
1109
+ issue("ConflictingAction", action.id, `Action "${action.id}" has conflicting definitions; action identifiers must be unique.`);
1110
+ }
1111
+ };
1112
+ const migrations = allMigrations(declarations);
1113
+ const migrationIds = /* @__PURE__ */ new Map();
1114
+ const registered = /* @__PURE__ */ new Set();
1115
+ for (const migration of declarations.migrations) {
1116
+ if (registered.has(migration) || migrationIds.has(migration.id)) issue("DuplicateMigration", migration.id, `Migration "${migration.id}" is registered more than once. Register a migration once; register the result of Migration.withRevert in place of the original.`);
1117
+ registered.add(migration);
1118
+ migrationIds.set(migration.id, migration);
1119
+ }
1120
+ for (const migration of migrations) {
1121
+ const known = migrationIds.get(migration.id);
1122
+ if (known !== void 0 && known !== migration && !registered.has(migration)) issue("DuplicateMigration", migration.id, `Migration "${migration.id}" has another definition inside a shortcut.`);
1123
+ if (known === void 0) migrationIds.set(migration.id, migration);
1124
+ requireVersion(migration.from, `migration "${migration.id}"`);
1125
+ requireVersion(migration.to, `migration "${migration.id}"`);
1126
+ if (migration.from.id === migration.to.id) issue("SelfMigration", migration.id, `Migration "${migration.id}" starts and ends at the same version.`);
1127
+ for (const change of migration.addresses) visitChange(change);
1128
+ const sides = [["forward", migration.content], ["revert", migration.revert]];
1129
+ for (const [direction, content] of sides) {
1130
+ if (content === void 0) continue;
1131
+ if (!migration.noop && !hasOccurrences(content) && !hasProse(content)) issue("EmptyMigration", migration.id, `The ${direction} side of migration "${migration.id}" is empty. Use Migration.noop to declare a zero-work transition.`);
1132
+ const counts = /* @__PURE__ */ new Map();
1133
+ for (const action of actionsOfSteps(stepsOf(content))) {
1134
+ visitAction(action);
1135
+ counts.set(action.id, (counts.get(action.id) ?? 0) + 1);
1136
+ }
1137
+ for (const [actionId, count] of counts) {
1138
+ if (count < 2) continue;
1139
+ issue("DuplicateOccurrence", migration.id, `Action "${actionId}" occurs ${count} times in the ${direction} side of migration "${migration.id}". Use Action.ref to mention an action, or a separate action instance to repeat the work.`);
1140
+ }
1141
+ }
1142
+ }
1143
+ const edgeSides = /* @__PURE__ */ new Map();
1144
+ const addSide = (from, to, label) => {
1145
+ const key = JSON.stringify([from.id, to.id]);
1146
+ const side = edgeSides.get(key) ?? {
1147
+ from: from.id,
1148
+ to: to.id,
1149
+ labels: []
1150
+ };
1151
+ side.labels.push(label);
1152
+ edgeSides.set(key, side);
1153
+ };
1154
+ for (const migration of new Set(migrationIds.values())) {
1155
+ if (!registered.has(migration)) continue;
1156
+ addSide(migration.from, migration.to, `"${migration.id}"`);
1157
+ if (migration.revert !== void 0) addSide(migration.to, migration.from, `the revert of "${migration.id}"`);
1158
+ }
1159
+ for (const { from, to, labels } of edgeSides.values()) {
1160
+ if (labels.length < 2) continue;
1161
+ issue("DuplicateEdge", `${from} -> ${to}`, `${labels.join(" and ")} both go from "${from}" to "${to}". Merge them into one migration.`);
1162
+ }
1163
+ const rules = /* @__PURE__ */ new Set();
1164
+ for (const rule of declarations.rules) {
1165
+ if (rules.has(rule.id)) issue("DuplicateRule", rule.id, `Rule "${rule.id}" is registered more than once.`);
1166
+ rules.add(rule.id);
1167
+ if (rule.match.length === 0) issue("InvalidRule", rule.id, `Rule "${rule.id}" matches nothing.`);
1168
+ const patternActions = actionsOfSteps(rule.match);
1169
+ const replacementActions = actionsOfSteps(rule.replacement);
1170
+ for (const action of [...patternActions, ...replacementActions]) visitAction(action);
1171
+ if (new Set(replacementActions.map((action) => action.id)).size !== replacementActions.length) issue("InvalidRule", rule.id, `Rule "${rule.id}" repeats an action in its replacement.`);
1172
+ if (rule.match.length > 0 && stepKey(rule.match) === stepKey(rule.replacement)) issue("InvalidRule", rule.id, `Rule "${rule.id}" replaces its match with itself.`);
1173
+ }
1174
+ const shortcuts = /* @__PURE__ */ new Set();
1175
+ for (const shortcut of declarations.shortcuts) {
1176
+ if (shortcuts.has(shortcut.id)) issue("DuplicateShortcut", shortcut.id, `Shortcut "${shortcut.id}" is registered more than once.`);
1177
+ shortcuts.add(shortcut.id);
1178
+ requireVersion(shortcut.from, `shortcut "${shortcut.id}"`);
1179
+ requireVersion(shortcut.to, `shortcut "${shortcut.id}"`);
1180
+ const unknown = shortcut.replaces.filter((migration) => !registered.has(migration));
1181
+ if (unknown.length > 0) issue("InvalidShortcut", shortcut.id, `Shortcut "${shortcut.id}" replaces unregistered migrations: ${unknown.map((migration) => migration.id).join(", ")}.`);
1182
+ if (!isChain(shortcut.replaces, shortcut.from, shortcut.to)) issue("InvalidShortcut", shortcut.id, `Shortcut "${shortcut.id}" must replace a consecutive route from "${shortcut.from.id}" to "${shortcut.to.id}".`);
1183
+ if (!isChain(shortcut.migrations, shortcut.from, shortcut.to)) issue("InvalidShortcut", shortcut.id, `The migrations of shortcut "${shortcut.id}" must form a route from "${shortcut.from.id}" to "${shortcut.to.id}".`);
1184
+ }
1185
+ for (const [id, referrers] of unregistered) issue("UnregisteredVersion", id, `Version "${id}" is referenced by ${referrers.join(", ")} but is not registered.`);
1186
+ return Array$1.sort(issues, issueOrder);
1187
+ };
1188
+ const memberCost = (migration) => migration.cost ?? 1;
1189
+ const makeContext = (declarations) => {
1190
+ const versions = new Map(declarations.versions.map((version) => [version.id, version]));
1191
+ const ancestors = /* @__PURE__ */ new Map();
1192
+ const ancestorsOf = (id) => {
1193
+ const known = ancestors.get(id);
1194
+ if (known !== void 0) return known;
1195
+ const result = /* @__PURE__ */ new Set();
1196
+ let current = versions.get(id)?.previous;
1197
+ while (current !== void 0 && !result.has(current.id)) {
1198
+ result.add(current.id);
1199
+ current = versions.get(current.id)?.previous;
1200
+ }
1201
+ ancestors.set(id, result);
1202
+ return result;
1203
+ };
1204
+ for (const id of versions.keys()) ancestorsOf(id);
1205
+ const classOf = (from, to) => {
1206
+ if (ancestorsOf(to).has(from)) return "up";
1207
+ if (ancestorsOf(from).has(to)) return "down";
1208
+ return "cross";
1209
+ };
1210
+ const edges = declarations.migrations.flatMap((migration) => {
1211
+ const forward = {
1212
+ from: migration.from,
1213
+ to: migration.to,
1214
+ members: [{
1215
+ migration,
1216
+ direction: "forward"
1217
+ }],
1218
+ shortcut: void 0,
1219
+ cost: memberCost(migration),
1220
+ class: classOf(migration.from.id, migration.to.id)
1221
+ };
1222
+ if (migration.revert === void 0) return [forward];
1223
+ return [forward, {
1224
+ from: migration.to,
1225
+ to: migration.from,
1226
+ members: [{
1227
+ migration,
1228
+ direction: "revert"
1229
+ }],
1230
+ shortcut: void 0,
1231
+ cost: memberCost(migration),
1232
+ class: classOf(migration.to.id, migration.from.id)
1233
+ }];
1234
+ });
1235
+ for (const shortcut of declarations.shortcuts) edges.push({
1236
+ from: shortcut.from,
1237
+ to: shortcut.to,
1238
+ members: shortcut.migrations.map((migration) => ({
1239
+ migration,
1240
+ direction: "forward"
1241
+ })),
1242
+ shortcut,
1243
+ cost: shortcut.cost ?? shortcut.migrations.reduce((total, migration) => total + memberCost(migration), 0),
1244
+ class: classOf(shortcut.from.id, shortcut.to.id)
1245
+ });
1246
+ return {
1247
+ declarations,
1248
+ versions,
1249
+ ancestors,
1250
+ edges
1251
+ };
1252
+ };
1253
+ const requestDirection = (context, from, to) => {
1254
+ if (from === to) return "none";
1255
+ if (context.ancestors.get(to)?.has(from)) return "upgrade";
1256
+ if (context.ancestors.get(from)?.has(to)) return "downgrade";
1257
+ return "cross-branch";
1258
+ };
1259
+ /**
1260
+ * Edge classes allowed together in one route. A route never mixes moves toward
1261
+ * ancestors with moves toward descendants, so sharing an ancestor does not authorize a
1262
+ * downgrade-and-upgrade detour. Explicit cross-branch migrations fit either family.
1263
+ */
1264
+ const families = [/* @__PURE__ */ new Set(["up", "cross"]), /* @__PURE__ */ new Set(["down", "cross"])];
1265
+ const routeCost = (edges) => edges.reduce((total, edge) => total + edge.cost, 0);
1266
+ const routeOf = (from, edges) => {
1267
+ let id = routeStart(from.id);
1268
+ const hops = [];
1269
+ for (const edge of edges) {
1270
+ if (edge.shortcut === void 0) {
1271
+ id += routeHop(edge.to.id);
1272
+ hops.push({
1273
+ _tag: "Migrations",
1274
+ from: edge.from,
1275
+ to: edge.to,
1276
+ migrations: edge.members
1277
+ });
1278
+ continue;
1279
+ }
1280
+ id += routeShortcut(edge.shortcut.id, edge.to.id);
1281
+ hops.push({
1282
+ _tag: "Shortcut",
1283
+ from: edge.from,
1284
+ to: edge.to,
1285
+ shortcut: edge.shortcut
1286
+ });
1287
+ }
1288
+ return {
1289
+ id,
1290
+ hops
1291
+ };
1292
+ };
1293
+ const graphOf = (context, family) => {
1294
+ const nodes = /* @__PURE__ */ new Map();
1295
+ return {
1296
+ graph: Graph.directed((mutable) => {
1297
+ for (const id of context.versions.keys()) nodes.set(id, Graph.addNode(mutable, id));
1298
+ for (const edge of context.edges) {
1299
+ if (!family.has(edge.class)) continue;
1300
+ const source = nodes.get(edge.from.id);
1301
+ const target = nodes.get(edge.to.id);
1302
+ if (source !== void 0 && target !== void 0) Graph.addEdge(mutable, source, target, edge);
1303
+ }
1304
+ }),
1305
+ nodes
1306
+ };
1307
+ };
1308
+ const enumerateRoutes = (context, from, to) => {
1309
+ const routes = /* @__PURE__ */ new Map();
1310
+ for (const family of families) {
1311
+ const { graph, nodes } = graphOf(context, family);
1312
+ const source = nodes.get(from.id);
1313
+ const target = nodes.get(to.id);
1314
+ if (source === void 0 || target === void 0) continue;
1315
+ for (const path of Graph.simplePaths(graph, {
1316
+ source,
1317
+ target,
1318
+ limit: 101
1319
+ })) routes.set(routeOf(from, path.costs).id, path.costs);
1320
+ }
1321
+ const found = [...routes.values()];
1322
+ return {
1323
+ routes: found.slice(0, 100),
1324
+ overLimit: found.length > 100
1325
+ };
1326
+ };
1327
+ const toNode = (items) => items.flatMap((item) => {
1328
+ if (item._tag === "Occ") return [item.occurrence];
1329
+ if (item._tag === "Barrier") return [];
1330
+ return [{
1331
+ _tag: "Parallel",
1332
+ branches: item.branches.map((branch) => {
1333
+ const children = toNode(branch);
1334
+ const [only] = children;
1335
+ return children.length === 1 && only !== void 0 ? only : {
1336
+ _tag: "Sequence",
1337
+ children
1338
+ };
1339
+ }),
1340
+ concurrency: item.concurrency
1341
+ }];
1342
+ });
1343
+ const contentOf = (member) => (member.direction === "forward" ? member.migration.content : member.migration.revert) ?? [];
1344
+ const buildPlan = (context, from, to, direction, edges) => {
1345
+ const route = routeOf(from, edges);
1346
+ const members = edges.flatMap((edge) => edge.members);
1347
+ const items = members.flatMap((member, index) => {
1348
+ const content = contentOf(member);
1349
+ const make = (action, instruction) => ({
1350
+ _tag: "Occurrence",
1351
+ id: declaredOccurrenceId(member.migration, member.direction, action),
1352
+ action,
1353
+ migration: member.migration,
1354
+ direction: member.direction,
1355
+ instruction,
1356
+ origin: { _tag: "Declared" }
1357
+ });
1358
+ const declared = itemsOf(stepsOf(content), make, index);
1359
+ if (declared.length === 0 && hasProse(content)) return [{
1360
+ _tag: "Barrier",
1361
+ step: index
1362
+ }];
1363
+ return declared;
1364
+ });
1365
+ const rewritten = rewrite(items, context.declarations.rules);
1366
+ if (rewritten._tag === "Failure") {
1367
+ const failure = rewritten.failure;
1368
+ switch (failure._tag) {
1369
+ case "RewriteCycle": return Result.fail(new RewriteCycle({
1370
+ route: route.id,
1371
+ rules: failure.rules,
1372
+ actions: failure.actions
1373
+ }));
1374
+ case "ConflictingRewrites": return Result.fail(new ConflictingRewrites({
1375
+ route: route.id,
1376
+ outcomes: failure.outcomes
1377
+ }));
1378
+ }
1379
+ return Result.fail(new RewriteLimitExceeded({
1380
+ route: route.id,
1381
+ limit: failure.limit,
1382
+ value: failure.value
1383
+ }));
1384
+ }
1385
+ const { items: optimized, trace } = rewritten.outcome;
1386
+ const explanations = trace.map((application) => ({
1387
+ _tag: "Rewrite",
1388
+ rule: application.rule,
1389
+ removed: application.removed,
1390
+ produced: application.produced
1391
+ }));
1392
+ const steps = members.map((member, index) => {
1393
+ const stepItems = optimized.filter((item) => item.step === index);
1394
+ const content = contentOf(member);
1395
+ const declaredCount = actionsOfSteps(stepsOf(content)).length;
1396
+ const retained = occurrencesOf(stepItems);
1397
+ const guide = resolveGuide(content, retained, (action) => declaredOccurrenceId(member.migration, member.direction, action));
1398
+ const allRemoved = declaredCount > 0 && retained.length === 0;
1399
+ const noop = member.migration.noop && content.length === 0;
1400
+ const omitted = noop || allRemoved;
1401
+ if (omitted) explanations.push({
1402
+ _tag: "OmittedStep",
1403
+ migration: member.migration,
1404
+ direction: member.direction,
1405
+ reason: noop ? "noop" : "all-actions-removed"
1406
+ });
1407
+ const [stepFrom, stepTo] = member.direction === "forward" ? [member.migration.from, member.migration.to] : [member.migration.to, member.migration.from];
1408
+ return {
1409
+ _tag: "Step",
1410
+ migration: member.migration,
1411
+ direction: member.direction,
1412
+ from: stepFrom,
1413
+ to: stepTo,
1414
+ node: {
1415
+ _tag: "Sequence",
1416
+ children: toNode(stepItems)
1417
+ },
1418
+ guide: omitted ? [] : guide,
1419
+ omitted
1420
+ };
1421
+ });
1422
+ const changes = [];
1423
+ for (const member of members) for (const change of member.migration.addresses) if (!changes.some((known) => known.id === change.id)) changes.push(change);
1424
+ return Result.succeed({
1425
+ _tag: "Plan",
1426
+ from,
1427
+ to,
1428
+ direction,
1429
+ route,
1430
+ steps,
1431
+ occurrences: occurrencesOf(optimized),
1432
+ changes,
1433
+ explanations,
1434
+ coverage: "static"
1435
+ });
1436
+ };
1437
+ const summaryOf = (candidate) => ({
1438
+ id: candidate.route.id,
1439
+ migrations: candidate.edges.flatMap((edge) => edge.members.map((member) => member.migration.id)),
1440
+ shortcuts: candidate.edges.flatMap((edge) => edge.shortcut === void 0 ? [] : [edge.shortcut.id]),
1441
+ actions: Result.isSuccess(candidate.plan) ? candidate.plan.success.occurrences.length : void 0,
1442
+ cost: candidate.cost,
1443
+ failure: Result.isFailure(candidate.plan) ? candidate.plan.failure.message : void 0
1444
+ });
1445
+ /** Migration tokens of a route, with shortcut hops expanded to the route they replace. */
1446
+ const canonicalTokens = (candidate) => JSON.stringify(candidate.edges.flatMap((edge) => edge.shortcut === void 0 ? edge.members.map((member) => [member.direction, member.migration.id]) : edge.shortcut.replaces.map((migration) => ["forward", migration.id])));
1447
+ const shortcutCount = (candidate) => candidate.edges.filter((edge) => edge.shortcut !== void 0).length;
1448
+ const minimal = (candidates, measure) => {
1449
+ const measured = candidates.flatMap((candidate) => {
1450
+ const value = measure(candidate);
1451
+ return value === void 0 ? [] : [{
1452
+ candidate,
1453
+ value
1454
+ }];
1455
+ });
1456
+ const best = Math.min(...measured.map((entry) => entry.value));
1457
+ return measured.filter((entry) => entry.value === best).map((entry) => entry.candidate);
1458
+ };
1459
+ const applyPolicy = (policy, candidates) => {
1460
+ switch (policy) {
1461
+ case "fewest-actions": return minimal(candidates, (candidate) => Result.isSuccess(candidate.plan) ? candidate.plan.success.occurrences.length : void 0);
1462
+ case "fewest-migrations": return minimal(candidates, (candidate) => candidate.edges.reduce((total, edge) => total + edge.members.length, 0));
1463
+ case "lowest-cost": return minimal(candidates, (candidate) => candidate.cost);
1464
+ }
1465
+ return candidates.filter((candidate) => !candidates.some((other) => other !== candidate && canonicalTokens(other) === canonicalTokens(candidate) && shortcutCount(other) > shortcutCount(candidate)));
1466
+ };
1467
+ const depthOf = (context, id) => context.ancestors.get(id)?.size ?? 0;
1468
+ /** Distance between two versions in the release ancestry tree. */
1469
+ const ancestryDistance = (context, self, that) => {
1470
+ const selfLine = [self, ...ancestorsInOrder(context, self)];
1471
+ const thatLine = /* @__PURE__ */ new Set([that, ...ancestorsInOrder(context, that)]);
1472
+ const common = selfLine.find((id) => thatLine.has(id));
1473
+ if (common === void 0) return Number.POSITIVE_INFINITY;
1474
+ return depthOf(context, self) + depthOf(context, that) - 2 * depthOf(context, common);
1475
+ };
1476
+ const ancestorsInOrder = (context, id) => {
1477
+ const result = [];
1478
+ let current = context.versions.get(id)?.previous;
1479
+ while (current !== void 0 && !result.includes(current.id)) {
1480
+ result.push(current.id);
1481
+ current = context.versions.get(current.id)?.previous;
1482
+ }
1483
+ return result;
1484
+ };
1485
+ /** The ancestry path between two versions, through their closest common ancestor. */
1486
+ const ancestryPath = (context, from, to) => {
1487
+ const fromLine = [from, ...ancestorsInOrder(context, from)];
1488
+ const toLine = [to, ...ancestorsInOrder(context, to)];
1489
+ const common = fromLine.find((id) => toLine.includes(id));
1490
+ if (common === void 0) return [];
1491
+ return [...fromLine.slice(0, fromLine.indexOf(common) + 1), ...Array$1.reverse(toLine.slice(0, toLine.indexOf(common)))];
1492
+ };
1493
+ const reachable = (context, from, family) => {
1494
+ const seen = /* @__PURE__ */ new Set([from]);
1495
+ const queue = [from];
1496
+ for (let current = queue.shift(); current !== void 0; current = queue.shift()) for (const edge of context.edges) {
1497
+ if (edge.from.id !== current || !family.has(edge.class) || seen.has(edge.to.id)) continue;
1498
+ seen.add(edge.to.id);
1499
+ queue.push(edge.to.id);
1500
+ }
1501
+ seen.delete(from);
1502
+ return [...seen];
1503
+ };
1504
+ const familiesFor = (direction) => {
1505
+ if (direction === "upgrade") return [families[0]];
1506
+ if (direction === "downgrade") return [families[1]];
1507
+ return families;
1508
+ };
1509
+ const unsupported = (context, from, to, direction) => {
1510
+ const allowed = familiesFor(direction).flatMap((family) => family === void 0 ? [] : [family]);
1511
+ const reachableIds = Array$1.sort(new Set(allowed.flatMap((family) => reachable(context, from, family))), Order.String);
1512
+ const distances = reachableIds.map((id) => ({
1513
+ id,
1514
+ distance: ancestryDistance(context, id, to)
1515
+ }));
1516
+ const best = Math.min(...distances.map((entry) => entry.distance));
1517
+ const closest = Number.isFinite(best) ? distances.filter((entry) => entry.distance === best).map((entry) => entry.id) : [];
1518
+ const path = ancestryPath(context, from, to);
1519
+ const blockers = [];
1520
+ for (let index = 0; index + 1 < path.length; index++) {
1521
+ const hopFrom = path[index];
1522
+ const hopTo = path[index + 1];
1523
+ if (hopFrom === void 0 || hopTo === void 0) continue;
1524
+ if (context.edges.some((edge) => edge.from.id === hopFrom && edge.to.id === hopTo)) continue;
1525
+ blockers.push({
1526
+ from: hopFrom,
1527
+ to: hopTo,
1528
+ reason: `No migration is declared from "${hopFrom}" to "${hopTo}".`
1529
+ });
1530
+ }
1531
+ const turn = path.find((id) => context.ancestors.get(from)?.has(id) === true && context.ancestors.get(to)?.has(id) === true);
1532
+ if (blockers.length === 0 && turn !== void 0) blockers.push({
1533
+ from,
1534
+ to,
1535
+ reason: `A route through "${turn}" would combine a downgrade with an upgrade. Declare a migration from "${from}" to "${to}".`
1536
+ });
1537
+ return new UnsupportedRoute({
1538
+ from,
1539
+ to,
1540
+ direction,
1541
+ reachable: reachableIds,
1542
+ closest,
1543
+ blockers
1544
+ });
1545
+ };
1546
+ const lookup = (context, reference) => {
1547
+ const id = typeof reference === "string" ? reference : reference.id;
1548
+ const version = context.versions.get(id);
1549
+ return version === void 0 ? Result.fail(new UnknownVersion({
1550
+ version: id,
1551
+ known: [...context.versions.keys()]
1552
+ })) : Result.succeed(version);
1553
+ };
1554
+ const candidatesBetween = (context, from, to) => {
1555
+ const direction = requestDirection(context, from.id, to.id);
1556
+ const { routes, overLimit } = enumerateRoutes(context, from, to);
1557
+ if (overLimit) return Result.fail(new TooManyRoutes({
1558
+ from: from.id,
1559
+ to: to.id,
1560
+ limit: 100
1561
+ }));
1562
+ return Result.succeed(routes.map((edges) => ({
1563
+ route: routeOf(from, edges),
1564
+ edges,
1565
+ plan: buildPlan(context, from, to, direction, edges),
1566
+ cost: routeCost(edges)
1567
+ })));
1568
+ };
1569
+ const resolve$1 = (context, options) => Result.gen(function* () {
1570
+ const from = yield* lookup(context, options.from);
1571
+ const to = yield* lookup(context, options.to);
1572
+ const direction = requestDirection(context, from.id, to.id);
1573
+ if (direction === "none") return yield* buildPlan(context, from, to, direction, []);
1574
+ const candidates = yield* candidatesBetween(context, from, to);
1575
+ if (candidates.length === 0) return yield* Result.fail(unsupported(context, from.id, to.id, direction));
1576
+ if (options.route !== void 0) {
1577
+ const selected = candidates.find((candidate) => candidate.route.id === options.route);
1578
+ if (selected === void 0) return yield* Result.fail(new UnknownRoute({
1579
+ route: options.route,
1580
+ candidates: candidates.map(summaryOf)
1581
+ }));
1582
+ return yield* selected.plan;
1583
+ }
1584
+ const chosen = options.policy === void 0 ? candidates : applyPolicy(options.policy, candidates);
1585
+ const [only] = chosen;
1586
+ if (chosen.length === 1 && only !== void 0) return yield* only.plan;
1587
+ return yield* Result.fail(new AmbiguousRoute({
1588
+ from: from.id,
1589
+ to: to.id,
1590
+ candidates: (chosen.length === 0 ? candidates : chosen).map(summaryOf),
1591
+ policy: options.policy
1592
+ }));
1593
+ });
1594
+ const semverOrder = (self, that) => {
1595
+ const parsedSelf = SemVer.parse(self);
1596
+ const parsedThat = SemVer.parse(that);
1597
+ if (Result.isFailure(parsedSelf) || Result.isFailure(parsedThat)) return void 0;
1598
+ return SemVer.Order(parsedSelf.success, parsedThat.success);
1599
+ };
1600
+ /**
1601
+ * Destinations reachable from a version. Cross-branch destinations are classified by
1602
+ * semver order when both identifiers parse, and listed in both directions otherwise.
1603
+ * Classification is presentation only; it does not change routing.
1604
+ */
1605
+ const destinations = (context, from, kind) => {
1606
+ const family = kind === "upgrade" ? families[0] : families[1];
1607
+ if (family === void 0) return [];
1608
+ return reachable(context, from.id, family).flatMap((id) => {
1609
+ const version = context.versions.get(id);
1610
+ if (version === void 0) return [];
1611
+ const direction = requestDirection(context, from.id, id);
1612
+ if (direction === "cross-branch") {
1613
+ const order = semverOrder(id, from.id);
1614
+ if (order !== void 0 && (kind === "upgrade" ? order < 0 : order > 0)) return [];
1615
+ } else if (direction !== kind) return [];
1616
+ const { routes, overLimit } = enumerateRoutes(context, from, version);
1617
+ if (!overLimit) return [{
1618
+ version,
1619
+ routes: routes.map((edges) => routeOf(from, edges).id)
1620
+ }];
1621
+ return [{
1622
+ version,
1623
+ routes: Array$1.sort(routes, Order.mapInput(Order.Number, (edges) => routeCost(edges))).map((edges) => routeOf(from, edges).id),
1624
+ overLimit: true
1625
+ }];
1626
+ });
1627
+ };
1628
+ // src/features/planning/history.ts
1629
+ var history_exports = /* @__PURE__ */ __exportAll({
1630
+ AmbiguousRoute: () => AmbiguousRoute,
1631
+ ConflictingRewrites: () => ConflictingRewrites,
1632
+ InvalidHistory: () => InvalidHistory,
1633
+ RewriteCycle: () => RewriteCycle,
1634
+ RewriteLimitExceeded: () => RewriteLimitExceeded,
1635
+ TooManyRoutes: () => TooManyRoutes,
1636
+ UnknownRoute: () => UnknownRoute,
1637
+ UnknownVersion: () => UnknownVersion,
1638
+ UnsupportedRoute: () => UnsupportedRoute,
1639
+ downgrades: () => downgrades,
1640
+ isHistory: () => isHistory,
1641
+ make: () => make$4,
1642
+ resolve: () => resolve,
1643
+ upgrades: () => upgrades,
1644
+ validate: () => validate
1645
+ });
1646
+ /**
1647
+ * Registers declarations. Migrations are registered independently of versions, so
1648
+ * routes can be added later without changing published release definitions.
1649
+ *
1650
+ * `make` does not throw. Use `History.validate` to list declaration issues;
1651
+ * resolution fails with `InvalidHistory` when there are any.
1652
+ *
1653
+ * @since @next
1654
+ */
1655
+ const make$4 = (declarations) => ({
1656
+ _tag: "History",
1657
+ versions: declarations.versions,
1658
+ migrations: declarations.migrations,
1659
+ rules: declarations.rules ?? [],
1660
+ shortcuts: declarations.shortcuts ?? []
1661
+ });
1662
+ /** @since @next */
1663
+ const isHistory = (value) => Predicate.isTagged(value, "History");
1664
+ const contexts = /* @__PURE__ */ new WeakMap();
1665
+ const prepare = (history) => {
1666
+ const cached = contexts.get(history);
1667
+ if (cached !== void 0) return cached;
1668
+ const prepared = {
1669
+ issues: validate$1(history),
1670
+ context: makeContext(history)
1671
+ };
1672
+ contexts.set(history, prepared);
1673
+ return prepared;
1674
+ };
1675
+ /**
1676
+ * Lists declaration issues in a deterministic order. An empty list means valid.
1677
+ *
1678
+ * @since @next
1679
+ */
1680
+ const validate = (history) => prepare(history).issues;
1681
+ const valid = (history) => {
1682
+ const { issues, context } = prepare(history);
1683
+ return issues.length === 0 ? Result.succeed(context) : Result.fail(new InvalidHistory({ issues }));
1684
+ };
1685
+ /**
1686
+ * Resolves an optimized plan between two versions. Planning needs no handlers or
1687
+ * execution services, and it never reads or modifies consumer files.
1688
+ *
1689
+ * When several routes connect the versions, resolution fails with `AmbiguousRoute`
1690
+ * unless the `route` option selects one or a route `policy` leaves exactly one.
1691
+ *
1692
+ * @example
1693
+ * ```ts
1694
+ * const result = History.resolve(history, { from: "1.5.3", to: "2.0.0" });
1695
+ * if (Result.isSuccess(result)) console.log(result.success.route.id);
1696
+ * ```
1697
+ *
1698
+ * @since @next
1699
+ */
1700
+ const resolve = (history, options) => Result.flatMap(valid(history), (context) => resolve$1(context, options));
1701
+ /**
1702
+ * Destinations reachable by upgrade from a version, with their candidate routes.
1703
+ *
1704
+ * @since @next
1705
+ */
1706
+ const upgrades = (history, options) => reachableFrom(history, options.from, "upgrade");
1707
+ /**
1708
+ * Destinations reachable by downgrade from a version, with their candidate routes.
1709
+ *
1710
+ * @since @next
1711
+ */
1712
+ const downgrades = (history, options) => reachableFrom(history, options.from, "downgrade");
1713
+ const reachableFrom = (history, from, kind) => Result.flatMap(valid(history), (context) => Result.map(lookup(context, from), (version) => destinations(context, version, kind)));
1714
+ // src/foundation/instruction.ts
1715
+ const isInstruction = (value) => Predicate.isTagged(value, "Instruction");
1716
+ /** Builds prose from a tagged template. Throws on values that are not text or mentions. */
1717
+ const prose = (strings, values, context) => {
1718
+ const literals = dedent(strings);
1719
+ const content = [];
1720
+ const pushText = (text) => {
1721
+ if (text === "") return;
1722
+ const last = content.at(-1);
1723
+ if (last?._tag === "Text") {
1724
+ content[content.length - 1] = {
1725
+ _tag: "Text",
1726
+ text: last.text + text
1727
+ };
1728
+ return;
1729
+ }
1730
+ content.push({
1731
+ _tag: "Text",
1732
+ text
1733
+ });
1734
+ };
1735
+ for (const [index, literal] of literals.entries()) {
1736
+ pushText(literal);
1737
+ if (index >= values.length) continue;
1738
+ const value = values[index];
1739
+ if (isScalar(value)) {
1740
+ pushText(String(value));
1741
+ continue;
1742
+ }
1743
+ if (isRef(value)) {
1744
+ content.push(value);
1745
+ continue;
1746
+ }
1747
+ if (isAction(value)) throw new TypeError(`${context}: action "${value.id}" cannot be interpolated here because it would declare another occurrence. Use Action.ref(action) to mention it.`);
1748
+ throw new TypeError(`${context}: cannot interpolate ${describeValue(value)}.`);
1749
+ }
1750
+ return content;
1751
+ };
1752
+ /**
1753
+ * Associates prose with one action occurrence.
1754
+ *
1755
+ * @example
1756
+ * ```ts
1757
+ * Migration.instruction(renameTimeout)`
1758
+ * Rename the timeout option, keeping its existing value.
1759
+ * `;
1760
+ * ```
1761
+ *
1762
+ * @since @next
1763
+ */
1764
+ const instruction = (action) => (strings, ...values) => ({
1765
+ _tag: "Instruction",
1766
+ action,
1767
+ content: prose(strings, values, `Instruction for "${action.id}"`)
1768
+ });
1769
+ // src/foundation/migration.ts
1770
+ var migration_exports = /* @__PURE__ */ __exportAll({
1771
+ instruction: () => instruction,
1772
+ isMigration: () => isMigration,
1773
+ make: () => make$3,
1774
+ noop: () => noop,
1775
+ withRevert: () => withRevert
1776
+ });
1777
+ /** @since @next */
1778
+ const isMigration = (value) => Predicate.isTagged(value, "Migration");
1779
+ const isStep = (value) => isAction(value) || isInstruction(value) || isSequence(value) || isParallel(value);
1780
+ const validateStep = (step, context) => {
1781
+ if (isSequence(step)) {
1782
+ for (const child of step.children) checkStep(child, context);
1783
+ return;
1784
+ }
1785
+ if (isParallel(step)) for (const branch of step.branches) checkStep(branch, context);
1786
+ };
1787
+ const checkStep = (value, context) => {
1788
+ if (!isStep(value)) throw new TypeError(`${context}: a group can only contain actions, instructions, and groups.`);
1789
+ validateStep(value, context);
1790
+ };
1791
+ /** Builds content from a tagged template. */
1792
+ const content = (strings, values, context) => {
1793
+ const literals = dedent(strings);
1794
+ const result = [];
1795
+ const pushText = (text) => {
1796
+ if (text === "") return;
1797
+ const last = result.at(-1);
1798
+ if (last?._tag === "Text") {
1799
+ result[result.length - 1] = {
1800
+ _tag: "Text",
1801
+ text: last.text + text
1802
+ };
1803
+ return;
1804
+ }
1805
+ result.push({
1806
+ _tag: "Text",
1807
+ text
1808
+ });
1809
+ };
1810
+ for (const [index, literal] of literals.entries()) {
1811
+ pushText(literal);
1812
+ if (index >= values.length) continue;
1813
+ const value = values[index];
1814
+ if (isScalar(value)) {
1815
+ pushText(String(value));
1816
+ continue;
1817
+ }
1818
+ if (isRef(value)) {
1819
+ result.push(value);
1820
+ continue;
1821
+ }
1822
+ if (isStep(value)) {
1823
+ validateStep(value, context);
1824
+ result.push(value);
1825
+ continue;
1826
+ }
1827
+ throw new TypeError(`${context}: cannot interpolate ${describeValue(value)}.`);
1828
+ }
1829
+ return result;
1830
+ };
1831
+ /**
1832
+ * Declares a migration between exact versions. Interpolated actions, instruction blocks,
1833
+ * and groups declare occurrences; `Action.ref` only mentions an action.
1834
+ *
1835
+ * @example
1836
+ * ```ts
1837
+ * const migrate152To200 = Migration.make("1.5.2-to-2.0.0", {
1838
+ * from: v152,
1839
+ * to: v200,
1840
+ * addresses: [timeoutRenamed],
1841
+ * })`
1842
+ * Update the configuration for export A:
1843
+ *
1844
+ * ${renameExportA}
1845
+ * `;
1846
+ * ```
1847
+ *
1848
+ * @since @next
1849
+ */
1850
+ const make$3 = (id, options) => (strings, ...values) => ({
1851
+ _tag: "Migration",
1852
+ id,
1853
+ from: options.from,
1854
+ to: options.to,
1855
+ addresses: options.addresses ?? [],
1856
+ noop: false,
1857
+ cost: options.cost,
1858
+ content: content(strings, values, `Migration "${id}"`),
1859
+ revert: void 0
1860
+ });
1861
+ /**
1862
+ * Declares a supported transition that requires no consumer work. It is a directed edge
1863
+ * like any migration. Do not use it to hide missing support for changes that need
1864
+ * instructions.
1865
+ *
1866
+ * @since @next
1867
+ */
1868
+ const noop = (id, options) => ({
1869
+ _tag: "Migration",
1870
+ id,
1871
+ from: options.from,
1872
+ to: options.to,
1873
+ addresses: options.addresses ?? [],
1874
+ noop: true,
1875
+ cost: options.cost,
1876
+ content: [],
1877
+ revert: options.reversible === true ? [] : void 0
1878
+ });
1879
+ /**
1880
+ * Adds a reverse transition. Register the returned migration in place of the original:
1881
+ * both share the same identifier. On a `Migration.noop`, the reverse is real work: only
1882
+ * the forward side stays zero-work.
1883
+ *
1884
+ * @example
1885
+ * ```ts
1886
+ * const reversible = Migration.withRevert(migrate152To200)`
1887
+ * Restore the previous configuration:
1888
+ *
1889
+ * ${restoreTimeout}
1890
+ * `;
1891
+ * ```
1892
+ *
1893
+ * @since @next
1894
+ */
1895
+ const withRevert = (migration) => (strings, ...values) => ({
1896
+ ...migration,
1897
+ revert: content(strings, values, `Revert of migration "${migration.id}"`)
1898
+ });
1899
+ // src/features/package.ts
1900
+ var package_exports = /* @__PURE__ */ __exportAll({
1901
+ isPackage: () => isPackage,
1902
+ make: () => make$2
1903
+ });
1904
+ /**
1905
+ * Defines the modeled package. It holds no renderer settings, release metadata, or
1906
+ * handlers.
1907
+ *
1908
+ * @example
1909
+ * ```ts
1910
+ * export const widgets = Package.make("@acme/widgets", { history });
1911
+ * ```
1912
+ *
1913
+ * @since @next
1914
+ */
1915
+ const make$2 = (name, options) => ({
1916
+ _tag: "Package",
1917
+ name,
1918
+ history: options.history
1919
+ });
1920
+ /** @since @next */
1921
+ const isPackage = (value) => Predicate.isTagged(value, "Package");
1922
+ // src/foundation/plan.ts
1923
+ var plan_exports = /* @__PURE__ */ __exportAll({
1924
+ isEmpty: () => isEmpty,
1925
+ withRuntimeCoverage: () => withRuntimeCoverage
1926
+ });
1927
+ /**
1928
+ * Whether the plan has no action occurrences. An empty plan is valid.
1929
+ *
1930
+ * @since @next
1931
+ */
1932
+ const isEmpty = (plan) => plan.occurrences.length === 0;
1933
+ /**
1934
+ * Marks a plan for run-time coverage checks only. Use it for dynamically selected or
1935
+ * loaded plans whose action union is not known statically. Executors still reject
1936
+ * missing handlers before any action body runs.
1937
+ *
1938
+ * @since @next
1939
+ */
1940
+ const withRuntimeCoverage = (plan) => ({
1941
+ ...plan,
1942
+ coverage: "runtime"
1943
+ });
1944
+ // src/foundation/rule.ts
1945
+ var rule_exports = /* @__PURE__ */ __exportAll({
1946
+ isRule: () => isRule,
1947
+ replace: () => replace
1948
+ });
1949
+ /**
1950
+ * Declares a replacement. Cancellation, composition, and supersession all use it.
1951
+ *
1952
+ * The author asserts that the replacement is equivalent to the matched occurrences.
1953
+ * deltafold checks the rule's structure and where it applies, but it cannot prove the
1954
+ * equivalence.
1955
+ *
1956
+ * Ordinary rules match consecutive occurrences inside one sequential branch, including
1957
+ * across migration boundaries of a route. They never match across parallel branches.
1958
+ *
1959
+ * @example
1960
+ * ```ts
1961
+ * const cancelRoundTrip = Rule.replace("cancel-timeout-round-trip", {
1962
+ * match: [renameTimeout, restoreTimeout],
1963
+ * replacement: [],
1964
+ * });
1965
+ * const combineRenames = Rule.replace("combine-renames", {
1966
+ * match: [renameAtoB, renameBtoC],
1967
+ * replacement: [renameAtoC],
1968
+ * });
1969
+ * ```
1970
+ *
1971
+ * @since @next
1972
+ */
1973
+ const replace = (id, options) => ({
1974
+ _tag: "Rule",
1975
+ id,
1976
+ match: options.match,
1977
+ replacement: options.replacement
1978
+ });
1979
+ /** @since @next */
1980
+ const isRule = (value) => Predicate.isTagged(value, "Rule");
1981
+ // src/foundation/shortcut.ts
1982
+ var shortcut_exports = /* @__PURE__ */ __exportAll({
1983
+ isShortcut: () => isShortcut,
1984
+ make: () => make$1
1985
+ });
1986
+ /**
1987
+ * Declares a shortcut. The author asserts that its migrations are equivalent to the
1988
+ * canonical route it replaces; deltafold does not prove it.
1989
+ *
1990
+ * @example
1991
+ * ```ts
1992
+ * const fastUpgrade = Shortcut.make("fast-upgrade", {
1993
+ * from: v201,
1994
+ * to: v208,
1995
+ * replaces: [migrate202, migrate203, migrate204],
1996
+ * migrations: [migrateDirectlyTo208],
1997
+ * });
1998
+ * ```
1999
+ *
2000
+ * @since @next
2001
+ */
2002
+ const make$1 = (id, options) => ({
2003
+ _tag: "Shortcut",
2004
+ id,
2005
+ from: options.from,
2006
+ to: options.to,
2007
+ replaces: options.replaces,
2008
+ migrations: options.migrations,
2009
+ cost: options.cost
2010
+ });
2011
+ /** @since @next */
2012
+ const isShortcut = (value) => Predicate.isTagged(value, "Shortcut");
2013
+ // src/foundation/version.ts
2014
+ var version_exports = /* @__PURE__ */ __exportAll({
2015
+ isVersion: () => isVersion,
2016
+ make: () => make,
2017
+ withMetadata: () => withMetadata
2018
+ });
2019
+ /**
2020
+ * Declares a version.
2021
+ *
2022
+ * @example
2023
+ * ```ts
2024
+ * const v0 = Version.make("0.0.0", { changes: [] });
2025
+ * const v100 = Version.make("1.0.0", { previous: v0, changes: [timeoutRenamed] });
2026
+ * ```
2027
+ *
2028
+ * @since @next
2029
+ */
2030
+ const make = (id, options) => ({
2031
+ _tag: "Version",
2032
+ id,
2033
+ previous: options.previous,
2034
+ changes: options.changes
2035
+ });
2036
+ /** @since @next */
2037
+ const isVersion = (value) => Predicate.isTagged(value, "Version");
2038
+ /**
2039
+ * Annotates a version with release metadata.
2040
+ *
2041
+ * @example
2042
+ * ```ts
2043
+ * export const release200 = Version.withMetadata(v200, {
2044
+ * releasedAt: "2026-11-06T12:00:00Z",
2045
+ * commit: "abc123",
2046
+ * });
2047
+ * ```
2048
+ *
2049
+ * @since @next
2050
+ */
2051
+ const withMetadata = (version, metadata) => ({
2052
+ _tag: "Release",
2053
+ version,
2054
+ metadata
2055
+ });
2056
+ export { action_exports as Action, change_exports as Change, executor_exports as Executor, handler_exports as Handler, history_exports as History, migration_exports as Migration, package_exports as Package, plan_exports as Plan, rule_exports as Rule, shortcut_exports as Shortcut, version_exports as Version };
2057
+
2058
+ //# sourceMappingURL=index.js.map