deltafold 0.2.0 → 0.2.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.
- package/README.md +33 -1
- package/dist/changelog.d.ts +10 -10
- package/dist/changelog.js +4 -4
- package/dist/changelog.js.map +1 -1
- package/dist/{document-BZcZo9nr.js → document-HfPyYxEd.js} +20 -20
- package/dist/{document-BZcZo9nr.js.map → document-HfPyYxEd.js.map} +1 -1
- package/dist/{document-DWHsgywm.d.ts → document-gtXeGFJR.d.ts} +41 -41
- package/dist/{document-DWHsgywm.d.ts.map → document-gtXeGFJR.d.ts.map} +1 -1
- package/dist/html.d.ts +2 -2
- package/dist/html.js +2 -2
- package/dist/html.js.map +1 -1
- package/dist/index.d.ts +437 -105
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +750 -273
- package/dist/index.js.map +1 -1
- package/dist/markdown.d.ts +2 -2
- package/dist/markdown.js +2 -2
- package/dist/markdown.js.map +1 -1
- package/dist/{mdast-DiRsYwPU.js → mdast-Oqkh0Gs1.js} +2 -2
- package/dist/{mdast-DiRsYwPU.js.map → mdast-Oqkh0Gs1.js.map} +1 -1
- package/dist/{package-BfBYnaCz.d.ts → package-CA5R57IC.d.ts} +117 -112
- package/dist/{package-BfBYnaCz.d.ts.map → package-CA5R57IC.d.ts.map} +1 -1
- package/package.json +3 -3
- package/src/features/documents/changelog.ts +8 -8
- package/src/features/documents/document.ts +39 -39
- package/src/features/documents/index.ts +2 -2
- package/src/features/execution/executor.ts +485 -313
- package/src/features/execution/handler.ts +30 -30
- package/src/features/execution/interaction.ts +11 -11
- package/src/features/execution/observation.ts +489 -0
- package/src/features/execution/observer.ts +395 -0
- package/src/features/package.ts +3 -3
- package/src/features/planning/history.ts +10 -10
- package/src/features/planning/identifiers.ts +7 -4
- package/src/features/planning/resolve-error.ts +13 -13
- package/src/features/planning/resolve.ts +11 -4
- package/src/features/planning/validate.ts +1 -1
- package/src/foundation/action.ts +17 -17
- package/src/foundation/change.ts +10 -10
- package/src/foundation/instruction.ts +5 -5
- package/src/foundation/migration.ts +12 -12
- package/src/foundation/plan.ts +23 -18
- package/src/foundation/rule.ts +6 -6
- package/src/foundation/shortcut.ts +6 -6
- package/src/foundation/version.ts +6 -6
- package/src/index.ts +14 -12
- package/src/renderers/html.ts +1 -1
- package/src/renderers/markdown.ts +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["define","make","TypeId","make","promise","effect","effect","Arr","replace","validate","Arr","Arr","resolve","make","validateDeclarations","resolveRoute","lookupVersion","make","make","make"],"sources":["../src/foundation/action.ts","../src/foundation/template.ts","../src/foundation/change.ts","../src/features/execution/settlement.ts","../src/features/execution/promise-callback.ts","../src/features/execution/handler.ts","../src/features/execution/executor.ts","../src/features/execution/interaction.ts","../src/features/planning/resolve-error.ts","../src/features/planning/guide.ts","../src/features/planning/identifiers.ts","../src/features/planning/rewrite.ts","../src/features/planning/validate.ts","../src/features/planning/resolve.ts","../src/features/planning/history.ts","../src/foundation/instruction.ts","../src/foundation/migration.ts","../src/features/package.ts","../src/foundation/plan.ts","../src/foundation/rule.ts","../src/foundation/shortcut.ts","../src/foundation/version.ts"],"sourcesContent":["import { Predicate } from \"effect\";\n\nimport type { Instruction } from \"./instruction.ts\";\n\n/**\n * Describes one kind of consumer-owned operation and its payload.\n *\n * @since @next\n */\nexport type Kind<P> = {\n\treadonly _tag: \"ActionKind\";\n\treadonly kind: string;\n\treadonly describe: (payload: P) => string;\n\t/** Creates an action instance with a stable identifier. */\n\treadonly make: <const Id extends string>(id: Id, payload: P) => Action<Id, P>;\n};\n\n/**\n * One concrete instruction. Its `id` identifies the instruction across plans, handler\n * bindings, rules, and reports.\n *\n * @since @next\n */\nexport type Action<Id extends string = string, P = unknown> = {\n\treadonly _tag: \"Action\";\n\treadonly id: Id;\n\treadonly kind: string;\n\treadonly payload: P;\n\t/** The description produced by the kind's `describe` function. */\n\treadonly description: string;\n};\n\n/**\n * Any action instance.\n *\n * @since @next\n */\nexport type Any = Action<string, any>;\n\n/**\n * A mention of an action in prose. It does not declare an occurrence.\n *\n * @since @next\n */\nexport type Ref = {\n\treadonly _tag: \"ActionRef\";\n\treadonly action: Any;\n};\n\n/**\n * Children run one after another.\n *\n * @since @next\n */\nexport type Sequence<A extends Any = Any> = {\n\treadonly _tag: \"Sequence\";\n\treadonly children: ReadonlyArray<Step>;\n\t/** Type-level record of the action instances in `children`. */\n\treadonly \"~actions\"?: A;\n};\n\n/**\n * How many branches of a parallel group may run at the same time.\n *\n * @since @next\n */\nexport type Concurrency = number | \"unbounded\";\n\n/**\n * Branches are independent of each other and may run concurrently. The group asserts\n * that independence; the concurrency limit only controls scheduling.\n *\n * @since @next\n */\nexport type Parallel<A extends Any = Any> = {\n\treadonly _tag: \"Parallel\";\n\treadonly branches: ReadonlyArray<Step>;\n\treadonly concurrency: Concurrency;\n\t/** Type-level record of the action instances in `branches`. */\n\treadonly \"~actions\"?: A;\n};\n\n/**\n * A node that declares action occurrences.\n *\n * @since @next\n */\nexport type Step<A extends Any = Any> = A | Instruction<A> | Sequence<A> | Parallel<A>;\n\n/**\n * Extracts the action instances declared by a step.\n *\n * @since @next\n */\nexport type ActionsOf<S> =\n\tS extends Action<infer Id, infer P>\n\t\t? Action<Id, P>\n\t\t: S extends Instruction<infer A>\n\t\t\t? A\n\t\t\t: S extends Sequence<infer A>\n\t\t\t\t? A\n\t\t\t\t: S extends Parallel<infer A>\n\t\t\t\t\t? A\n\t\t\t\t\t: never;\n\n/**\n * Defines an action kind.\n *\n * @example\n * ```ts\n * const RenameKey = Action.define<{ target: string; from: string; to: string }>(\n * \t\"config.rename\",\n * \t{ describe: ({ target, from, to }) => `In ${target}, rename \"${from}\" to \"${to}\"` },\n * );\n * const renameExportA = RenameKey.make(\"rename-export-a-timeout\", {\n * \ttarget: \"export-a\",\n * \tfrom: \"timeout\",\n * \tto: \"requestTimeout\",\n * });\n * ```\n *\n * @since @next\n */\nexport const define = <P>(\n\tkind: string,\n\toptions: { readonly describe?: (payload: P) => string } = {},\n): Kind<P> => {\n\tconst describe = options.describe ?? (() => kind);\n\n\treturn {\n\t\t_tag: \"ActionKind\",\n\t\tkind,\n\t\tdescribe,\n\t\tmake: (id, payload) => ({\n\t\t\t_tag: \"Action\",\n\t\t\tid,\n\t\t\tkind,\n\t\t\tpayload,\n\t\t\tdescription: describe(payload),\n\t\t}),\n\t};\n};\n\n/**\n * Mentions an action in prose without declaring another occurrence.\n *\n * @since @next\n */\nexport const ref = (action: Any): Ref => ({ _tag: \"ActionRef\", action });\n\n/**\n * Declares steps that run one after another.\n *\n * @since @next\n */\nexport const sequence = <const S extends ReadonlyArray<Step>>(\n\tchildren: S,\n): Sequence<ActionsOf<S[number]>> => ({ _tag: \"Sequence\", children });\n\n/**\n * Declares independent branches that may run concurrently. Each branch can be a single\n * step or a sequence.\n *\n * @since @next\n */\nexport const parallel = <const S extends ReadonlyArray<Step>>(\n\tbranches: S,\n\toptions: { readonly concurrency?: Concurrency } = {},\n): Parallel<ActionsOf<S[number]>> => ({\n\t_tag: \"Parallel\",\n\tbranches,\n\tconcurrency: options.concurrency ?? \"unbounded\",\n});\n\n/** @since @next */\nexport const isAction = (value: unknown): value is Any =>\n\tPredicate.isTagged(value, \"Action\") && Predicate.hasProperty(value, \"id\");\n\n/** @since @next */\nexport const isRef = (value: unknown): value is Ref => Predicate.isTagged(value, \"ActionRef\");\n\n/** @since @next */\nexport const isSequence = (value: unknown): value is Sequence =>\n\tPredicate.isTagged(value, \"Sequence\");\n\n/** @since @next */\nexport const isParallel = (value: unknown): value is Parallel =>\n\tPredicate.isTagged(value, \"Parallel\");\n","import dedentText from \"dedent\";\n\nconst placeholder = \"\\u0000\";\n\n/**\n * Removes the common indentation of a tagged template and its surrounding whitespace.\n *\n * Returns one literal string per original literal, so interpolated values stay at their\n * positions and are never stringified or re-indented.\n */\nexport const dedent = (strings: ReadonlyArray<string>): ReadonlyArray<string> =>\n\tdedentText(strings.join(placeholder)).split(placeholder);\n\n/** Scalar values that interpolate as text. */\nexport type Scalar = string | number | boolean | bigint;\n\nexport const isScalar = (value: unknown): value is Scalar =>\n\ttypeof value === \"string\" ||\n\ttypeof value === \"number\" ||\n\ttypeof value === \"boolean\" ||\n\ttypeof value === \"bigint\";\n\nexport const describeValue = (value: unknown): string => {\n\tif (value === null) return \"null\";\n\tif (Array.isArray(value)) return \"an array\";\n\n\treturn typeof value === \"object\" ? \"an object\" : typeof value;\n};\n","import { Predicate } from \"effect\";\n\nimport { describeValue, dedent, isScalar, type Scalar } from \"./template.ts\";\n\n/**\n * The metadata of a change whose shape is not known statically.\n *\n * @since @next\n */\nexport type Metadata = { readonly [field: string]: unknown };\n\n/** @since @next */\nexport type NoMetadata = { readonly [field: string]: undefined };\n\n/**\n * A human-readable record of one logical change. A change can exist before it is\n * assigned to a release, and it does not need an executable migration.\n *\n * deltafold does not interpret `metadata`. Consumers choose its fields, such as a\n * classification or a breaking flag, and what they mean.\n *\n * @since @next\n */\nexport type Change<M extends object = Metadata> = {\n\treadonly _tag: \"Change\";\n\t/** Stable identifier. Editing the description does not change identity. */\n\treadonly id: string;\n\treadonly metadata: M;\n\treadonly description: string;\n\t/** Historical relationship only: it does not cancel actions or create routes. */\n\treadonly reverts: ReadonlyArray<Any>;\n\t/** The change that an adapted backport was derived from. */\n\treadonly backportOf: Any | undefined;\n};\n\n/**\n * A change whose metadata type is not known statically. Its metadata is an object, so\n * reading a field requires narrowing first.\n *\n * @since @next\n */\nexport type Any = Change<object>;\n\n/**\n * Relationships to other changes.\n *\n * @since @next\n */\nexport type Relations = {\n\treadonly reverts?: ReadonlyArray<Any>;\n\treadonly backportOf?: Any;\n};\n\n/**\n * Takes the description as a tagged template and returns the change.\n *\n * @since @next\n */\nexport type Describe<M extends object> = (\n\tstrings: TemplateStringsArray,\n\t...values: ReadonlyArray<Scalar>\n) => Change<M>;\n\nconst describe =\n\t<M extends object>(id: string, metadata: M, relations: Relations): Describe<M> =>\n\t(strings, ...values) => {\n\t\tconst literals = dedent(strings);\n\t\tlet description = \"\";\n\t\tfor (const [index, literal] of literals.entries()) {\n\t\t\tdescription += literal;\n\t\t\tif (index >= values.length) continue;\n\n\t\t\tconst value: unknown = values[index];\n\t\t\tif (!isScalar(value)) {\n\t\t\t\tthrow new TypeError(`Change \"${id}\": cannot interpolate ${describeValue(value)}.`);\n\t\t\t}\n\t\t\tdescription += String(value);\n\t\t}\n\n\t\treturn {\n\t\t\t_tag: \"Change\",\n\t\t\tid,\n\t\t\tmetadata,\n\t\t\tdescription,\n\t\t\treverts: relations.reverts ?? [],\n\t\t\tbackportOf: relations.backportOf,\n\t\t};\n\t};\n\n/**\n * Declares a change. The tagged template is its description. Metadata is optional, and\n * its type is inferred from the value, literals included.\n *\n * @example\n * ```ts\n * const retriesAdded = Change.make(\"2026-11-20.add-retries\")`\n * \tAdd a retry limit option.\n * `;\n * const timeoutRenamed = Change.make(\"2026-11-06.rename-timeout\", { breaking: true })`\n * \tRename the timeout configuration option to requestTimeout.\n * `;\n * ```\n *\n * @since @next\n */\nexport function make(id: string): Describe<NoMetadata>;\nexport function make<const M extends object>(\n\tid: string,\n\tmetadata: M,\n\trelations?: Relations,\n): Describe<M>;\nexport function make(id: string, metadata: object = {}, relations: Relations = {}) {\n\treturn describe(id, metadata, relations);\n}\n\n/**\n * Makes changes that share one metadata shape.\n *\n * @since @next\n */\nexport type Definition<M extends object> = {\n\treadonly make: (id: string, metadata: M, relations?: Relations) => Describe<M>;\n};\n\n/**\n * Defines a reusable change factory whose metadata must have the type `M`.\n *\n * @example\n * ```ts\n * const ConfigChange = Change.define<{\n * \treadonly kind: \"added\" | \"changed\" | \"fixed\";\n * \treadonly breaking: boolean;\n * }>();\n * const timeoutRenamed = ConfigChange.make(\"2026-11-06.rename-timeout\", {\n * \tkind: \"changed\",\n * \tbreaking: true,\n * })`\n * \tRename the timeout configuration option to requestTimeout.\n * `;\n * ```\n *\n * @since @next\n */\nexport const define = <M extends object>(): Definition<M> => ({ make: make<M> });\n\n/** @since @next */\nexport const isChange = (value: unknown): value is Change => Predicate.isTagged(value, \"Change\");\n","import { Context, Duration, Effect, Option } from \"effect\";\n\n/**\n * How the executor learns whether an interrupted Promise callback settled. Effect stops\n * waiting for a Promise when it is interrupted, but the Promise itself can keep running.\n */\nexport type Settlement = {\n\t/** How long to keep waiting for an interrupted Promise before reporting it pending. */\n\treadonly grace: Duration.Input;\n\t/** Receives an interrupted Promise that did not settle within the grace period. */\n\treadonly unsettled: (promise: Promise<void>) => void;\n};\n\nexport const SettlementReference = Context.Reference<Settlement>(\"deltafold/Settlement\", {\n\tdefaultValue: () => ({ grace: Duration.zero, unsettled: () => {} }),\n});\n\n/**\n * Runs a Promise-producing effect. If it is interrupted after the Promise started,\n * waits up to the settlement grace period and hands a still-pending Promise to the\n * settlement, which can hold resources until it settles.\n */\nexport const trackPromise = <T, E, R>(\n\tstart: (capture: (promise: Promise<T>) => Promise<T>) => Effect.Effect<T, E, R>,\n): Effect.Effect<T, E, R> =>\n\tEffect.suspend(() => {\n\t\tlet pending: Promise<T> | undefined;\n\t\tconst capture = (promise: Promise<T>) => {\n\t\t\tpending = promise;\n\n\t\t\treturn promise;\n\t\t};\n\n\t\treturn start(capture).pipe(\n\t\t\tEffect.onInterrupt(() =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst started = pending;\n\t\t\t\t\tif (started === undefined) return;\n\n\t\t\t\t\tconst settles = started.then(\n\t\t\t\t\t\t() => undefined,\n\t\t\t\t\t\t() => undefined,\n\t\t\t\t\t);\n\t\t\t\t\tconst settlement = yield* SettlementReference;\n\t\t\t\t\tconst settled = yield* Effect.promise(() => settles).pipe(\n\t\t\t\t\t\tEffect.timeoutOption(settlement.grace),\n\t\t\t\t\t);\n\t\t\t\t\tif (Option.isNone(settled)) settlement.unsettled(settles);\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t});\n","import { Context, Effect, Schema } from \"effect\";\n\nimport type { ValueOf } from \"../../types.ts\";\nimport { trackPromise } from \"./settlement.ts\";\n\n/** Named Effect services that Promise callbacks declare. */\nexport type ServiceMap = { readonly [name: string | symbol]: Context.Key<any, any> };\n\n// oxlint-disable-next-line typescript/no-generated-empty-object-type -- Callbacks without services declare an empty service map.\nexport type NoServices = Record<never, never>;\n\n/** The `AbortSignal` aborted on interruption, and the declared services, resolved. */\nexport type PromiseContext<S extends ServiceMap = NoServices> = {\n\treadonly signal: AbortSignal;\n\treadonly services: { readonly [K in keyof S]: S[K][\"Service\"] };\n};\n\nexport type ServiceIds<S extends ServiceMap> = ValueOf<{\n\t[K in keyof S]: S[K] extends Context.Key<infer I, any> ? I : never;\n}>;\n\n/** Recognizes a declared rejection: a schema, or a type guard. */\nexport type ErrorGuard = Schema.Top | ((cause: unknown) => cause is any);\n\nexport type GuardedError<G> = G extends Schema.Top\n\t? G[\"Type\"]\n\t: G extends ((cause: unknown) => cause is infer E)\n\t\t? E\n\t\t: never;\n\nconst declaredError =\n\t<G extends ReadonlyArray<ErrorGuard>>(guards: G) =>\n\t(cause: unknown): cause is GuardedError<G[number]> =>\n\t\tguards.some((guard) => (Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause)));\n\n/**\n * Turns Promise callbacks into Effects. Declared services are resolved before each\n * call, rejections that a guard recognizes keep their type, and `unexpected` wraps the\n * rest.\n */\nexport const adaptPromise = <S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>>(options: {\n\treadonly services?: S | undefined;\n\treadonly errors?: G | undefined;\n}) => {\n\tconst isDeclared = declaredError(options.errors ?? []);\n\tconst services: ServiceMap = options.services ?? {};\n\t// The callbacks require exactly the declared services. Reading them from the context\n\t// keeps that requirement typed; only the record of resolved services needs a cast,\n\t// because Object.fromEntries does not track keys.\n\tconst resolve = Effect.map(\n\t\tEffect.context<ServiceIds<S>>(),\n\t\t(context) =>\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\t\t\tObject.fromEntries(\n\t\t\t\tReflect.ownKeys(services).map((name) => [\n\t\t\t\t\tname,\n\t\t\t\t\tContext.get(context, services[name]!),\n\t\t\t\t]),\n\t\t\t) as { readonly [K in keyof S]: S[K][\"Service\"] },\n\t);\n\n\treturn <T, U>(\n\t\tcallback: (context: PromiseContext<S>) => PromiseLike<T> | T,\n\t\tunexpected: (cause: unknown) => U,\n\t): Effect.Effect<T, GuardedError<G[number]> | U, ServiceIds<S>> =>\n\t\tEffect.flatMap(resolve, (resolved) =>\n\t\t\ttrackPromise((capture) =>\n\t\t\t\tEffect.tryPromise({\n\t\t\t\t\t// Declaring `signal` makes Effect.tryPromise allocate an AbortController.\n\t\t\t\t\ttry: (signal) =>\n\t\t\t\t\t\tcapture(Promise.resolve(callback({ signal, services: resolved }))),\n\t\t\t\t\tcatch: (cause) => (isDeclared(cause) ? cause : unexpected(cause)),\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n};\n","import { Data, Effect, Predicate, Scope } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Callback from \"./promise-callback.ts\";\nimport { adaptPromise } from \"./promise-callback.ts\";\n\ntype NoServices = Callback.NoServices;\ntype ServiceIds<S extends ServiceMap> = Callback.ServiceIds<S>;\ntype GuardedError<G> = Callback.GuardedError<G>;\n\n/**\n * Where a handler failure or interruption happened: the read-only prepare phase, or the\n * apply phase that changes state. A manual handler has neither: the executor waits for a\n * person in `confirmation`, then runs the handler's optional check in `verification`.\n *\n * @since @next\n */\nexport type Phase = \"prepare\" | \"apply\" | \"confirmation\" | \"verification\";\n\n/**\n * Who performs an action: a handler's apply phase, or a person whose confirmation the\n * executor waits for.\n *\n * @since @next\n */\nexport type Performer = \"automated\" | \"manual\";\n\n/**\n * A person confirmed manual work, and the handler's `verify` check returned `false`.\n *\n * @since @next\n */\nexport class VerificationFailed extends Data.TaggedError(\"VerificationFailed\")<{\n\treadonly actionId: string;\n\treadonly kind: string;\n}> {\n\toverride get message() {\n\t\treturn `Manual work for action \"${this.actionId}\" was confirmed, but its verification check did not pass`;\n\t}\n}\n\n/**\n * A Promise handler rejected or threw a value that none of its declared error guards\n * recognized, or its prepare phase returned something other than `Handler.prepared` or\n * `Handler.skip`.\n *\n * @since @next\n */\nexport class UnexpectedHandlerError extends Data.TaggedError(\"UnexpectedHandlerError\")<{\n\treadonly actionId: string;\n\treadonly kind: string;\n\treadonly phase: Phase;\n\treadonly cause: unknown;\n}> {\n\toverride get message() {\n\t\treturn `Handler for action \"${this.actionId}\" failed unexpectedly in its ${this.phase} phase`;\n\t}\n}\n\nconst PreparationTypeId = \"~deltafold/Preparation\";\n\n/**\n * A prepare phase decided to apply. The apply phase receives `value` unchanged; the\n * executor never reads, validates, or serializes it.\n *\n * @since @next\n */\nexport type Prepared<out P> = {\n\treadonly [PreparationTypeId]: typeof PreparationTypeId;\n\treadonly _tag: \"Prepared\";\n\treadonly value: P;\n};\n\n/**\n * A prepare phase decided that the action does not apply. The occurrence is skipped\n * with `reason`.\n *\n * @since @next\n */\nexport type Skip = {\n\treadonly [PreparationTypeId]: typeof PreparationTypeId;\n\treadonly _tag: \"Skip\";\n\treadonly reason: string;\n};\n\n/**\n * What a prepare phase returns: `Handler.prepared(value)` or `Handler.skip(reason)`.\n *\n * @since @next\n */\nexport type Preparation<P> = Prepared<P> | Skip;\n\n/** The value that a prepare phase passes to its apply phase. */\ntype PreparedValue<T> = T extends Prepared<infer P> ? P : never;\n\n/**\n * Ends a prepare phase with the value its apply phase receives. Wrapping the value keeps\n * it apart from a skip, whatever its shape.\n *\n * @since @next\n */\nexport function prepared(): Prepared<void>;\nexport function prepared<P>(value: P): Prepared<P>;\nexport function prepared(value?: unknown): Prepared<unknown> {\n\treturn { [PreparationTypeId]: PreparationTypeId, _tag: \"Prepared\", value };\n}\n\n/**\n * Ends a prepare phase by skipping the occurrence. The apply phase does not run.\n *\n * @since @next\n */\nexport const skip = (reason: string): Skip => ({\n\t[PreparationTypeId]: PreparationTypeId,\n\t_tag: \"Skip\",\n\treason,\n});\n\nconst isPreparation = (value: unknown): value is Preparation<unknown> =>\n\tPredicate.hasProperty(value, PreparationTypeId);\n\nconst notAPreparation = () =>\n\tnew TypeError(\"A prepare phase must return Handler.prepared(value) or Handler.skip(reason)\");\n\n/**\n * How an occurrence continues after its prepare phase: skipped, applied by an effect\n * that already holds the prepared value, or confirmed by a person. `verify` checks\n * confirmed work and fails when the check does not pass.\n *\n * @since @next\n */\nexport type Step<E, R> =\n\t| Skip\n\t| { readonly _tag: \"Apply\"; readonly apply: Effect.Effect<void, E, R> }\n\t| { readonly _tag: \"Confirm\"; readonly verify: Effect.Effect<void, E, R> | undefined };\n\nconst applyStep = <E, R>(apply: Effect.Effect<void, E, R>): Step<E, R> => ({\n\t_tag: \"Apply\",\n\tapply,\n});\n\nconst TypeId = \"~deltafold/Handler\";\n\n/**\n * Implements one action instance. `E` and `R` are the errors and Effect services of both\n * phases together. A prepared value stays inside the handler, so handlers with\n * different prepared values share this type.\n *\n * @since @next\n */\nexport type Handler<out A extends Action.Any, out E = never, out R = never> = {\n\treadonly [TypeId]: typeof TypeId;\n\treadonly action: A;\n\t/** A `manual` handler has no phases of its own: a person does the work. */\n\treadonly performer: Performer;\n\t/** Whether the handler has a prepare phase. */\n\treadonly prepares: boolean;\n\t/**\n\t * Runs the prepare phase, if any, and resolves to the next step. Both phases share\n\t * `scope`, the occurrence's scope, so resources acquired while preparing stay open\n\t * until the executor closes it after the occurrence ends.\n\t */\n\treadonly prepare: (scope: Scope.Scope) => Effect.Effect<Step<E, R>, E, R>;\n};\n\n/**\n * Any handler.\n *\n * @since @next\n */\nexport type Any = Handler<Action.Any, any, any>;\n\n/**\n * The errors of a handler or a union of handlers.\n *\n * @since @next\n */\nexport type Error<H> = H extends Handler<any, infer E, any> ? E : never;\n\n/**\n * The Effect services of a handler or a union of handlers.\n *\n * @since @next\n */\nexport type Services<H> = H extends Handler<any, any, infer R> ? R : never;\n\n/**\n * The action identifiers implemented by a handler or a union of handlers.\n *\n * @since @next\n */\nexport type ActionId<H> = H extends Handler<infer A, any, any> ? A[\"id\"] : never;\n\n/** @since @next */\nexport const isHandler = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId);\n\nconst make = <A extends Action.Any, E, R>(\n\taction: A,\n\tprepares: boolean,\n\tprepare: (scope: Scope.Scope) => Effect.Effect<Step<E, R>, E, R>,\n): Handler<A, E, R> => ({ [TypeId]: TypeId, action, performer: \"automated\", prepares, prepare });\n\n/**\n * Named Effect services that a Promise handler declares.\n *\n * @since @next\n */\nexport type ServiceMap = Callback.ServiceMap;\n\n/**\n * The second argument of Promise handler callbacks: the `AbortSignal` that\n * `Effect.tryPromise` aborts on interruption, and the declared services, resolved.\n *\n * @since @next\n */\nexport type PromiseContext<S extends ServiceMap = NoServices> = Callback.PromiseContext<S>;\n\n/**\n * The second argument of a Promise apply phase: the Promise context and the action\n * payload.\n *\n * @since @next\n */\nexport type PromiseApplyContext<Payload, S extends ServiceMap = NoServices> = PromiseContext<S> & {\n\treadonly payload: Payload;\n};\n\n/**\n * A Promise handler with a prepare phase. `prepare` reads state and returns\n * `Handler.prepared(value)` or `Handler.skip(reason)`; `apply` receives the value. Each\n * phase gets its own signal.\n *\n * @since @next\n */\nexport type PromisePhases<Payload, T extends Preparation<unknown>, S extends ServiceMap> = {\n\treadonly prepare: (payload: Payload, context: PromiseContext<S>) => PromiseLike<T> | T;\n\treadonly apply: (\n\t\tprepared: PreparedValue<T>,\n\t\tcontext: PromiseApplyContext<Payload, S>,\n\t) => PromiseLike<unknown>;\n};\n\n/**\n * Recognizes a declared rejection: a schema, or a type guard such as an `instanceof`\n * check. Guards must declare their parameter type, for example\n * `(cause: unknown): cause is NotFound => cause instanceof NotFound`.\n *\n * @since @next\n */\nexport type ErrorGuard = Callback.ErrorGuard;\n\n/** @since @next */\nexport type PromiseOptions<S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>> = {\n\t/** Effect services resolved for the callbacks and added to the handler requirements. */\n\treadonly services?: S;\n\t/**\n\t * Guards for rejections that keep their own type. Other rejections become\n\t * `UnexpectedHandlerError`. A guard does not prove that the callback throws only\n\t * those errors.\n\t */\n\treadonly errors?: G;\n};\n\ntype PromiseHandler<A extends Action.Any, S extends ServiceMap, G> = Handler<\n\tA,\n\tGuardedError<G> | UnexpectedHandlerError,\n\tServiceIds<S>\n>;\n\n/**\n * Implements an action with Promise callbacks. The callbacks run lazily through\n * `Effect.tryPromise`, and receive its `AbortSignal` and the declared services.\n *\n * Pass one callback to apply the action directly, or `{ prepare, apply }` to decide\n * first. `prepare` must only read: a dry run calls it and never calls `apply`. A real\n * run calls `apply` once with the prepared value.\n *\n * @example\n * ```ts\n * Handler.promise(\n * \tupdateRemoteConfig,\n * \tasync (payload, { signal, services: { editor } }) => {\n * \t\tawait editor.update(payload, { signal });\n * \t},\n * \t{ services: { editor: ConfigEditor } },\n * );\n * ```\n *\n * @example\n * ```ts\n * Handler.promise(renameTimeout, {\n * \tprepare: async ({ file, from }, { signal }) => {\n * \t\tconst config = await readConfig(file, { signal });\n * \t\treturn from in config ? Handler.prepared(config) : Handler.skip(`${file} has no ${from}`);\n * \t},\n * \tapply: async (config, { payload, signal }) => {\n * \t\tawait writeConfig(payload.file, rename(config, payload), { signal });\n * \t},\n * });\n * ```\n *\n * @since @next\n */\nexport function promise<\n\tA extends Action.Any,\n\tconst S extends ServiceMap = NoServices,\n\tconst G extends ReadonlyArray<ErrorGuard> = [],\n>(\n\taction: A,\n\tapply: (payload: A[\"payload\"], context: PromiseContext<S>) => PromiseLike<unknown>,\n\toptions?: PromiseOptions<S, G>,\n): PromiseHandler<A, S, G[number]>;\nexport function promise<\n\tA extends Action.Any,\n\tT extends Preparation<unknown> = Skip,\n\tconst S extends ServiceMap = NoServices,\n\tconst G extends ReadonlyArray<ErrorGuard> = [],\n>(\n\taction: A,\n\tphases: PromisePhases<A[\"payload\"], T, S>,\n\toptions?: PromiseOptions<S, G>,\n): PromiseHandler<A, S, G[number]>;\nexport function promise<\n\tA extends Action.Any,\n\tS extends ServiceMap,\n\tG extends ReadonlyArray<ErrorGuard>,\n>(\n\taction: A,\n\trun:\n\t\t| ((payload: A[\"payload\"], context: PromiseContext<S>) => PromiseLike<unknown>)\n\t\t| PromisePhases<A[\"payload\"], Preparation<unknown>, S>,\n\toptions?: PromiseOptions<S, G>,\n): PromiseHandler<A, S, G[number]> {\n\ttype E = GuardedError<G[number]> | UnexpectedHandlerError;\n\n\tconst adaptCallback = adaptPromise(options ?? {});\n\tconst unexpected = (phase: Phase, cause: unknown) =>\n\t\tnew UnexpectedHandlerError({ actionId: action.id, kind: action.kind, phase, cause });\n\n\tconst adapt = <T>(\n\t\tphase: Phase,\n\t\tcallback: (context: PromiseContext<S>) => PromiseLike<T> | T,\n\t): Effect.Effect<T, E, ServiceIds<S>> =>\n\t\tadaptCallback(callback, (cause) => unexpected(phase, cause));\n\n\tif (Predicate.isFunction(run)) {\n\t\tconst apply = Effect.asVoid(adapt(\"apply\", (context) => run(action.payload, context)));\n\n\t\treturn make(action, false, () => Effect.succeed(applyStep(apply)));\n\t}\n\n\tconst prepare = adapt(\"prepare\", (context) => run.prepare(action.payload, context)).pipe(\n\t\tEffect.filterOrFail(isPreparation, () => unexpected(\"prepare\", notAPreparation())),\n\t\tEffect.map((preparation): Step<E, ServiceIds<S>> =>\n\t\t\tpreparation._tag === \"Skip\"\n\t\t\t\t? preparation\n\t\t\t\t: applyStep(\n\t\t\t\t\t\tEffect.asVoid(\n\t\t\t\t\t\t\tadapt(\"apply\", (context) =>\n\t\t\t\t\t\t\t\trun.apply(preparation.value, {\n\t\t\t\t\t\t\t\t\t...context,\n\t\t\t\t\t\t\t\t\tpayload: action.payload,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t),\n\t);\n\n\treturn make(action, true, () => prepare);\n}\n\n/**\n * The second argument of an Effect apply phase.\n *\n * @since @next\n */\nexport type EffectApplyContext<Payload> = { readonly payload: Payload };\n\n/**\n * An Effect handler with a prepare phase. `prepare` reads state and succeeds with\n * `Handler.prepared(value)` or `Handler.skip(reason)`; `apply` receives the value.\n *\n * @since @next\n */\nexport type EffectPhases<Payload, T extends Preparation<unknown>, E1, R1, E2, R2> = {\n\treadonly prepare: (payload: Payload) => Effect.Effect<T, E1, R1>;\n\treadonly apply: (\n\t\tprepared: PreparedValue<T>,\n\t\tcontext: EffectApplyContext<Payload>,\n\t) => Effect.Effect<unknown, E2, R2>;\n};\n\n/**\n * Implements an action with an Effect. The handler keeps its own errors and services,\n * and stops through native Effect interruption.\n *\n * Pass one function to apply the action directly, or `{ prepare, apply }` to decide\n * first. `prepare` must only read: a dry run runs it and never runs `apply`. A real run\n * runs `apply` once with the prepared value. Both phases run in the occurrence's\n * `Scope`, so a resource acquired while preparing, such as a lock, stays open until the\n * occurrence ends; the handler does not require `Scope`.\n *\n * @example\n * ```ts\n * Handler.effect(renameTimeout, {\n * \tprepare: ({ file, from }) =>\n * \t\tEffect.gen(function* () {\n * \t\t\tconst files = yield* ConfigFiles;\n * \t\t\tconst config = yield* files.lock(file);\n * \t\t\treturn from in config.data ? Handler.prepared(config) : Handler.skip(`${file} has no ${from}`);\n * \t\t}),\n * \tapply: (config, { payload }) => config.write(rename(config.data, payload)),\n * });\n * ```\n *\n * @since @next\n */\nexport function effect<A extends Action.Any, E = never, R = never>(\n\taction: A,\n\tapply: (payload: A[\"payload\"]) => Effect.Effect<unknown, E, R>,\n): Handler<A, E, Exclude<R, Scope.Scope>>;\nexport function effect<\n\tA extends Action.Any,\n\tT extends Preparation<unknown> = Skip,\n\tE1 = never,\n\tR1 = never,\n\tE2 = never,\n\tR2 = never,\n>(\n\taction: A,\n\tphases: EffectPhases<A[\"payload\"], T, E1, R1, E2, R2>,\n): Handler<A, E1 | E2, Exclude<R1 | R2, Scope.Scope>>;\nexport function effect<A extends Action.Any, E1, R1, E2, R2>(\n\taction: A,\n\trun:\n\t\t| ((payload: A[\"payload\"]) => Effect.Effect<unknown, E1, R1>)\n\t\t| EffectPhases<A[\"payload\"], Preparation<unknown>, E1, R1, E2, R2>,\n): Handler<A, E1 | E2, Exclude<R1 | R2, Scope.Scope>> {\n\ttype E = E1 | E2;\n\ttype R = Exclude<R1 | R2, Scope.Scope>;\n\n\tif (Predicate.isFunction(run)) {\n\t\tconst apply = Effect.asVoid(Effect.suspend(() => run(action.payload)));\n\n\t\treturn make(action, false, (scope) =>\n\t\t\tEffect.succeed(applyStep<E, R>(Scope.provide(apply, scope))),\n\t\t);\n\t}\n\n\treturn make(action, true, (scope) =>\n\t\tEffect.suspend(() => run.prepare(action.payload)).pipe(\n\t\t\tScope.provide(scope),\n\t\t\tEffect.filterOrElse(isPreparation, () => Effect.die(notAPreparation())),\n\t\t\tEffect.map((preparation): Step<E, R> =>\n\t\t\t\tpreparation._tag === \"Skip\"\n\t\t\t\t\t? preparation\n\t\t\t\t\t: applyStep(\n\t\t\t\t\t\t\tScope.provide(\n\t\t\t\t\t\t\t\tEffect.asVoid(\n\t\t\t\t\t\t\t\t\tEffect.suspend(() =>\n\t\t\t\t\t\t\t\t\t\trun.apply(preparation.value, { payload: action.payload }),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tscope,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t),\n\t\t),\n\t);\n}\n\nconst verified = <E, R>(action: Action.Any, check: Effect.Effect<boolean, E, R>) =>\n\tEffect.flatMap(check, (passed) =>\n\t\tpassed\n\t\t\t? Effect.void\n\t\t\t: Effect.fail(new VerificationFailed({ actionId: action.id, kind: action.kind })),\n\t);\n\nconst makeManual = <A extends Action.Any, E, R>(\n\taction: A,\n\tverify: ((scope: Scope.Scope) => Effect.Effect<void, E, R>) | undefined,\n): Handler<A, E, R> => ({\n\t[TypeId]: TypeId,\n\taction,\n\tperformer: \"manual\",\n\tprepares: false,\n\tprepare: (scope) => Effect.succeed({ _tag: \"Confirm\", verify: verify?.(scope) }),\n});\n\n/** @since @next */\nexport type ManualOptions<Payload, S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>> = {\n\t/** Effect services resolved for `verify` and added to the handler requirements. */\n\treadonly services?: S;\n\t/** Guards for rejections of `verify` that keep their own type. */\n\treadonly errors?: G;\n\t/**\n\t * Read-only check that runs after the person confirms. Returning `false` fails the\n\t * occurrence with `VerificationFailed`. A passing check is evidence that the work is\n\t * in place, not proof of how it was done.\n\t */\n\treadonly verify?: (\n\t\tpayload: Payload,\n\t\tcontext: PromiseContext<S>,\n\t) => boolean | PromiseLike<boolean>;\n};\n\n/**\n * Declares that a person performs the action. A manual handler has no prepare or apply\n * phase. In a real run the executor asks its `interaction` to confirm the work, showing\n * the occurrence's own instruction or description, and never completes the occurrence\n * on its own. A dry run reports that a person would be asked. The optional `verify`\n * check is a Promise callback that runs only after the confirmation.\n *\n * The same action can have a manual handler in one environment and an automated one in\n * another.\n *\n * @example\n * ```ts\n * Handler.manual(rotateApiKey, {\n * \tservices: { keys: KeyStore },\n * \tverify: (payload, { services: { keys } }) => keys.isFresh(payload.service),\n * });\n * ```\n *\n * @since @next\n */\nexport function manual<A extends Action.Any>(action: A): Handler<A>;\nexport function manual<\n\tA extends Action.Any,\n\tconst S extends ServiceMap = NoServices,\n\tconst G extends ReadonlyArray<ErrorGuard> = [],\n>(\n\taction: A,\n\toptions: ManualOptions<A[\"payload\"], S, G>,\n): Handler<A, GuardedError<G[number]> | UnexpectedHandlerError | VerificationFailed, ServiceIds<S>>;\nexport function manual<\n\tA extends Action.Any,\n\tS extends ServiceMap,\n\tG extends ReadonlyArray<ErrorGuard>,\n>(\n\taction: A,\n\toptions?: ManualOptions<A[\"payload\"], S, G>,\n): Handler<\n\tA,\n\tGuardedError<G[number]> | UnexpectedHandlerError | VerificationFailed,\n\tServiceIds<S>\n> {\n\tconst adapt = adaptPromise(options ?? {});\n\tconst verify = options?.verify;\n\tif (verify === undefined) return makeManual(action, undefined);\n\n\tconst check = verified(\n\t\taction,\n\t\tadapt(\n\t\t\t(context) => verify(action.payload, context),\n\t\t\t(cause) =>\n\t\t\t\tnew UnexpectedHandlerError({\n\t\t\t\t\tactionId: action.id,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tphase: \"verification\",\n\t\t\t\t\tcause,\n\t\t\t\t}),\n\t\t),\n\t);\n\n\treturn makeManual(action, () => check);\n}\n\n/** @since @next */\nexport type ManualEffectOptions<Payload, E, R> = {\n\t/**\n\t * Read-only check that runs after the person confirms. Succeeding with `false` fails\n\t * the occurrence with `VerificationFailed`. It runs in the occurrence's `Scope`.\n\t */\n\treadonly verify?: (payload: Payload) => Effect.Effect<boolean, E, R>;\n};\n\n/**\n * `Handler.manual` with an Effect `verify` check, which keeps its own errors and\n * services.\n *\n * @since @next\n */\nexport function manualEffect<A extends Action.Any>(action: A): Handler<A>;\nexport function manualEffect<A extends Action.Any, E = never, R = never>(\n\taction: A,\n\toptions: ManualEffectOptions<A[\"payload\"], E, R>,\n): Handler<A, E | VerificationFailed, Exclude<R, Scope.Scope>>;\nexport function manualEffect<A extends Action.Any, E, R>(\n\taction: A,\n\toptions?: ManualEffectOptions<A[\"payload\"], E, R>,\n): Handler<A, E | VerificationFailed, Exclude<R, Scope.Scope>> {\n\tconst verify = options?.verify;\n\tif (verify === undefined) return makeManual(action, undefined);\n\n\treturn makeManual(action, (scope) =>\n\t\tScope.provide(\n\t\t\tverified(\n\t\t\t\taction,\n\t\t\t\tEffect.suspend(() => verify(action.payload)),\n\t\t\t),\n\t\t\tscope,\n\t\t),\n\t);\n}\n","import {\n\tCause,\n\tContext,\n\tData,\n\tDeferred,\n\tDuration,\n\tEffect,\n\tEqual,\n\tExit,\n\tFiber,\n\tLayer,\n\tOption,\n\tScope,\n} from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Plan from \"../../foundation/plan.ts\";\nimport type { Node, Occurrence } from \"../../foundation/plan.ts\";\nimport * as Handler from \"./handler.ts\";\nimport type * as Interaction from \"./interaction.ts\";\nimport { SettlementReference } from \"./settlement.ts\";\n\n/**\n * What happened to one occurrence, or what a dry run predicts.\n *\n * @since @next\n */\nexport type Outcome<E = unknown> =\n\t| { readonly _tag: \"Completed\"; readonly performer: \"automated\" }\n\t| {\n\t\t\treadonly _tag: \"Completed\";\n\t\t\treadonly performer: \"manual\";\n\t\t\t/**\n\t\t\t * What supports completion. `asserted`: the person said so and nothing checked\n\t\t\t * it. `verified`: the person said so and the handler's `verify` check passed.\n\t\t\t * Neither proves how the work was done.\n\t\t\t */\n\t\t\treadonly confirmation: \"asserted\" | \"verified\";\n\t }\n\t| { readonly _tag: \"Skipped\"; readonly reason: string }\n\t/** The person asked to confirm manual work answered that it is not done. */\n\t| { readonly _tag: \"Declined\" }\n\t| {\n\t\t\treadonly _tag: \"Failed\";\n\t\t\treadonly phase: Handler.Phase;\n\t\t\t/** The typed failure, when the cause has one. Defects only appear in `cause`. */\n\t\t\treadonly error: E | undefined;\n\t\t\treadonly cause: Cause.Cause<E>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"Interrupted\";\n\t\t\treadonly phase: Handler.Phase;\n\t\t\t/** `handler`: an Effect handler interrupted itself. */\n\t\t\treadonly reason: InterruptReason;\n\t\t\t/**\n\t\t\t * Whether the interrupted work is known to have stopped. An interrupted Promise\n\t\t\t * that has not settled within the grace period may still be changing external\n\t\t\t * state.\n\t\t\t */\n\t\t\treadonly settled: boolean;\n\t }\n\t/** Not started because execution stopped first. */\n\t| { readonly _tag: \"Unattempted\" }\n\t/**\n\t * `evaluated`: whether a prepare phase ran and decided to apply. A `manual` occurrence\n\t * would wait for a person; a dry run never asks.\n\t */\n\t| {\n\t\t\treadonly _tag: \"WouldExecute\";\n\t\t\treadonly evaluated: boolean;\n\t\t\treadonly performer: Handler.Performer;\n\t }\n\t| { readonly _tag: \"WouldSkip\"; readonly reason: string }\n\t| {\n\t\t\treadonly _tag: \"Undetermined\";\n\t\t\treadonly reason: string;\n\t\t\t/** A `manual` occurrence would wait for a person if it executes. */\n\t\t\treadonly performer: Handler.Performer;\n\t }\n\t| {\n\t\t\treadonly _tag: \"PreparationFailed\";\n\t\t\treadonly error: E | undefined;\n\t\t\treadonly cause: Cause.Cause<E>;\n\t };\n\n/** @since @next */\nexport type OccurrenceReport<A extends Action.Any = Action.Any, E = unknown> = {\n\treadonly occurrence: Occurrence<A>;\n\treadonly outcome: Outcome<E>;\n};\n\n/** @since @next */\nexport type Report<A extends Action.Any = Action.Any, E = unknown> = {\n\treadonly _tag: \"Report\";\n\treadonly mode: \"execute\" | \"dry-run\";\n\treadonly status:\n\t\t| \"completed\"\n\t\t| \"failed\"\n\t\t| \"interrupted\"\n\t\t| \"not-started\"\n\t\t| \"would-complete\"\n\t\t| \"would-fail\";\n\treadonly from: string;\n\treadonly to: string;\n\treadonly route: string;\n\t/** Every occurrence in plan order. */\n\treadonly occurrences: ReadonlyArray<OccurrenceReport<A, E>>;\n\t/**\n\t * Whether any apply phase started or any person was asked to do manual work. Either\n\t * may have partially changed state.\n\t */\n\treadonly bodiesStarted: boolean;\n\t/** Progress is not persisted. Rerunning the plan repeats completed actions. */\n\treadonly persistence: \"none\";\n};\n\n/**\n * A handler is missing, duplicated, or bound to a different definition.\n *\n * @since @next\n */\nexport type CoverageIssue = {\n\treadonly _tag: \"Missing\" | \"Duplicate\" | \"Mismatched\";\n\treadonly occurrenceId: string;\n\treadonly actionId: string;\n\treadonly description: string;\n\treadonly migrationId: string;\n\t/** The rule that produced the occurrence, for replacements. */\n\treadonly rule: string | undefined;\n\t/** The occurrences a replacement stands for, so the missing handler is discoverable. */\n\treadonly replaces: ReadonlyArray<{\n\t\treadonly occurrenceId: string;\n\t\treadonly description: string;\n\t}>;\n};\n\nconst HandlerCoverageBase = Data.TaggedError(\"HandlerCoverageError\");\n\n/**\n * Handler coverage failed before any handler phase ran. Every occurrence needs exactly\n * one handler, for the same action definition: the same identifier, kind, and payload.\n * For an occurrence that a rule produced, the issue names the rule and the occurrences\n * it replaced.\n *\n * @since @next\n */\nexport class HandlerCoverageError<A extends Action.Any = Action.Any> extends HandlerCoverageBase<{\n\treadonly issues: ReadonlyArray<CoverageIssue>;\n\treadonly report: Report<A, never>;\n}> {\n\toverride get message() {\n\t\treturn `Handler coverage failed for ${this.issues.length} occurrence(s): ${this.issues\n\t\t\t.map(\n\t\t\t\t(issue) =>\n\t\t\t\t\t`${issue._tag.toLowerCase()} handler for \"${issue.actionId}\" (${issue.description})`,\n\t\t\t)\n\t\t\t.join(\"; \")}.`;\n\t}\n}\n\nconst InteractionUnavailableBase = Data.TaggedError(\"InteractionUnavailable\");\n\n/**\n * The plan has manual handlers, and the run has no `interaction` to ask a person. The\n * run fails before any handler phase or prompt.\n *\n * @since @next\n */\nexport class InteractionUnavailable<\n\tA extends Action.Any = Action.Any,\n> extends InteractionUnavailableBase<{\n\t/** The occurrences that a manual handler covers, in plan order. */\n\treadonly occurrences: ReadonlyArray<Occurrence<A>>;\n\treadonly report: Report<A, never>;\n}> {\n\toverride get message() {\n\t\treturn `No interaction is available to confirm manual work for ${this.occurrences\n\t\t\t.map((occurrence) => `\"${occurrence.id}\" (${occurrence.action.description})`)\n\t\t\t.join(\n\t\t\t\t\", \",\n\t\t\t)}. Supply the \\`interaction\\` option, or bind automated handlers to these actions.`;\n\t}\n}\n\nconst listIds = (entries: ReadonlyArray<OccurrenceReport>) =>\n\tentries\n\t\t.map((entry) =>\n\t\t\tentry.outcome._tag === \"Failed\"\n\t\t\t\t? `\"${entry.occurrence.id}\" (${entry.outcome.phase})`\n\t\t\t\t: `\"${entry.occurrence.id}\"`,\n\t\t)\n\t\t.join(\", \");\n\nconst ExecutionFailedBase = Data.TaggedError(\"ExecutionFailed\");\n\n/**\n * An occurrence failed, or a person declined manual work. Execution stopped admitting\n * new actions; started ones settled.\n *\n * @since @next\n */\nexport class ExecutionFailed<\n\tA extends Action.Any = Action.Any,\n\tE = unknown,\n> extends ExecutionFailedBase<{\n\treadonly failures: ReadonlyArray<OccurrenceReport<A, E>>;\n\t/** Manual occurrences that a person declined. */\n\treadonly declined: ReadonlyArray<OccurrenceReport<A, E>>;\n\treadonly report: Report<A, E>;\n}> {\n\toverride get message() {\n\t\tconst parts = [\n\t\t\t...(this.failures.length === 0\n\t\t\t\t? []\n\t\t\t\t: [`Execution failed at ${listIds(this.failures)}.`]),\n\t\t\t...(this.declined.length === 0\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t`Manual work was declined at ${listIds(this.declined)}, which stopped the run.`,\n\t\t\t\t\t]),\n\t\t];\n\n\t\treturn `${parts.join(\" \")} Completed actions were not rolled back.`;\n\t}\n}\n\nconst ExecutionInterruptedBase = Data.TaggedError(\"ExecutionInterrupted\");\n\n/**\n * Why an execution or an occurrence was interrupted: explicit cancellation, a configured\n * timeout, or an Effect handler that interrupted itself.\n *\n * @since @next\n */\nexport type InterruptReason = \"cancelled\" | \"timeout\" | \"handler\";\n\nconst interruptedBy: Record<InterruptReason, string> = {\n\tcancelled: \"cancelled\",\n\ttimeout: \"stopped by a timeout\",\n\thandler: \"interrupted by a handler\",\n};\n\n/**\n * Explicit cancellation, a configured timeout, or a handler's own interruption stopped\n * execution.\n *\n * @since @next\n */\nexport class ExecutionInterrupted<\n\tA extends Action.Any = Action.Any,\n\tE = unknown,\n> extends ExecutionInterruptedBase<{\n\treadonly reason: InterruptReason;\n\treadonly report: Report<A, E>;\n}> {\n\toverride get message() {\n\t\tconst pending = this.report.occurrences.filter(\n\t\t\t(entry) => entry.outcome._tag === \"Interrupted\" && !entry.outcome.settled,\n\t\t);\n\t\tconst suffix =\n\t\t\tpending.length === 0\n\t\t\t\t? \"\"\n\t\t\t\t: ` ${pending.length} interrupted action(s) had not settled and may still be running.`;\n\n\t\treturn `Execution was ${interruptedBy[this.reason]}.${suffix}`;\n\t}\n}\n\n/** @since @next */\nexport type ExecutionError<A extends Action.Any, E> =\n\t| HandlerCoverageError<A>\n\t| InteractionUnavailable<A>\n\t| ExecutionFailed<A, E>\n\t| ExecutionInterrupted<A, E>;\n\n/**\n * Action identifiers of a statically covered plan that no handler in the array\n * implements.\n *\n * @since @next\n */\nexport type Uncovered<A extends Action.Any, H, C extends Plan.Coverage> = \"runtime\" extends C\n\t? never\n\t: A extends Action.Any\n\t\t? string extends A[\"id\"]\n\t\t\t? never\n\t\t\t: A[\"id\"] extends Handler.ActionId<H>\n\t\t\t\t? never\n\t\t\t\t: A[\"id\"]\n\t\t: never;\n\n/** Rejects a handler array that leaves statically known actions uncovered, naming them. */\ntype CoverageCheck<A extends Action.Any, H, C extends Plan.Coverage> = [\n\tUncovered<A, H, C>,\n] extends [never]\n\t? unknown\n\t: { readonly handlers: `Missing a handler for action \"${Uncovered<A, H, C>}\"` };\n\n/**\n * Errors an execution can report for its occurrences.\n *\n * @since @next\n */\nexport type Errors<H, I = never> = Handler.Error<H> | Interaction.Error<I>;\n\n/**\n * Effect services an execution requires: the services of its handlers and of its\n * interaction.\n *\n * @since @next\n */\nexport type Requirements<H, I = never> = Handler.Services<H> | Interaction.Services<I>;\n\n/** @since @next */\nexport type Options<H extends Handler.Any, I extends Interaction.Any = never> = {\n\treadonly handlers?: ReadonlyArray<H>;\n\t/**\n\t * Asks a person to confirm the work of manual handlers. A run whose plan has manual\n\t * handlers fails with `InteractionUnavailable` before it starts when this is absent.\n\t * A dry run never asks and does not need it.\n\t */\n\treadonly interaction?: I;\n\t/**\n\t * Run prepare phases without running any apply phase. A prepare phase that may\n\t * depend on an earlier action is reported `Undetermined`, because the dry run does\n\t * not apply that action.\n\t */\n\treadonly dryRun?: boolean;\n\t/**\n\t * Limit for each phase of an occurrence: the prepare phase and the apply phase each\n\t * get the full limit, and so does the verification of manual work. Exceeding it\n\t * interrupts that action and stops admitting new ones. It applies to dry-run prepare\n\t * phases too. It never limits the wait for a person to confirm manual work; cancel\n\t * the run to end that wait.\n\t */\n\treadonly timeout?: Duration.Input;\n\t/**\n\t * How long to wait for an interrupted Promise callback to settle before reporting it\n\t * as possibly still running. Defaults to 5 seconds.\n\t */\n\treadonly settleTimeout?: Duration.Input;\n};\n\n/** A handler as the executor runs it: its action is erased, its channels are not. */\ntype Internal<E, R> = Handler.Handler<Action.Any, E, R>;\n\ntype Resolved<E, R> = Map<string, Internal<E, R>>;\n\nconst describeReplaces = (occurrence: Occurrence) =>\n\toccurrence.origin._tag === \"Replacement\"\n\t\t? occurrence.origin.replaces.map((replaced) => ({\n\t\t\t\toccurrenceId: replaced.id,\n\t\t\t\tdescription: replaced.action.description,\n\t\t\t}))\n\t\t: [];\n\nconst coverage = <E, R>(\n\tplan: Plan.Any,\n\thandlers: ReadonlyArray<Internal<E, R>>,\n): { readonly resolved: Resolved<E, R>; readonly issues: ReadonlyArray<CoverageIssue> } => {\n\tconst byAction = new Map<string, Array<Internal<E, R>>>();\n\tfor (const handler of handlers) {\n\t\tconst list = byAction.get(handler.action.id) ?? [];\n\t\tlist.push(handler);\n\t\tbyAction.set(handler.action.id, list);\n\t}\n\n\tconst resolved: Resolved<E, R> = new Map();\n\tconst issues: Array<CoverageIssue> = [];\n\tfor (const occurrence of plan.occurrences) {\n\t\tconst issue = (tag: CoverageIssue[\"_tag\"]) =>\n\t\t\tissues.push({\n\t\t\t\t_tag: tag,\n\t\t\t\toccurrenceId: occurrence.id,\n\t\t\t\tactionId: occurrence.action.id,\n\t\t\t\tdescription: occurrence.action.description,\n\t\t\t\tmigrationId: occurrence.migration.id,\n\t\t\t\trule:\n\t\t\t\t\toccurrence.origin._tag === \"Replacement\"\n\t\t\t\t\t\t? occurrence.origin.rule.id\n\t\t\t\t\t\t: undefined,\n\t\t\t\treplaces: describeReplaces(occurrence),\n\t\t\t});\n\n\t\tconst candidates = byAction.get(occurrence.action.id) ?? [];\n\t\tconst [selected] = candidates;\n\t\tif (candidates.length > 1) issue(\"Duplicate\");\n\t\telse if (selected === undefined) issue(\"Missing\");\n\t\telse if (\n\t\t\tselected.action.kind !== occurrence.action.kind ||\n\t\t\t!Equal.equals(selected.action.payload, occurrence.action.payload)\n\t\t) {\n\t\t\tissue(\"Mismatched\");\n\t\t} else resolved.set(occurrence.id, selected);\n\t}\n\n\treturn { resolved, issues };\n};\n\nconst report = <A extends Action.Any, E>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tmode: Report[\"mode\"],\n\tstatus: Report[\"status\"],\n\toutcomes: ReadonlyMap<string, Outcome<E>>,\n\tbodiesStarted: boolean,\n): Report<A, E> => ({\n\t_tag: \"Report\",\n\tmode,\n\tstatus,\n\tfrom: plan.from.id,\n\tto: plan.to.id,\n\troute: plan.route.id,\n\toccurrences: plan.occurrences.map((occurrence) => ({\n\t\toccurrence,\n\t\toutcome: outcomes.get(occurrence.id) ?? { _tag: \"Unattempted\" },\n\t})),\n\tbodiesStarted,\n\tpersistence: \"none\",\n});\n\nconst failureOf = <E>(cause: Cause.Cause<E>) => ({\n\terror: Option.getOrUndefined(Cause.findErrorOption(cause)),\n\tcause,\n});\n\n/** The exit an occurrence's scope closes with, so finalizers see how it ended. */\nconst exitOf = <E>(outcome: Outcome<E> | undefined): Exit.Exit<void, E> => {\n\tswitch (outcome?._tag) {\n\t\tcase \"Failed\":\n\t\tcase \"PreparationFailed\":\n\t\t\treturn Exit.failCause(outcome.cause);\n\t\tcase \"Interrupted\":\n\t\t\treturn Exit.interrupt();\n\t\tdefault:\n\t\t\treturn Exit.void;\n\t}\n};\n\nconst forEachBranch = <R>(\n\tbranches: ReadonlyArray<Node>,\n\tconcurrency: Action.Concurrency,\n\trun: (node: Node) => Effect.Effect<void, never, R>,\n) => Effect.forEach(branches, run, { concurrency, discard: true });\n\n/** Registers a callback that cancels the execution. Only `runPromise` uses it. */\ntype Subscribe = (cancel: () => void) => void;\n\n/**\n * Receives the fiber that closes an occurrence scope after an interrupted Promise\n * settles, so the caller can keep the services it built open until then.\n */\ntype Retain = (fiber: Fiber.Fiber<void>) => void;\n\ntype StopReason = \"failure\" | InterruptReason;\n\ntype PhaseResult<T, E> =\n\t| { readonly _tag: \"Done\"; readonly exit: Exit.Exit<T, E> }\n\t| {\n\t\t\treadonly _tag: \"Interrupted\";\n\t\t\treadonly reason: \"cancelled\" | \"timeout\";\n\t\t\treadonly settled: boolean;\n\t };\n\ntype ControlOptions = Pick<Options<never>, \"timeout\" | \"settleTimeout\">;\n\n/** Waiting for a person is `untimed`: only cancellation ends it. */\ntype Timing = \"timed\" | \"untimed\";\n\n/**\n * Logs a cleanup failure that the report cannot carry, with the occurrence or the\n * services layer that owned the resources.\n */\nconst logCleanupFailure = (owner: Record<string, string>) => (cause: Cause.Cause<unknown>) =>\n\tEffect.logError(\"deltafold: cleanup failed\", cause).pipe(Effect.annotateLogs(owner));\n\n/** Admission state, cancellation, and timeouts shared by real and dry runs. */\nconst makeControl = (options: ControlOptions, subscribe: Subscribe | undefined) =>\n\tEffect.gen(function* () {\n\t\tconst halt: { reason: StopReason | undefined } = { reason: undefined };\n\t\tconst cancelled = yield* Deferred.make<\"cancelled\">();\n\t\tconst settleTimeout = options.settleTimeout ?? Duration.seconds(5);\n\n\t\tconst stop = (reason: StopReason) => {\n\t\t\thalt.reason ??= reason;\n\t\t};\n\t\t// A failure can be the first stop reason, so cancellation is also tracked on its own.\n\t\tlet cancellationArrived = false;\n\t\tsubscribe?.(() => {\n\t\t\tcancellationArrived = true;\n\t\t\tstop(\"cancelled\");\n\t\t\tDeferred.doneUnsafe(cancelled, Exit.succeed(\"cancelled\"));\n\t\t});\n\n\t\t/**\n\t\t * Runs one phase, racing it against cancellation and its own timeout. An\n\t\t * interrupted Promise that outlives the settlement grace period goes to `unsettled`.\n\t\t */\n\t\tconst runPhase = <T, E, R>(\n\t\t\twork: Effect.Effect<T, E, R>,\n\t\t\tunsettled: Array<Promise<void>>,\n\t\t\ttiming: Timing = \"timed\",\n\t\t): Effect.Effect<PhaseResult<T, E>, never, R> =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tlet settled = true;\n\t\t\t\tconst tracked = work.pipe(\n\t\t\t\t\tEffect.provideService(SettlementReference, {\n\t\t\t\t\t\tgrace: settleTimeout,\n\t\t\t\t\t\tunsettled: (promise) => {\n\t\t\t\t\t\t\tsettled = false;\n\t\t\t\t\t\t\tunsettled.push(promise);\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst stopSignals: Array<Effect.Effect<\"cancelled\" | \"timeout\">> = [\n\t\t\t\t\tDeferred.await(cancelled),\n\t\t\t\t];\n\t\t\t\tif (options.timeout !== undefined && timing === \"timed\") {\n\t\t\t\t\tstopSignals.push(Effect.as(Effect.sleep(options.timeout), \"timeout\" as const));\n\t\t\t\t}\n\t\t\t\tconst result = yield* Effect.raceFirst(\n\t\t\t\t\tEffect.map(Effect.exit(tracked), (exit) => ({ _tag: \"Done\" as const, exit })),\n\t\t\t\t\tEffect.raceAll(stopSignals).pipe(\n\t\t\t\t\t\t// Stop admission as soon as the signal fires. The race returns only after\n\t\t\t\t\t\t// the interrupted work has had its settlement grace period.\n\t\t\t\t\t\tEffect.tap((reason) => Effect.sync(() => stop(reason))),\n\t\t\t\t\t\tEffect.map((reason) => ({ _tag: \"Stop\" as const, reason })),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (result._tag === \"Done\") return result;\n\n\t\t\t\t// A timeout interrupts only this action. Siblings settle as after any failure.\n\t\t\t\treturn { _tag: \"Interrupted\" as const, reason: result.reason, settled };\n\t\t\t});\n\n\t\treturn { halt, stop, runPhase, isCancelled: () => cancellationArrived };\n\t});\n\n/**\n * Runs one occurrence in its own scope, which both phases share. `use` returns the\n * exit to close the scope with. The scope closes as soon as the occurrence ends, and\n * a failing finalizer goes to `onCleanupFailure`. If an interrupted Promise has not\n * settled, the scope stays open until it does, possibly forever; a failing\n * finalizer is then logged, because the report may already have been returned.\n */\nconst inScope = <E, R>(\n\tretain: Retain,\n\toccurrenceId: string,\n\tuse: (\n\t\tscope: Scope.Scope,\n\t\tunsettled: Array<Promise<void>>,\n\t) => Effect.Effect<Exit.Exit<void, E>, never, R>,\n\tonCleanupFailure: (cause: Cause.Cause<never>) => Effect.Effect<void>,\n): Effect.Effect<void, never, R> =>\n\tEffect.uninterruptibleMask((restore) =>\n\t\tEffect.gen(function* () {\n\t\t\tconst scope = yield* Scope.make();\n\t\t\tconst unsettled: Array<Promise<void>> = [];\n\t\t\tconst used = yield* Effect.exit(restore(use(scope, unsettled)));\n\t\t\tconst end = Exit.isSuccess(used) ? used.value : used;\n\t\t\tif (unsettled.length > 0) {\n\t\t\t\tconst fiber = yield* Effect.forkDetach(\n\t\t\t\t\tEffect.promise(() => Promise.all(unsettled)).pipe(\n\t\t\t\t\t\tEffect.andThen(Scope.close(scope, end)),\n\t\t\t\t\t\tEffect.catchCause(logCleanupFailure({ occurrence: occurrenceId })),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tretain(fiber);\n\t\t\t} else {\n\t\t\t\tconst closed = yield* Effect.exit(Scope.close(scope, end));\n\t\t\t\tif (Exit.isFailure(closed)) yield* onCleanupFailure(closed.cause);\n\t\t\t}\n\n\t\t\treturn yield* used;\n\t\t}),\n\t).pipe(Effect.asVoid);\n\nconst interrupted = <A extends Action.Any, E>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tmode: Report[\"mode\"],\n\treason: InterruptReason,\n\toutcomes: ReadonlyMap<string, Outcome<E>>,\n\tbodiesStarted: boolean,\n) =>\n\tnew ExecutionInterrupted({\n\t\treason,\n\t\treport: report(plan, mode, \"interrupted\", outcomes, bodiesStarted),\n\t});\n\n/**\n * The outcome of a phase that did not succeed. `undefined` when it succeeded. An Effect\n * handler that interrupted itself stops admission.\n */\nconst unsuccessful = <T, E>(\n\tphase: Handler.Phase,\n\tresult: PhaseResult<T, E>,\n\tstop: (reason: StopReason) => void,\n): Outcome<E> | undefined => {\n\tif (result._tag === \"Interrupted\") {\n\t\treturn {\n\t\t\t_tag: \"Interrupted\",\n\t\t\tphase,\n\t\t\treason: result.reason,\n\t\t\tsettled: result.settled,\n\t\t};\n\t}\n\tif (Exit.isFailure(result.exit) && Cause.hasInterruptsOnly(result.exit.cause)) {\n\t\tstop(\"handler\");\n\n\t\treturn { _tag: \"Interrupted\", phase, reason: \"handler\", settled: true };\n\t}\n\n\treturn undefined;\n};\n\nconst execute = <A extends Action.Any, E, R>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tresolved: Resolved<E, R>,\n\tinteraction: Interaction.Interaction<E, R> | undefined,\n\toptions: ControlOptions,\n\tsubscribe: Subscribe | undefined,\n\tretain: Retain,\n): Effect.Effect<Report<A, E>, ExecutionFailed<A, E> | ExecutionInterrupted<A, E>, R> =>\n\tEffect.gen(function* () {\n\t\tconst outcomes = new Map<string, Outcome<E>>();\n\t\tconst { halt, stop, runPhase, isCancelled } = yield* makeControl(options, subscribe);\n\t\tlet bodiesStarted = false;\n\n\t\tconst runOccurrence = (occurrence: Occurrence) => {\n\t\t\tif (halt.reason !== undefined) return Effect.void;\n\n\t\t\tconst handler = resolved.get(occurrence.id);\n\t\t\tif (handler === undefined) return Effect.void;\n\n\t\t\tlet phase: Handler.Phase = \"prepare\";\n\t\t\tconst end = (outcome: Outcome<E>) => {\n\t\t\t\toutcomes.set(occurrence.id, outcome);\n\n\t\t\t\treturn exitOf(outcome);\n\t\t\t};\n\t\t\tconst fail = (cause: Cause.Cause<E>) => {\n\t\t\t\tstop(\"failure\");\n\n\t\t\t\treturn end({ _tag: \"Failed\", phase, ...failureOf(cause) });\n\t\t\t};\n\n\t\t\tconst use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tlet step: Handler.Step<E, R>;\n\t\t\t\t\tif (handler.prepares) {\n\t\t\t\t\t\tconst preparation = yield* runPhase(handler.prepare(scope), unsettled);\n\t\t\t\t\t\tconst stopped = unsuccessful(\"prepare\", preparation, stop);\n\t\t\t\t\t\tif (stopped !== undefined) return end(stopped);\n\t\t\t\t\t\tif (preparation._tag !== \"Done\") return Exit.void;\n\t\t\t\t\t\tif (Exit.isFailure(preparation.exit)) return fail(preparation.exit.cause);\n\t\t\t\t\t\tstep = preparation.exit.value;\n\t\t\t\t\t\t// The occurrence has started, so a sibling failure or timeout lets it\n\t\t\t\t\t\t// finish. Cancellation that arrived while preparing keeps it from\n\t\t\t\t\t\t// applying, and the prepared value is discarded.\n\t\t\t\t\t\tif (step._tag === \"Apply\" && halt.reason === \"cancelled\") return Exit.void;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst started = yield* Effect.exit(handler.prepare(scope));\n\t\t\t\t\t\tif (Exit.isFailure(started)) return fail(started.cause);\n\t\t\t\t\t\tstep = started.value;\n\t\t\t\t\t}\n\t\t\t\t\tif (step._tag === \"Skip\") return end({ _tag: \"Skipped\", reason: step.reason });\n\t\t\t\t\tif (step._tag === \"Confirm\") {\n\t\t\t\t\t\t// The interaction preflight guarantees one for every manual occurrence.\n\t\t\t\t\t\tif (interaction === undefined) return Exit.void;\n\n\t\t\t\t\t\tphase = \"confirmation\";\n\t\t\t\t\t\t// The person may start changing state as soon as they are asked.\n\t\t\t\t\t\tbodiesStarted = true;\n\t\t\t\t\t\tconst asked = yield* runPhase(\n\t\t\t\t\t\t\tinteraction.confirm({ occurrence }),\n\t\t\t\t\t\t\tunsettled,\n\t\t\t\t\t\t\t\"untimed\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst unanswered = unsuccessful(\"confirmation\", asked, stop);\n\t\t\t\t\t\tif (unanswered !== undefined) return end(unanswered);\n\t\t\t\t\t\tif (asked._tag !== \"Done\") return Exit.void;\n\t\t\t\t\t\tif (Exit.isFailure(asked.exit)) return fail(asked.exit.cause);\n\t\t\t\t\t\tif (asked.exit.value === \"declined\") {\n\t\t\t\t\t\t\tstop(\"failure\");\n\n\t\t\t\t\t\t\treturn end({ _tag: \"Declined\" });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (step.verify === undefined) {\n\t\t\t\t\t\t\treturn end({\n\t\t\t\t\t\t\t\t_tag: \"Completed\",\n\t\t\t\t\t\t\t\tperformer: \"manual\",\n\t\t\t\t\t\t\t\tconfirmation: \"asserted\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tphase = \"verification\";\n\t\t\t\t\t\t// Cancellation that arrived with the confirmation keeps the check from\n\t\t\t\t\t\t// starting.\n\t\t\t\t\t\tif (isCancelled()) {\n\t\t\t\t\t\t\treturn end({\n\t\t\t\t\t\t\t\t_tag: \"Interrupted\",\n\t\t\t\t\t\t\t\tphase,\n\t\t\t\t\t\t\t\treason: \"cancelled\",\n\t\t\t\t\t\t\t\tsettled: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst checked = yield* runPhase(step.verify, unsettled);\n\t\t\t\t\t\tconst unchecked = unsuccessful(\"verification\", checked, stop);\n\t\t\t\t\t\tif (unchecked !== undefined) return end(unchecked);\n\t\t\t\t\t\tif (checked._tag !== \"Done\") return Exit.void;\n\t\t\t\t\t\tif (Exit.isFailure(checked.exit)) return fail(checked.exit.cause);\n\n\t\t\t\t\t\treturn end({\n\t\t\t\t\t\t\t_tag: \"Completed\",\n\t\t\t\t\t\t\tperformer: \"manual\",\n\t\t\t\t\t\t\tconfirmation: \"verified\",\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tphase = \"apply\";\n\t\t\t\t\tbodiesStarted = true;\n\t\t\t\t\tconst applied = yield* runPhase(step.apply, unsettled);\n\t\t\t\t\tconst stopped = unsuccessful(\"apply\", applied, stop);\n\t\t\t\t\tif (stopped !== undefined) return end(stopped);\n\t\t\t\t\tif (applied._tag !== \"Done\") return Exit.void;\n\t\t\t\t\tif (Exit.isFailure(applied.exit)) return fail(applied.exit.cause);\n\n\t\t\t\t\treturn end({ _tag: \"Completed\", performer: \"automated\" });\n\t\t\t\t});\n\n\t\t\t// A finalizer that fails before the report is part of the execution: it fails an\n\t\t\t// occurrence that otherwise ended normally. An interrupted occurrence keeps its\n\t\t\t// outcome, and the failure is logged.\n\t\t\tconst onCleanupFailure = (cause: Cause.Cause<never>) =>\n\t\t\t\tEffect.suspend(() => {\n\t\t\t\t\tconst outcome = outcomes.get(occurrence.id);\n\t\t\t\t\tif (outcome?._tag === \"Interrupted\") {\n\t\t\t\t\t\treturn logCleanupFailure({ occurrence: occurrence.id })(cause);\n\t\t\t\t\t}\n\t\t\t\t\tstop(\"failure\");\n\t\t\t\t\toutcomes.set(occurrence.id, {\n\t\t\t\t\t\t_tag: \"Failed\",\n\t\t\t\t\t\tphase,\n\t\t\t\t\t\t...failureOf(\n\t\t\t\t\t\t\toutcome?._tag === \"Failed\"\n\t\t\t\t\t\t\t\t? Cause.combine(outcome.cause, cause)\n\t\t\t\t\t\t\t\t: cause,\n\t\t\t\t\t\t),\n\t\t\t\t\t});\n\n\t\t\t\t\treturn Effect.void;\n\t\t\t\t});\n\n\t\t\treturn inScope(retain, occurrence.id, use, onCleanupFailure);\n\t\t};\n\n\t\tconst runNode = (node: Node): Effect.Effect<void, never, R> => {\n\t\t\tswitch (node._tag) {\n\t\t\t\tcase \"Occurrence\":\n\t\t\t\t\treturn runOccurrence(node);\n\t\t\t\tcase \"Sequence\":\n\t\t\t\t\treturn Effect.forEach(node.children, runNode, { discard: true });\n\t\t\t}\n\n\t\t\t// Sibling failures stop admission through `halt`; they never interrupt branches.\n\t\t\treturn forEachBranch(node.branches, node.concurrency, runNode);\n\t\t};\n\n\t\tfor (const step of plan.steps) {\n\t\t\t// Migration steps are barriers: a step starts only after the previous one settled.\n\t\t\tif (halt.reason !== undefined) break;\n\t\t\tyield* runNode(step.node);\n\t\t}\n\n\t\tif (halt.reason === undefined)\n\t\t\treturn report(plan, \"execute\", \"completed\", outcomes, bodiesStarted);\n\t\tif (halt.reason === \"failure\") {\n\t\t\tconst result = report(plan, \"execute\", \"failed\", outcomes, bodiesStarted);\n\n\t\t\treturn yield* new ExecutionFailed({\n\t\t\t\tfailures: result.occurrences.filter((entry) => entry.outcome._tag === \"Failed\"),\n\t\t\t\tdeclined: result.occurrences.filter((entry) => entry.outcome._tag === \"Declined\"),\n\t\t\t\treport: result,\n\t\t\t});\n\t\t}\n\n\t\treturn yield* interrupted(plan, \"execute\", halt.reason, outcomes, bodiesStarted);\n\t});\n\nconst dryRun = <A extends Action.Any, E, R>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tresolved: Resolved<E, R>,\n\toptions: ControlOptions,\n\tsubscribe: Subscribe | undefined,\n\tretain: Retain,\n): Effect.Effect<Report<A, E>, ExecutionInterrupted<A, E>, R> =>\n\tEffect.gen(function* () {\n\t\tconst outcomes = new Map<string, Outcome<E>>();\n\t\tconst { halt, stop, runPhase } = yield* makeControl(options, subscribe);\n\t\tlet failedAt: string | undefined;\n\n\t\t/** Runs a prepare phase in the occurrence's scope and records what it predicts. */\n\t\tconst prepare = (id: string, handler: Internal<E, R>) => {\n\t\t\tconst end = (outcome: Outcome<E>) => {\n\t\t\t\toutcomes.set(id, outcome);\n\n\t\t\t\treturn exitOf(outcome);\n\t\t\t};\n\t\t\tconst use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst preparation = yield* runPhase(handler.prepare(scope), unsettled);\n\t\t\t\t\tconst stopped = unsuccessful(\"prepare\", preparation, stop);\n\t\t\t\t\tif (stopped !== undefined) return end(stopped);\n\t\t\t\t\tif (preparation._tag !== \"Done\") return Exit.void;\n\t\t\t\t\tif (Exit.isFailure(preparation.exit)) {\n\t\t\t\t\t\tfailedAt = id;\n\n\t\t\t\t\t\treturn end({\n\t\t\t\t\t\t\t_tag: \"PreparationFailed\",\n\t\t\t\t\t\t\t...failureOf(preparation.exit.cause),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\t// A dry run never applies: the prepared value is discarded.\n\t\t\t\t\tconst step = preparation.exit.value;\n\n\t\t\t\t\treturn end(\n\t\t\t\t\t\tstep._tag === \"Skip\"\n\t\t\t\t\t\t\t? { _tag: \"WouldSkip\", reason: step.reason }\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t_tag: \"WouldExecute\",\n\t\t\t\t\t\t\t\t\tevaluated: true,\n\t\t\t\t\t\t\t\t\tperformer: handler.performer,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\tconst onCleanupFailure = (cause: Cause.Cause<never>) =>\n\t\t\t\tEffect.suspend(() => {\n\t\t\t\t\tconst outcome = outcomes.get(id);\n\t\t\t\t\tif (outcome?._tag === \"Interrupted\") {\n\t\t\t\t\t\treturn logCleanupFailure({ occurrence: id })(cause);\n\t\t\t\t\t}\n\t\t\t\t\tfailedAt ??= id;\n\t\t\t\t\toutcomes.set(id, {\n\t\t\t\t\t\t_tag: \"PreparationFailed\",\n\t\t\t\t\t\t...failureOf(\n\t\t\t\t\t\t\toutcome?._tag === \"PreparationFailed\"\n\t\t\t\t\t\t\t\t? Cause.combine(outcome.cause, cause)\n\t\t\t\t\t\t\t\t: cause,\n\t\t\t\t\t\t),\n\t\t\t\t\t});\n\n\t\t\t\t\treturn Effect.void;\n\t\t\t\t});\n\n\t\t\treturn inScope(retain, id, use, onCleanupFailure);\n\t\t};\n\n\t\t/** Returns whether the node would or might change state. */\n\t\tconst visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tif (node._tag === \"Sequence\") {\n\t\t\t\t\tlet current = dirty;\n\t\t\t\t\tfor (const child of node.children) current = yield* visit(child, current);\n\n\t\t\t\t\treturn current;\n\t\t\t\t}\n\t\t\t\tif (node._tag === \"Parallel\") {\n\t\t\t\t\t// Branches are independent: each starts from the state before the group.\n\t\t\t\t\t// They are evaluated one at a time so the report is deterministic.\n\t\t\t\t\tlet changed = dirty;\n\t\t\t\t\tfor (const branch of node.branches)\n\t\t\t\t\t\tchanged = (yield* visit(branch, dirty)) || changed;\n\n\t\t\t\t\treturn changed;\n\t\t\t\t}\n\n\t\t\t\tconst handler = resolved.get(node.id);\n\t\t\t\tif (handler === undefined || halt.reason !== undefined) return dirty;\n\t\t\t\tif (failedAt !== undefined) {\n\t\t\t\t\toutcomes.set(node.id, {\n\t\t\t\t\t\t_tag: \"Undetermined\",\n\t\t\t\t\t\treason: `Execution would stop at the failed preparation of \"${failedAt}\".`,\n\t\t\t\t\t\tperformer: handler.performer,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (!handler.prepares) {\n\t\t\t\t\toutcomes.set(node.id, {\n\t\t\t\t\t\t_tag: \"WouldExecute\",\n\t\t\t\t\t\tevaluated: false,\n\t\t\t\t\t\tperformer: handler.performer,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (dirty) {\n\t\t\t\t\toutcomes.set(node.id, {\n\t\t\t\t\t\t_tag: \"Undetermined\",\n\t\t\t\t\t\treason: \"The prepare phase depends on earlier actions that a dry run does not apply.\",\n\t\t\t\t\t\tperformer: handler.performer,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tyield* prepare(node.id, handler);\n\n\t\t\t\treturn outcomes.get(node.id)?._tag !== \"WouldSkip\";\n\t\t\t});\n\n\t\t// Later migrations conservatively depend on every earlier migration.\n\t\tlet dirty = false;\n\t\tfor (const step of plan.steps) dirty = yield* visit(step.node, dirty);\n\n\t\tif (halt.reason !== undefined && halt.reason !== \"failure\") {\n\t\t\treturn yield* interrupted(plan, \"dry-run\", halt.reason, outcomes, false);\n\t\t}\n\n\t\treturn report(\n\t\t\tplan,\n\t\t\t\"dry-run\",\n\t\t\tfailedAt === undefined ? \"would-complete\" : \"would-fail\",\n\t\t\toutcomes,\n\t\t\tfalse,\n\t\t);\n\t});\n\nconst run = <\n\tA extends Action.Any,\n\tC extends Plan.Coverage,\n\tH extends Handler.Any,\n\tI extends Interaction.Any,\n>(\n\tplan: Plan.Plan<A, C>,\n\toptions: Options<H, I>,\n\tsubscribe: Subscribe | undefined,\n\tretain: Retain,\n): Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>>, Requirements<H, I>> => {\n\t// Handlers and interactions are covariant in their errors and services, and\n\t// `Errors<H, I>` and `Requirements<H, I>` collect them from each handler in `H` and\n\t// from `I`, so every handler and the interaction fit these shapes. From here on the\n\t// compiler checks both channels.\n\tconst handlers: ReadonlyArray<Internal<Errors<H, I>, Requirements<H, I>>> =\n\t\toptions.handlers ?? [];\n\tconst interaction: Interaction.Interaction<Errors<H, I>, Requirements<H, I>> | undefined =\n\t\toptions.interaction;\n\n\treturn Effect.gen(function* () {\n\t\tconst checked = coverage(plan, handlers);\n\t\tif (checked.issues.length > 0) {\n\t\t\treturn yield* new HandlerCoverageError({\n\t\t\t\tissues: checked.issues,\n\t\t\t\treport: report(\n\t\t\t\t\tplan,\n\t\t\t\t\toptions.dryRun === true ? \"dry-run\" : \"execute\",\n\t\t\t\t\t\"not-started\",\n\t\t\t\t\tnew Map<string, Outcome<never>>(),\n\t\t\t\t\tfalse,\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\n\t\tif (options.dryRun === true) {\n\t\t\treturn yield* dryRun(plan, checked.resolved, options, subscribe, retain);\n\t\t}\n\n\t\t// Nobody can answer for manual work, so the run must not start and stop halfway.\n\t\tconst manual = plan.occurrences.filter(\n\t\t\t(occurrence) => checked.resolved.get(occurrence.id)?.performer === \"manual\",\n\t\t);\n\t\tif (manual.length > 0 && interaction === undefined) {\n\t\t\treturn yield* new InteractionUnavailable({\n\t\t\t\toccurrences: manual,\n\t\t\t\treport: report(\n\t\t\t\t\tplan,\n\t\t\t\t\t\"execute\",\n\t\t\t\t\t\"not-started\",\n\t\t\t\t\tnew Map<string, Outcome<never>>(),\n\t\t\t\t\tfalse,\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\n\t\treturn yield* execute(plan, checked.resolved, interaction, options, subscribe, retain);\n\t});\n};\n\n/**\n * Runs a plan as an Effect. Coverage, and the interaction that manual handlers need,\n * are checked before any handler phase runs. Steps\n * are sequential barriers; parallel groups run their branches concurrently. On failure,\n * no new action starts, and actions already running settle before the effect fails\n * with the partial report.\n *\n * Each occurrence has its own scope, shared by its phases and closed when it ends. An\n * interrupted Promise that has not settled keeps its occurrence's scope open until it\n * settles, after the effect has ended. Services that the caller provides stay the\n * caller's to release.\n *\n * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the\n * signal passed to Promise callbacks. The effect then ends as interrupted, without a\n * report.\n *\n * @since @next\n */\nexport const effect = <\n\tA extends Action.Any,\n\tC extends Plan.Coverage,\n\tH extends Handler.Any = never,\n\tI extends Interaction.Any = never,\n>(\n\tplan: Plan.Plan<A, C>,\n\toptions: Options<H, I> & CoverageCheck<A, H, C>,\n): Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>>, Requirements<H, I>> =>\n\trun(plan, options, undefined, () => {});\n\ntype ServicesOption<R, LE> = [R] extends [never]\n\t? {\n\t\t\t/** Handlers and interactions without Effect services need none. */\n\t\t\treadonly services?: Context.Context<never> | Layer.Layer<never, LE>;\n\t\t}\n\t: {\n\t\t\t/** Supplies the Effect services of the handlers and the interaction. */\n\t\t\treadonly services: Context.Context<R> | Layer.Layer<R, LE>;\n\t\t};\n\n/** @since @next */\nexport type PromiseOptions<H extends Handler.Any, I extends Interaction.Any = never> = Options<\n\tH,\n\tI\n> & {\n\t/**\n\t * Explicit cancellation. Aborting stops admission, interrupts running actions and\n\t * pending confirmations, and rejects with `ExecutionInterrupted` and the partial\n\t * report.\n\t */\n\treadonly signal?: AbortSignal;\n};\n\n/**\n * Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,\n * `InteractionUnavailable`, `ExecutionFailed`, or `ExecutionInterrupted`, each carrying\n * the partial report.\n * Building a supplied services layer can also reject with the layer's own error,\n * without a report.\n *\n * A services layer is built for this run. A services context stays owned by the\n * caller. A Promise callback that ignores its signal can keep running after\n * cancellation or a timeout, beyond `settleTimeout`; the report marks it as possibly\n * still running. Its occurrence's scope and the run's services layer then stay open\n * until it settles, possibly forever, and close in that order. A cleanup failure after\n * the Promise resolved is logged through Effect.\n *\n * @since @next\n */\nexport const runPromise = <\n\tA extends Action.Any,\n\tC extends Plan.Coverage,\n\tH extends Handler.Any = never,\n\tI extends Interaction.Any = never,\n\tLE = never,\n>(\n\tplan: Plan.Plan<A, C>,\n\toptions: PromiseOptions<H, I> & ServicesOption<Requirements<H, I>, LE> & CoverageCheck<A, H, C>,\n): Promise<Report<A, Errors<H, I>>> => {\n\tconst { signal } = options;\n\tconst notStarted = () =>\n\t\tnew ExecutionInterrupted({\n\t\t\treason: \"cancelled\",\n\t\t\treport: report(\n\t\t\t\tplan,\n\t\t\t\toptions.dryRun === true ? \"dry-run\" : \"execute\",\n\t\t\t\t\"interrupted\",\n\t\t\t\tnew Map<string, Outcome<Errors<H, I>>>(),\n\t\t\t\tfalse,\n\t\t\t),\n\t\t});\n\tif (signal?.aborted === true) return Promise.reject(notStarted());\n\n\t// Until the run installs its own cancellation, an abort stops building the services\n\t// layer. Afterwards the run stops admission and reports partial progress.\n\tconst abortedBeforeRun = Deferred.makeUnsafe<void>();\n\tlet cancelRun: (() => void) | undefined;\n\tconst onAbort = () => {\n\t\tif (cancelRun === undefined) Deferred.doneUnsafe(abortedBeforeRun, Effect.void);\n\t\telse cancelRun();\n\t};\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\tconst subscribe: Subscribe | undefined =\n\t\tsignal === undefined\n\t\t\t? undefined\n\t\t\t: (cancel) => {\n\t\t\t\t\tcancelRun = cancel;\n\t\t\t\t\tif (signal.aborted) cancel();\n\t\t\t\t};\n\tconst retained: Array<Fiber.Fiber<void>> = [];\n\tconst program = run(plan, options, subscribe, (fiber) => retained.push(fiber));\n\tconst services: Context.Context<never> | Layer.Layer<never, LE> | undefined = options.services;\n\tconst provided =\n\t\tservices === undefined\n\t\t\t? program\n\t\t\t: Context.isContext(services)\n\t\t\t\t? Effect.provideContext(program, services)\n\t\t\t\t: // runPromise is the entry point: the caller's layer is built for this one run,\n\t\t\t\t\t// in a scope that outlives the run while retained occurrence scopes are open.\n\t\t\t\t\tEffect.uninterruptibleMask((restore) =>\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tconst scope = yield* Scope.make();\n\t\t\t\t\t\t\tconst built = yield* Effect.exit(\n\t\t\t\t\t\t\t\trestore(Layer.buildWithScope(services, scope)),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (Exit.isFailure(built)) {\n\t\t\t\t\t\t\t\tyield* Scope.close(scope, built);\n\n\t\t\t\t\t\t\t\treturn yield* built;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst exit = yield* Effect.exit(\n\t\t\t\t\t\t\t\trestore(Effect.provideContext(program, built.value)),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (retained.length === 0) yield* Scope.close(scope, exit);\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tyield* Effect.forkDetach(\n\t\t\t\t\t\t\t\t\tFiber.awaitAll(retained).pipe(\n\t\t\t\t\t\t\t\t\t\tEffect.andThen(Scope.close(scope, exit)),\n\t\t\t\t\t\t\t\t\t\tEffect.catchCause(\n\t\t\t\t\t\t\t\t\t\t\tlogCleanupFailure({ owner: \"services layer\" }),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn yield* exit;\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\tconst cancellable =\n\t\tsignal === undefined\n\t\t\t? provided\n\t\t\t: Effect.raceFirst(\n\t\t\t\t\tprovided,\n\t\t\t\t\tEffect.andThen(Deferred.await(abortedBeforeRun), Effect.fail(notStarted())),\n\t\t\t\t);\n\n\treturn Effect.runPromiseExit(\n\t\t// `ServicesOption` requires services that cover every requirement. A layer that\n\t\t// fails to build rejects with its own error.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion, effecttsgo/unsafe-effect-type-assertion\n\t\tcancellable as Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>> | LE>,\n\t)\n\t\t.finally(() => signal?.removeEventListener(\"abort\", onAbort))\n\t\t.then((exit) => {\n\t\t\tif (Exit.isSuccess(exit)) return exit.value;\n\n\t\t\tthrow Cause.squash(exit.cause);\n\t\t});\n};\n","import { Data, Effect, Predicate } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type { Occurrence } from \"../../foundation/plan.ts\";\nimport type * as Callback from \"./promise-callback.ts\";\nimport { adaptPromise } from \"./promise-callback.ts\";\n\n/**\n * What a person says about manual work. There is no other answer: free-form input never\n * reaches a report.\n *\n * @since @next\n */\nexport type Answer = \"confirmed\" | \"declined\";\n\n/**\n * A request to confirm manual work. The occurrence carries the action, its description,\n * and the migration instruction that declared it, which is what to show the person.\n *\n * @since @next\n */\nexport type Request<A extends Action.Any = Action.Any> = {\n\treadonly occurrence: Occurrence<A>;\n};\n\n/**\n * A Promise interaction rejected with a value that none of its declared error guards\n * recognized (`rejected`), or an interaction answered with something other than\n * `\"confirmed\"` or `\"declined\"` (`invalid-answer`). An invalid answer is never kept: it\n * may be text that the person typed.\n *\n * @since @next\n */\nexport class UnexpectedInteractionError extends Data.TaggedError(\"UnexpectedInteractionError\")<{\n\treadonly occurrenceId: string;\n\treadonly reason: \"rejected\" | \"invalid-answer\";\n\t/** The rejection. Always `undefined` for an invalid answer. */\n\treadonly cause: unknown;\n}> {\n\toverride get message() {\n\t\treturn this.reason === \"rejected\"\n\t\t\t? `The interaction failed unexpectedly while confirming \"${this.occurrenceId}\"`\n\t\t\t: `The interaction answered neither \"confirmed\" nor \"declined\" for \"${this.occurrenceId}\"`;\n\t}\n}\n\nconst isAnswer = (value: unknown): value is Answer => value === \"confirmed\" || value === \"declined\";\n\nconst checkAnswer = (request: Request) => (answer: unknown) =>\n\tisAnswer(answer)\n\t\t? Effect.succeed(answer)\n\t\t: Effect.fail(\n\t\t\t\tnew UnexpectedInteractionError({\n\t\t\t\t\toccurrenceId: request.occurrence.id,\n\t\t\t\t\treason: \"invalid-answer\",\n\t\t\t\t\tcause: undefined,\n\t\t\t\t}),\n\t\t\t);\n\nconst TypeId = \"~deltafold/Interaction\";\n\n/**\n * Asks a person to confirm the manual work of a plan. The executor has no terminal or\n * user interface of its own: the consumer running the plan supplies one of these.\n *\n * Parallel branches can ask at the same time. An interaction that owns one terminal\n * serializes its own prompts. A failure or a decline elsewhere stops new actions but\n * does not withdraw a request that was already made; only cancellation does.\n *\n * @since @next\n */\nexport type Interaction<out E = never, out R = never> = {\n\treadonly [TypeId]: typeof TypeId;\n\treadonly confirm: (request: Request) => Effect.Effect<Answer, E, R>;\n};\n\n/**\n * Any interaction.\n *\n * @since @next\n */\nexport type Any = Interaction<any, any>;\n\n/**\n * The errors of an interaction.\n *\n * @since @next\n */\nexport type Error<I> = I extends Interaction<infer E, any> ? E : never;\n\n/**\n * The Effect services of an interaction.\n *\n * @since @next\n */\nexport type Services<I> = I extends Interaction<any, infer R> ? R : never;\n\n/** @since @next */\nexport const isInteraction = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId);\n\n/** @since @next */\nexport type PromiseOptions<\n\tS extends Callback.ServiceMap,\n\tG extends ReadonlyArray<Callback.ErrorGuard>,\n> = {\n\t/** Effect services resolved for the callback and added to the run's requirements. */\n\treadonly services?: S;\n\t/** Guards for rejections that keep their own type. */\n\treadonly errors?: G;\n};\n\n/**\n * Confirms manual work with a Promise callback. It receives `{ signal, services }`: an\n * `AbortSignal` that aborts when the run is cancelled, so it can stop asking, and the\n * declared services.\n *\n * @example\n * ```ts\n * // The migration's instruction for this action, or the action's description.\n * const textOf = ({ action, instruction }: Plan.Occurrence) =>\n * \tinstruction?.content\n * \t\t.map((part) => (part._tag === \"Text\" ? part.text : part.action.description))\n * \t\t.join(\"\") ?? action.description;\n *\n * const interaction = Interaction.promise(async ({ occurrence }, { signal }) =>\n * \t(await ask(textOf(occurrence), { signal })) ? \"confirmed\" : \"declined\",\n * );\n * ```\n *\n * @since @next\n */\nexport const promise = <\n\tconst S extends Callback.ServiceMap = Callback.NoServices,\n\tconst G extends ReadonlyArray<Callback.ErrorGuard> = [],\n>(\n\tconfirm: (request: Request, context: Callback.PromiseContext<S>) => PromiseLike<Answer>,\n\toptions?: PromiseOptions<S, G>,\n): Interaction<\n\tCallback.GuardedError<G[number]> | UnexpectedInteractionError,\n\tCallback.ServiceIds<S>\n> => {\n\tconst adapt = adaptPromise(options ?? {});\n\n\treturn {\n\t\t[TypeId]: TypeId,\n\t\tconfirm: (request) =>\n\t\t\tadapt<unknown, UnexpectedInteractionError>(\n\t\t\t\t(context) => confirm(request, context),\n\t\t\t\t(cause) =>\n\t\t\t\t\tnew UnexpectedInteractionError({\n\t\t\t\t\t\toccurrenceId: request.occurrence.id,\n\t\t\t\t\t\treason: \"rejected\",\n\t\t\t\t\t\tcause,\n\t\t\t\t\t}),\n\t\t\t).pipe(Effect.flatMap(checkAnswer(request))),\n\t};\n};\n\n/**\n * Confirms manual work with an Effect, which keeps its own errors and services and\n * stops through Effect interruption when the run is cancelled.\n *\n * @since @next\n */\nexport const effect = <E = never, R = never>(\n\tconfirm: (request: Request) => Effect.Effect<Answer, E, R>,\n): Interaction<E | UnexpectedInteractionError, R> => ({\n\t[TypeId]: TypeId,\n\tconfirm: (request) =>\n\t\tEffect.flatMap(\n\t\t\tEffect.suspend(() => confirm(request)),\n\t\t\tcheckAnswer(request),\n\t\t),\n});\n","import { Data } from \"effect\";\n\nimport type { RequestDirection } from \"../../foundation/plan.ts\";\nimport type { Issue } from \"./validate.ts\";\n\n/**\n * A candidate route, summarized for diagnostics and explicit selection.\n *\n * @since @next\n */\nexport type RouteSummary = {\n\t/** Pass this as the `route` option to select the route. */\n\treadonly id: string;\n\treadonly migrations: ReadonlyArray<string>;\n\treadonly shortcuts: ReadonlyArray<string>;\n\t/** Optimized action count, or `undefined` when the route failed to optimize. */\n\treadonly actions: number | undefined;\n\treadonly cost: number;\n\t/** Why the route cannot be planned, if it cannot. */\n\treadonly failure: string | undefined;\n};\n\n/**\n * An ancestry hop with no declared route in the requested direction.\n *\n * @since @next\n */\nexport type Blocker = {\n\treadonly from: string;\n\treadonly to: string;\n\treadonly reason: string;\n};\n\n/**\n * The history's declarations are invalid. Resolution needs a valid history.\n *\n * @since @next\n */\nexport class InvalidHistory extends Data.TaggedError(\"InvalidHistory\")<{\n\treadonly issues: ReadonlyArray<Issue>;\n}> {\n\toverride get message() {\n\t\treturn `The history has ${this.issues.length} declaration issue(s): ${this.issues\n\t\t\t.map((issue) => issue.message)\n\t\t\t.join(\" \")}`;\n\t}\n}\n\n/** @since @next */\nexport class UnknownVersion extends Data.TaggedError(\"UnknownVersion\")<{\n\treadonly version: string;\n\treadonly known: ReadonlyArray<string>;\n}> {\n\toverride get message() {\n\t\treturn `Version \"${this.version}\" is not registered in the history.`;\n\t}\n}\n\n/**\n * No declared route connects the versions. This never means that no work is needed:\n * declare `Migration.noop` for a supported zero-work transition.\n *\n * @since @next\n */\nexport class UnsupportedRoute extends Data.TaggedError(\"UnsupportedRoute\")<{\n\treadonly from: string;\n\treadonly to: string;\n\treadonly direction: RequestDirection;\n\t/** Versions that are reachable from `from` in the requested direction. */\n\treadonly reachable: ReadonlyArray<string>;\n\t/** Reachable versions closest to `to` along release ancestry. Ties are all listed. */\n\treadonly closest: ReadonlyArray<string>;\n\treadonly blockers: ReadonlyArray<Blocker>;\n}> {\n\toverride get message() {\n\t\tconst closest =\n\t\t\tthis.closest.length === 0 ? \"\" : ` Closest reachable: ${this.closest.join(\", \")}.`;\n\n\t\treturn `No declared ${this.direction} route from \"${this.from}\" to \"${this.to}\".${closest}`;\n\t}\n}\n\n/**\n * Several routes connect the versions and no selection or policy chose one.\n *\n * @since @next\n */\nexport class AmbiguousRoute extends Data.TaggedError(\"AmbiguousRoute\")<{\n\treadonly from: string;\n\treadonly to: string;\n\treadonly candidates: ReadonlyArray<RouteSummary>;\n\treadonly policy: string | undefined;\n}> {\n\toverride get message() {\n\t\tconst ids = this.candidates.map((candidate) => `\"${candidate.id}\"`).join(\", \");\n\t\tconst reason =\n\t\t\tthis.policy === undefined ? \"\" : ` after applying the \"${this.policy}\" policy`;\n\n\t\treturn `${this.candidates.length} routes connect \"${this.from}\" and \"${this.to}\"${reason}: ${ids}. Select one with the \\`route\\` option, or choose a route policy.`;\n\t}\n}\n\n/**\n * The `route` option names no candidate route.\n *\n * @since @next\n */\nexport class UnknownRoute extends Data.TaggedError(\"UnknownRoute\")<{\n\treadonly route: string;\n\treadonly candidates: ReadonlyArray<RouteSummary>;\n}> {\n\toverride get message() {\n\t\treturn `No candidate route has the identifier \"${this.route}\". Candidates: ${this.candidates\n\t\t\t.map((candidate) => `\"${candidate.id}\"`)\n\t\t\t.join(\", \")}.`;\n\t}\n}\n\n/**\n * Rules rewrite a sequence back into itself.\n *\n * @since @next\n */\nexport class RewriteCycle extends Data.TaggedError(\"RewriteCycle\")<{\n\treadonly route: string;\n\treadonly rules: ReadonlyArray<string>;\n\treadonly actions: string;\n}> {\n\toverride get message() {\n\t\treturn `Rules ${this.rules.map((rule) => `\"${rule}\"`).join(\", \")} rewrite a sequence back into itself on route \"${this.route}\".`;\n\t}\n}\n\n/**\n * Rules can produce different results depending on which applies first.\n *\n * @since @next\n */\nexport class ConflictingRewrites extends Data.TaggedError(\"ConflictingRewrites\")<{\n\treadonly route: string;\n\treadonly outcomes: ReadonlyArray<{\n\t\treadonly actions: string;\n\t\treadonly rules: ReadonlyArray<string>;\n\t}>;\n}> {\n\toverride get message() {\n\t\treturn `Rules produce ${this.outcomes.length} different results on route \"${this.route}\", depending on the order they apply in.`;\n\t}\n}\n\n/**\n * Optimization explored too many states or chained too many rule applications, for\n * example because a rule keeps growing the sequence.\n *\n * @since @next\n */\nexport class RewriteLimitExceeded extends Data.TaggedError(\"RewriteLimitExceeded\")<{\n\treadonly route: string;\n\treadonly limit: \"states\" | \"depth\";\n\treadonly value: number;\n}> {\n\toverride get message() {\n\t\treturn this.limit === \"states\"\n\t\t\t? `Optimizing route \"${this.route}\" explored more than ${this.value} states.`\n\t\t\t: `Optimizing route \"${this.route}\" chained more than ${this.value} rule applications.`;\n\t}\n}\n\n/**\n * More candidate routes exist than the resolver enumerates.\n *\n * @since @next\n */\nexport class TooManyRoutes extends Data.TaggedError(\"TooManyRoutes\")<{\n\treadonly from: string;\n\treadonly to: string;\n\treadonly limit: number;\n}> {\n\toverride get message() {\n\t\treturn `More than ${this.limit} routes connect \"${this.from}\" and \"${this.to}\".`;\n\t}\n}\n\n/** @since @next */\nexport type RewriteError = RewriteCycle | ConflictingRewrites | RewriteLimitExceeded;\n\n/**\n * Why a plan could not be resolved. `UnsupportedRoute` lists the reachable versions, the\n * closest ones by release ancestry, and blockers. `AmbiguousRoute` lists the candidate\n * routes: pass one as `route`, or choose a `policy`.\n *\n * @since @next\n */\nexport type ResolveError =\n\t| InvalidHistory\n\t| UnknownVersion\n\t| UnsupportedRoute\n\t| AmbiguousRoute\n\t| UnknownRoute\n\t| TooManyRoutes\n\t| RewriteError;\n","import type * as Action from \"../../foundation/action.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { GuideItem, Occurrence } from \"../../foundation/plan.ts\";\n\n/** The declared occurrence a retained occurrence is rendered at. */\nconst anchorOf = (occurrence: Occurrence): Occurrence => {\n\tif (occurrence.origin._tag === \"Declared\") return occurrence;\n\n\tconst first = occurrence.origin.replaces[0];\n\n\treturn first === undefined ? occurrence : anchorOf(first);\n};\n\n/**\n * Resolves a migration's content against the occurrences that survived optimization.\n * Removed occurrences disappear with their instruction blocks. Replacements render at\n * the position of the first occurrence they replaced, using their own instruction or\n * description. Unassociated prose stays.\n */\nexport const resolveGuide = (\n\tcontent: Migration.Content,\n\tretained: ReadonlyArray<Occurrence>,\n\tdeclaredId: (action: Action.Any) => string,\n): ReadonlyArray<GuideItem> => {\n\tconst byAnchor = new Map<string, Array<Occurrence>>();\n\tfor (const occurrence of retained) {\n\t\tconst anchor = anchorOf(occurrence).id;\n\t\tconst list = byAnchor.get(anchor) ?? [];\n\t\tlist.push(occurrence);\n\t\tbyAnchor.set(anchor, list);\n\t}\n\n\tconst renderStep = (step: Action.Step): ReadonlyArray<GuideItem> => {\n\t\tif (step._tag === \"Action\" || step._tag === \"Instruction\") {\n\t\t\tconst action = step._tag === \"Action\" ? step : step.action;\n\n\t\t\treturn (byAnchor.get(declaredId(action)) ?? []).map((occurrence) => ({\n\t\t\t\t_tag: \"Occurrence\",\n\t\t\t\toccurrence,\n\t\t\t}));\n\t\t}\n\n\t\tconst children = (step._tag === \"Sequence\" ? step.children : step.branches)\n\t\t\t.map((child) => renderStep(child))\n\t\t\t.filter((items) => items.length > 0);\n\t\tif (children.length === 0) return [];\n\n\t\treturn [{ _tag: \"Group\", kind: step._tag, children }];\n\t};\n\n\treturn content.flatMap((fragment): ReadonlyArray<GuideItem> => {\n\t\tif (fragment._tag === \"Text\" || fragment._tag === \"ActionRef\") return [fragment];\n\n\t\treturn renderStep(fragment);\n\t});\n};\n","import type * as Action from \"../../foundation/action.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { Direction, Occurrence } from \"../../foundation/plan.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\n\n// Author identifiers may contain any character. Each format escapes its own separators,\n// and the backslash itself, so distinct components never produce the same identifier.\nconst escape = (value: string, separators: RegExp) => value.replace(separators, \"\\\\$&\");\n\nconst occurrencePart = (id: string) => escape(id, /[\\\\/()+]/g);\n\nconst routePart = (id: string) => escape(id, /[\\\\>[\\]]/g);\n\n/** `<migration>/<action>` forward, `<migration>/revert/<action>` in reverse. */\nexport const declaredOccurrenceId = (\n\tmigration: Migration.Any,\n\tdirection: Direction,\n\taction: Action.Any,\n): string =>\n\tdirection === \"forward\"\n\t\t? `${occurrencePart(migration.id)}/${occurrencePart(action.id)}`\n\t\t: `${occurrencePart(migration.id)}/revert/${occurrencePart(action.id)}`;\n\n/**\n * `<rule>(<replaced>+<replaced>)/<action>`. Replaced identifiers are complete occurrence\n * identifiers, so they nest without further escaping.\n */\nexport const replacementOccurrenceId = (\n\trule: Rule.Any,\n\treplaced: ReadonlyArray<Occurrence>,\n\taction: Action.Any,\n): string =>\n\t`${occurrencePart(rule.id)}(${replaced.map((occurrence) => occurrence.id).join(\"+\")})/${occurrencePart(action.id)}`;\n\n/** The first version of a route identifier. */\nexport const routeStart = (version: string): string => routePart(version);\n\n/** A migration hop: `>` and the target version. */\nexport const routeHop = (to: string): string => `>${routePart(to)}`;\n\n/** A shortcut hop: `>[shortcut]>` and the target version. */\nexport const routeShortcut = (shortcut: string, to: string): string =>\n\t`>[${routePart(shortcut)}]>${routePart(to)}`;\n","import { Array as Arr, Order } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { Occurrence } from \"../../foundation/plan.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\nimport { replacementOccurrenceId } from \"./identifiers.ts\";\n\n/**\n * A top-level element of a route's sequential spine, or of one parallel branch. `step`\n * is the index of the plan step that owns the element.\n */\nexport type Item =\n\t| { readonly _tag: \"Occ\"; readonly occurrence: Occurrence; readonly step: number }\n\t| {\n\t\t\treadonly _tag: \"Par\";\n\t\t\treadonly branches: ReadonlyArray<ReadonlyArray<Item>>;\n\t\t\treadonly concurrency: Action.Concurrency;\n\t\t\treadonly step: number;\n\t }\n\t/** A text-only migration: prose instructions that rules must not match around. */\n\t| { readonly _tag: \"Barrier\"; readonly step: number };\n\nexport type Application = {\n\treadonly rule: Rule.Any;\n\treadonly removed: ReadonlyArray<Occurrence>;\n\treadonly produced: ReadonlyArray<Occurrence>;\n};\n\nexport type Outcome = {\n\treadonly items: ReadonlyArray<Item>;\n\treadonly trace: ReadonlyArray<Application>;\n};\n\nexport type Failure =\n\t| {\n\t\t\treadonly _tag: \"RewriteCycle\";\n\t\t\t/** Rules applied around the cycle, in order. */\n\t\t\treadonly rules: ReadonlyArray<string>;\n\t\t\t/** The action sequence that repeats. */\n\t\t\treadonly actions: string;\n\t }\n\t| {\n\t\t\treadonly _tag: \"ConflictingRewrites\";\n\t\t\treadonly outcomes: ReadonlyArray<{\n\t\t\t\treadonly actions: string;\n\t\t\t\treadonly rules: ReadonlyArray<string>;\n\t\t\t}>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"RewriteLimitExceeded\";\n\t\t\treadonly limit: \"states\" | \"depth\";\n\t\t\treadonly value: number;\n\t };\n\nclass RewriteFailure {\n\treadonly failure: Failure;\n\n\tconstructor(failure: Failure) {\n\t\tthis.failure = failure;\n\t}\n}\n\n/** The largest number of distinct states explored while normalizing one sequence. */\nexport const stateLimit = 10_000;\n\n/** The largest number of rule applications in one chain of rewrites. */\nexport const depthLimit = 256;\n\nconst occurrencesOf = (items: ReadonlyArray<Item>): ReadonlyArray<Occurrence> =>\n\titems.flatMap((item) => {\n\t\tif (item._tag === \"Occ\") return [item.occurrence];\n\t\tif (item._tag === \"Par\") return item.branches.flatMap(occurrencesOf);\n\n\t\treturn [];\n\t});\n\nexport { occurrencesOf };\n\nconst groupKey = (branches: ReadonlyArray<string>) =>\n\t`{${Arr.sort(\n\t\tbranches.map((branch) => `[${branch}]`),\n\t\tOrder.String,\n\t).join(\"|\")}}`;\n\n/** A key that identifies a sequence by its action structure. Branch order is ignored. */\nexport const keyOf = (items: ReadonlyArray<Item>): string =>\n\titems\n\t\t.map((item) => {\n\t\t\tif (item._tag === \"Occ\") return JSON.stringify(item.occurrence.action.id);\n\t\t\tif (item._tag === \"Barrier\") return \"#\";\n\n\t\t\treturn groupKey(item.branches.map(keyOf));\n\t\t})\n\t\t.join(\",\");\n\n/** A key that identifies declared steps by their action structure. Branch order is ignored. */\nexport const stepKey = (steps: ReadonlyArray<Action.Step>): string =>\n\tsteps\n\t\t.map((step) => {\n\t\t\tswitch (step._tag) {\n\t\t\t\tcase \"Action\":\n\t\t\t\t\treturn JSON.stringify(step.id);\n\t\t\t\tcase \"Instruction\":\n\t\t\t\t\treturn JSON.stringify(step.action.id);\n\t\t\t\tcase \"Sequence\":\n\t\t\t\t\treturn stepKey(step.children);\n\t\t\t}\n\t\t\tconst branches = step.branches.map((branch) => stepKey([branch]));\n\t\t\tif (branches.length === 1) return branches[0];\n\n\t\t\treturn groupKey(branches);\n\t\t})\n\t\t.filter((key) => key !== \"\")\n\t\t.join(\",\");\n\nexport type MakeOccurrence = (\n\taction: Action.Any,\n\tinstruction: Migration.Instruction | undefined,\n) => Occurrence;\n\n/** Converts declared steps to items. Sequences flatten; single-branch groups flatten. */\nexport const itemsOf = (\n\tsteps: ReadonlyArray<Action.Step>,\n\tmake: MakeOccurrence,\n\tstep: number,\n): ReadonlyArray<Item> =>\n\tsteps.flatMap((declared): ReadonlyArray<Item> => {\n\t\tswitch (declared._tag) {\n\t\t\tcase \"Action\":\n\t\t\t\treturn [{ _tag: \"Occ\", occurrence: make(declared, undefined), step }];\n\t\t\tcase \"Instruction\":\n\t\t\t\treturn [{ _tag: \"Occ\", occurrence: make(declared.action, declared), step }];\n\t\t\tcase \"Sequence\":\n\t\t\t\treturn itemsOf(declared.children, make, step);\n\t\t}\n\n\t\treturn parallelOf(\n\t\t\tdeclared.branches.map((branch) => itemsOf([branch], make, step)),\n\t\t\tdeclared.concurrency,\n\t\t\tstep,\n\t\t);\n\t});\n\n/** Drops empty branches and flattens a group that has a single branch left. */\nconst parallelOf = (\n\tbranches: ReadonlyArray<ReadonlyArray<Item>>,\n\tconcurrency: Action.Concurrency,\n\tstep: number,\n): ReadonlyArray<Item> => {\n\tconst nonEmpty = branches.filter((branch) => branch.length > 0);\n\tif (nonEmpty.length === 0) return [];\n\tif (nonEmpty.length === 1) return nonEmpty[0] ?? [];\n\n\treturn [{ _tag: \"Par\", branches: nonEmpty, concurrency, step }];\n};\n\nconst matchesAt = (\n\tpattern: ReadonlyArray<Rule.Pattern>,\n\titems: ReadonlyArray<Item>,\n\tposition: number,\n): boolean =>\n\tpattern.every((expected, offset) => {\n\t\tconst item = items[position + offset];\n\t\tif (item === undefined) return false;\n\t\tif (expected._tag === \"Action\") {\n\t\t\treturn item._tag === \"Occ\" && item.occurrence.action.id === expected.id;\n\t\t}\n\n\t\treturn item._tag === \"Par\" && keyOf([item]) === stepKey([expected]);\n\t});\n\ntype Transition = {\n\treadonly next: ReadonlyArray<Item>;\n\treadonly application: Application;\n};\n\n/** Replaces the match of a rule at a position with occurrences that record their provenance. */\nconst replace = (rule: Rule.Any, items: ReadonlyArray<Item>, position: number): Transition => {\n\tconst matched = items.slice(position, position + rule.match.length);\n\tconst removed = occurrencesOf(matched);\n\tconst first = removed[0];\n\t// A non-empty match always covers at least one occurrence.\n\tif (first === undefined) throw new Error(`Rule \"${rule.id}\" matched no occurrences`);\n\tconst step = matched[0]?.step ?? 0;\n\tconst produced: Array<Occurrence> = [];\n\tconst make: MakeOccurrence = (action, instruction) => {\n\t\tconst occurrence: Occurrence = {\n\t\t\t_tag: \"Occurrence\",\n\t\t\tid: replacementOccurrenceId(rule, removed, action),\n\t\t\taction,\n\t\t\tmigration: first.migration,\n\t\t\tdirection: first.direction,\n\t\t\tinstruction,\n\t\t\torigin: { _tag: \"Replacement\", rule, replaces: removed },\n\t\t};\n\t\tproduced.push(occurrence);\n\n\t\treturn occurrence;\n\t};\n\tconst next = [\n\t\t...items.slice(0, position),\n\t\t...itemsOf(rule.replacement, make, step),\n\t\t...items.slice(position + rule.match.length),\n\t];\n\n\treturn { next, application: { rule, removed, produced } };\n};\n\nconst makeNormalizer = (rules: ReadonlyArray<Rule.Any>) => {\n\tconst ordered = Arr.sort(\n\t\trules,\n\t\tOrder.mapInput(Order.String, (rule: Rule.Any) => rule.id),\n\t);\n\n\t/**\n\t * Every single rule application available in a sequence: at any position of the\n\t * sequence itself, or inside any branch of its groups. Branch-local and whole-group\n\t * rewrites compete as transitions from the same state.\n\t */\n\tconst transitions = (items: ReadonlyArray<Item>): ReadonlyArray<Transition> => {\n\t\tconst found: Array<Transition> = [];\n\t\tfor (let position = 0; position < items.length; position++) {\n\t\t\tfor (const rule of ordered) {\n\t\t\t\tif (rule.match.length > 0 && matchesAt(rule.match, items, position)) {\n\t\t\t\t\tfound.push(replace(rule, items, position));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst item = items[position];\n\t\t\tif (item?._tag !== \"Par\") continue;\n\t\t\tfor (const [index, branch] of item.branches.entries()) {\n\t\t\t\tfor (const inner of transitions(branch)) {\n\t\t\t\t\tconst branches = item.branches.map((other, otherIndex) =>\n\t\t\t\t\t\totherIndex === index ? inner.next : other,\n\t\t\t\t\t);\n\t\t\t\t\tfound.push({\n\t\t\t\t\t\tnext: [\n\t\t\t\t\t\t\t...items.slice(0, position),\n\t\t\t\t\t\t\t...parallelOf(branches, item.concurrency, item.step),\n\t\t\t\t\t\t\t...items.slice(position + 1),\n\t\t\t\t\t\t],\n\t\t\t\t\t\tapplication: inner.application,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn found;\n\t};\n\n\t/**\n\t * Explores every rewrite order of the whole sequence, nested groups included, under\n\t * one shared state and depth budget.\n\t */\n\tconst normalize = (input: ReadonlyArray<Item>): Outcome => {\n\t\tconst seen = new Set<string>();\n\t\tconst onPath = new Map<string, number>();\n\t\tconst normals = new Map<string, Outcome>();\n\n\t\tconst visit = (items: ReadonlyArray<Item>, trace: ReadonlyArray<Application>): void => {\n\t\t\tconst key = keyOf(items);\n\t\t\tconst entered = onPath.get(key);\n\t\t\tif (entered !== undefined) {\n\t\t\t\tthrow new RewriteFailure({\n\t\t\t\t\t_tag: \"RewriteCycle\",\n\t\t\t\t\trules: trace.slice(entered).map((application) => application.rule.id),\n\t\t\t\t\tactions: key,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (seen.has(key)) return;\n\n\t\t\tseen.add(key);\n\t\t\tif (seen.size > stateLimit) {\n\t\t\t\tthrow new RewriteFailure({\n\t\t\t\t\t_tag: \"RewriteLimitExceeded\",\n\t\t\t\t\tlimit: \"states\",\n\t\t\t\t\tvalue: stateLimit,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (trace.length > depthLimit) {\n\t\t\t\tthrow new RewriteFailure({\n\t\t\t\t\t_tag: \"RewriteLimitExceeded\",\n\t\t\t\t\tlimit: \"depth\",\n\t\t\t\t\tvalue: depthLimit,\n\t\t\t\t});\n\t\t\t}\n\t\t\tonPath.set(key, trace.length);\n\n\t\t\tconst available = transitions(items);\n\t\t\tfor (const { next, application } of available) visit(next, [...trace, application]);\n\t\t\tif (available.length === 0) normals.set(key, { items, trace });\n\n\t\t\tonPath.delete(key);\n\t\t};\n\n\t\tvisit(input, []);\n\n\t\tif (normals.size > 1) {\n\t\t\tthrow new RewriteFailure({\n\t\t\t\t_tag: \"ConflictingRewrites\",\n\t\t\t\toutcomes: [...normals.entries()].map(([actions, outcome]) => ({\n\t\t\t\t\tactions,\n\t\t\t\t\trules: outcome.trace.map((application) => application.rule.id),\n\t\t\t\t})),\n\t\t\t});\n\t\t}\n\n\t\tconst [outcome] = normals.values();\n\n\t\treturn outcome ?? { items: input, trace: [] };\n\t};\n\n\treturn { normalize };\n};\n\n/** Applies rules to a sequence until no rule matches. */\nexport const rewrite = (\n\titems: ReadonlyArray<Item>,\n\trules: ReadonlyArray<Rule.Any>,\n):\n\t| { readonly _tag: \"Success\"; readonly outcome: Outcome }\n\t| { readonly _tag: \"Failure\"; readonly failure: Failure } => {\n\ttry {\n\t\treturn { _tag: \"Success\", outcome: makeNormalizer(rules).normalize(items) };\n\t} catch (error) {\n\t\tif (error instanceof RewriteFailure) return { _tag: \"Failure\", failure: error.failure };\n\n\t\tthrow error;\n\t}\n};\n","import { Array as Arr, Equal, Graph, Option, Order } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Change from \"../../foundation/change.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\nimport type * as Shortcut from \"../../foundation/shortcut.ts\";\nimport type { Version } from \"../../foundation/version.ts\";\nimport { stepKey } from \"./rewrite.ts\";\n\n/**\n * A problem in a history's declarations.\n *\n * @since @next\n */\nexport type Issue = {\n\treadonly _tag:\n\t\t| \"DuplicateVersion\"\n\t\t| \"UnregisteredVersion\"\n\t\t| \"AncestryCycle\"\n\t\t| \"ConflictingChange\"\n\t\t| \"ConflictingAction\"\n\t\t| \"DuplicateMigration\"\n\t\t| \"DuplicateEdge\"\n\t\t| \"SelfMigration\"\n\t\t| \"EmptyMigration\"\n\t\t| \"DuplicateOccurrence\"\n\t\t| \"DuplicateRule\"\n\t\t| \"InvalidRule\"\n\t\t| \"DuplicateShortcut\"\n\t\t| \"InvalidShortcut\";\n\t/** The identifier of the declaration the issue is about. */\n\treadonly subject: string;\n\treadonly message: string;\n};\n\nexport type Declarations = {\n\treadonly versions: ReadonlyArray<Version>;\n\treadonly migrations: ReadonlyArray<Migration.Any>;\n\treadonly rules: ReadonlyArray<Rule.Any>;\n\treadonly shortcuts: ReadonlyArray<Shortcut.Any>;\n};\n\nconst issueOrder = Order.combine(\n\tOrder.combine(\n\t\tOrder.mapInput(Order.String, (issue: Issue) => issue._tag),\n\t\tOrder.mapInput(Order.String, (issue: Issue) => issue.subject),\n\t),\n\tOrder.mapInput(Order.String, (issue: Issue) => issue.message),\n);\n\n/** Action instances declared by steps, in declaration order. */\nexport const actionsOfSteps = (steps: ReadonlyArray<Action.Step>): ReadonlyArray<Action.Any> =>\n\tsteps.flatMap((step): ReadonlyArray<Action.Any> => {\n\t\tswitch (step._tag) {\n\t\t\tcase \"Action\":\n\t\t\t\treturn [step];\n\t\t\tcase \"Instruction\":\n\t\t\t\treturn [step.action];\n\t\t\tcase \"Sequence\":\n\t\t\t\treturn actionsOfSteps(step.children);\n\t\t}\n\n\t\treturn actionsOfSteps(step.branches);\n\t});\n\nexport const stepsOf = (content: Migration.Content): ReadonlyArray<Action.Step> =>\n\tcontent.flatMap((fragment) =>\n\t\tfragment._tag === \"Text\" || fragment._tag === \"ActionRef\" ? [] : [fragment],\n\t);\n\n/** Whether two definitions with the same identifier describe the same change. */\nconst sameDefinition = (self: Change.Any, that: Change.Any): boolean =>\n\tself === that ||\n\t(self.id === that.id &&\n\t\tEqual.equals(self.metadata, that.metadata) &&\n\t\tself.description === that.description &&\n\t\tself.backportOf?.id === that.backportOf?.id &&\n\t\tself.reverts.length === that.reverts.length &&\n\t\tself.reverts.every((change, index) => change.id === that.reverts[index]?.id));\n\n/** Whether content declares at least one occurrence. Empty groups declare none. */\nconst hasOccurrences = (content: Migration.Content): boolean =>\n\tactionsOfSteps(stepsOf(content)).length > 0;\n\n/** Whether content has prose or mentions. */\nexport const hasProse = (content: Migration.Content): boolean =>\n\tcontent.some(\n\t\t(fragment) =>\n\t\t\tfragment._tag === \"ActionRef\" ||\n\t\t\t(fragment._tag === \"Text\" && fragment.text.trim() !== \"\"),\n\t);\n\nconst sameAction = (self: Action.Any, that: Action.Any) =>\n\tself === that || (self.kind === that.kind && Equal.equals(self.payload, that.payload));\n\n/** Collects every distinct migration: registered ones and those inside shortcuts. */\nexport const allMigrations = (declarations: Declarations): ReadonlyArray<Migration.Any> => {\n\tconst result: Array<Migration.Any> = [...declarations.migrations];\n\tfor (const shortcut of declarations.shortcuts) {\n\t\tfor (const migration of shortcut.migrations) {\n\t\t\tif (!result.includes(migration)) result.push(migration);\n\t\t}\n\t}\n\n\treturn result;\n};\n\nconst isChain = (migrations: ReadonlyArray<Migration.Any>, from: Version, to: Version): boolean => {\n\tlet current = from.id;\n\tfor (const migration of migrations) {\n\t\tif (migration.from.id !== current) return false;\n\t\tcurrent = migration.to.id;\n\t}\n\n\treturn migrations.length > 0 && current === to.id;\n};\n\nexport const validate = (declarations: Declarations): ReadonlyArray<Issue> => {\n\tconst issues: Array<Issue> = [];\n\tconst issue = (tag: Issue[\"_tag\"], subject: string, message: string) =>\n\t\tissues.push({ _tag: tag, subject, message });\n\n\t// Versions and ancestry.\n\tconst versions = new Map<string, Version>();\n\tfor (const version of declarations.versions) {\n\t\tif (versions.has(version.id)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateVersion\",\n\t\t\t\tversion.id,\n\t\t\t\t`Version \"${version.id}\" is registered more than once.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tversions.set(version.id, version);\n\t}\n\tconst unregistered = new Map<string, Array<string>>();\n\tconst requireVersion = (version: Version, referencedBy: string) => {\n\t\tif (versions.get(version.id) !== undefined) return;\n\n\t\tconst referrers = unregistered.get(version.id) ?? [];\n\t\tif (!referrers.includes(referencedBy)) referrers.push(referencedBy);\n\t\tunregistered.set(version.id, referrers);\n\t};\n\tfor (const version of versions.values()) {\n\t\tif (version.previous !== undefined)\n\t\t\trequireVersion(version.previous, `version \"${version.id}\"`);\n\t}\n\tconst ancestry = Graph.directed<string, undefined>((graph) => {\n\t\tconst nodes = new Map<string, Graph.NodeIndex>();\n\t\tfor (const id of versions.keys()) nodes.set(id, Graph.addNode(graph, id));\n\t\tfor (const version of versions.values()) {\n\t\t\tconst source = nodes.get(version.id);\n\t\t\tconst target =\n\t\t\t\tversion.previous === undefined ? undefined : nodes.get(version.previous.id);\n\t\t\tif (source !== undefined && target !== undefined)\n\t\t\t\tGraph.addEdge(graph, source, target, undefined);\n\t\t}\n\t});\n\tconst cycle = Graph.findCycle(ancestry);\n\tif (Option.isSome(cycle)) {\n\t\tconst ids = cycle.value.path.flatMap((index) =>\n\t\t\tOption.toArray(Graph.getNode(ancestry, index)),\n\t\t);\n\t\tissue(\n\t\t\t\"AncestryCycle\",\n\t\t\tids[0] ?? \"\",\n\t\t\t`Release ancestry contains a cycle: ${ids.join(\" -> \")}.`,\n\t\t);\n\t}\n\n\t// Change definitions.\n\tconst changes = new Map<string, Change.Any>();\n\t// Every distinct object is compared and has its relationships followed, so a repeated\n\t// definition cannot hide a conflict between the changes it refers to.\n\tconst visited = new Set<Change.Any>();\n\tconst conflictingChanges = new Set<string>();\n\tconst visitChange = (change: Change.Any) => {\n\t\tif (visited.has(change)) return;\n\t\tvisited.add(change);\n\t\tconst known = changes.get(change.id);\n\t\tif (known === undefined) changes.set(change.id, change);\n\t\telse if (!sameDefinition(known, change) && !conflictingChanges.has(change.id)) {\n\t\t\tconflictingChanges.add(change.id);\n\t\t\tissue(\n\t\t\t\t\"ConflictingChange\",\n\t\t\t\tchange.id,\n\t\t\t\t`Change \"${change.id}\" has conflicting definitions.`,\n\t\t\t);\n\t\t}\n\t\tfor (const reverted of change.reverts) visitChange(reverted);\n\t\tif (change.backportOf !== undefined) visitChange(change.backportOf);\n\t};\n\tfor (const version of declarations.versions) {\n\t\tfor (const change of version.changes) visitChange(change);\n\t}\n\n\t// Action identities.\n\tconst actions = new Map<string, Action.Any>();\n\tconst conflicting = new Set<string>();\n\tconst visitAction = (action: Action.Any) => {\n\t\tconst known = actions.get(action.id);\n\t\tif (known === undefined) {\n\t\t\tactions.set(action.id, action);\n\n\t\t\treturn;\n\t\t}\n\t\tif (!sameAction(known, action) && !conflicting.has(action.id)) {\n\t\t\tconflicting.add(action.id);\n\t\t\tissue(\n\t\t\t\t\"ConflictingAction\",\n\t\t\t\taction.id,\n\t\t\t\t`Action \"${action.id}\" has conflicting definitions; action identifiers must be unique.`,\n\t\t\t);\n\t\t}\n\t};\n\n\t// Migrations.\n\tconst migrations = allMigrations(declarations);\n\tconst migrationIds = new Map<string, Migration.Any>();\n\tconst registered = new Set<Migration.Any>();\n\tfor (const migration of declarations.migrations) {\n\t\tif (registered.has(migration) || migrationIds.has(migration.id)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateMigration\",\n\t\t\t\tmigration.id,\n\t\t\t\t`Migration \"${migration.id}\" is registered more than once. Register a migration once; register the result of Migration.withRevert in place of the original.`,\n\t\t\t);\n\t\t}\n\t\tregistered.add(migration);\n\t\tmigrationIds.set(migration.id, migration);\n\t}\n\tfor (const migration of migrations) {\n\t\tconst known = migrationIds.get(migration.id);\n\t\tif (known !== undefined && known !== migration && !registered.has(migration)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateMigration\",\n\t\t\t\tmigration.id,\n\t\t\t\t`Migration \"${migration.id}\" has another definition inside a shortcut.`,\n\t\t\t);\n\t\t}\n\t\tif (known === undefined) migrationIds.set(migration.id, migration);\n\n\t\trequireVersion(migration.from, `migration \"${migration.id}\"`);\n\t\trequireVersion(migration.to, `migration \"${migration.id}\"`);\n\t\tif (migration.from.id === migration.to.id) {\n\t\t\tissue(\n\t\t\t\t\"SelfMigration\",\n\t\t\t\tmigration.id,\n\t\t\t\t`Migration \"${migration.id}\" starts and ends at the same version.`,\n\t\t\t);\n\t\t}\n\t\tfor (const change of migration.addresses) visitChange(change);\n\n\t\tconst sides: ReadonlyArray<[string, Migration.Content | undefined]> = [\n\t\t\t[\"forward\", migration.content],\n\t\t\t[\"revert\", migration.revert],\n\t\t];\n\t\tfor (const [direction, content] of sides) {\n\t\t\tif (content === undefined) continue;\n\t\t\tif (!migration.noop && !hasOccurrences(content) && !hasProse(content)) {\n\t\t\t\tissue(\n\t\t\t\t\t\"EmptyMigration\",\n\t\t\t\t\tmigration.id,\n\t\t\t\t\t`The ${direction} side of migration \"${migration.id}\" is empty. Use Migration.noop to declare a zero-work transition.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst counts = new Map<string, number>();\n\t\t\tfor (const action of actionsOfSteps(stepsOf(content))) {\n\t\t\t\tvisitAction(action);\n\t\t\t\tcounts.set(action.id, (counts.get(action.id) ?? 0) + 1);\n\t\t\t}\n\t\t\tfor (const [actionId, count] of counts) {\n\t\t\t\tif (count < 2) continue;\n\n\t\t\t\tissue(\n\t\t\t\t\t\"DuplicateOccurrence\",\n\t\t\t\t\tmigration.id,\n\t\t\t\t\t`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.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Edges. Each pair of versions has at most one migration side, so a transition's work\n\t// lives in one migration.\n\tconst edgeSides = new Map<\n\t\tstring,\n\t\t{ readonly from: string; readonly to: string; readonly labels: Array<string> }\n\t>();\n\tconst addSide = (from: Version, to: Version, label: string) => {\n\t\tconst key = JSON.stringify([from.id, to.id]);\n\t\tconst side = edgeSides.get(key) ?? { from: from.id, to: to.id, labels: [] };\n\t\tside.labels.push(label);\n\t\tedgeSides.set(key, side);\n\t};\n\t// A migration registered twice is already a DuplicateMigration issue.\n\tfor (const migration of new Set(migrationIds.values())) {\n\t\tif (!registered.has(migration)) continue;\n\t\taddSide(migration.from, migration.to, `\"${migration.id}\"`);\n\t\tif (migration.revert !== undefined)\n\t\t\taddSide(migration.to, migration.from, `the revert of \"${migration.id}\"`);\n\t}\n\tfor (const { from, to, labels } of edgeSides.values()) {\n\t\tif (labels.length < 2) continue;\n\n\t\tissue(\n\t\t\t\"DuplicateEdge\",\n\t\t\t`${from} -> ${to}`,\n\t\t\t`${labels.join(\" and \")} both go from \"${from}\" to \"${to}\". Merge them into one migration.`,\n\t\t);\n\t}\n\n\t// Rules.\n\tconst rules = new Set<string>();\n\tfor (const rule of declarations.rules) {\n\t\tif (rules.has(rule.id)) {\n\t\t\tissue(\"DuplicateRule\", rule.id, `Rule \"${rule.id}\" is registered more than once.`);\n\t\t}\n\t\trules.add(rule.id);\n\t\tif (rule.match.length === 0) {\n\t\t\tissue(\"InvalidRule\", rule.id, `Rule \"${rule.id}\" matches nothing.`);\n\t\t}\n\t\tconst patternActions = actionsOfSteps(rule.match);\n\t\tconst replacementActions = actionsOfSteps(rule.replacement);\n\t\tfor (const action of [...patternActions, ...replacementActions]) visitAction(action);\n\t\tconst unique = new Set(replacementActions.map((action) => action.id));\n\t\tif (unique.size !== replacementActions.length) {\n\t\t\tissue(\n\t\t\t\t\"InvalidRule\",\n\t\t\t\trule.id,\n\t\t\t\t`Rule \"${rule.id}\" repeats an action in its replacement.`,\n\t\t\t);\n\t\t}\n\t\t// Same actions in a different structure, such as a sequence made parallel, is a\n\t\t// real replacement.\n\t\tif (rule.match.length > 0 && stepKey(rule.match) === stepKey(rule.replacement)) {\n\t\t\tissue(\"InvalidRule\", rule.id, `Rule \"${rule.id}\" replaces its match with itself.`);\n\t\t}\n\t}\n\n\t// Shortcuts.\n\tconst shortcuts = new Set<string>();\n\tfor (const shortcut of declarations.shortcuts) {\n\t\tif (shortcuts.has(shortcut.id)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`Shortcut \"${shortcut.id}\" is registered more than once.`,\n\t\t\t);\n\t\t}\n\t\tshortcuts.add(shortcut.id);\n\t\trequireVersion(shortcut.from, `shortcut \"${shortcut.id}\"`);\n\t\trequireVersion(shortcut.to, `shortcut \"${shortcut.id}\"`);\n\t\tconst unknown = shortcut.replaces.filter((migration) => !registered.has(migration));\n\t\tif (unknown.length > 0) {\n\t\t\tissue(\n\t\t\t\t\"InvalidShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`Shortcut \"${shortcut.id}\" replaces unregistered migrations: ${unknown.map((migration) => migration.id).join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\tif (!isChain(shortcut.replaces, shortcut.from, shortcut.to)) {\n\t\t\tissue(\n\t\t\t\t\"InvalidShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`Shortcut \"${shortcut.id}\" must replace a consecutive route from \"${shortcut.from.id}\" to \"${shortcut.to.id}\".`,\n\t\t\t);\n\t\t}\n\t\tif (!isChain(shortcut.migrations, shortcut.from, shortcut.to)) {\n\t\t\tissue(\n\t\t\t\t\"InvalidShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`The migrations of shortcut \"${shortcut.id}\" must form a route from \"${shortcut.from.id}\" to \"${shortcut.to.id}\".`,\n\t\t\t);\n\t\t}\n\t}\n\n\tfor (const [id, referrers] of unregistered) {\n\t\tissue(\n\t\t\t\"UnregisteredVersion\",\n\t\t\tid,\n\t\t\t`Version \"${id}\" is referenced by ${referrers.join(\", \")} but is not registered.`,\n\t\t);\n\t}\n\n\treturn Arr.sort(issues, issueOrder);\n};\n","import { Array as Arr, Graph, Order, Result, SemVer } from \"effect\";\n\nimport type * as Change from \"../../foundation/change.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type {\n\tDirection,\n\tExplanation,\n\tHop,\n\tNode,\n\tPlan,\n\tRequestDirection,\n\tRoute,\n\tStep,\n} from \"../../foundation/plan.ts\";\nimport type * as Shortcut from \"../../foundation/shortcut.ts\";\nimport type { Version } from \"../../foundation/version.ts\";\nimport { resolveGuide } from \"./guide.ts\";\nimport { declaredOccurrenceId, routeHop, routeShortcut, routeStart } from \"./identifiers.ts\";\nimport {\n\tAmbiguousRoute,\n\tConflictingRewrites,\n\tRewriteCycle,\n\tRewriteLimitExceeded,\n\tTooManyRoutes,\n\tUnknownRoute,\n\tUnknownVersion,\n\tUnsupportedRoute,\n\ttype Blocker,\n\ttype ResolveError,\n\ttype RewriteError,\n\ttype RouteSummary,\n} from \"./resolve-error.ts\";\nimport { itemsOf, occurrencesOf, rewrite, type Item, type MakeOccurrence } from \"./rewrite.ts\";\nimport { actionsOfSteps, hasProse, stepsOf, type Declarations } from \"./validate.ts\";\n\n/**\n * Route policies for choosing between candidate routes. Each one is opt-in, and a policy\n * that leaves a tie still fails as ambiguous.\n *\n * - `fewest-actions`: the fewest action occurrences after optimization.\n * - `fewest-migrations`: the fewest migration steps.\n * - `lowest-cost`: the lowest total cost. A migration costs 1 unless it declares\n * `cost`; a shortcut costs its declared `cost` or the total of its migrations.\n * - `prefer-shortcuts`: a route through a shortcut over the route the shortcut replaces.\n *\n * @since @next\n */\nexport type RoutePolicy =\n\t| \"fewest-actions\"\n\t| \"fewest-migrations\"\n\t| \"lowest-cost\"\n\t| \"prefer-shortcuts\";\n\n/** The largest number of candidate routes enumerated between two versions. */\nexport const routeLimit = 100;\n\ntype Member = { readonly migration: Migration.Any; readonly direction: Direction };\n\ntype Edge = {\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly members: ReadonlyArray<Member>;\n\treadonly shortcut: Shortcut.Any | undefined;\n\treadonly cost: number;\n\treadonly class: \"up\" | \"down\" | \"cross\";\n};\n\ntype Candidate = {\n\treadonly route: Route;\n\treadonly edges: ReadonlyArray<Edge>;\n\treadonly plan: Result.Result<Plan, RewriteError>;\n\treadonly cost: number;\n};\n\nexport type Context = {\n\treadonly declarations: Declarations;\n\treadonly versions: ReadonlyMap<string, Version>;\n\t/** Strict ancestors of each version, by identifier. */\n\treadonly ancestors: ReadonlyMap<string, ReadonlySet<string>>;\n\treadonly edges: ReadonlyArray<Edge>;\n};\n\nconst memberCost = (migration: Migration.Any) => migration.cost ?? 1;\n\nexport const makeContext = (declarations: Declarations): Context => {\n\tconst versions = new Map(declarations.versions.map((version) => [version.id, version]));\n\tconst ancestors = new Map<string, ReadonlySet<string>>();\n\tconst ancestorsOf = (id: string): ReadonlySet<string> => {\n\t\tconst known = ancestors.get(id);\n\t\tif (known !== undefined) return known;\n\n\t\tconst result = new Set<string>();\n\t\tlet current = versions.get(id)?.previous;\n\t\twhile (current !== undefined && !result.has(current.id)) {\n\t\t\tresult.add(current.id);\n\t\t\tcurrent = versions.get(current.id)?.previous;\n\t\t}\n\t\tancestors.set(id, result);\n\n\t\treturn result;\n\t};\n\tfor (const id of versions.keys()) ancestorsOf(id);\n\n\tconst classOf = (from: string, to: string): Edge[\"class\"] => {\n\t\tif (ancestorsOf(to).has(from)) return \"up\";\n\t\tif (ancestorsOf(from).has(to)) return \"down\";\n\n\t\treturn \"cross\";\n\t};\n\n\t// Validation guarantees at most one migration side per pair of versions.\n\tconst edges: Array<Edge> = declarations.migrations.flatMap((migration): Array<Edge> => {\n\t\tconst forward: Edge = {\n\t\t\tfrom: migration.from,\n\t\t\tto: migration.to,\n\t\t\tmembers: [{ migration, direction: \"forward\" }],\n\t\t\tshortcut: undefined,\n\t\t\tcost: memberCost(migration),\n\t\t\tclass: classOf(migration.from.id, migration.to.id),\n\t\t};\n\t\tif (migration.revert === undefined) return [forward];\n\n\t\treturn [\n\t\t\tforward,\n\t\t\t{\n\t\t\t\tfrom: migration.to,\n\t\t\t\tto: migration.from,\n\t\t\t\tmembers: [{ migration, direction: \"revert\" }],\n\t\t\t\tshortcut: undefined,\n\t\t\t\tcost: memberCost(migration),\n\t\t\t\tclass: classOf(migration.to.id, migration.from.id),\n\t\t\t},\n\t\t];\n\t});\n\tfor (const shortcut of declarations.shortcuts) {\n\t\tedges.push({\n\t\t\tfrom: shortcut.from,\n\t\t\tto: shortcut.to,\n\t\t\tmembers: shortcut.migrations.map((migration) => ({ migration, direction: \"forward\" })),\n\t\t\tshortcut,\n\t\t\tcost:\n\t\t\t\tshortcut.cost ??\n\t\t\t\tshortcut.migrations.reduce((total, migration) => total + memberCost(migration), 0),\n\t\t\tclass: classOf(shortcut.from.id, shortcut.to.id),\n\t\t});\n\t}\n\n\treturn { declarations, versions, ancestors, edges };\n};\n\nconst requestDirection = (context: Context, from: string, to: string): RequestDirection => {\n\tif (from === to) return \"none\";\n\tif (context.ancestors.get(to)?.has(from)) return \"upgrade\";\n\tif (context.ancestors.get(from)?.has(to)) return \"downgrade\";\n\n\treturn \"cross-branch\";\n};\n\n/**\n * Edge classes allowed together in one route. A route never mixes moves toward\n * ancestors with moves toward descendants, so sharing an ancestor does not authorize a\n * downgrade-and-upgrade detour. Explicit cross-branch migrations fit either family.\n */\nconst families: ReadonlyArray<ReadonlySet<Edge[\"class\"]>> = [\n\tnew Set([\"up\", \"cross\"]),\n\tnew Set([\"down\", \"cross\"]),\n];\n\nconst routeCost = (edges: ReadonlyArray<Edge>) =>\n\tedges.reduce((total, edge) => total + edge.cost, 0);\n\nconst routeOf = (from: Version, edges: ReadonlyArray<Edge>): Route => {\n\tlet id = routeStart(from.id);\n\tconst hops: Array<Hop> = [];\n\tfor (const edge of edges) {\n\t\tif (edge.shortcut === undefined) {\n\t\t\tid += routeHop(edge.to.id);\n\t\t\thops.push({\n\t\t\t\t_tag: \"Migrations\",\n\t\t\t\tfrom: edge.from,\n\t\t\t\tto: edge.to,\n\t\t\t\tmigrations: edge.members,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tid += routeShortcut(edge.shortcut.id, edge.to.id);\n\t\thops.push({ _tag: \"Shortcut\", from: edge.from, to: edge.to, shortcut: edge.shortcut });\n\t}\n\n\treturn { id, hops };\n};\n\nconst graphOf = (context: Context, family: ReadonlySet<Edge[\"class\"]>) => {\n\tconst nodes = new Map<string, Graph.NodeIndex>();\n\tconst graph = Graph.directed<string, Edge>((mutable) => {\n\t\tfor (const id of context.versions.keys()) nodes.set(id, Graph.addNode(mutable, id));\n\t\tfor (const edge of context.edges) {\n\t\t\tif (!family.has(edge.class)) continue;\n\n\t\t\tconst source = nodes.get(edge.from.id);\n\t\t\tconst target = nodes.get(edge.to.id);\n\t\t\tif (source !== undefined && target !== undefined)\n\t\t\t\tGraph.addEdge(mutable, source, target, edge);\n\t\t}\n\t});\n\n\treturn { graph, nodes };\n};\n\ntype Enumerated = {\n\t/** At most `routeLimit` routes, in search order. */\n\treadonly routes: ReadonlyArray<ReadonlyArray<Edge>>;\n\t/** Whether the search stopped because more routes exist. */\n\treadonly overLimit: boolean;\n};\n\nconst enumerateRoutes = (context: Context, from: Version, to: Version): Enumerated => {\n\tconst routes = new Map<string, ReadonlyArray<Edge>>();\n\tfor (const family of families) {\n\t\tconst { graph, nodes } = graphOf(context, family);\n\t\tconst source = nodes.get(from.id);\n\t\tconst target = nodes.get(to.id);\n\t\tif (source === undefined || target === undefined) continue;\n\n\t\tfor (const path of Graph.simplePaths(graph, { source, target, limit: routeLimit + 1 })) {\n\t\t\troutes.set(routeOf(from, path.costs).id, path.costs);\n\t\t}\n\t}\n\tconst found = [...routes.values()];\n\n\treturn { routes: found.slice(0, routeLimit), overLimit: found.length > routeLimit };\n};\n\nconst toNode = (items: ReadonlyArray<Item>): ReadonlyArray<Node> =>\n\titems.flatMap((item): ReadonlyArray<Node> => {\n\t\tif (item._tag === \"Occ\") return [item.occurrence];\n\t\tif (item._tag === \"Barrier\") return [];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\t_tag: \"Parallel\",\n\t\t\t\tbranches: item.branches.map((branch) => {\n\t\t\t\t\tconst children = toNode(branch);\n\t\t\t\t\tconst [only] = children;\n\n\t\t\t\t\treturn children.length === 1 && only !== undefined\n\t\t\t\t\t\t? only\n\t\t\t\t\t\t: { _tag: \"Sequence\", children };\n\t\t\t\t}),\n\t\t\t\tconcurrency: item.concurrency,\n\t\t\t},\n\t\t];\n\t});\n\nconst contentOf = (member: Member): Migration.Content =>\n\t(member.direction === \"forward\" ? member.migration.content : member.migration.revert) ?? [];\n\nconst buildPlan = (\n\tcontext: Context,\n\tfrom: Version,\n\tto: Version,\n\tdirection: RequestDirection,\n\tedges: ReadonlyArray<Edge>,\n): Result.Result<Plan, RewriteError> => {\n\tconst route = routeOf(from, edges);\n\tconst members = edges.flatMap((edge) => edge.members);\n\n\tconst items = members.flatMap((member, index): ReadonlyArray<Item> => {\n\t\tconst content = contentOf(member);\n\t\tconst make: MakeOccurrence = (action, instruction) => ({\n\t\t\t_tag: \"Occurrence\",\n\t\t\tid: declaredOccurrenceId(member.migration, member.direction, action),\n\t\t\taction,\n\t\t\tmigration: member.migration,\n\t\t\tdirection: member.direction,\n\t\t\tinstruction,\n\t\t\torigin: { _tag: \"Declared\" },\n\t\t});\n\t\tconst declared = itemsOf(stepsOf(content), make, index);\n\t\tif (declared.length === 0 && hasProse(content)) return [{ _tag: \"Barrier\", step: index }];\n\n\t\treturn declared;\n\t});\n\n\tconst rewritten = rewrite(items, context.declarations.rules);\n\tif (rewritten._tag === \"Failure\") {\n\t\tconst failure = rewritten.failure;\n\t\tswitch (failure._tag) {\n\t\t\tcase \"RewriteCycle\":\n\t\t\t\treturn Result.fail(\n\t\t\t\t\tnew RewriteCycle({\n\t\t\t\t\t\troute: route.id,\n\t\t\t\t\t\trules: failure.rules,\n\t\t\t\t\t\tactions: failure.actions,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\tcase \"ConflictingRewrites\":\n\t\t\t\treturn Result.fail(\n\t\t\t\t\tnew ConflictingRewrites({ route: route.id, outcomes: failure.outcomes }),\n\t\t\t\t);\n\t\t}\n\n\t\treturn Result.fail(\n\t\t\tnew RewriteLimitExceeded({\n\t\t\t\troute: route.id,\n\t\t\t\tlimit: failure.limit,\n\t\t\t\tvalue: failure.value,\n\t\t\t}),\n\t\t);\n\t}\n\tconst { items: optimized, trace } = rewritten.outcome;\n\n\tconst explanations: Array<Explanation> = trace.map((application) => ({\n\t\t_tag: \"Rewrite\",\n\t\trule: application.rule,\n\t\tremoved: application.removed,\n\t\tproduced: application.produced,\n\t}));\n\n\tconst steps = members.map((member, index): Step => {\n\t\tconst stepItems = optimized.filter((item) => item.step === index);\n\t\tconst content = contentOf(member);\n\t\tconst declaredCount = actionsOfSteps(stepsOf(content)).length;\n\t\tconst retained = occurrencesOf(stepItems);\n\t\tconst guide = resolveGuide(content, retained, (action) =>\n\t\t\tdeclaredOccurrenceId(member.migration, member.direction, action),\n\t\t);\n\t\tconst allRemoved = declaredCount > 0 && retained.length === 0;\n\t\t// `noop` describes the zero-work sides. A revert added to a noop migration is work.\n\t\tconst noop = member.migration.noop && content.length === 0;\n\t\tconst omitted = noop || allRemoved;\n\t\tif (omitted) {\n\t\t\texplanations.push({\n\t\t\t\t_tag: \"OmittedStep\",\n\t\t\t\tmigration: member.migration,\n\t\t\t\tdirection: member.direction,\n\t\t\t\treason: noop ? \"noop\" : \"all-actions-removed\",\n\t\t\t});\n\t\t}\n\t\tconst [stepFrom, stepTo] =\n\t\t\tmember.direction === \"forward\"\n\t\t\t\t? [member.migration.from, member.migration.to]\n\t\t\t\t: [member.migration.to, member.migration.from];\n\n\t\treturn {\n\t\t\t_tag: \"Step\",\n\t\t\tmigration: member.migration,\n\t\t\tdirection: member.direction,\n\t\t\tfrom: stepFrom,\n\t\t\tto: stepTo,\n\t\t\tnode: { _tag: \"Sequence\", children: toNode(stepItems) },\n\t\t\tguide: omitted ? [] : guide,\n\t\t\tomitted,\n\t\t};\n\t});\n\n\tconst changes: Array<Change.Any> = [];\n\tfor (const member of members) {\n\t\tfor (const change of member.migration.addresses) {\n\t\t\tif (!changes.some((known) => known.id === change.id)) changes.push(change);\n\t\t}\n\t}\n\n\treturn Result.succeed({\n\t\t_tag: \"Plan\",\n\t\tfrom,\n\t\tto,\n\t\tdirection,\n\t\troute,\n\t\tsteps,\n\t\toccurrences: occurrencesOf(optimized),\n\t\tchanges,\n\t\texplanations,\n\t\tcoverage: \"static\",\n\t});\n};\n\nconst summaryOf = (candidate: Candidate): RouteSummary => ({\n\tid: candidate.route.id,\n\tmigrations: candidate.edges.flatMap((edge) =>\n\t\tedge.members.map((member) => member.migration.id),\n\t),\n\tshortcuts: candidate.edges.flatMap((edge) =>\n\t\tedge.shortcut === undefined ? [] : [edge.shortcut.id],\n\t),\n\tactions: Result.isSuccess(candidate.plan)\n\t\t? candidate.plan.success.occurrences.length\n\t\t: undefined,\n\tcost: candidate.cost,\n\tfailure: Result.isFailure(candidate.plan) ? candidate.plan.failure.message : undefined,\n});\n\n/** Migration tokens of a route, with shortcut hops expanded to the route they replace. */\nconst canonicalTokens = (candidate: Candidate) =>\n\tJSON.stringify(\n\t\tcandidate.edges.flatMap((edge) =>\n\t\t\tedge.shortcut === undefined\n\t\t\t\t? edge.members.map((member) => [member.direction, member.migration.id])\n\t\t\t\t: edge.shortcut.replaces.map((migration) => [\"forward\", migration.id]),\n\t\t),\n\t);\n\nconst shortcutCount = (candidate: Candidate) =>\n\tcandidate.edges.filter((edge) => edge.shortcut !== undefined).length;\n\nconst minimal = (\n\tcandidates: ReadonlyArray<Candidate>,\n\tmeasure: (candidate: Candidate) => number | undefined,\n): ReadonlyArray<Candidate> => {\n\tconst measured = candidates.flatMap((candidate) => {\n\t\tconst value = measure(candidate);\n\n\t\treturn value === undefined ? [] : [{ candidate, value }];\n\t});\n\tconst best = Math.min(...measured.map((entry) => entry.value));\n\n\treturn measured.filter((entry) => entry.value === best).map((entry) => entry.candidate);\n};\n\nconst applyPolicy = (\n\tpolicy: RoutePolicy,\n\tcandidates: ReadonlyArray<Candidate>,\n): ReadonlyArray<Candidate> => {\n\tswitch (policy) {\n\t\tcase \"fewest-actions\":\n\t\t\treturn minimal(candidates, (candidate) =>\n\t\t\t\tResult.isSuccess(candidate.plan)\n\t\t\t\t\t? candidate.plan.success.occurrences.length\n\t\t\t\t\t: undefined,\n\t\t\t);\n\t\tcase \"fewest-migrations\":\n\t\t\treturn minimal(candidates, (candidate) =>\n\t\t\t\tcandidate.edges.reduce((total, edge) => total + edge.members.length, 0),\n\t\t\t);\n\t\tcase \"lowest-cost\":\n\t\t\treturn minimal(candidates, (candidate) => candidate.cost);\n\t}\n\n\t// prefer-shortcuts: drop a route when another candidate is the same canonical route\n\t// with more of it replaced by shortcuts. Unrelated routes stay ambiguous.\n\treturn candidates.filter(\n\t\t(candidate) =>\n\t\t\t!candidates.some(\n\t\t\t\t(other) =>\n\t\t\t\t\tother !== candidate &&\n\t\t\t\t\tcanonicalTokens(other) === canonicalTokens(candidate) &&\n\t\t\t\t\tshortcutCount(other) > shortcutCount(candidate),\n\t\t\t),\n\t);\n};\n\nconst depthOf = (context: Context, id: string) => context.ancestors.get(id)?.size ?? 0;\n\n/** Distance between two versions in the release ancestry tree. */\nconst ancestryDistance = (context: Context, self: string, that: string): number => {\n\tconst selfLine = [self, ...ancestorsInOrder(context, self)];\n\tconst thatLine = new Set([that, ...ancestorsInOrder(context, that)]);\n\tconst common = selfLine.find((id) => thatLine.has(id));\n\tif (common === undefined) return Number.POSITIVE_INFINITY;\n\n\treturn depthOf(context, self) + depthOf(context, that) - 2 * depthOf(context, common);\n};\n\nconst ancestorsInOrder = (context: Context, id: string): ReadonlyArray<string> => {\n\tconst result: Array<string> = [];\n\tlet current = context.versions.get(id)?.previous;\n\twhile (current !== undefined && !result.includes(current.id)) {\n\t\tresult.push(current.id);\n\t\tcurrent = context.versions.get(current.id)?.previous;\n\t}\n\n\treturn result;\n};\n\n/** The ancestry path between two versions, through their closest common ancestor. */\nconst ancestryPath = (context: Context, from: string, to: string): ReadonlyArray<string> => {\n\tconst fromLine = [from, ...ancestorsInOrder(context, from)];\n\tconst toLine = [to, ...ancestorsInOrder(context, to)];\n\tconst common = fromLine.find((id) => toLine.includes(id));\n\tif (common === undefined) return [];\n\n\treturn [\n\t\t...fromLine.slice(0, fromLine.indexOf(common) + 1),\n\t\t...Arr.reverse(toLine.slice(0, toLine.indexOf(common))),\n\t];\n};\n\nexport const reachable = (\n\tcontext: Context,\n\tfrom: string,\n\tfamily: ReadonlySet<Edge[\"class\"]>,\n): ReadonlyArray<string> => {\n\tconst seen = new Set([from]);\n\tconst queue = [from];\n\tfor (let current = queue.shift(); current !== undefined; current = queue.shift()) {\n\t\tfor (const edge of context.edges) {\n\t\t\tif (edge.from.id !== current || !family.has(edge.class) || seen.has(edge.to.id))\n\t\t\t\tcontinue;\n\n\t\t\tseen.add(edge.to.id);\n\t\t\tqueue.push(edge.to.id);\n\t\t}\n\t}\n\tseen.delete(from);\n\n\treturn [...seen];\n};\n\nconst familiesFor = (direction: RequestDirection) => {\n\tif (direction === \"upgrade\") return [families[0]];\n\tif (direction === \"downgrade\") return [families[1]];\n\n\treturn families;\n};\n\nconst unsupported = (context: Context, from: string, to: string, direction: RequestDirection) => {\n\tconst allowed = familiesFor(direction).flatMap((family) =>\n\t\tfamily === undefined ? [] : [family],\n\t);\n\tconst reachableIds = Arr.sort(\n\t\tnew Set(allowed.flatMap((family) => reachable(context, from, family))),\n\t\tOrder.String,\n\t);\n\tconst distances = reachableIds.map((id) => ({\n\t\tid,\n\t\tdistance: ancestryDistance(context, id, to),\n\t}));\n\tconst best = Math.min(...distances.map((entry) => entry.distance));\n\tconst closest = Number.isFinite(best)\n\t\t? distances.filter((entry) => entry.distance === best).map((entry) => entry.id)\n\t\t: [];\n\n\tconst path = ancestryPath(context, from, to);\n\tconst blockers: Array<Blocker> = [];\n\tfor (let index = 0; index + 1 < path.length; index++) {\n\t\tconst hopFrom = path[index];\n\t\tconst hopTo = path[index + 1];\n\t\tif (hopFrom === undefined || hopTo === undefined) continue;\n\t\tif (context.edges.some((edge) => edge.from.id === hopFrom && edge.to.id === hopTo))\n\t\t\tcontinue;\n\n\t\tblockers.push({\n\t\t\tfrom: hopFrom,\n\t\t\tto: hopTo,\n\t\t\treason: `No migration is declared from \"${hopFrom}\" to \"${hopTo}\".`,\n\t\t});\n\t}\n\n\t// The common ancestor where an ancestry path turns from moving down to moving up.\n\tconst turn = path.find(\n\t\t(id) =>\n\t\t\tcontext.ancestors.get(from)?.has(id) === true &&\n\t\t\tcontext.ancestors.get(to)?.has(id) === true,\n\t);\n\tif (blockers.length === 0 && turn !== undefined) {\n\t\tblockers.push({\n\t\t\tfrom,\n\t\t\tto,\n\t\t\treason: `A route through \"${turn}\" would combine a downgrade with an upgrade. Declare a migration from \"${from}\" to \"${to}\".`,\n\t\t});\n\t}\n\n\treturn new UnsupportedRoute({\n\t\tfrom,\n\t\tto,\n\t\tdirection,\n\t\treachable: reachableIds,\n\t\tclosest,\n\t\tblockers,\n\t});\n};\n\n/** @since @next */\nexport type ResolveOptions = {\n\treadonly from: Version | string;\n\treadonly to: Version | string;\n\t/** Selects a candidate route by identifier. */\n\treadonly route?: string;\n\t/** Chooses between candidate routes. Ties still fail as ambiguous. */\n\treadonly policy?: RoutePolicy;\n};\n\nexport const lookup = (context: Context, reference: Version | string) => {\n\tconst id = typeof reference === \"string\" ? reference : reference.id;\n\tconst version = context.versions.get(id);\n\n\treturn version === undefined\n\t\t? Result.fail(new UnknownVersion({ version: id, known: [...context.versions.keys()] }))\n\t\t: Result.succeed(version);\n};\n\nexport const candidatesBetween = (\n\tcontext: Context,\n\tfrom: Version,\n\tto: Version,\n): Result.Result<ReadonlyArray<Candidate>, TooManyRoutes> => {\n\tconst direction = requestDirection(context, from.id, to.id);\n\tconst { routes, overLimit } = enumerateRoutes(context, from, to);\n\tif (overLimit) {\n\t\treturn Result.fail(new TooManyRoutes({ from: from.id, to: to.id, limit: routeLimit }));\n\t}\n\n\treturn Result.succeed(\n\t\troutes.map((edges) => ({\n\t\t\troute: routeOf(from, edges),\n\t\t\tedges,\n\t\t\tplan: buildPlan(context, from, to, direction, edges),\n\t\t\tcost: routeCost(edges),\n\t\t})),\n\t);\n};\n\nexport const resolve = (\n\tcontext: Context,\n\toptions: ResolveOptions,\n): Result.Result<Plan, ResolveError> =>\n\tResult.gen(function* () {\n\t\tconst from = yield* lookup(context, options.from);\n\t\tconst to = yield* lookup(context, options.to);\n\t\tconst direction = requestDirection(context, from.id, to.id);\n\t\tif (direction === \"none\") {\n\t\t\treturn yield* buildPlan(context, from, to, direction, []);\n\t\t}\n\n\t\tconst candidates = yield* candidatesBetween(context, from, to);\n\t\tif (candidates.length === 0)\n\t\t\treturn yield* Result.fail(unsupported(context, from.id, to.id, direction));\n\n\t\tif (options.route !== undefined) {\n\t\t\tconst selected = candidates.find((candidate) => candidate.route.id === options.route);\n\t\t\tif (selected === undefined) {\n\t\t\t\treturn yield* Result.fail(\n\t\t\t\t\tnew UnknownRoute({\n\t\t\t\t\t\troute: options.route,\n\t\t\t\t\t\tcandidates: candidates.map(summaryOf),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn yield* selected.plan;\n\t\t}\n\n\t\tconst chosen =\n\t\t\toptions.policy === undefined ? candidates : applyPolicy(options.policy, candidates);\n\t\tconst [only] = chosen;\n\t\tif (chosen.length === 1 && only !== undefined) return yield* only.plan;\n\n\t\treturn yield* Result.fail(\n\t\t\tnew AmbiguousRoute({\n\t\t\t\tfrom: from.id,\n\t\t\t\tto: to.id,\n\t\t\t\tcandidates: (chosen.length === 0 ? candidates : chosen).map(summaryOf),\n\t\t\t\tpolicy: options.policy,\n\t\t\t}),\n\t\t);\n\t});\n\n/**\n * A reachable destination and the identifiers of its candidate routes.\n *\n * @since @next\n */\nexport type Destination = {\n\treadonly version: Version;\n\treadonly routes: ReadonlyArray<string>;\n\t/**\n\t * Present when more routes exist than route search explores. `routes` then lists the\n\t * routes found, cheapest first, and `History.resolve` to this destination fails with\n\t * `TooManyRoutes`.\n\t */\n\treadonly overLimit?: true;\n};\n\nconst semverOrder = (self: string, that: string): number | undefined => {\n\tconst parsedSelf = SemVer.parse(self);\n\tconst parsedThat = SemVer.parse(that);\n\tif (Result.isFailure(parsedSelf) || Result.isFailure(parsedThat)) return undefined;\n\n\treturn SemVer.Order(parsedSelf.success, parsedThat.success);\n};\n\n/**\n * Destinations reachable from a version. Cross-branch destinations are classified by\n * semver order when both identifiers parse, and listed in both directions otherwise.\n * Classification is presentation only; it does not change routing.\n */\nexport const destinations = (\n\tcontext: Context,\n\tfrom: Version,\n\tkind: \"upgrade\" | \"downgrade\",\n): ReadonlyArray<Destination> => {\n\tconst family = kind === \"upgrade\" ? families[0] : families[1];\n\tif (family === undefined) return [];\n\n\treturn reachable(context, from.id, family).flatMap((id) => {\n\t\tconst version = context.versions.get(id);\n\t\tif (version === undefined) return [];\n\n\t\tconst direction = requestDirection(context, from.id, id);\n\t\tif (direction === \"cross-branch\") {\n\t\t\tconst order = semverOrder(id, from.id);\n\t\t\tif (order !== undefined && (kind === \"upgrade\" ? order < 0 : order > 0)) return [];\n\t\t} else if (direction !== kind) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst { routes, overLimit } = enumerateRoutes(context, from, version);\n\t\tif (!overLimit) {\n\t\t\treturn [{ version, routes: routes.map((edges) => routeOf(from, edges).id) }];\n\t\t}\n\t\tconst cheapest = Arr.sort(\n\t\t\troutes,\n\t\t\tOrder.mapInput(Order.Number, (edges: ReadonlyArray<Edge>) => routeCost(edges)),\n\t\t);\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tversion,\n\t\t\t\troutes: cheapest.map((edges) => routeOf(from, edges).id),\n\t\t\t\toverLimit: true as const,\n\t\t\t},\n\t\t];\n\t});\n};\n","import { Predicate, Result } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Change from \"../../foundation/change.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { Plan } from \"../../foundation/plan.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\nimport type * as Shortcut from \"../../foundation/shortcut.ts\";\nimport type { Version } from \"../../foundation/version.ts\";\nimport { InvalidHistory, type ResolveError, type UnknownVersion } from \"./resolve-error.ts\";\nimport {\n\tdestinations,\n\tlookup as lookupVersion,\n\tmakeContext,\n\tresolve as resolveRoute,\n\ttype Context,\n\ttype Destination,\n\ttype ResolveOptions,\n\ttype RoutePolicy,\n} from \"./resolve.ts\";\nimport { validate as validateDeclarations, type Issue } from \"./validate.ts\";\n\nexport * from \"./resolve-error.ts\";\nexport type { Destination, Issue, ResolveOptions, RoutePolicy };\n\n/** @since @next */\nexport type History<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"History\";\n\treadonly versions: ReadonlyArray<Version>;\n\treadonly migrations: ReadonlyArray<Migration.Any>;\n\treadonly rules: ReadonlyArray<Rule.Any>;\n\treadonly shortcuts: ReadonlyArray<Shortcut.Any>;\n\t/** Type-level record of every action instance that a plan can contain. */\n\treadonly \"~actions\"?: A;\n\t/** Type-level record of every change that a plan's `changes` can contain. */\n\treadonly \"~changes\"?: C;\n};\n\n/**\n * Any history.\n *\n * @since @next\n */\nexport type Any = History<any>;\n\n/**\n * Every action instance that a plan resolved from the history can contain.\n *\n * @since @next\n */\nexport type ActionsOf<H> = H extends History<infer A> ? A : never;\n\n/**\n * Every change that a plan resolved from the history can list in `changes`.\n *\n * @since @next\n */\nexport type ChangesOf<H> = H extends History<any, infer C> ? C : never;\n\n/**\n * Registers declarations. Migrations are registered independently of versions, so\n * routes can be added later without changing published release definitions.\n *\n * `make` does not throw. Use `History.validate` to list declaration issues;\n * resolution fails with `InvalidHistory` when there are any.\n *\n * @since @next\n */\nexport const make = <\n\tconst M extends ReadonlyArray<Migration.Any>,\n\tconst R extends ReadonlyArray<Rule.Any> = [],\n\tconst S extends ReadonlyArray<Shortcut.Any> = [],\n>(declarations: {\n\treadonly versions: ReadonlyArray<Version>;\n\treadonly migrations: M;\n\treadonly rules?: R;\n\treadonly shortcuts?: S;\n}): History<\n\tMigration.ActionsOf<M[number]> | Rule.ActionsOf<R[number]> | Shortcut.ActionsOf<S[number]>,\n\tMigration.ChangesOf<M[number]> | Shortcut.ChangesOf<S[number]>\n> => ({\n\t_tag: \"History\",\n\tversions: declarations.versions,\n\tmigrations: declarations.migrations,\n\trules: declarations.rules ?? [],\n\tshortcuts: declarations.shortcuts ?? [],\n});\n\n/** @since @next */\nexport const isHistory = (value: unknown): value is Any => Predicate.isTagged(value, \"History\");\n\nconst contexts = new WeakMap<\n\tAny,\n\t{ readonly issues: ReadonlyArray<Issue>; readonly context: Context }\n>();\n\nconst prepare = (history: Any) => {\n\tconst cached = contexts.get(history);\n\tif (cached !== undefined) return cached;\n\n\tconst prepared = { issues: validateDeclarations(history), context: makeContext(history) };\n\tcontexts.set(history, prepared);\n\n\treturn prepared;\n};\n\n/**\n * Lists declaration issues in a deterministic order. An empty list means valid.\n *\n * @since @next\n */\nexport const validate = (history: Any): ReadonlyArray<Issue> => prepare(history).issues;\n\nconst valid = (history: Any): Result.Result<Context, InvalidHistory> => {\n\tconst { issues, context } = prepare(history);\n\n\treturn issues.length === 0\n\t\t? Result.succeed(context)\n\t\t: Result.fail(new InvalidHistory({ issues }));\n};\n\n/**\n * Resolves an optimized plan between two versions. Planning needs no handlers or\n * execution services, and it never reads or modifies consumer files.\n *\n * When several routes connect the versions, resolution fails with `AmbiguousRoute`\n * unless the `route` option selects one or a route `policy` leaves exactly one.\n *\n * @example\n * ```ts\n * const result = History.resolve(history, { from: \"1.5.3\", to: \"2.0.0\" });\n * if (Result.isSuccess(result)) console.log(result.success.route.id);\n * ```\n *\n * @since @next\n */\nexport const resolve = <A extends Action.Any, C extends Change.Any>(\n\thistory: History<A, C>,\n\toptions: ResolveOptions,\n): Result.Result<Plan<A, \"static\", C>, ResolveError> =>\n\t// Every occurrence and change comes from the history's declarations, whose unions are\n\t// `A` and `C`.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\tResult.flatMap(valid(history), (context) => resolveRoute(context, options)) as Result.Result<\n\t\tPlan<A, \"static\", C>,\n\t\tResolveError\n\t>;\n\n/**\n * Destinations reachable by upgrade from a version, with their candidate routes.\n *\n * @since @next\n */\nexport const upgrades = (\n\thistory: Any,\n\toptions: { readonly from: Version | string },\n): Result.Result<ReadonlyArray<Destination>, InvalidHistory | UnknownVersion> =>\n\treachableFrom(history, options.from, \"upgrade\");\n\n/**\n * Destinations reachable by downgrade from a version, with their candidate routes.\n *\n * @since @next\n */\nexport const downgrades = (\n\thistory: Any,\n\toptions: { readonly from: Version | string },\n): Result.Result<ReadonlyArray<Destination>, InvalidHistory | UnknownVersion> =>\n\treachableFrom(history, options.from, \"downgrade\");\n\nconst reachableFrom = (history: Any, from: Version | string, kind: \"upgrade\" | \"downgrade\") =>\n\tResult.flatMap(valid(history), (context) =>\n\t\tResult.map(lookupVersion(context, from), (version) => destinations(context, version, kind)),\n\t);\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\nimport { isAction, isRef } from \"./action.ts\";\nimport { describeValue, dedent, isScalar, type Scalar } from \"./template.ts\";\n\n/**\n * Literal prose.\n *\n * @since @next\n */\nexport type Text = {\n\treadonly _tag: \"Text\";\n\treadonly text: string;\n};\n\n/**\n * Prose content: text and action mentions.\n *\n * @since @next\n */\nexport type Prose = ReadonlyArray<Text | Action.Ref>;\n\n/**\n * Values accepted inside prose templates.\n *\n * @since @next\n */\nexport type ProseValue = Scalar | Action.Ref;\n\n/**\n * Prose associated with exactly one action occurrence. The block declares that\n * occurrence; when optimization removes the action, the block leaves the resolved guide\n * with it.\n *\n * @since @next\n */\nexport type Instruction<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Instruction\";\n\treadonly action: A;\n\treadonly content: Prose;\n};\n\nexport const isInstruction = (value: unknown): value is Instruction =>\n\tPredicate.isTagged(value, \"Instruction\");\n\n/** Builds prose from a tagged template. Throws on values that are not text or mentions. */\nexport const prose = (\n\tstrings: ReadonlyArray<string>,\n\tvalues: ReadonlyArray<unknown>,\n\tcontext: string,\n): Prose => {\n\tconst literals = dedent(strings);\n\tconst content: Array<Text | Action.Ref> = [];\n\n\tconst pushText = (text: string) => {\n\t\tif (text === \"\") return;\n\n\t\tconst last = content.at(-1);\n\t\tif (last?._tag === \"Text\") {\n\t\t\tcontent[content.length - 1] = { _tag: \"Text\", text: last.text + text };\n\n\t\t\treturn;\n\t\t}\n\t\tcontent.push({ _tag: \"Text\", text });\n\t};\n\n\tfor (const [index, literal] of literals.entries()) {\n\t\tpushText(literal);\n\t\tif (index >= values.length) continue;\n\n\t\tconst value = values[index];\n\t\tif (isScalar(value)) {\n\t\t\tpushText(String(value));\n\t\t\tcontinue;\n\t\t}\n\t\tif (isRef(value)) {\n\t\t\tcontent.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isAction(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${context}: action \"${value.id}\" cannot be interpolated here because it would declare another occurrence. Use Action.ref(action) to mention it.`,\n\t\t\t);\n\t\t}\n\t\tthrow new TypeError(`${context}: cannot interpolate ${describeValue(value)}.`);\n\t}\n\n\treturn content;\n};\n\n/**\n * Associates prose with one action occurrence.\n *\n * @example\n * ```ts\n * Migration.instruction(renameTimeout)`\n * \tRename the timeout option, keeping its existing value.\n * `;\n * ```\n *\n * @since @next\n */\nexport const instruction =\n\t<A extends Action.Any>(action: A) =>\n\t(strings: TemplateStringsArray, ...values: ReadonlyArray<ProseValue>): Instruction<A> => ({\n\t\t_tag: \"Instruction\",\n\t\taction,\n\t\tcontent: prose(strings, values, `Instruction for \"${action.id}\"`),\n\t});\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\nimport { isAction, isParallel, isRef, isSequence } from \"./action.ts\";\nimport type * as Change from \"./change.ts\";\nimport { instruction, isInstruction, type Text } from \"./instruction.ts\";\nimport { describeValue, dedent, isScalar, type Scalar } from \"./template.ts\";\nimport type { Version } from \"./version.ts\";\n\nexport { instruction };\nexport type { Instruction, Prose, ProseValue, Text } from \"./instruction.ts\";\n\n/**\n * Prose, mentions, and occurrence-declaring steps in template order.\n *\n * @since @next\n */\nexport type Content<A extends Action.Any = Action.Any> = ReadonlyArray<\n\tText | Action.Ref | Action.Step<A>\n>;\n\n/**\n * Values accepted in migration templates.\n *\n * @since @next\n */\nexport type Interpolation = Scalar | Action.Ref | Action.Step;\n\n/** @since @next */\nexport type Migration<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"Migration\";\n\treadonly id: string;\n\treadonly from: Version;\n\treadonly to: Version;\n\t/** The logical changes this transition handles. */\n\treadonly addresses: ReadonlyArray<C>;\n\t/** Whether this is an explicit zero-work transition. */\n\treadonly noop: boolean;\n\t/** Author-declared cost, used only by the `lowest-cost` route policy. */\n\treadonly cost: number | undefined;\n\treadonly content: Content;\n\t/** The reverse transition, from `to` back to `from`. Absent means no reverse edge. */\n\treadonly revert: Content | undefined;\n\t/** Type-level record of the action instances in `content` and `revert`. */\n\treadonly \"~actions\"?: A;\n};\n\n/**\n * Any migration.\n *\n * @since @next\n */\nexport type Any = Migration<any>;\n\n/**\n * The action instances a migration can contribute to a plan.\n *\n * @since @next\n */\nexport type ActionsOf<M> = M extends Migration<infer A> ? A : never;\n\n/**\n * The changes a migration addresses.\n *\n * @since @next\n */\nexport type ChangesOf<M> = M extends Migration<any, infer C> ? C : never;\n\n/** @since @next */\nexport type Options<C extends Change.Any = Change.Any> = {\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly addresses?: ReadonlyArray<C>;\n\treadonly cost?: number;\n};\n\n/** @since @next */\nexport const isMigration = (value: unknown): value is Any => Predicate.isTagged(value, \"Migration\");\n\nconst isStep = (value: unknown): value is Action.Step =>\n\tisAction(value) || isInstruction(value) || isSequence(value) || isParallel(value);\n\nconst validateStep = (step: Action.Step, context: string): void => {\n\tif (isSequence(step)) {\n\t\tfor (const child of step.children) checkStep(child, context);\n\n\t\treturn;\n\t}\n\tif (isParallel(step)) {\n\t\tfor (const branch of step.branches) checkStep(branch, context);\n\t}\n};\n\nconst checkStep = (value: unknown, context: string): void => {\n\tif (!isStep(value)) {\n\t\tthrow new TypeError(\n\t\t\t`${context}: a group can only contain actions, instructions, and groups.`,\n\t\t);\n\t}\n\tvalidateStep(value, context);\n};\n\n/** Builds content from a tagged template. */\nconst content = (\n\tstrings: ReadonlyArray<string>,\n\tvalues: ReadonlyArray<unknown>,\n\tcontext: string,\n): Content => {\n\tconst literals = dedent(strings);\n\tconst result: Array<Text | Action.Ref | Action.Step> = [];\n\n\tconst pushText = (text: string) => {\n\t\tif (text === \"\") return;\n\n\t\tconst last = result.at(-1);\n\t\tif (last?._tag === \"Text\") {\n\t\t\tresult[result.length - 1] = { _tag: \"Text\", text: last.text + text };\n\n\t\t\treturn;\n\t\t}\n\t\tresult.push({ _tag: \"Text\", text });\n\t};\n\n\tfor (const [index, literal] of literals.entries()) {\n\t\tpushText(literal);\n\t\tif (index >= values.length) continue;\n\n\t\tconst value = values[index];\n\t\tif (isScalar(value)) {\n\t\t\tpushText(String(value));\n\t\t\tcontinue;\n\t\t}\n\t\tif (isRef(value)) {\n\t\t\tresult.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isStep(value)) {\n\t\t\tvalidateStep(value, context);\n\t\t\tresult.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new TypeError(`${context}: cannot interpolate ${describeValue(value)}.`);\n\t}\n\n\treturn result;\n};\n\n/**\n * Declares a migration between exact versions. Interpolated actions, instruction blocks,\n * and groups declare occurrences; `Action.ref` only mentions an action.\n *\n * @example\n * ```ts\n * const migrate152To200 = Migration.make(\"1.5.2-to-2.0.0\", {\n * \tfrom: v152,\n * \tto: v200,\n * \taddresses: [timeoutRenamed],\n * })`\n * \tUpdate the configuration for export A:\n *\n * \t${renameExportA}\n * `;\n * ```\n *\n * @since @next\n */\nexport const make =\n\t<C extends Change.Any = never>(id: string, options: Options<C>) =>\n\t<const V extends ReadonlyArray<Interpolation>>(\n\t\tstrings: TemplateStringsArray,\n\t\t...values: V\n\t): Migration<Action.ActionsOf<V[number]>, C> => ({\n\t\t_tag: \"Migration\",\n\t\tid,\n\t\tfrom: options.from,\n\t\tto: options.to,\n\t\taddresses: options.addresses ?? [],\n\t\tnoop: false,\n\t\tcost: options.cost,\n\t\tcontent: content(strings, values, `Migration \"${id}\"`),\n\t\trevert: undefined,\n\t});\n\n/** @since @next */\nexport type NoopOptions<C extends Change.Any = Change.Any> = Options<C> & {\n\t/** Also declares the reverse transition as zero-work. */\n\treadonly reversible?: boolean;\n};\n\n/**\n * Declares a supported transition that requires no consumer work. It is a directed edge\n * like any migration. Do not use it to hide missing support for changes that need\n * instructions.\n *\n * @since @next\n */\nexport const noop = <C extends Change.Any = never>(\n\tid: string,\n\toptions: NoopOptions<C>,\n): Migration<never, C> => ({\n\t_tag: \"Migration\",\n\tid,\n\tfrom: options.from,\n\tto: options.to,\n\taddresses: options.addresses ?? [],\n\tnoop: true,\n\tcost: options.cost,\n\tcontent: [],\n\trevert: options.reversible === true ? [] : undefined,\n});\n\n/**\n * Adds a reverse transition. Register the returned migration in place of the original:\n * both share the same identifier. On a `Migration.noop`, the reverse is real work: only\n * the forward side stays zero-work.\n *\n * @example\n * ```ts\n * const reversible = Migration.withRevert(migrate152To200)`\n * \tRestore the previous configuration:\n *\n * \t${restoreTimeout}\n * `;\n * ```\n *\n * @since @next\n */\nexport const withRevert =\n\t<A extends Action.Any, C extends Change.Any>(migration: Migration<A, C>) =>\n\t<const V extends ReadonlyArray<Interpolation>>(\n\t\tstrings: TemplateStringsArray,\n\t\t...values: V\n\t): Migration<A | Action.ActionsOf<V[number]>, C> => ({\n\t\t...migration,\n\t\trevert: content(strings, values, `Revert of migration \"${migration.id}\"`),\n\t});\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"../foundation/action.ts\";\nimport type { History } from \"./planning/history.ts\";\n\n/** @since @next */\nexport type Package<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Package\";\n\t/** The name of the modeled package, for example `@acme/widgets`. */\n\treadonly name: string;\n\treadonly history: History<A>;\n};\n\n/**\n * Defines the modeled package. It holds no renderer settings, release metadata, or\n * handlers.\n *\n * @example\n * ```ts\n * export const widgets = Package.make(\"@acme/widgets\", { history });\n * ```\n *\n * @since @next\n */\nexport const make = <A extends Action.Any>(\n\tname: string,\n\toptions: { readonly history: History<A> },\n): Package<A> => ({ _tag: \"Package\", name, history: options.history });\n\n/** @since @next */\nexport const isPackage = (value: unknown): value is Package<any> =>\n\tPredicate.isTagged(value, \"Package\");\n","import type * as Action from \"./action.ts\";\nimport type * as Change from \"./change.ts\";\nimport type { Instruction, Text } from \"./instruction.ts\";\nimport type * as Migration from \"./migration.ts\";\nimport type * as Rule from \"./rule.ts\";\nimport type * as Shortcut from \"./shortcut.ts\";\nimport type { Version } from \"./version.ts\";\n\n/**\n * Which side of a migration runs.\n *\n * @since @next\n */\nexport type Direction = \"forward\" | \"revert\";\n\n/**\n * How an occurrence entered the plan.\n *\n * @since @next\n */\nexport type Origin =\n\t| { readonly _tag: \"Declared\" }\n\t| {\n\t\t\treadonly _tag: \"Replacement\";\n\t\t\treadonly rule: Rule.Any;\n\t\t\t/** The occurrences the rule replaced, in order. */\n\t\t\treadonly replaces: ReadonlyArray<Occurrence>;\n\t };\n\n/**\n * One execution of an action instance in a plan. Its `id` is stable across prose edits:\n * it combines the migration, direction, and action identifiers, or the rule and the\n * replaced occurrences for a replacement.\n *\n * @since @next\n */\nexport type Occurrence<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Occurrence\";\n\t/**\n\t * Unique within the plan. Built from the migration, direction, and action identifiers,\n\t * or from the rule and the replaced occurrences. Separator characters in author\n\t * identifiers are escaped with a backslash, so identifiers never collide.\n\t */\n\treadonly id: string;\n\treadonly action: A;\n\t/** The migration whose step contains this occurrence. */\n\treadonly migration: Migration.Any;\n\treadonly direction: Direction;\n\t/** The instruction block that declared this occurrence, if any. */\n\treadonly instruction: Instruction | undefined;\n\treadonly origin: Origin;\n};\n\n/** @since @next */\nexport type Sequence<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Sequence\";\n\treadonly children: ReadonlyArray<Node<A>>;\n};\n\n/** @since @next */\nexport type Parallel<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Parallel\";\n\treadonly branches: ReadonlyArray<Node<A>>;\n\treadonly concurrency: Action.Concurrency;\n};\n\n/**\n * The declared execution structure.\n *\n * @since @next\n */\nexport type Node<A extends Action.Any = Action.Any> = Occurrence<A> | Sequence<A> | Parallel<A>;\n\n/**\n * Resolved prose for a guide. Occurrences render as their instruction or description.\n *\n * @since @next\n */\nexport type GuideItem<A extends Action.Any = Action.Any> =\n\t| Text\n\t| Action.Ref\n\t| { readonly _tag: \"Occurrence\"; readonly occurrence: Occurrence<A> }\n\t| {\n\t\t\treadonly _tag: \"Group\";\n\t\t\treadonly kind: \"Sequence\" | \"Parallel\";\n\t\t\t/** One entry per retained child or branch. */\n\t\t\treadonly children: ReadonlyArray<ReadonlyArray<GuideItem<A>>>;\n\t };\n\n/**\n * One migration in the route. Steps are sequential barriers: a step starts only after\n * the previous step completed.\n *\n * @since @next\n */\nexport type Step<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Step\";\n\treadonly migration: Migration.Any;\n\treadonly direction: Direction;\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly node: Sequence<A>;\n\t/** Resolved guide content. Empty when the step is omitted from the guide. */\n\treadonly guide: ReadonlyArray<GuideItem<A>>;\n\t/**\n\t * Whether the normal resolved guide leaves this step out: a noop, or a migration whose\n\t * actions were all removed by rules.\n\t */\n\treadonly omitted: boolean;\n};\n\n/**\n * Why the plan differs from the declared migrations.\n *\n * @since @next\n */\nexport type Explanation =\n\t| {\n\t\t\treadonly _tag: \"Rewrite\";\n\t\t\treadonly rule: Rule.Any;\n\t\t\treadonly removed: ReadonlyArray<Occurrence>;\n\t\t\treadonly produced: ReadonlyArray<Occurrence>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"OmittedStep\";\n\t\t\treadonly migration: Migration.Any;\n\t\t\treadonly direction: Direction;\n\t\t\treadonly reason: \"noop\" | \"all-actions-removed\";\n\t };\n\n/**\n * A hop in a route: the migrations between two versions, or a shortcut.\n *\n * @since @next\n */\nexport type Hop =\n\t| {\n\t\t\treadonly _tag: \"Migrations\";\n\t\t\treadonly from: Version;\n\t\t\treadonly to: Version;\n\t\t\t/**\n\t\t\t * The migration side that moves between these versions. Validation allows one\n\t\t\t * side per transition, so this holds exactly one entry.\n\t\t\t */\n\t\t\treadonly migrations: ReadonlyArray<{\n\t\t\t\treadonly migration: Migration.Any;\n\t\t\t\treadonly direction: Direction;\n\t\t\t}>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"Shortcut\";\n\t\t\treadonly from: Version;\n\t\t\treadonly to: Version;\n\t\t\treadonly shortcut: Shortcut.Any;\n\t };\n\n/** @since @next */\nexport type Route = {\n\t/**\n\t * Identifies the route for explicit selection: version identifiers joined by `>`,\n\t * with shortcut hops written as `[shortcut-id]`. A backslash escapes `\\`, `>`, `[`,\n\t * and `]` inside identifiers, so a version `a>b` appears as `a\\>b`.\n\t */\n\treadonly id: string;\n\treadonly hops: ReadonlyArray<Hop>;\n};\n\n/**\n * How the requested target relates to the source in release ancestry.\n *\n * @since @next\n */\nexport type RequestDirection = \"none\" | \"upgrade\" | \"downgrade\" | \"cross-branch\";\n\n/**\n * When executors check handler coverage. Static plans also expose uncovered actions in\n * the execution's type.\n *\n * @since @next\n */\nexport type Coverage = \"static\" | \"runtime\";\n\n/**\n * A resolved, optimized route between two versions. Every step stays traceable to its\n * migration and the changes that migration addresses.\n *\n * @since @next\n */\nexport type Plan<\n\tA extends Action.Any = Action.Any,\n\tC extends Coverage = \"static\",\n\tCh extends Change.Any = Change.Any,\n> = {\n\treadonly _tag: \"Plan\";\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly direction: RequestDirection;\n\treadonly route: Route;\n\treadonly steps: ReadonlyArray<Step<A>>;\n\t/** Occurrences in plan order. */\n\treadonly occurrences: ReadonlyArray<Occurrence<A>>;\n\t/** The changes addressed by the route's migrations. */\n\treadonly changes: ReadonlyArray<Ch>;\n\treadonly explanations: ReadonlyArray<Explanation>;\n\t/**\n\t * Whether executors check handler coverage only at run time. Plans resolved from a\n\t * history are checked statically against its conservative action union.\n\t */\n\treadonly coverage: C;\n};\n\n/**\n * Any plan.\n *\n * @since @next\n */\nexport type Any = Plan<any, any>;\n\n/**\n * The action instances of a plan.\n *\n * @since @next\n */\nexport type ActionsOf<P> = P extends Plan<infer A, any> ? A : never;\n\n/**\n * Whether the plan has no action occurrences. An empty plan is valid.\n *\n * @since @next\n */\nexport const isEmpty = (plan: Any): boolean => plan.occurrences.length === 0;\n\n/**\n * Marks a plan for run-time coverage checks only. Use it for dynamically selected or\n * loaded plans whose action union is not known statically. Executors still reject\n * missing handlers before any action body runs.\n *\n * @since @next\n */\nexport const withRuntimeCoverage = <A extends Action.Any, Ch extends Change.Any>(\n\tplan: Plan<A, Coverage, Ch>,\n): Plan<A, \"runtime\", Ch> => ({\n\t...plan,\n\tcoverage: \"runtime\",\n});\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\n\n/**\n * What a rule matches: an action instance, or a parallel group matched by its branch\n * structure. Matching a parallel group is an explicit structural rule.\n *\n * @since @next\n */\nexport type Pattern = Action.Any | Action.Parallel;\n\n/** @since @next */\nexport type Rule<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Rule\";\n\treadonly id: string;\n\treadonly match: ReadonlyArray<Pattern>;\n\t/** Steps that take the place of the match. An empty replacement cancels it. */\n\treadonly replacement: ReadonlyArray<Action.Step<A>>;\n};\n\n/**\n * Any rule.\n *\n * @since @next\n */\nexport type Any = Rule<any>;\n\n/**\n * The action instances a rule can contribute to a plan.\n *\n * @since @next\n */\nexport type ActionsOf<R> = R extends Rule<infer A> ? A : never;\n\n/**\n * Declares a replacement. Cancellation, composition, and supersession all use it.\n *\n * The author asserts that the replacement is equivalent to the matched occurrences.\n * deltafold checks the rule's structure and where it applies, but it cannot prove the\n * equivalence.\n *\n * Ordinary rules match consecutive occurrences inside one sequential branch, including\n * across migration boundaries of a route. They never match across parallel branches.\n *\n * @example\n * ```ts\n * const cancelRoundTrip = Rule.replace(\"cancel-timeout-round-trip\", {\n * \tmatch: [renameTimeout, restoreTimeout],\n * \treplacement: [],\n * });\n * const combineRenames = Rule.replace(\"combine-renames\", {\n * \tmatch: [renameAtoB, renameBtoC],\n * \treplacement: [renameAtoC],\n * });\n * ```\n *\n * @since @next\n */\nexport const replace = <A extends Action.Any = never>(\n\tid: string,\n\toptions: {\n\t\treadonly match: ReadonlyArray<Pattern>;\n\t\treadonly replacement: ReadonlyArray<Action.Step<A>>;\n\t},\n): Rule<A> => ({\n\t_tag: \"Rule\",\n\tid,\n\tmatch: options.match,\n\treplacement: options.replacement,\n});\n\n/** @since @next */\nexport const isRule = (value: unknown): value is Any => Predicate.isTagged(value, \"Rule\");\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\nimport type * as Change from \"./change.ts\";\nimport type * as Migration from \"./migration.ts\";\nimport type { Version } from \"./version.ts\";\n\n/** @since @next */\nexport type Shortcut<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"Shortcut\";\n\treadonly id: string;\n\treadonly from: Version;\n\treadonly to: Version;\n\t/** The canonical route this shortcut replaces, in order. */\n\treadonly replaces: ReadonlyArray<Migration.Any>;\n\t/** The migrations that run instead, in order. */\n\treadonly migrations: ReadonlyArray<Migration.Migration<A, C>>;\n\t/** Author-declared cost, used only by the `lowest-cost` route policy. */\n\treadonly cost: number | undefined;\n};\n\n/**\n * Any shortcut.\n *\n * @since @next\n */\nexport type Any = Shortcut<any>;\n\n/**\n * The action instances a shortcut can contribute to a plan.\n *\n * @since @next\n */\nexport type ActionsOf<S> = S extends Shortcut<infer A> ? A : never;\n\n/**\n * The changes addressed by a shortcut's migrations.\n *\n * @since @next\n */\nexport type ChangesOf<S> = S extends Shortcut<any, infer C> ? C : never;\n\n/**\n * Declares a shortcut. The author asserts that its migrations are equivalent to the\n * canonical route it replaces; deltafold does not prove it.\n *\n * @example\n * ```ts\n * const fastUpgrade = Shortcut.make(\"fast-upgrade\", {\n * \tfrom: v201,\n * \tto: v208,\n * \treplaces: [migrate202, migrate203, migrate204],\n * \tmigrations: [migrateDirectlyTo208],\n * });\n * ```\n *\n * @since @next\n */\nexport const make = <A extends Action.Any, C extends Change.Any = never>(\n\tid: string,\n\toptions: {\n\t\treadonly from: Version;\n\t\treadonly to: Version;\n\t\treadonly replaces: ReadonlyArray<Migration.Any>;\n\t\treadonly migrations: ReadonlyArray<Migration.Migration<A, C>>;\n\t\treadonly cost?: number;\n\t},\n): Shortcut<A, C> => ({\n\t_tag: \"Shortcut\",\n\tid,\n\tfrom: options.from,\n\tto: options.to,\n\treplaces: options.replaces,\n\tmigrations: options.migrations,\n\tcost: options.cost,\n});\n\n/** @since @next */\nexport const isShortcut = (value: unknown): value is Any => Predicate.isTagged(value, \"Shortcut\");\n","import { Predicate } from \"effect\";\n\nimport type * as Change from \"./change.ts\";\n\n/** @since @next */\nexport type Version<C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"Version\";\n\treadonly id: string;\n\t/**\n\t * The release this version descends from. Absent for a root such as `0.0.0`. Only\n\t * this field sets ancestry: several versions can share a predecessor, and declaration\n\t * order and semver order have no effect.\n\t */\n\treadonly previous: Version | undefined;\n\t/** The changes that shipped in this release. */\n\treadonly changes: ReadonlyArray<C>;\n};\n\n/** @since @next */\nexport type Options<C extends Change.Any = Change.Any> = {\n\treadonly previous?: Version;\n\treadonly changes: ReadonlyArray<C>;\n};\n\n/**\n * Declares a version.\n *\n * @example\n * ```ts\n * const v0 = Version.make(\"0.0.0\", { changes: [] });\n * const v100 = Version.make(\"1.0.0\", { previous: v0, changes: [timeoutRenamed] });\n * ```\n *\n * @since @next\n */\nexport const make = <C extends Change.Any = never>(\n\tid: string,\n\toptions: Options<C>,\n): Version<C> => ({\n\t_tag: \"Version\",\n\tid,\n\tprevious: options.previous,\n\tchanges: options.changes,\n});\n\n/** @since @next */\nexport const isVersion = (value: unknown): value is Version => Predicate.isTagged(value, \"Version\");\n\n/**\n * Release metadata attached to a version by release tooling. It does not modify the\n * version registered in history.\n *\n * @since @next\n */\nexport type Release<M> = {\n\treadonly _tag: \"Release\";\n\treadonly version: Version;\n\treadonly metadata: M;\n};\n\n/**\n * Annotates a version with release metadata.\n *\n * @example\n * ```ts\n * export const release200 = Version.withMetadata(v200, {\n * \treleasedAt: \"2026-11-06T12:00:00Z\",\n * \tcommit: \"abc123\",\n * });\n * ```\n *\n * @since @next\n */\nexport const withMetadata = <const M>(version: Version, metadata: M): Release<M> => ({\n\t_tag: \"Release\",\n\tversion,\n\tmetadata,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,MAAaA,YACZ,MACA,UAA0D,CAAC,MAC9C;CACb,MAAM,WAAW,QAAQ,mBAAmB;CAE5C,OAAO;EACN,MAAM;EACN;EACA;EACA,OAAO,IAAI,aAAa;GACvB,MAAM;GACN;GACA;GACA;GACA,aAAa,SAAS,OAAO;EAC9B;CACD;AACD;;;;;;AAOA,MAAa,OAAO,YAAsB;CAAE,MAAM;CAAa;AAAO;;;;;;AAOtE,MAAa,YACZ,cACqC;CAAE,MAAM;CAAY;AAAS;;;;;;;AAQnE,MAAa,YACZ,UACA,UAAkD,CAAC,OACd;CACrC,MAAM;CACN;CACA,aAAa,QAAQ,eAAe;AACrC;;AAGA,MAAa,YAAY,UACxB,UAAU,SAAS,OAAO,QAAQ,KAAK,UAAU,YAAY,OAAO,IAAI;;AAGz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;AAGA,MAAa,cAAc,UAAiC,UAAU,SAAS,OAAO,UAAU;;;;;;;;;;;;;;;;;;AC3ChG,MAAa,QACZ,IACA,aACiB;CACjB,MAAM;CACN;CACA,UAAU,QAAQ;CAClB,SAAS,QAAQ;AAClB;;AAGA,MAAa,aAAa,UAAqC,UAAU,SAAS,OAAO,SAAS;;;;;;;;;;;;;;AA2BlG,MAAa,gBAAyB,SAAkB,cAA6B;CACpF,MAAM;CACN;CACA;AACD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["define","make","TypeId","make","promise","effect","summaryOf","noop","effect","TypeId","promise","effect","Arr","replace","validate","Arr","Arr","resolve","make","validateDeclarations","resolveRoute","lookupVersion","make","make","make"],"sources":["../src/foundation/action.ts","../src/foundation/template.ts","../src/foundation/change.ts","../src/features/execution/settlement.ts","../src/features/execution/promise-callback.ts","../src/features/execution/handler.ts","../src/features/execution/observation.ts","../src/features/execution/executor.ts","../src/features/execution/interaction.ts","../src/features/planning/resolve-error.ts","../src/features/planning/guide.ts","../src/features/planning/identifiers.ts","../src/features/planning/rewrite.ts","../src/features/planning/validate.ts","../src/features/planning/resolve.ts","../src/features/planning/history.ts","../src/foundation/instruction.ts","../src/foundation/migration.ts","../src/features/execution/observer.ts","../src/features/package.ts","../src/foundation/plan.ts","../src/foundation/rule.ts","../src/foundation/shortcut.ts","../src/foundation/version.ts"],"sourcesContent":["import { Predicate } from \"effect\";\n\nimport type { Instruction } from \"./instruction.ts\";\n\n/**\n * Describes one kind of consumer-owned operation and its payload.\n *\n * @since 0.0.1\n */\nexport type Kind<P> = {\n\treadonly _tag: \"ActionKind\";\n\treadonly kind: string;\n\treadonly describe: (payload: P) => string;\n\t/** Creates an action instance with a stable identifier. */\n\treadonly make: <const Id extends string>(id: Id, payload: P) => Action<Id, P>;\n};\n\n/**\n * One concrete instruction. Its `id` identifies the instruction across plans, handler\n * bindings, rules, and reports.\n *\n * @since 0.0.1\n */\nexport type Action<Id extends string = string, P = unknown> = {\n\treadonly _tag: \"Action\";\n\treadonly id: Id;\n\treadonly kind: string;\n\treadonly payload: P;\n\t/** The description produced by the kind's `describe` function. */\n\treadonly description: string;\n};\n\n/**\n * Any action instance.\n *\n * @since 0.0.1\n */\nexport type Any = Action<string, any>;\n\n/**\n * A mention of an action in prose. It does not declare an occurrence.\n *\n * @since 0.0.1\n */\nexport type Ref = {\n\treadonly _tag: \"ActionRef\";\n\treadonly action: Any;\n};\n\n/**\n * Children run one after another.\n *\n * @since 0.0.1\n */\nexport type Sequence<A extends Any = Any> = {\n\treadonly _tag: \"Sequence\";\n\treadonly children: ReadonlyArray<Step>;\n\t/** Type-level record of the action instances in `children`. */\n\treadonly \"~actions\"?: A;\n};\n\n/**\n * How many branches of a parallel group may run at the same time.\n *\n * @since 0.0.1\n */\nexport type Concurrency = number | \"unbounded\";\n\n/**\n * Branches are independent of each other and may run concurrently. The group asserts\n * that independence; the concurrency limit only controls scheduling.\n *\n * @since 0.0.1\n */\nexport type Parallel<A extends Any = Any> = {\n\treadonly _tag: \"Parallel\";\n\treadonly branches: ReadonlyArray<Step>;\n\treadonly concurrency: Concurrency;\n\t/** Type-level record of the action instances in `branches`. */\n\treadonly \"~actions\"?: A;\n};\n\n/**\n * A node that declares action occurrences.\n *\n * @since 0.0.1\n */\nexport type Step<A extends Any = Any> = A | Instruction<A> | Sequence<A> | Parallel<A>;\n\n/**\n * Extracts the action instances declared by a step.\n *\n * @since 0.0.1\n */\nexport type ActionsOf<S> =\n\tS extends Action<infer Id, infer P>\n\t\t? Action<Id, P>\n\t\t: S extends Instruction<infer A>\n\t\t\t? A\n\t\t\t: S extends Sequence<infer A>\n\t\t\t\t? A\n\t\t\t\t: S extends Parallel<infer A>\n\t\t\t\t\t? A\n\t\t\t\t\t: never;\n\n/**\n * Defines an action kind.\n *\n * @example\n * ```ts\n * const RenameKey = Action.define<{ target: string; from: string; to: string }>(\n * \t\"config.rename\",\n * \t{ describe: ({ target, from, to }) => `In ${target}, rename \"${from}\" to \"${to}\"` },\n * );\n * const renameExportA = RenameKey.make(\"rename-export-a-timeout\", {\n * \ttarget: \"export-a\",\n * \tfrom: \"timeout\",\n * \tto: \"requestTimeout\",\n * });\n * ```\n *\n * @since 0.0.1\n */\nexport const define = <P>(\n\tkind: string,\n\toptions: { readonly describe?: (payload: P) => string } = {},\n): Kind<P> => {\n\tconst describe = options.describe ?? (() => kind);\n\n\treturn {\n\t\t_tag: \"ActionKind\",\n\t\tkind,\n\t\tdescribe,\n\t\tmake: (id, payload) => ({\n\t\t\t_tag: \"Action\",\n\t\t\tid,\n\t\t\tkind,\n\t\t\tpayload,\n\t\t\tdescription: describe(payload),\n\t\t}),\n\t};\n};\n\n/**\n * Mentions an action in prose without declaring another occurrence.\n *\n * @since 0.0.1\n */\nexport const ref = (action: Any): Ref => ({ _tag: \"ActionRef\", action });\n\n/**\n * Declares steps that run one after another.\n *\n * @since 0.0.1\n */\nexport const sequence = <const S extends ReadonlyArray<Step>>(\n\tchildren: S,\n): Sequence<ActionsOf<S[number]>> => ({ _tag: \"Sequence\", children });\n\n/**\n * Declares independent branches that may run concurrently. Each branch can be a single\n * step or a sequence.\n *\n * @since 0.0.1\n */\nexport const parallel = <const S extends ReadonlyArray<Step>>(\n\tbranches: S,\n\toptions: { readonly concurrency?: Concurrency } = {},\n): Parallel<ActionsOf<S[number]>> => ({\n\t_tag: \"Parallel\",\n\tbranches,\n\tconcurrency: options.concurrency ?? \"unbounded\",\n});\n\n/** @since 0.0.1 */\nexport const isAction = (value: unknown): value is Any =>\n\tPredicate.isTagged(value, \"Action\") && Predicate.hasProperty(value, \"id\");\n\n/** @since 0.0.1 */\nexport const isRef = (value: unknown): value is Ref => Predicate.isTagged(value, \"ActionRef\");\n\n/** @since 0.0.1 */\nexport const isSequence = (value: unknown): value is Sequence =>\n\tPredicate.isTagged(value, \"Sequence\");\n\n/** @since 0.0.1 */\nexport const isParallel = (value: unknown): value is Parallel =>\n\tPredicate.isTagged(value, \"Parallel\");\n","import dedentText from \"dedent\";\n\nconst placeholder = \"\\u0000\";\n\n/**\n * Removes the common indentation of a tagged template and its surrounding whitespace.\n *\n * Returns one literal string per original literal, so interpolated values stay at their\n * positions and are never stringified or re-indented.\n */\nexport const dedent = (strings: ReadonlyArray<string>): ReadonlyArray<string> =>\n\tdedentText(strings.join(placeholder)).split(placeholder);\n\n/** Scalar values that interpolate as text. */\nexport type Scalar = string | number | boolean | bigint;\n\nexport const isScalar = (value: unknown): value is Scalar =>\n\ttypeof value === \"string\" ||\n\ttypeof value === \"number\" ||\n\ttypeof value === \"boolean\" ||\n\ttypeof value === \"bigint\";\n\nexport const describeValue = (value: unknown): string => {\n\tif (value === null) return \"null\";\n\tif (Array.isArray(value)) return \"an array\";\n\n\treturn typeof value === \"object\" ? \"an object\" : typeof value;\n};\n","import { Predicate } from \"effect\";\n\nimport { describeValue, dedent, isScalar, type Scalar } from \"./template.ts\";\n\n/**\n * The metadata of a change whose shape is not known statically.\n *\n * @since 0.0.1\n */\nexport type Metadata = { readonly [field: string]: unknown };\n\n/** @since 0.0.1 */\nexport type NoMetadata = { readonly [field: string]: undefined };\n\n/**\n * A human-readable record of one logical change. A change can exist before it is\n * assigned to a release, and it does not need an executable migration.\n *\n * deltafold does not interpret `metadata`. Consumers choose its fields, such as a\n * classification or a breaking flag, and what they mean.\n *\n * @since 0.0.1\n */\nexport type Change<M extends object = Metadata> = {\n\treadonly _tag: \"Change\";\n\t/** Stable identifier. Editing the description does not change identity. */\n\treadonly id: string;\n\treadonly metadata: M;\n\treadonly description: string;\n\t/** Historical relationship only: it does not cancel actions or create routes. */\n\treadonly reverts: ReadonlyArray<Any>;\n\t/** The change that an adapted backport was derived from. */\n\treadonly backportOf: Any | undefined;\n};\n\n/**\n * A change whose metadata type is not known statically. Its metadata is an object, so\n * reading a field requires narrowing first.\n *\n * @since 0.0.1\n */\nexport type Any = Change<object>;\n\n/**\n * Relationships to other changes.\n *\n * @since 0.0.1\n */\nexport type Relations = {\n\treadonly reverts?: ReadonlyArray<Any>;\n\treadonly backportOf?: Any;\n};\n\n/**\n * Takes the description as a tagged template and returns the change.\n *\n * @since 0.0.1\n */\nexport type Describe<M extends object> = (\n\tstrings: TemplateStringsArray,\n\t...values: ReadonlyArray<Scalar>\n) => Change<M>;\n\nconst describe =\n\t<M extends object>(id: string, metadata: M, relations: Relations): Describe<M> =>\n\t(strings, ...values) => {\n\t\tconst literals = dedent(strings);\n\t\tlet description = \"\";\n\t\tfor (const [index, literal] of literals.entries()) {\n\t\t\tdescription += literal;\n\t\t\tif (index >= values.length) continue;\n\n\t\t\tconst value: unknown = values[index];\n\t\t\tif (!isScalar(value)) {\n\t\t\t\tthrow new TypeError(`Change \"${id}\": cannot interpolate ${describeValue(value)}.`);\n\t\t\t}\n\t\t\tdescription += String(value);\n\t\t}\n\n\t\treturn {\n\t\t\t_tag: \"Change\",\n\t\t\tid,\n\t\t\tmetadata,\n\t\t\tdescription,\n\t\t\treverts: relations.reverts ?? [],\n\t\t\tbackportOf: relations.backportOf,\n\t\t};\n\t};\n\n/**\n * Declares a change. The tagged template is its description. Metadata is optional, and\n * its type is inferred from the value, literals included.\n *\n * @example\n * ```ts\n * const retriesAdded = Change.make(\"2026-11-20.add-retries\")`\n * \tAdd a retry limit option.\n * `;\n * const timeoutRenamed = Change.make(\"2026-11-06.rename-timeout\", { breaking: true })`\n * \tRename the timeout configuration option to requestTimeout.\n * `;\n * ```\n *\n * @since 0.0.1\n */\nexport function make(id: string): Describe<NoMetadata>;\nexport function make<const M extends object>(\n\tid: string,\n\tmetadata: M,\n\trelations?: Relations,\n): Describe<M>;\nexport function make(id: string, metadata: object = {}, relations: Relations = {}) {\n\treturn describe(id, metadata, relations);\n}\n\n/**\n * Makes changes that share one metadata shape.\n *\n * @since 0.0.1\n */\nexport type Definition<M extends object> = {\n\treadonly make: (id: string, metadata: M, relations?: Relations) => Describe<M>;\n};\n\n/**\n * Defines a reusable change factory whose metadata must have the type `M`.\n *\n * @example\n * ```ts\n * const ConfigChange = Change.define<{\n * \treadonly kind: \"added\" | \"changed\" | \"fixed\";\n * \treadonly breaking: boolean;\n * }>();\n * const timeoutRenamed = ConfigChange.make(\"2026-11-06.rename-timeout\", {\n * \tkind: \"changed\",\n * \tbreaking: true,\n * })`\n * \tRename the timeout configuration option to requestTimeout.\n * `;\n * ```\n *\n * @since 0.0.1\n */\nexport const define = <M extends object>(): Definition<M> => ({ make: make<M> });\n\n/** @since 0.0.1 */\nexport const isChange = (value: unknown): value is Change => Predicate.isTagged(value, \"Change\");\n","import { Context, Duration, Effect, Option } from \"effect\";\n\n/**\n * How the executor learns whether an interrupted Promise callback settled. Effect stops\n * waiting for a Promise when it is interrupted, but the Promise itself can keep running.\n */\nexport type Settlement = {\n\t/** How long to keep waiting for an interrupted Promise before reporting it pending. */\n\treadonly grace: Duration.Input;\n\t/** Receives an interrupted Promise that did not settle within the grace period. */\n\treadonly unsettled: (promise: Promise<void>) => void;\n};\n\nexport const SettlementReference = Context.Reference<Settlement>(\"deltafold/Settlement\", {\n\tdefaultValue: () => ({ grace: Duration.zero, unsettled: () => {} }),\n});\n\n/**\n * Runs a Promise-producing effect. If it is interrupted after the Promise started,\n * waits up to the settlement grace period and hands a still-pending Promise to the\n * settlement, which can hold resources until it settles.\n */\nexport const trackPromise = <T, E, R>(\n\tstart: (capture: (promise: Promise<T>) => Promise<T>) => Effect.Effect<T, E, R>,\n): Effect.Effect<T, E, R> =>\n\tEffect.suspend(() => {\n\t\tlet pending: Promise<T> | undefined;\n\t\tconst capture = (promise: Promise<T>) => {\n\t\t\tpending = promise;\n\n\t\t\treturn promise;\n\t\t};\n\n\t\treturn start(capture).pipe(\n\t\t\tEffect.onInterrupt(() =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst started = pending;\n\t\t\t\t\tif (started === undefined) return;\n\n\t\t\t\t\tconst settles = started.then(\n\t\t\t\t\t\t() => undefined,\n\t\t\t\t\t\t() => undefined,\n\t\t\t\t\t);\n\t\t\t\t\tconst settlement = yield* SettlementReference;\n\t\t\t\t\tconst settled = yield* Effect.promise(() => settles).pipe(\n\t\t\t\t\t\tEffect.timeoutOption(settlement.grace),\n\t\t\t\t\t);\n\t\t\t\t\tif (Option.isNone(settled)) settlement.unsettled(settles);\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t});\n","import { Context, Effect, Schema } from \"effect\";\n\nimport type { ValueOf } from \"../../types.ts\";\nimport { trackPromise } from \"./settlement.ts\";\n\n/** Named Effect services that Promise callbacks declare. */\nexport type ServiceMap = { readonly [name: string | symbol]: Context.Key<any, any> };\n\n// oxlint-disable-next-line typescript/no-generated-empty-object-type -- Callbacks without services declare an empty service map.\nexport type NoServices = Record<never, never>;\n\n/** The `AbortSignal` aborted on interruption, and the declared services, resolved. */\nexport type PromiseContext<S extends ServiceMap = NoServices> = {\n\treadonly signal: AbortSignal;\n\treadonly services: { readonly [K in keyof S]: S[K][\"Service\"] };\n};\n\nexport type ServiceIds<S extends ServiceMap> = ValueOf<{\n\t[K in keyof S]: S[K] extends Context.Key<infer I, any> ? I : never;\n}>;\n\n/** Recognizes a declared rejection: a schema, or a type guard. */\nexport type ErrorGuard = Schema.Top | ((cause: unknown) => cause is any);\n\nexport type GuardedError<G> = G extends Schema.Top\n\t? G[\"Type\"]\n\t: G extends ((cause: unknown) => cause is infer E)\n\t\t? E\n\t\t: never;\n\nconst declaredError =\n\t<G extends ReadonlyArray<ErrorGuard>>(guards: G) =>\n\t(cause: unknown): cause is GuardedError<G[number]> =>\n\t\tguards.some((guard) => (Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause)));\n\n/**\n * Turns Promise callbacks into Effects. Declared services are resolved before each\n * call, rejections that a guard recognizes keep their type, and `unexpected` wraps the\n * rest.\n */\nexport const adaptPromise = <S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>>(options: {\n\treadonly services?: S | undefined;\n\treadonly errors?: G | undefined;\n}) => {\n\tconst isDeclared = declaredError(options.errors ?? []);\n\tconst services: ServiceMap = options.services ?? {};\n\t// The callbacks require exactly the declared services. Reading them from the context\n\t// keeps that requirement typed; only the record of resolved services needs a cast,\n\t// because Object.fromEntries does not track keys.\n\tconst resolve = Effect.map(\n\t\tEffect.context<ServiceIds<S>>(),\n\t\t(context) =>\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\t\t\tObject.fromEntries(\n\t\t\t\tReflect.ownKeys(services).map((name) => [\n\t\t\t\t\tname,\n\t\t\t\t\tContext.get(context, services[name]!),\n\t\t\t\t]),\n\t\t\t) as { readonly [K in keyof S]: S[K][\"Service\"] },\n\t);\n\n\treturn <T, U>(\n\t\tcallback: (context: PromiseContext<S>) => PromiseLike<T> | T,\n\t\tunexpected: (cause: unknown) => U,\n\t): Effect.Effect<T, GuardedError<G[number]> | U, ServiceIds<S>> =>\n\t\tEffect.flatMap(resolve, (resolved) =>\n\t\t\ttrackPromise((capture) =>\n\t\t\t\tEffect.tryPromise({\n\t\t\t\t\t// Declaring `signal` makes Effect.tryPromise allocate an AbortController.\n\t\t\t\t\ttry: (signal) =>\n\t\t\t\t\t\tcapture(Promise.resolve(callback({ signal, services: resolved }))),\n\t\t\t\t\tcatch: (cause) => (isDeclared(cause) ? cause : unexpected(cause)),\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n};\n","import { Data, Effect, Predicate, Scope } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Callback from \"./promise-callback.ts\";\nimport { adaptPromise } from \"./promise-callback.ts\";\n\ntype NoServices = Callback.NoServices;\ntype ServiceIds<S extends ServiceMap> = Callback.ServiceIds<S>;\ntype GuardedError<G> = Callback.GuardedError<G>;\n\n/**\n * Where a handler failure or interruption happened: the read-only prepare phase, or the\n * apply phase that changes state. A manual handler has neither: the executor waits for a\n * person in `confirmation`, then runs the handler's optional check in `verification`.\n *\n * @since 0.0.1\n */\nexport type Phase = \"prepare\" | \"apply\" | \"confirmation\" | \"verification\";\n\n/**\n * Who performs an action: a handler's apply phase, or a person whose confirmation the\n * executor waits for.\n *\n * @since 0.2.0\n */\nexport type Performer = \"automated\" | \"manual\";\n\n/**\n * A person confirmed manual work, and the handler's `verify` check returned `false`.\n *\n * @since 0.2.0\n */\nexport class VerificationFailed extends Data.TaggedError(\"VerificationFailed\")<{\n\treadonly actionId: string;\n\treadonly kind: string;\n}> {\n\toverride get message() {\n\t\treturn `Manual work for action \"${this.actionId}\" was confirmed, but its verification check did not pass`;\n\t}\n}\n\n/**\n * A Promise handler rejected or threw a value that none of its declared error guards\n * recognized, or its prepare phase returned something other than `Handler.prepared` or\n * `Handler.skip`.\n *\n * @since 0.0.1\n */\nexport class UnexpectedHandlerError extends Data.TaggedError(\"UnexpectedHandlerError\")<{\n\treadonly actionId: string;\n\treadonly kind: string;\n\treadonly phase: Phase;\n\treadonly cause: unknown;\n}> {\n\toverride get message() {\n\t\treturn `Handler for action \"${this.actionId}\" failed unexpectedly in its ${this.phase} phase`;\n\t}\n}\n\nconst PreparationTypeId = \"~deltafold/Preparation\";\n\n/**\n * A prepare phase decided to apply. The apply phase receives `value` unchanged; the\n * executor never reads, validates, or serializes it.\n *\n * @since 0.1.0\n */\nexport type Prepared<out P> = {\n\treadonly [PreparationTypeId]: typeof PreparationTypeId;\n\treadonly _tag: \"Prepared\";\n\treadonly value: P;\n};\n\n/**\n * A prepare phase decided that the action does not apply. The occurrence is skipped\n * with `reason`.\n *\n * @since 0.1.0\n */\nexport type Skip = {\n\treadonly [PreparationTypeId]: typeof PreparationTypeId;\n\treadonly _tag: \"Skip\";\n\treadonly reason: string;\n};\n\n/**\n * What a prepare phase returns: `Handler.prepared(value)` or `Handler.skip(reason)`.\n *\n * @since 0.1.0\n */\nexport type Preparation<P> = Prepared<P> | Skip;\n\n/** The value that a prepare phase passes to its apply phase. */\ntype PreparedValue<T> = T extends Prepared<infer P> ? P : never;\n\n/**\n * Ends a prepare phase with the value its apply phase receives. Wrapping the value keeps\n * it apart from a skip, whatever its shape.\n *\n * @since 0.1.0\n */\nexport function prepared(): Prepared<void>;\nexport function prepared<P>(value: P): Prepared<P>;\nexport function prepared(value?: unknown): Prepared<unknown> {\n\treturn { [PreparationTypeId]: PreparationTypeId, _tag: \"Prepared\", value };\n}\n\n/**\n * Ends a prepare phase by skipping the occurrence. The apply phase does not run.\n *\n * @since 0.1.0\n */\nexport const skip = (reason: string): Skip => ({\n\t[PreparationTypeId]: PreparationTypeId,\n\t_tag: \"Skip\",\n\treason,\n});\n\nconst isPreparation = (value: unknown): value is Preparation<unknown> =>\n\tPredicate.hasProperty(value, PreparationTypeId);\n\nconst notAPreparation = () =>\n\tnew TypeError(\"A prepare phase must return Handler.prepared(value) or Handler.skip(reason)\");\n\n/**\n * How an occurrence continues after its prepare phase: skipped, applied by an effect\n * that already holds the prepared value, or confirmed by a person. `verify` checks\n * confirmed work and fails when the check does not pass.\n *\n * @since 0.1.0\n */\nexport type Step<E, R> =\n\t| Skip\n\t| { readonly _tag: \"Apply\"; readonly apply: Effect.Effect<void, E, R> }\n\t| { readonly _tag: \"Confirm\"; readonly verify: Effect.Effect<void, E, R> | undefined };\n\nconst applyStep = <E, R>(apply: Effect.Effect<void, E, R>): Step<E, R> => ({\n\t_tag: \"Apply\",\n\tapply,\n});\n\nconst TypeId = \"~deltafold/Handler\";\n\n/**\n * Implements one action instance. `E` and `R` are the errors and Effect services of both\n * phases together. A prepared value stays inside the handler, so handlers with\n * different prepared values share this type.\n *\n * @since 0.0.1\n */\nexport type Handler<out A extends Action.Any, out E = never, out R = never> = {\n\treadonly [TypeId]: typeof TypeId;\n\treadonly action: A;\n\t/** A `manual` handler has no phases of its own: a person does the work. */\n\treadonly performer: Performer;\n\t/** Whether the handler has a prepare phase. */\n\treadonly prepares: boolean;\n\t/**\n\t * Runs the prepare phase, if any, and resolves to the next step. Both phases share\n\t * `scope`, the occurrence's scope, so resources acquired while preparing stay open\n\t * until the executor closes it after the occurrence ends.\n\t */\n\treadonly prepare: (scope: Scope.Scope) => Effect.Effect<Step<E, R>, E, R>;\n};\n\n/**\n * Any handler.\n *\n * @since 0.0.1\n */\nexport type Any = Handler<Action.Any, any, any>;\n\n/**\n * The errors of a handler or a union of handlers.\n *\n * @since 0.0.1\n */\nexport type Error<H> = H extends Handler<any, infer E, any> ? E : never;\n\n/**\n * The Effect services of a handler or a union of handlers.\n *\n * @since 0.0.1\n */\nexport type Services<H> = H extends Handler<any, any, infer R> ? R : never;\n\n/**\n * The action identifiers implemented by a handler or a union of handlers.\n *\n * @since 0.0.1\n */\nexport type ActionId<H> = H extends Handler<infer A, any, any> ? A[\"id\"] : never;\n\n/** @since 0.0.1 */\nexport const isHandler = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId);\n\nconst make = <A extends Action.Any, E, R>(\n\taction: A,\n\tprepares: boolean,\n\tprepare: (scope: Scope.Scope) => Effect.Effect<Step<E, R>, E, R>,\n): Handler<A, E, R> => ({ [TypeId]: TypeId, action, performer: \"automated\", prepares, prepare });\n\n/**\n * Named Effect services that a Promise handler declares.\n *\n * @since 0.0.1\n */\nexport type ServiceMap = Callback.ServiceMap;\n\n/**\n * The second argument of Promise handler callbacks: the `AbortSignal` that\n * `Effect.tryPromise` aborts on interruption, and the declared services, resolved.\n *\n * @since 0.0.1\n */\nexport type PromiseContext<S extends ServiceMap = NoServices> = Callback.PromiseContext<S>;\n\n/**\n * The second argument of a Promise apply phase: the Promise context and the action\n * payload.\n *\n * @since 0.1.0\n */\nexport type PromiseApplyContext<Payload, S extends ServiceMap = NoServices> = PromiseContext<S> & {\n\treadonly payload: Payload;\n};\n\n/**\n * A Promise handler with a prepare phase. `prepare` reads state and returns\n * `Handler.prepared(value)` or `Handler.skip(reason)`; `apply` receives the value. Each\n * phase gets its own signal.\n *\n * @since 0.1.0\n */\nexport type PromisePhases<Payload, T extends Preparation<unknown>, S extends ServiceMap> = {\n\treadonly prepare: (payload: Payload, context: PromiseContext<S>) => PromiseLike<T> | T;\n\treadonly apply: (\n\t\tprepared: PreparedValue<T>,\n\t\tcontext: PromiseApplyContext<Payload, S>,\n\t) => PromiseLike<unknown>;\n};\n\n/**\n * Recognizes a declared rejection: a schema, or a type guard such as an `instanceof`\n * check. Guards must declare their parameter type, for example\n * `(cause: unknown): cause is NotFound => cause instanceof NotFound`.\n *\n * @since 0.0.1\n */\nexport type ErrorGuard = Callback.ErrorGuard;\n\n/** @since 0.0.1 */\nexport type PromiseOptions<S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>> = {\n\t/** Effect services resolved for the callbacks and added to the handler requirements. */\n\treadonly services?: S;\n\t/**\n\t * Guards for rejections that keep their own type. Other rejections become\n\t * `UnexpectedHandlerError`. A guard does not prove that the callback throws only\n\t * those errors.\n\t */\n\treadonly errors?: G;\n};\n\ntype PromiseHandler<A extends Action.Any, S extends ServiceMap, G> = Handler<\n\tA,\n\tGuardedError<G> | UnexpectedHandlerError,\n\tServiceIds<S>\n>;\n\n/**\n * Implements an action with Promise callbacks. The callbacks run lazily through\n * `Effect.tryPromise`, and receive its `AbortSignal` and the declared services.\n *\n * Pass one callback to apply the action directly, or `{ prepare, apply }` to decide\n * first. `prepare` must only read: a dry run calls it and never calls `apply`. A real\n * run calls `apply` once with the prepared value.\n *\n * @example\n * ```ts\n * Handler.promise(\n * \tupdateRemoteConfig,\n * \tasync (payload, { signal, services: { editor } }) => {\n * \t\tawait editor.update(payload, { signal });\n * \t},\n * \t{ services: { editor: ConfigEditor } },\n * );\n * ```\n *\n * @example\n * ```ts\n * Handler.promise(renameTimeout, {\n * \tprepare: async ({ file, from }, { signal }) => {\n * \t\tconst config = await readConfig(file, { signal });\n * \t\treturn from in config ? Handler.prepared(config) : Handler.skip(`${file} has no ${from}`);\n * \t},\n * \tapply: async (config, { payload, signal }) => {\n * \t\tawait writeConfig(payload.file, rename(config, payload), { signal });\n * \t},\n * });\n * ```\n *\n * @since 0.0.1\n */\nexport function promise<\n\tA extends Action.Any,\n\tconst S extends ServiceMap = NoServices,\n\tconst G extends ReadonlyArray<ErrorGuard> = [],\n>(\n\taction: A,\n\tapply: (payload: A[\"payload\"], context: PromiseContext<S>) => PromiseLike<unknown>,\n\toptions?: PromiseOptions<S, G>,\n): PromiseHandler<A, S, G[number]>;\nexport function promise<\n\tA extends Action.Any,\n\tT extends Preparation<unknown> = Skip,\n\tconst S extends ServiceMap = NoServices,\n\tconst G extends ReadonlyArray<ErrorGuard> = [],\n>(\n\taction: A,\n\tphases: PromisePhases<A[\"payload\"], T, S>,\n\toptions?: PromiseOptions<S, G>,\n): PromiseHandler<A, S, G[number]>;\nexport function promise<\n\tA extends Action.Any,\n\tS extends ServiceMap,\n\tG extends ReadonlyArray<ErrorGuard>,\n>(\n\taction: A,\n\trun:\n\t\t| ((payload: A[\"payload\"], context: PromiseContext<S>) => PromiseLike<unknown>)\n\t\t| PromisePhases<A[\"payload\"], Preparation<unknown>, S>,\n\toptions?: PromiseOptions<S, G>,\n): PromiseHandler<A, S, G[number]> {\n\ttype E = GuardedError<G[number]> | UnexpectedHandlerError;\n\n\tconst adaptCallback = adaptPromise(options ?? {});\n\tconst unexpected = (phase: Phase, cause: unknown) =>\n\t\tnew UnexpectedHandlerError({ actionId: action.id, kind: action.kind, phase, cause });\n\n\tconst adapt = <T>(\n\t\tphase: Phase,\n\t\tcallback: (context: PromiseContext<S>) => PromiseLike<T> | T,\n\t): Effect.Effect<T, E, ServiceIds<S>> =>\n\t\tadaptCallback(callback, (cause) => unexpected(phase, cause));\n\n\tif (Predicate.isFunction(run)) {\n\t\tconst apply = Effect.asVoid(adapt(\"apply\", (context) => run(action.payload, context)));\n\n\t\treturn make(action, false, () => Effect.succeed(applyStep(apply)));\n\t}\n\n\tconst prepare = adapt(\"prepare\", (context) => run.prepare(action.payload, context)).pipe(\n\t\tEffect.filterOrFail(isPreparation, () => unexpected(\"prepare\", notAPreparation())),\n\t\tEffect.map((preparation): Step<E, ServiceIds<S>> =>\n\t\t\tpreparation._tag === \"Skip\"\n\t\t\t\t? preparation\n\t\t\t\t: applyStep(\n\t\t\t\t\t\tEffect.asVoid(\n\t\t\t\t\t\t\tadapt(\"apply\", (context) =>\n\t\t\t\t\t\t\t\trun.apply(preparation.value, {\n\t\t\t\t\t\t\t\t\t...context,\n\t\t\t\t\t\t\t\t\tpayload: action.payload,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t),\n\t);\n\n\treturn make(action, true, () => prepare);\n}\n\n/**\n * The second argument of an Effect apply phase.\n *\n * @since 0.1.0\n */\nexport type EffectApplyContext<Payload> = { readonly payload: Payload };\n\n/**\n * An Effect handler with a prepare phase. `prepare` reads state and succeeds with\n * `Handler.prepared(value)` or `Handler.skip(reason)`; `apply` receives the value.\n *\n * @since 0.1.0\n */\nexport type EffectPhases<Payload, T extends Preparation<unknown>, E1, R1, E2, R2> = {\n\treadonly prepare: (payload: Payload) => Effect.Effect<T, E1, R1>;\n\treadonly apply: (\n\t\tprepared: PreparedValue<T>,\n\t\tcontext: EffectApplyContext<Payload>,\n\t) => Effect.Effect<unknown, E2, R2>;\n};\n\n/**\n * Implements an action with an Effect. The handler keeps its own errors and services,\n * and stops through native Effect interruption.\n *\n * Pass one function to apply the action directly, or `{ prepare, apply }` to decide\n * first. `prepare` must only read: a dry run runs it and never runs `apply`. A real run\n * runs `apply` once with the prepared value. Both phases run in the occurrence's\n * `Scope`, so a resource acquired while preparing, such as a lock, stays open until the\n * occurrence ends; the handler does not require `Scope`.\n *\n * @example\n * ```ts\n * Handler.effect(renameTimeout, {\n * \tprepare: ({ file, from }) =>\n * \t\tEffect.gen(function* () {\n * \t\t\tconst files = yield* ConfigFiles;\n * \t\t\tconst config = yield* files.lock(file);\n * \t\t\treturn from in config.data ? Handler.prepared(config) : Handler.skip(`${file} has no ${from}`);\n * \t\t}),\n * \tapply: (config, { payload }) => config.write(rename(config.data, payload)),\n * });\n * ```\n *\n * @since 0.0.1\n */\nexport function effect<A extends Action.Any, E = never, R = never>(\n\taction: A,\n\tapply: (payload: A[\"payload\"]) => Effect.Effect<unknown, E, R>,\n): Handler<A, E, Exclude<R, Scope.Scope>>;\nexport function effect<\n\tA extends Action.Any,\n\tT extends Preparation<unknown> = Skip,\n\tE1 = never,\n\tR1 = never,\n\tE2 = never,\n\tR2 = never,\n>(\n\taction: A,\n\tphases: EffectPhases<A[\"payload\"], T, E1, R1, E2, R2>,\n): Handler<A, E1 | E2, Exclude<R1 | R2, Scope.Scope>>;\nexport function effect<A extends Action.Any, E1, R1, E2, R2>(\n\taction: A,\n\trun:\n\t\t| ((payload: A[\"payload\"]) => Effect.Effect<unknown, E1, R1>)\n\t\t| EffectPhases<A[\"payload\"], Preparation<unknown>, E1, R1, E2, R2>,\n): Handler<A, E1 | E2, Exclude<R1 | R2, Scope.Scope>> {\n\ttype E = E1 | E2;\n\ttype R = Exclude<R1 | R2, Scope.Scope>;\n\n\tif (Predicate.isFunction(run)) {\n\t\tconst apply = Effect.asVoid(Effect.suspend(() => run(action.payload)));\n\n\t\treturn make(action, false, (scope) =>\n\t\t\tEffect.succeed(applyStep<E, R>(Scope.provide(apply, scope))),\n\t\t);\n\t}\n\n\treturn make(action, true, (scope) =>\n\t\tEffect.suspend(() => run.prepare(action.payload)).pipe(\n\t\t\tScope.provide(scope),\n\t\t\tEffect.filterOrElse(isPreparation, () => Effect.die(notAPreparation())),\n\t\t\tEffect.map((preparation): Step<E, R> =>\n\t\t\t\tpreparation._tag === \"Skip\"\n\t\t\t\t\t? preparation\n\t\t\t\t\t: applyStep(\n\t\t\t\t\t\t\tScope.provide(\n\t\t\t\t\t\t\t\tEffect.asVoid(\n\t\t\t\t\t\t\t\t\tEffect.suspend(() =>\n\t\t\t\t\t\t\t\t\t\trun.apply(preparation.value, { payload: action.payload }),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tscope,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t),\n\t\t),\n\t);\n}\n\nconst verified = <E, R>(action: Action.Any, check: Effect.Effect<boolean, E, R>) =>\n\tEffect.flatMap(check, (passed) =>\n\t\tpassed\n\t\t\t? Effect.void\n\t\t\t: Effect.fail(new VerificationFailed({ actionId: action.id, kind: action.kind })),\n\t);\n\nconst makeManual = <A extends Action.Any, E, R>(\n\taction: A,\n\tverify: ((scope: Scope.Scope) => Effect.Effect<void, E, R>) | undefined,\n): Handler<A, E, R> => ({\n\t[TypeId]: TypeId,\n\taction,\n\tperformer: \"manual\",\n\tprepares: false,\n\tprepare: (scope) => Effect.succeed({ _tag: \"Confirm\", verify: verify?.(scope) }),\n});\n\n/** @since 0.2.0 */\nexport type ManualOptions<Payload, S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>> = {\n\t/** Effect services resolved for `verify` and added to the handler requirements. */\n\treadonly services?: S;\n\t/** Guards for rejections of `verify` that keep their own type. */\n\treadonly errors?: G;\n\t/**\n\t * Read-only check that runs after the person confirms. Returning `false` fails the\n\t * occurrence with `VerificationFailed`. A passing check is evidence that the work is\n\t * in place, not proof of how it was done.\n\t */\n\treadonly verify?: (\n\t\tpayload: Payload,\n\t\tcontext: PromiseContext<S>,\n\t) => boolean | PromiseLike<boolean>;\n};\n\n/**\n * Declares that a person performs the action. A manual handler has no prepare or apply\n * phase. In a real run the executor asks its `interaction` to confirm the work, showing\n * the occurrence's own instruction or description, and never completes the occurrence\n * on its own. A dry run reports that a person would be asked. The optional `verify`\n * check is a Promise callback that runs only after the confirmation.\n *\n * The same action can have a manual handler in one environment and an automated one in\n * another.\n *\n * @example\n * ```ts\n * Handler.manual(rotateApiKey, {\n * \tservices: { keys: KeyStore },\n * \tverify: (payload, { services: { keys } }) => keys.isFresh(payload.service),\n * });\n * ```\n *\n * @since 0.2.0\n */\nexport function manual<A extends Action.Any>(action: A): Handler<A>;\nexport function manual<\n\tA extends Action.Any,\n\tconst S extends ServiceMap = NoServices,\n\tconst G extends ReadonlyArray<ErrorGuard> = [],\n>(\n\taction: A,\n\toptions: ManualOptions<A[\"payload\"], S, G>,\n): Handler<A, GuardedError<G[number]> | UnexpectedHandlerError | VerificationFailed, ServiceIds<S>>;\nexport function manual<\n\tA extends Action.Any,\n\tS extends ServiceMap,\n\tG extends ReadonlyArray<ErrorGuard>,\n>(\n\taction: A,\n\toptions?: ManualOptions<A[\"payload\"], S, G>,\n): Handler<\n\tA,\n\tGuardedError<G[number]> | UnexpectedHandlerError | VerificationFailed,\n\tServiceIds<S>\n> {\n\tconst adapt = adaptPromise(options ?? {});\n\tconst verify = options?.verify;\n\tif (verify === undefined) return makeManual(action, undefined);\n\n\tconst check = verified(\n\t\taction,\n\t\tadapt(\n\t\t\t(context) => verify(action.payload, context),\n\t\t\t(cause) =>\n\t\t\t\tnew UnexpectedHandlerError({\n\t\t\t\t\tactionId: action.id,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tphase: \"verification\",\n\t\t\t\t\tcause,\n\t\t\t\t}),\n\t\t),\n\t);\n\n\treturn makeManual(action, () => check);\n}\n\n/** @since 0.2.0 */\nexport type ManualEffectOptions<Payload, E, R> = {\n\t/**\n\t * Read-only check that runs after the person confirms. Succeeding with `false` fails\n\t * the occurrence with `VerificationFailed`. It runs in the occurrence's `Scope`.\n\t */\n\treadonly verify?: (payload: Payload) => Effect.Effect<boolean, E, R>;\n};\n\n/**\n * `Handler.manual` with an Effect `verify` check, which keeps its own errors and\n * services.\n *\n * @since 0.2.0\n */\nexport function manualEffect<A extends Action.Any>(action: A): Handler<A>;\nexport function manualEffect<A extends Action.Any, E = never, R = never>(\n\taction: A,\n\toptions: ManualEffectOptions<A[\"payload\"], E, R>,\n): Handler<A, E | VerificationFailed, Exclude<R, Scope.Scope>>;\nexport function manualEffect<A extends Action.Any, E, R>(\n\taction: A,\n\toptions?: ManualEffectOptions<A[\"payload\"], E, R>,\n): Handler<A, E | VerificationFailed, Exclude<R, Scope.Scope>> {\n\tconst verify = options?.verify;\n\tif (verify === undefined) return makeManual(action, undefined);\n\n\treturn makeManual(action, (scope) =>\n\t\tScope.provide(\n\t\t\tverified(\n\t\t\t\taction,\n\t\t\t\tEffect.suspend(() => verify(action.payload)),\n\t\t\t),\n\t\t\tscope,\n\t\t),\n\t);\n}\n","import {\n\tCause,\n\tClock,\n\tDeferred,\n\tDuration,\n\tEffect,\n\tExit,\n\tFiber,\n\tOption,\n\tPredicate,\n\tSemaphore,\n} from \"effect\";\n\nimport type * as Plan from \"../../foundation/plan.ts\";\nimport type { Occurrence, Step } from \"../../foundation/plan.ts\";\nimport type { Outcome, Report } from \"./executor.ts\";\nimport type { Phase } from \"./handler.ts\";\nimport type * as Observer from \"./observer.ts\";\n\n/** Finds the identifier of the plan step that declared an occurrence's migration side. */\ntype StepIdOf = (occurrence: Occurrence) => string;\n\nconst stepIdsOf =\n\t(plan: Plan.Any): StepIdOf =>\n\t(occurrence) =>\n\t\tplan.steps.find(\n\t\t\t(step) =>\n\t\t\t\tstep.migration === occurrence.migration && step.direction === occurrence.direction,\n\t\t)?.id ?? occurrence.migration.id;\n\n/** Declared occurrences behind an occurrence, through nested replacements, in order. */\nconst leavesOf = (occurrence: Occurrence): ReadonlyArray<Occurrence> =>\n\toccurrence.origin._tag === \"Declared\"\n\t\t? [occurrence]\n\t\t: occurrence.origin.replaces.flatMap(leavesOf);\n\nconst sourcesOf = (occurrence: Occurrence, stepIdOf: StepIdOf): ReadonlyArray<string> => [\n\t...new Set(leavesOf(occurrence).map(stepIdOf)),\n];\n\nconst occurrencesOfNode = (node: Plan.Node): ReadonlyArray<Occurrence> => {\n\tswitch (node._tag) {\n\t\tcase \"Occurrence\":\n\t\t\treturn [node];\n\t\tcase \"Sequence\":\n\t\t\treturn node.children.flatMap(occurrencesOfNode);\n\t}\n\n\treturn node.branches.flatMap(occurrencesOfNode);\n};\n\nconst stepInfoOf = (\n\tstep: Step,\n\tindex: number,\n\tplan: Plan.Any,\n\tstepIdOf: StepIdOf,\n): Observer.StepInfo => {\n\tconst occurrences = occurrencesOfNode(step.node);\n\tconst base = {\n\t\tid: step.id,\n\t\tindex,\n\t\tmigration: step.migration.id,\n\t\tdirection: step.direction,\n\t\tfrom: step.from.id,\n\t\tto: step.to.id,\n\t\toccurrences: occurrences.map((occurrence) => occurrence.id),\n\t\tabsorbs: [\n\t\t\t...new Set(occurrences.flatMap((occurrence) => sourcesOf(occurrence, stepIdOf))),\n\t\t].filter((id) => id !== step.id),\n\t};\n\tif (occurrences.length > 0) return { ...base, kind: \"execute\" };\n\tif (!step.omitted) return { ...base, kind: \"prose\" };\n\tconst omitted = plan.explanations.find(\n\t\t(explanation) =>\n\t\t\texplanation._tag === \"OmittedStep\" &&\n\t\t\texplanation.migration.id === step.migration.id &&\n\t\t\texplanation.direction === step.direction,\n\t);\n\n\treturn {\n\t\t...base,\n\t\tkind: \"omitted\",\n\t\treason:\n\t\t\tomitted?._tag === \"OmittedStep\" && omitted.reason === \"all-actions-removed\"\n\t\t\t\t? \"all-actions-removed\"\n\t\t\t\t: \"noop\",\n\t};\n};\n\nconst actionInfoOf = (\n\toccurrence: Occurrence,\n\tstep: string,\n\tstepIdOf: StepIdOf,\n): Observer.ActionInfo => ({\n\toccurrence: occurrence.id,\n\taction: occurrence.action.id,\n\tkind: occurrence.action.kind,\n\tdescription: occurrence.action.description,\n\tmigration: occurrence.migration.id,\n\tdirection: occurrence.direction,\n\tstep,\n\torigin:\n\t\toccurrence.origin._tag === \"Declared\"\n\t\t\t? { _tag: \"Declared\" }\n\t\t\t: {\n\t\t\t\t\t_tag: \"Replacement\",\n\t\t\t\t\trule: occurrence.origin.rule.id,\n\t\t\t\t\treplaces: occurrence.origin.replaces.map((replaced) => replaced.id),\n\t\t\t\t},\n\tsources: sourcesOf(occurrence, stepIdOf),\n});\n\n/**\n * Reads a handler error's tag once, so a getter cannot pass the check with one value and\n * return another. A tag that cannot be read, even by a throwing getter, is absent.\n */\nconst errorTagOf = (error: unknown): string | undefined => {\n\ttry {\n\t\tif (!Predicate.hasProperty(error, \"_tag\")) return undefined;\n\t\tconst tag: unknown = error._tag;\n\n\t\treturn typeof tag === \"string\" ? tag : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\n/** Copies only the fields observers may see. */\nconst summaryOf = (outcome: Outcome): Observer.OutcomeSummary => {\n\tswitch (outcome._tag) {\n\t\tcase \"Completed\":\n\t\t\treturn outcome.performer === \"manual\"\n\t\t\t\t? { _tag: \"Completed\", performer: \"manual\", confirmation: outcome.confirmation }\n\t\t\t\t: { _tag: \"Completed\", performer: \"automated\" };\n\t\tcase \"Skipped\":\n\t\t\treturn { _tag: \"Skipped\", reason: outcome.reason };\n\t\tcase \"Declined\":\n\t\t\treturn { _tag: \"Declined\" };\n\t\tcase \"Failed\":\n\t\t\treturn { _tag: \"Failed\", phase: outcome.phase, errorTag: errorTagOf(outcome.error) };\n\t\tcase \"Interrupted\":\n\t\t\treturn {\n\t\t\t\t_tag: \"Interrupted\",\n\t\t\t\tphase: outcome.phase,\n\t\t\t\treason: outcome.reason,\n\t\t\t\tsettled: outcome.settled,\n\t\t\t};\n\t\tcase \"Unattempted\":\n\t\t\treturn { _tag: \"Unattempted\" };\n\t\tcase \"WouldExecute\":\n\t\t\treturn {\n\t\t\t\t_tag: \"WouldExecute\",\n\t\t\t\tevaluated: outcome.evaluated,\n\t\t\t\tperformer: outcome.performer,\n\t\t\t};\n\t\tcase \"WouldSkip\":\n\t\t\treturn { _tag: \"WouldSkip\", reason: outcome.reason };\n\t\tcase \"Undetermined\":\n\t\t\treturn { _tag: \"Undetermined\", reason: outcome.reason, performer: outcome.performer };\n\t}\n\n\treturn { _tag: \"PreparationFailed\", errorTag: errorTagOf(outcome.error) };\n};\n\nconst emptyCounts = (): { -readonly [K in keyof Observer.Counts]: number } => ({\n\tCompleted: 0,\n\tSkipped: 0,\n\tDeclined: 0,\n\tFailed: 0,\n\tInterrupted: 0,\n\tUnattempted: 0,\n\tWouldExecute: 0,\n\tWouldSkip: 0,\n\tUndetermined: 0,\n\tPreparationFailed: 0,\n\tunsettled: 0,\n});\n\n/** Emits events for one run. Without observers, every method is a no-op. */\nexport type Emitter<R> = {\n\treadonly runStarted: Effect.Effect<void, never, R>;\n\treadonly stepStarted: (step: Step) => Effect.Effect<void, never, R>;\n\treadonly stepSettled: (step: Step) => Effect.Effect<void, never, R>;\n\treadonly phaseStarted: (occurrence: Occurrence, phase: Phase) => Effect.Effect<void, never, R>;\n\t/**\n\t * Emits the occurrence's current outcome from the shared outcome map, if it has one or\n\t * has started. An occurrence that never started and has no outcome emits nothing.\n\t */\n\treadonly settled: (occurrence: Occurrence) => Effect.Effect<void, never, R>;\n\treadonly runFinished: (status: Report[\"status\"]) => Effect.Effect<void, never, R>;\n\t/** Emits a report-less `RunFinished` after fiber interruption, if the run had started. */\n\treadonly interrupted: Effect.Effect<void, never, R>;\n\treadonly failures: ReadonlyArray<Observer.ObservationFailure>;\n};\n\nconst noop: Emitter<never> = {\n\trunStarted: Effect.void,\n\tstepStarted: () => Effect.void,\n\tstepSettled: () => Effect.void,\n\tphaseStarted: () => Effect.void,\n\tsettled: () => Effect.void,\n\trunFinished: () => Effect.void,\n\tinterrupted: Effect.void,\n\tfailures: [],\n};\n\nexport type EmitterOptions<R> = {\n\treadonly plan: Plan.Any;\n\treadonly mode: Report[\"mode\"];\n\treadonly runId: string | undefined;\n\treadonly observers: ReadonlyArray<Observer.Observer<R>>;\n\treadonly outcomes: ReadonlyMap<string, Outcome>;\n\t/** Completes when cancellation or a timeout stops the run. */\n\treadonly stopped: Deferred.Deferred<void>;\n\treadonly grace: Duration.Input;\n\t/** Receives a fiber that ends when an abandoned callback stops, to keep services open. */\n\treadonly retain: (fiber: Fiber.Fiber<void>) => void;\n};\n\n/**\n * Delivery is awaited and serialized: one event at a time, to each observer in order.\n * Counters change under the same lock, so each event's progress is consistent with the\n * order observers see. Observer failures are recorded and never reach the run.\n */\nexport const makeEmitter = <R>(options: EmitterOptions<R>): Effect.Effect<Emitter<R>> =>\n\tEffect.gen(function* () {\n\t\tconst { plan, observers, outcomes, stopped, grace, retain } = options;\n\t\tif (observers.length === 0) return noop;\n\t\tconst stepIdOf = stepIdsOf(plan);\n\n\t\tconst lock = yield* Semaphore.make(1);\n\t\tconst failures: Array<Observer.ObservationFailure> = [];\n\t\tconst run: Observer.Run = {\n\t\t\tid: options.runId,\n\t\t\tmode: options.mode,\n\t\t\tfrom: plan.from.id,\n\t\t\tto: plan.to.id,\n\t\t\troute: plan.route.id,\n\t\t};\n\t\tconst steps = plan.steps.map((step, index) => stepInfoOf(step, index, plan, stepIdOf));\n\t\tconst infoOf = new Map(plan.steps.map((step, index) => [step, steps[index]]));\n\t\tconst ownerOf = new Map<string, string>();\n\t\tfor (const info of steps) for (const id of info.occurrences) ownerOf.set(id, info.id);\n\n\t\tconst state: {\n\t\t\tseq: number;\n\t\t\trunning: Set<string>;\n\t\t\tactionsFinished: number;\n\t\t\tstepsFinished: number;\n\t\t\tstarted: boolean;\n\t\t\tfinished: boolean;\n\t\t\t/** The event being delivered and the observer it is with, until every observer has it. */\n\t\t\tdelivering: { readonly event: Observer.Event; readonly observer: number } | undefined;\n\t\t} = {\n\t\t\tseq: 0,\n\t\t\trunning: new Set<string>(),\n\t\t\tactionsFinished: 0,\n\t\t\tstepsFinished: 0,\n\t\t\tstarted: false,\n\t\t\tfinished: false,\n\t\t\tdelivering: undefined,\n\t\t};\n\t\tconst stepsTotal = steps.filter((info) => info.kind !== \"omitted\").length;\n\t\tconst progress = (): Observer.Progress => ({\n\t\t\tsteps: { total: stepsTotal, finished: state.stepsFinished },\n\t\t\tactions: {\n\t\t\t\ttotal: plan.occurrences.length,\n\t\t\t\trunning: state.running.size,\n\t\t\t\tfinished: state.actionsFinished,\n\t\t\t},\n\t\t});\n\n\t\tconst countsOf = (occurrences: ReadonlyArray<Occurrence>, inFlight: boolean) => {\n\t\t\tconst counts = emptyCounts();\n\t\t\tfor (const occurrence of occurrences) {\n\t\t\t\tconst outcome = outcomes.get(occurrence.id);\n\t\t\t\tif (outcome === undefined && inFlight && state.running.has(occurrence.id)) {\n\t\t\t\t\tcounts.Interrupted += 1;\n\t\t\t\t\tcounts.unsettled += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst tag = outcome?._tag ?? \"Unattempted\";\n\t\t\t\tcounts[tag] += 1;\n\t\t\t\tif (outcome?._tag === \"Interrupted\" && !outcome.settled) counts.unsettled += 1;\n\t\t\t}\n\n\t\t\treturn counts;\n\t\t};\n\n\t\t/**\n\t\t * Interrupts an abandoned delivery without waiting for it to stop. The run's services\n\t\t * stay open until it does.\n\t\t */\n\t\tconst abandon = (fiber: Fiber.Fiber<Exit.Exit<unknown, unknown>>) =>\n\t\t\tEffect.map(Effect.forkDetach(Fiber.interrupt(fiber)), retain);\n\n\t\t/**\n\t\t * Bounds a delivery once the run has been stopped, or always when `bounded` is set.\n\t\t * The callback runs in its own fiber, with the run's services, so a delivery that\n\t\t * cannot be interrupted is still abandoned when the bound passes.\n\t\t */\n\t\tconst deliver = (\n\t\t\tobserver: Observer.Observer<R>,\n\t\t\tevent: Observer.Event,\n\t\t\tbounded: boolean,\n\t\t): Effect.Effect<Option.Option<Exit.Exit<unknown, unknown>>, never, R> =>\n\t\t\tEffect.uninterruptibleMask((restore) =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst fiber = yield* Effect.forkDetach(\n\t\t\t\t\t\tEffect.interruptible(observer.notify(event)),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstartImmediately: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\tconst limit = bounded\n\t\t\t\t\t\t? Effect.sleep(grace)\n\t\t\t\t\t\t: Effect.andThen(Deferred.await(stopped), Effect.sleep(grace));\n\t\t\t\t\tconst result = yield* restore(\n\t\t\t\t\t\tEffect.raceFirst(\n\t\t\t\t\t\t\tEffect.map(Fiber.await(fiber), (exit) =>\n\t\t\t\t\t\t\t\tOption.some(Exit.isSuccess(exit) ? exit.value : exit),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tEffect.as(limit, Option.none<Exit.Exit<unknown, unknown>>()),\n\t\t\t\t\t\t),\n\t\t\t\t\t).pipe(Effect.onInterrupt(() => abandon(fiber)));\n\t\t\t\t\tif (Option.isNone(result)) yield* abandon(fiber);\n\n\t\t\t\t\treturn result;\n\t\t\t\t}),\n\t\t\t);\n\n\t\tconst record = (\n\t\t\tobserver: number,\n\t\t\tevent: Observer.Event,\n\t\t\tresult: Option.Option<Exit.Exit<unknown, unknown>>,\n\t\t) => {\n\t\t\tif (Option.isNone(result)) {\n\t\t\t\tfailures.push({\n\t\t\t\t\tobserver,\n\t\t\t\t\tevent: event._tag,\n\t\t\t\t\tseq: event.seq,\n\t\t\t\t\treason: \"abandoned\",\n\t\t\t\t\tcause: Cause.interrupt(),\n\t\t\t\t});\n\t\t\t} else if (Exit.isFailure(result.value)) {\n\t\t\t\tfailures.push({\n\t\t\t\t\tobserver,\n\t\t\t\t\tevent: event._tag,\n\t\t\t\t\tseq: event.seq,\n\t\t\t\t\treason: \"failed\",\n\t\t\t\t\tcause: result.value.cause,\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\t/** Delivers an event to each observer from `first` on, in order. */\n\t\tconst deliverFrom = (event: Observer.Event, first: number, bounded: boolean) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tfor (const [offset, observer] of observers.slice(first).entries()) {\n\t\t\t\t\tconst index = first + offset;\n\t\t\t\t\tstate.delivering = { event, observer: index };\n\t\t\t\t\trecord(index, event, yield* deliver(observer, event, bounded));\n\t\t\t\t}\n\t\t\t\tstate.delivering = undefined;\n\t\t\t});\n\n\t\tconst emit = (\n\t\t\tupdate: () => void,\n\t\t\tbuild: (base: {\n\t\t\t\treadonly run: Observer.Run;\n\t\t\t\treadonly seq: number;\n\t\t\t\treadonly timestamp: number;\n\t\t\t\treadonly progress: Observer.Progress;\n\t\t\t}) => Observer.Event,\n\t\t\tbounded = false,\n\t\t): Effect.Effect<void, never, R> =>\n\t\t\tlock.withPermits(1)(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tupdate();\n\t\t\t\t\tconst timestamp = yield* Clock.currentTimeMillis;\n\t\t\t\t\tconst event = build({ run, seq: state.seq, timestamp, progress: progress() });\n\t\t\t\t\tstate.seq += 1;\n\t\t\t\t\tyield* deliverFrom(event, 0, bounded);\n\t\t\t\t}),\n\t\t\t);\n\n\t\tconst stepEvent = (step: Step) => infoOf.get(step) ?? stepInfoOf(step, -1, plan, stepIdOf);\n\t\tconst actionOf = (occurrence: Occurrence) =>\n\t\t\tactionInfoOf(occurrence, ownerOf.get(occurrence.id) ?? stepIdOf(occurrence), stepIdOf);\n\n\t\tconst finish = (status: Report[\"status\"], report: boolean, bounded: boolean) =>\n\t\t\temit(\n\t\t\t\t() => {\n\t\t\t\t\tstate.finished = true;\n\t\t\t\t},\n\t\t\t\t(base) => ({\n\t\t\t\t\t...base,\n\t\t\t\t\t_tag: \"RunFinished\",\n\t\t\t\t\tstatus,\n\t\t\t\t\tcounts: countsOf(plan.occurrences, !report),\n\t\t\t\t\treport,\n\t\t\t\t}),\n\t\t\t\tbounded,\n\t\t\t);\n\n\t\t/**\n\t\t * Ends the stream after fiber interruption. The delivery the interruption cut short is\n\t\t * abandoned. If it was `RunFinished`, the observers that had not received it get a\n\t\t * report-less one with the same `seq` instead, so each observer hears exactly one.\n\t\t */\n\t\tconst interrupted = Effect.suspend(() => {\n\t\t\tconst cut = state.delivering;\n\t\t\tif (cut !== undefined) {\n\t\t\t\trecord(cut.observer, cut.event, Option.none());\n\t\t\t\tstate.delivering = undefined;\n\t\t\t}\n\t\t\tif (!state.started) return Effect.void;\n\t\t\tif (!state.finished) return finish(\"interrupted\", false, true);\n\t\t\tif (cut?.event._tag !== \"RunFinished\") return Effect.void;\n\t\t\tconst event: Observer.Event = {\n\t\t\t\t...cut.event,\n\t\t\t\tstatus: \"interrupted\",\n\t\t\t\tcounts: countsOf(plan.occurrences, true),\n\t\t\t\treport: false,\n\t\t\t};\n\n\t\t\treturn lock.withPermits(1)(deliverFrom(event, cut.observer + 1, true));\n\t\t});\n\n\t\treturn {\n\t\t\trunStarted: emit(\n\t\t\t\t() => {\n\t\t\t\t\tstate.started = true;\n\t\t\t\t},\n\t\t\t\t(base) => ({ ...base, _tag: \"RunStarted\", steps }),\n\t\t\t),\n\t\t\tstepStarted: (step) =>\n\t\t\t\temit(\n\t\t\t\t\t() => {},\n\t\t\t\t\t(base) => ({ ...base, _tag: \"StepStarted\", step: stepEvent(step) }),\n\t\t\t\t),\n\t\t\tstepSettled: (step) =>\n\t\t\t\temit(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tstate.stepsFinished += 1;\n\t\t\t\t\t},\n\t\t\t\t\t(base) => ({\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\t_tag: \"StepSettled\",\n\t\t\t\t\t\tstep: stepEvent(step),\n\t\t\t\t\t\tcounts: countsOf(occurrencesOfNode(step.node), false),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\tphaseStarted: (occurrence, phase) =>\n\t\t\t\temit(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tstate.running.add(occurrence.id);\n\t\t\t\t\t},\n\t\t\t\t\t(base) => ({\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\t_tag: \"ActionPhaseStarted\",\n\t\t\t\t\t\taction: actionOf(occurrence),\n\t\t\t\t\t\tphase,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\tsettled: (occurrence) =>\n\t\t\t\tEffect.suspend(() =>\n\t\t\t\t\t!outcomes.has(occurrence.id) && !state.running.has(occurrence.id)\n\t\t\t\t\t\t? Effect.void\n\t\t\t\t\t\t: emit(\n\t\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\t\tstate.running.delete(occurrence.id);\n\t\t\t\t\t\t\t\t\tstate.actionsFinished += 1;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t(base) => ({\n\t\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\t\t_tag: \"ActionSettled\",\n\t\t\t\t\t\t\t\t\taction: actionOf(occurrence),\n\t\t\t\t\t\t\t\t\toutcome: summaryOf(\n\t\t\t\t\t\t\t\t\t\toutcomes.get(occurrence.id) ?? { _tag: \"Unattempted\" },\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t),\n\t\t\trunFinished: (status) => finish(status, true, false),\n\t\t\tinterrupted,\n\t\t\tfailures,\n\t\t};\n\t});\n","import {\n\tCause,\n\tContext,\n\tData,\n\tDeferred,\n\tDuration,\n\tEffect,\n\tEqual,\n\tExit,\n\tFiber,\n\tLayer,\n\tOption,\n\tScope,\n} from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Plan from \"../../foundation/plan.ts\";\nimport type { Node, Occurrence } from \"../../foundation/plan.ts\";\nimport * as Handler from \"./handler.ts\";\nimport type * as Interaction from \"./interaction.ts\";\nimport { makeEmitter, type Emitter } from \"./observation.ts\";\nimport type * as Observer from \"./observer.ts\";\nimport { SettlementReference } from \"./settlement.ts\";\n\n/**\n * What happened to one occurrence, or what a dry run predicts.\n *\n * @since 0.0.1\n */\nexport type Outcome<E = unknown> =\n\t| { readonly _tag: \"Completed\"; readonly performer: \"automated\" }\n\t| {\n\t\t\treadonly _tag: \"Completed\";\n\t\t\treadonly performer: \"manual\";\n\t\t\t/**\n\t\t\t * What supports completion. `asserted`: the person said so and nothing checked\n\t\t\t * it. `verified`: the person said so and the handler's `verify` check passed.\n\t\t\t * Neither proves how the work was done.\n\t\t\t */\n\t\t\treadonly confirmation: \"asserted\" | \"verified\";\n\t }\n\t| { readonly _tag: \"Skipped\"; readonly reason: string }\n\t/** The person asked to confirm manual work answered that it is not done. */\n\t| { readonly _tag: \"Declined\" }\n\t| {\n\t\t\treadonly _tag: \"Failed\";\n\t\t\treadonly phase: Handler.Phase;\n\t\t\t/** The typed failure, when the cause has one. Defects only appear in `cause`. */\n\t\t\treadonly error: E | undefined;\n\t\t\treadonly cause: Cause.Cause<E>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"Interrupted\";\n\t\t\treadonly phase: Handler.Phase;\n\t\t\t/** `handler`: an Effect handler interrupted itself. */\n\t\t\treadonly reason: InterruptReason;\n\t\t\t/**\n\t\t\t * Whether the interrupted work is known to have stopped. An interrupted Promise\n\t\t\t * that has not settled within the grace period may still be changing external\n\t\t\t * state.\n\t\t\t */\n\t\t\treadonly settled: boolean;\n\t }\n\t/** Not started because execution stopped first. */\n\t| { readonly _tag: \"Unattempted\" }\n\t/**\n\t * `evaluated`: whether a prepare phase ran and decided to apply. A `manual` occurrence\n\t * would wait for a person; a dry run never asks.\n\t */\n\t| {\n\t\t\treadonly _tag: \"WouldExecute\";\n\t\t\treadonly evaluated: boolean;\n\t\t\treadonly performer: Handler.Performer;\n\t }\n\t| { readonly _tag: \"WouldSkip\"; readonly reason: string }\n\t| {\n\t\t\treadonly _tag: \"Undetermined\";\n\t\t\treadonly reason: string;\n\t\t\t/** A `manual` occurrence would wait for a person if it executes. */\n\t\t\treadonly performer: Handler.Performer;\n\t }\n\t| {\n\t\t\treadonly _tag: \"PreparationFailed\";\n\t\t\treadonly error: E | undefined;\n\t\t\treadonly cause: Cause.Cause<E>;\n\t };\n\n/** @since 0.0.1 */\nexport type OccurrenceReport<A extends Action.Any = Action.Any, E = unknown> = {\n\treadonly occurrence: Occurrence<A>;\n\treadonly outcome: Outcome<E>;\n};\n\n/** @since 0.0.1 */\nexport type Report<A extends Action.Any = Action.Any, E = unknown> = {\n\treadonly _tag: \"Report\";\n\treadonly mode: \"execute\" | \"dry-run\";\n\treadonly status:\n\t\t| \"completed\"\n\t\t| \"failed\"\n\t\t| \"interrupted\"\n\t\t| \"not-started\"\n\t\t| \"would-complete\"\n\t\t| \"would-fail\";\n\treadonly from: string;\n\treadonly to: string;\n\treadonly route: string;\n\t/** Every occurrence in plan order. */\n\treadonly occurrences: ReadonlyArray<OccurrenceReport<A, E>>;\n\t/**\n\t * Whether any apply phase started or any person was asked to do manual work. Either\n\t * may have partially changed state.\n\t */\n\treadonly bodiesStarted: boolean;\n\t/** Progress is not persisted. Rerunning the plan repeats completed actions. */\n\treadonly persistence: \"none\";\n\t/** Observers that failed or were abandoned. Never affects outcomes or status. */\n\treadonly observation: ReadonlyArray<Observer.ObservationFailure>;\n};\n\n/**\n * A handler is missing, duplicated, or bound to a different definition.\n *\n * @since 0.0.1\n */\nexport type CoverageIssue = {\n\treadonly _tag: \"Missing\" | \"Duplicate\" | \"Mismatched\";\n\treadonly occurrenceId: string;\n\treadonly actionId: string;\n\treadonly description: string;\n\treadonly migrationId: string;\n\t/** The rule that produced the occurrence, for replacements. */\n\treadonly rule: string | undefined;\n\t/** The occurrences a replacement stands for, so the missing handler is discoverable. */\n\treadonly replaces: ReadonlyArray<{\n\t\treadonly occurrenceId: string;\n\t\treadonly description: string;\n\t}>;\n};\n\nconst HandlerCoverageBase = Data.TaggedError(\"HandlerCoverageError\");\n\n/**\n * Handler coverage failed before any handler phase ran. Every occurrence needs exactly\n * one handler, for the same action definition: the same identifier, kind, and payload.\n * For an occurrence that a rule produced, the issue names the rule and the occurrences\n * it replaced.\n *\n * @since 0.0.1\n */\nexport class HandlerCoverageError<A extends Action.Any = Action.Any> extends HandlerCoverageBase<{\n\treadonly issues: ReadonlyArray<CoverageIssue>;\n\treadonly report: Report<A, never>;\n}> {\n\toverride get message() {\n\t\treturn `Handler coverage failed for ${this.issues.length} occurrence(s): ${this.issues\n\t\t\t.map(\n\t\t\t\t(issue) =>\n\t\t\t\t\t`${issue._tag.toLowerCase()} handler for \"${issue.actionId}\" (${issue.description})`,\n\t\t\t)\n\t\t\t.join(\"; \")}.`;\n\t}\n}\n\nconst InteractionUnavailableBase = Data.TaggedError(\"InteractionUnavailable\");\n\n/**\n * The plan has manual handlers, and the run has no `interaction` to ask a person. The\n * run fails before any handler phase or prompt.\n *\n * @since 0.2.0\n */\nexport class InteractionUnavailable<\n\tA extends Action.Any = Action.Any,\n> extends InteractionUnavailableBase<{\n\t/** The occurrences that a manual handler covers, in plan order. */\n\treadonly occurrences: ReadonlyArray<Occurrence<A>>;\n\treadonly report: Report<A, never>;\n}> {\n\toverride get message() {\n\t\treturn `No interaction is available to confirm manual work for ${this.occurrences\n\t\t\t.map((occurrence) => `\"${occurrence.id}\" (${occurrence.action.description})`)\n\t\t\t.join(\n\t\t\t\t\", \",\n\t\t\t)}. Supply the \\`interaction\\` option, or bind automated handlers to these actions.`;\n\t}\n}\n\nconst listIds = (entries: ReadonlyArray<OccurrenceReport>) =>\n\tentries\n\t\t.map((entry) =>\n\t\t\tentry.outcome._tag === \"Failed\"\n\t\t\t\t? `\"${entry.occurrence.id}\" (${entry.outcome.phase})`\n\t\t\t\t: `\"${entry.occurrence.id}\"`,\n\t\t)\n\t\t.join(\", \");\n\nconst ExecutionFailedBase = Data.TaggedError(\"ExecutionFailed\");\n\n/**\n * An occurrence failed, or a person declined manual work. Execution stopped admitting\n * new actions; started ones settled.\n *\n * @since 0.0.1\n */\nexport class ExecutionFailed<\n\tA extends Action.Any = Action.Any,\n\tE = unknown,\n> extends ExecutionFailedBase<{\n\treadonly failures: ReadonlyArray<OccurrenceReport<A, E>>;\n\t/** Manual occurrences that a person declined. */\n\treadonly declined: ReadonlyArray<OccurrenceReport<A, E>>;\n\treadonly report: Report<A, E>;\n}> {\n\toverride get message() {\n\t\tconst parts = [\n\t\t\t...(this.failures.length === 0\n\t\t\t\t? []\n\t\t\t\t: [`Execution failed at ${listIds(this.failures)}.`]),\n\t\t\t...(this.declined.length === 0\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t`Manual work was declined at ${listIds(this.declined)}, which stopped the run.`,\n\t\t\t\t\t]),\n\t\t];\n\n\t\treturn `${parts.join(\" \")} Completed actions were not rolled back.`;\n\t}\n}\n\nconst ExecutionInterruptedBase = Data.TaggedError(\"ExecutionInterrupted\");\n\n/**\n * Why an execution or an occurrence was interrupted: explicit cancellation, a configured\n * timeout, or an Effect handler that interrupted itself.\n *\n * @since 0.0.1\n */\nexport type InterruptReason = \"cancelled\" | \"timeout\" | \"handler\";\n\nconst interruptedBy: Record<InterruptReason, string> = {\n\tcancelled: \"cancelled\",\n\ttimeout: \"stopped by a timeout\",\n\thandler: \"interrupted by a handler\",\n};\n\n/**\n * Explicit cancellation, a configured timeout, or a handler's own interruption stopped\n * execution.\n *\n * @since 0.0.1\n */\nexport class ExecutionInterrupted<\n\tA extends Action.Any = Action.Any,\n\tE = unknown,\n> extends ExecutionInterruptedBase<{\n\treadonly reason: InterruptReason;\n\treadonly report: Report<A, E>;\n}> {\n\toverride get message() {\n\t\tconst pending = this.report.occurrences.filter(\n\t\t\t(entry) => entry.outcome._tag === \"Interrupted\" && !entry.outcome.settled,\n\t\t);\n\t\tconst suffix =\n\t\t\tpending.length === 0\n\t\t\t\t? \"\"\n\t\t\t\t: ` ${pending.length} interrupted action(s) had not settled and may still be running.`;\n\n\t\treturn `Execution was ${interruptedBy[this.reason]}.${suffix}`;\n\t}\n}\n\n/** @since 0.0.1 */\nexport type ExecutionError<A extends Action.Any, E> =\n\t| HandlerCoverageError<A>\n\t| InteractionUnavailable<A>\n\t| ExecutionFailed<A, E>\n\t| ExecutionInterrupted<A, E>;\n\n/**\n * Action identifiers of a statically covered plan that no handler in the array\n * implements.\n *\n * @since 0.0.1\n */\nexport type Uncovered<A extends Action.Any, H, C extends Plan.Coverage> = \"runtime\" extends C\n\t? never\n\t: A extends Action.Any\n\t\t? string extends A[\"id\"]\n\t\t\t? never\n\t\t\t: A[\"id\"] extends Handler.ActionId<H>\n\t\t\t\t? never\n\t\t\t\t: A[\"id\"]\n\t\t: never;\n\n/** Rejects a handler array that leaves statically known actions uncovered, naming them. */\ntype CoverageCheck<A extends Action.Any, H, C extends Plan.Coverage> = [\n\tUncovered<A, H, C>,\n] extends [never]\n\t? unknown\n\t: { readonly handlers: `Missing a handler for action \"${Uncovered<A, H, C>}\"` };\n\n/**\n * Errors an execution can report for its occurrences.\n *\n * @since 0.0.1\n */\nexport type Errors<H, I = never> = Handler.Error<H> | Interaction.Error<I>;\n\n/**\n * Effect services an execution requires: the services of its handlers, its\n * interaction, and its observers.\n *\n * @since 0.0.1\n */\nexport type Requirements<H, I = never, O = never> =\n\t| Handler.Services<H>\n\t| Interaction.Services<I>\n\t| Observer.Services<O>;\n\n/** @since 0.0.1 */\nexport type Options<\n\tH extends Handler.Any,\n\tI extends Interaction.Any = never,\n\tO extends Observer.Any = never,\n> = {\n\treadonly handlers?: ReadonlyArray<H>;\n\t/**\n\t * Asks a person to confirm the work of manual handlers. A run whose plan has manual\n\t * handlers fails with `InteractionUnavailable` before it starts when this is absent.\n\t * A dry run never asks and does not need it.\n\t */\n\treadonly interaction?: I;\n\t/**\n\t * Receive the run's events, in array order. The executor waits for each observer\n\t * before it continues; an observer failure is recorded in `report.observation` and never changes\n\t * the outcome.\n\t */\n\treadonly observers?: ReadonlyArray<O>;\n\t/** Identifies the run in observer events. */\n\treadonly runId?: string;\n\t/**\n\t * Run prepare phases without running any apply phase. A prepare phase that may\n\t * depend on an earlier action is reported `Undetermined`, because the dry run does\n\t * not apply that action.\n\t */\n\treadonly dryRun?: boolean;\n\t/**\n\t * Limit for each phase of an occurrence: the prepare phase and the apply phase each\n\t * get the full limit, and so does the verification of manual work. Exceeding it\n\t * interrupts that action and stops admitting new ones. It applies to dry-run prepare\n\t * phases too. It never limits the wait for a person to confirm manual work; cancel\n\t * the run to end that wait.\n\t */\n\treadonly timeout?: Duration.Input;\n\t/**\n\t * How long to wait for an interrupted Promise callback to settle before reporting it\n\t * as possibly still running. Defaults to 5 seconds.\n\t */\n\treadonly settleTimeout?: Duration.Input;\n};\n\n/** A handler as the executor runs it: its action is erased, its channels are not. */\ntype Internal<E, R> = Handler.Handler<Action.Any, E, R>;\n\ntype Resolved<E, R> = Map<string, Internal<E, R>>;\n\nconst describeReplaces = (occurrence: Occurrence) =>\n\toccurrence.origin._tag === \"Replacement\"\n\t\t? occurrence.origin.replaces.map((replaced) => ({\n\t\t\t\toccurrenceId: replaced.id,\n\t\t\t\tdescription: replaced.action.description,\n\t\t\t}))\n\t\t: [];\n\nconst coverage = <E, R>(\n\tplan: Plan.Any,\n\thandlers: ReadonlyArray<Internal<E, R>>,\n): { readonly resolved: Resolved<E, R>; readonly issues: ReadonlyArray<CoverageIssue> } => {\n\tconst byAction = new Map<string, Array<Internal<E, R>>>();\n\tfor (const handler of handlers) {\n\t\tconst list = byAction.get(handler.action.id) ?? [];\n\t\tlist.push(handler);\n\t\tbyAction.set(handler.action.id, list);\n\t}\n\n\tconst resolved: Resolved<E, R> = new Map();\n\tconst issues: Array<CoverageIssue> = [];\n\tfor (const occurrence of plan.occurrences) {\n\t\tconst issue = (tag: CoverageIssue[\"_tag\"]) =>\n\t\t\tissues.push({\n\t\t\t\t_tag: tag,\n\t\t\t\toccurrenceId: occurrence.id,\n\t\t\t\tactionId: occurrence.action.id,\n\t\t\t\tdescription: occurrence.action.description,\n\t\t\t\tmigrationId: occurrence.migration.id,\n\t\t\t\trule:\n\t\t\t\t\toccurrence.origin._tag === \"Replacement\"\n\t\t\t\t\t\t? occurrence.origin.rule.id\n\t\t\t\t\t\t: undefined,\n\t\t\t\treplaces: describeReplaces(occurrence),\n\t\t\t});\n\n\t\tconst candidates = byAction.get(occurrence.action.id) ?? [];\n\t\tconst [selected] = candidates;\n\t\tif (candidates.length > 1) issue(\"Duplicate\");\n\t\telse if (selected === undefined) issue(\"Missing\");\n\t\telse if (\n\t\t\tselected.action.kind !== occurrence.action.kind ||\n\t\t\t!Equal.equals(selected.action.payload, occurrence.action.payload)\n\t\t) {\n\t\t\tissue(\"Mismatched\");\n\t\t} else resolved.set(occurrence.id, selected);\n\t}\n\n\treturn { resolved, issues };\n};\n\nconst report = <A extends Action.Any, E>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tmode: Report[\"mode\"],\n\tstatus: Report[\"status\"],\n\toutcomes: ReadonlyMap<string, Outcome<E>>,\n\tbodiesStarted: boolean,\n\tobservation: ReadonlyArray<Observer.ObservationFailure> = [],\n): Report<A, E> => ({\n\t_tag: \"Report\",\n\tmode,\n\tstatus,\n\tfrom: plan.from.id,\n\tto: plan.to.id,\n\troute: plan.route.id,\n\toccurrences: plan.occurrences.map((occurrence) => ({\n\t\toccurrence,\n\t\toutcome: outcomes.get(occurrence.id) ?? { _tag: \"Unattempted\" },\n\t})),\n\tbodiesStarted,\n\tpersistence: \"none\",\n\tobservation: [...observation],\n});\n\nconst failureOf = <E>(cause: Cause.Cause<E>) => ({\n\terror: Option.getOrUndefined(Cause.findErrorOption(cause)),\n\tcause,\n});\n\n/** The exit an occurrence's scope closes with, so finalizers see how it ended. */\nconst exitOf = <E>(outcome: Outcome<E> | undefined): Exit.Exit<void, E> => {\n\tswitch (outcome?._tag) {\n\t\tcase \"Failed\":\n\t\tcase \"PreparationFailed\":\n\t\t\treturn Exit.failCause(outcome.cause);\n\t\tcase \"Interrupted\":\n\t\t\treturn Exit.interrupt();\n\t\tdefault:\n\t\t\treturn Exit.void;\n\t}\n};\n\nconst forEachBranch = <R>(\n\tbranches: ReadonlyArray<Node>,\n\tconcurrency: Action.Concurrency,\n\trun: (node: Node) => Effect.Effect<void, never, R>,\n) => Effect.forEach(branches, run, { concurrency, discard: true });\n\n/** Registers a callback that cancels the execution. Only `runPromise` uses it. */\ntype Subscribe = (cancel: () => void) => void;\n\n/**\n * Receives the fiber that closes an occurrence scope after an interrupted Promise\n * settles, so the caller can keep the services it built open until then.\n */\ntype Retain = (fiber: Fiber.Fiber<void>) => void;\n\ntype StopReason = \"failure\" | InterruptReason;\n\ntype PhaseResult<T, E> =\n\t| { readonly _tag: \"Done\"; readonly exit: Exit.Exit<T, E> }\n\t| {\n\t\t\treadonly _tag: \"Interrupted\";\n\t\t\treadonly reason: \"cancelled\" | \"timeout\";\n\t\t\treadonly settled: boolean;\n\t };\n\ntype ControlOptions = Pick<Options<never>, \"timeout\" | \"settleTimeout\">;\n\n/** Waiting for a person is `untimed`: only cancellation ends it. */\ntype Timing = \"timed\" | \"untimed\";\n\n/**\n * Logs a cleanup failure that the report cannot carry, with the occurrence or the\n * services layer that owned the resources.\n */\nconst logCleanupFailure = (owner: Record<string, string>) => (cause: Cause.Cause<unknown>) =>\n\tEffect.logError(\"deltafold: cleanup failed\", cause).pipe(Effect.annotateLogs(owner));\n\n/** Admission state, cancellation, and timeouts shared by real and dry runs. */\nconst makeControl = (options: ControlOptions, subscribe: Subscribe | undefined) =>\n\tEffect.gen(function* () {\n\t\tconst halt: { reason: StopReason | undefined } = { reason: undefined };\n\t\tconst cancelled = yield* Deferred.make<\"cancelled\">();\n\t\t/** Completes on cancellation or a timeout. Observer deliveries are bounded from then on. */\n\t\tconst stopped = yield* Deferred.make<void>();\n\t\tconst settleTimeout = options.settleTimeout ?? Duration.seconds(5);\n\n\t\tconst stop = (reason: StopReason) => {\n\t\t\thalt.reason ??= reason;\n\t\t\tif (reason === \"cancelled\" || reason === \"timeout\") {\n\t\t\t\tDeferred.doneUnsafe(stopped, Exit.void);\n\t\t\t}\n\t\t};\n\t\t// A failure can be the first stop reason, so cancellation is also tracked on its own.\n\t\tlet cancellationArrived = false;\n\t\tsubscribe?.(() => {\n\t\t\tcancellationArrived = true;\n\t\t\tstop(\"cancelled\");\n\t\t\tDeferred.doneUnsafe(cancelled, Exit.succeed(\"cancelled\"));\n\t\t});\n\n\t\t/**\n\t\t * Runs one phase, racing it against cancellation and its own timeout. An\n\t\t * interrupted Promise that outlives the settlement grace period goes to `unsettled`.\n\t\t */\n\t\tconst runPhase = <T, E, R>(\n\t\t\twork: Effect.Effect<T, E, R>,\n\t\t\tunsettled: Array<Promise<void>>,\n\t\t\ttiming: Timing = \"timed\",\n\t\t): Effect.Effect<PhaseResult<T, E>, never, R> =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tlet settled = true;\n\t\t\t\tconst tracked = work.pipe(\n\t\t\t\t\tEffect.provideService(SettlementReference, {\n\t\t\t\t\t\tgrace: settleTimeout,\n\t\t\t\t\t\tunsettled: (promise) => {\n\t\t\t\t\t\t\tsettled = false;\n\t\t\t\t\t\t\tunsettled.push(promise);\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst stopSignals: Array<Effect.Effect<\"cancelled\" | \"timeout\">> = [\n\t\t\t\t\tDeferred.await(cancelled),\n\t\t\t\t];\n\t\t\t\tif (options.timeout !== undefined && timing === \"timed\") {\n\t\t\t\t\tstopSignals.push(Effect.as(Effect.sleep(options.timeout), \"timeout\" as const));\n\t\t\t\t}\n\t\t\t\tconst result = yield* Effect.raceFirst(\n\t\t\t\t\tEffect.map(Effect.exit(tracked), (exit) => ({ _tag: \"Done\" as const, exit })),\n\t\t\t\t\tEffect.raceAll(stopSignals).pipe(\n\t\t\t\t\t\t// Stop admission as soon as the signal fires. The race returns only after\n\t\t\t\t\t\t// the interrupted work has had its settlement grace period.\n\t\t\t\t\t\tEffect.tap((reason) => Effect.sync(() => stop(reason))),\n\t\t\t\t\t\tEffect.map((reason) => ({ _tag: \"Stop\" as const, reason })),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (result._tag === \"Done\") return result;\n\n\t\t\t\t// A timeout interrupts only this action. Siblings settle as after any failure.\n\t\t\t\treturn { _tag: \"Interrupted\" as const, reason: result.reason, settled };\n\t\t\t});\n\n\t\treturn {\n\t\t\thalt,\n\t\t\tstop,\n\t\t\trunPhase,\n\t\t\tisCancelled: () => cancellationArrived,\n\t\t\tstopped,\n\t\t\tsettleTimeout,\n\t\t};\n\t});\n\n/**\n * Runs one occurrence in its own scope, which both phases share. `use` returns the\n * exit to close the scope with. The scope closes as soon as the occurrence ends, and\n * a failing finalizer goes to `onCleanupFailure`. If an interrupted Promise has not\n * settled, the scope stays open until it does, possibly forever; a failing\n * finalizer is then logged, because the report may already have been returned.\n */\nconst inScope = <E, R>(\n\tretain: Retain,\n\toccurrenceId: string,\n\tuse: (\n\t\tscope: Scope.Scope,\n\t\tunsettled: Array<Promise<void>>,\n\t) => Effect.Effect<Exit.Exit<void, E>, never, R>,\n\tonCleanupFailure: (cause: Cause.Cause<never>) => Effect.Effect<void>,\n): Effect.Effect<void, never, R> =>\n\tEffect.uninterruptibleMask((restore) =>\n\t\tEffect.gen(function* () {\n\t\t\tconst scope = yield* Scope.make();\n\t\t\tconst unsettled: Array<Promise<void>> = [];\n\t\t\tconst used = yield* Effect.exit(restore(use(scope, unsettled)));\n\t\t\tconst end = Exit.isSuccess(used) ? used.value : used;\n\t\t\tif (unsettled.length > 0) {\n\t\t\t\tconst fiber = yield* Effect.forkDetach(\n\t\t\t\t\tEffect.promise(() => Promise.all(unsettled)).pipe(\n\t\t\t\t\t\tEffect.andThen(Scope.close(scope, end)),\n\t\t\t\t\t\tEffect.catchCause(logCleanupFailure({ occurrence: occurrenceId })),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tretain(fiber);\n\t\t\t} else {\n\t\t\t\tconst closed = yield* Effect.exit(Scope.close(scope, end));\n\t\t\t\tif (Exit.isFailure(closed)) yield* onCleanupFailure(closed.cause);\n\t\t\t}\n\n\t\t\treturn yield* used;\n\t\t}),\n\t).pipe(Effect.asVoid);\n\n/**\n * The outcome of a phase that did not succeed. `undefined` when it succeeded. An Effect\n * handler that interrupted itself stops admission.\n */\nconst unsuccessful = <T, E>(\n\tphase: Handler.Phase,\n\tresult: PhaseResult<T, E>,\n\tstop: (reason: StopReason) => void,\n): Outcome<E> | undefined => {\n\tif (result._tag === \"Interrupted\") {\n\t\treturn {\n\t\t\t_tag: \"Interrupted\",\n\t\t\tphase,\n\t\t\treason: result.reason,\n\t\t\tsettled: result.settled,\n\t\t};\n\t}\n\tif (Exit.isFailure(result.exit) && Cause.hasInterruptsOnly(result.exit.cause)) {\n\t\tstop(\"handler\");\n\n\t\treturn { _tag: \"Interrupted\", phase, reason: \"handler\", settled: true };\n\t}\n\n\treturn undefined;\n};\n\n/** The observers of one run, and the identifier their events carry. */\ntype Observation<R> = {\n\treadonly observers: ReadonlyArray<Observer.Observer<R>>;\n\treadonly runId: string | undefined;\n};\n\n/**\n * Creates the run's event emitter, and sends observers a report-less `RunFinished` if\n * the fiber running `body` is interrupted.\n */\nconst observed = <A extends Action.Any, T, E, R>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tmode: Report[\"mode\"],\n\tobservation: Observation<R>,\n\tcontrol: Effect.Success<ReturnType<typeof makeControl>>,\n\toutcomes: ReadonlyMap<string, Outcome>,\n\tretain: Retain,\n\tbody: (emitter: Emitter<R>) => Effect.Effect<T, E, R>,\n): Effect.Effect<T, E, R> =>\n\tEffect.gen(function* () {\n\t\tconst emitter = yield* makeEmitter({\n\t\t\tplan,\n\t\t\tmode,\n\t\t\trunId: observation.runId,\n\t\t\tobservers: observation.observers,\n\t\t\toutcomes,\n\t\t\tstopped: control.stopped,\n\t\t\tgrace: control.settleTimeout,\n\t\t\tretain,\n\t\t});\n\n\t\treturn yield* Effect.onInterrupt(body(emitter), () => emitter.interrupted);\n\t});\n\nconst execute = <A extends Action.Any, E, R>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tresolved: Resolved<E, R>,\n\tinteraction: Interaction.Interaction<E, R> | undefined,\n\tobservation: Observation<R>,\n\toptions: ControlOptions,\n\tsubscribe: Subscribe | undefined,\n\tretain: Retain,\n): Effect.Effect<Report<A, E>, ExecutionFailed<A, E> | ExecutionInterrupted<A, E>, R> =>\n\tEffect.gen(function* () {\n\t\tconst outcomes = new Map<string, Outcome<E>>();\n\t\tconst control = yield* makeControl(options, subscribe);\n\t\tconst { halt, stop, runPhase, isCancelled } = control;\n\t\tlet bodiesStarted = false;\n\n\t\treturn yield* observed(plan, \"execute\", observation, control, outcomes, retain, (emitter) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst runOccurrence = (occurrence: Occurrence) => {\n\t\t\t\t\tif (halt.reason !== undefined) return Effect.void;\n\n\t\t\t\t\tconst handler = resolved.get(occurrence.id);\n\t\t\t\t\tif (handler === undefined) return Effect.void;\n\n\t\t\t\t\tlet phase: Handler.Phase = \"prepare\";\n\t\t\t\t\tconst end = (outcome: Outcome<E>) => {\n\t\t\t\t\t\toutcomes.set(occurrence.id, outcome);\n\n\t\t\t\t\t\treturn exitOf(outcome);\n\t\t\t\t\t};\n\t\t\t\t\tconst fail = (cause: Cause.Cause<E>) => {\n\t\t\t\t\t\tstop(\"failure\");\n\n\t\t\t\t\t\treturn end({ _tag: \"Failed\", phase, ...failureOf(cause) });\n\t\t\t\t\t};\n\n\t\t\t\t\t// Observers are awaited before each phase, so admission is checked again after\n\t\t\t\t\t// they hear that it is starting. A handler that prepares has started once\n\t\t\t\t\t// preparation succeeds, and from then on only cancellation keeps it from going on.\n\t\t\t\t\tconst admitted = () =>\n\t\t\t\t\t\thandler.prepares ? !isCancelled() : halt.reason === undefined;\n\n\t\t\t\t\tconst use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tlet step: Handler.Step<E, R>;\n\t\t\t\t\t\t\tif (handler.prepares) {\n\t\t\t\t\t\t\t\tyield* emitter.phaseStarted(occurrence, \"prepare\");\n\t\t\t\t\t\t\t\tif (halt.reason !== undefined) return Exit.void;\n\t\t\t\t\t\t\t\tconst preparation = yield* runPhase(\n\t\t\t\t\t\t\t\t\thandler.prepare(scope),\n\t\t\t\t\t\t\t\t\tunsettled,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconst stopped = unsuccessful(\"prepare\", preparation, stop);\n\t\t\t\t\t\t\t\tif (stopped !== undefined) return end(stopped);\n\t\t\t\t\t\t\t\tif (preparation._tag !== \"Done\") return Exit.void;\n\t\t\t\t\t\t\t\tif (Exit.isFailure(preparation.exit)) {\n\t\t\t\t\t\t\t\t\treturn fail(preparation.exit.cause);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tstep = preparation.exit.value;\n\t\t\t\t\t\t\t\t// The occurrence has started, so a sibling failure or timeout lets it\n\t\t\t\t\t\t\t\t// finish. Cancellation that arrived while preparing keeps it from\n\t\t\t\t\t\t\t\t// applying, and the prepared value is discarded.\n\t\t\t\t\t\t\t\tif (step._tag === \"Apply\" && halt.reason === \"cancelled\") {\n\t\t\t\t\t\t\t\t\treturn Exit.void;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst started = yield* Effect.exit(handler.prepare(scope));\n\t\t\t\t\t\t\t\tif (Exit.isFailure(started)) return fail(started.cause);\n\t\t\t\t\t\t\t\tstep = started.value;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (step._tag === \"Skip\") {\n\t\t\t\t\t\t\t\treturn end({ _tag: \"Skipped\", reason: step.reason });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (step._tag === \"Confirm\") {\n\t\t\t\t\t\t\t\t// The interaction preflight guarantees one for every manual occurrence.\n\t\t\t\t\t\t\t\tif (interaction === undefined) return Exit.void;\n\n\t\t\t\t\t\t\t\tphase = \"confirmation\";\n\t\t\t\t\t\t\t\tyield* emitter.phaseStarted(occurrence, \"confirmation\");\n\t\t\t\t\t\t\t\tif (!admitted()) return Exit.void;\n\t\t\t\t\t\t\t\t// The person may start changing state as soon as they are asked.\n\t\t\t\t\t\t\t\tbodiesStarted = true;\n\t\t\t\t\t\t\t\tconst asked = yield* runPhase(\n\t\t\t\t\t\t\t\t\tinteraction.confirm({ occurrence }),\n\t\t\t\t\t\t\t\t\tunsettled,\n\t\t\t\t\t\t\t\t\t\"untimed\",\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tconst unanswered = unsuccessful(\"confirmation\", asked, stop);\n\t\t\t\t\t\t\t\tif (unanswered !== undefined) return end(unanswered);\n\t\t\t\t\t\t\t\tif (asked._tag !== \"Done\") return Exit.void;\n\t\t\t\t\t\t\t\tif (Exit.isFailure(asked.exit)) return fail(asked.exit.cause);\n\t\t\t\t\t\t\t\tif (asked.exit.value === \"declined\") {\n\t\t\t\t\t\t\t\t\tstop(\"failure\");\n\n\t\t\t\t\t\t\t\t\treturn end({ _tag: \"Declined\" });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (step.verify === undefined) {\n\t\t\t\t\t\t\t\t\treturn end({\n\t\t\t\t\t\t\t\t\t\t_tag: \"Completed\",\n\t\t\t\t\t\t\t\t\t\tperformer: \"manual\",\n\t\t\t\t\t\t\t\t\t\tconfirmation: \"asserted\",\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tphase = \"verification\";\n\t\t\t\t\t\t\t\t// Cancellation that arrived with the confirmation, or while observers\n\t\t\t\t\t\t\t\t// heard that the check is starting, keeps the check from starting.\n\t\t\t\t\t\t\t\tconst unverified = () =>\n\t\t\t\t\t\t\t\t\tend({\n\t\t\t\t\t\t\t\t\t\t_tag: \"Interrupted\",\n\t\t\t\t\t\t\t\t\t\tphase: \"verification\",\n\t\t\t\t\t\t\t\t\t\treason: \"cancelled\",\n\t\t\t\t\t\t\t\t\t\tsettled: true,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (isCancelled()) return unverified();\n\t\t\t\t\t\t\t\tyield* emitter.phaseStarted(occurrence, \"verification\");\n\t\t\t\t\t\t\t\tif (isCancelled()) return unverified();\n\t\t\t\t\t\t\t\tconst checked = yield* runPhase(step.verify, unsettled);\n\t\t\t\t\t\t\t\tconst unchecked = unsuccessful(\"verification\", checked, stop);\n\t\t\t\t\t\t\t\tif (unchecked !== undefined) return end(unchecked);\n\t\t\t\t\t\t\t\tif (checked._tag !== \"Done\") return Exit.void;\n\t\t\t\t\t\t\t\tif (Exit.isFailure(checked.exit)) return fail(checked.exit.cause);\n\n\t\t\t\t\t\t\t\treturn end({\n\t\t\t\t\t\t\t\t\t_tag: \"Completed\",\n\t\t\t\t\t\t\t\t\tperformer: \"manual\",\n\t\t\t\t\t\t\t\t\tconfirmation: \"verified\",\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tphase = \"apply\";\n\t\t\t\t\t\t\tyield* emitter.phaseStarted(occurrence, \"apply\");\n\t\t\t\t\t\t\tif (!admitted()) return Exit.void;\n\t\t\t\t\t\t\tbodiesStarted = true;\n\t\t\t\t\t\t\tconst applied = yield* runPhase(step.apply, unsettled);\n\t\t\t\t\t\t\tconst stopped = unsuccessful(\"apply\", applied, stop);\n\t\t\t\t\t\t\tif (stopped !== undefined) return end(stopped);\n\t\t\t\t\t\t\tif (applied._tag !== \"Done\") return Exit.void;\n\t\t\t\t\t\t\tif (Exit.isFailure(applied.exit)) return fail(applied.exit.cause);\n\n\t\t\t\t\t\t\treturn end({ _tag: \"Completed\", performer: \"automated\" });\n\t\t\t\t\t\t});\n\n\t\t\t\t\t// A finalizer that fails before the report is part of the execution: it fails\n\t\t\t\t\t// an occurrence that otherwise ended normally. An interrupted occurrence keeps\n\t\t\t\t\t// its outcome, and the failure is logged.\n\t\t\t\t\tconst onCleanupFailure = (cause: Cause.Cause<never>) =>\n\t\t\t\t\t\tEffect.suspend(() => {\n\t\t\t\t\t\t\tconst outcome = outcomes.get(occurrence.id);\n\t\t\t\t\t\t\tif (outcome?._tag === \"Interrupted\") {\n\t\t\t\t\t\t\t\treturn logCleanupFailure({ occurrence: occurrence.id })(cause);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstop(\"failure\");\n\t\t\t\t\t\t\toutcomes.set(occurrence.id, {\n\t\t\t\t\t\t\t\t_tag: \"Failed\",\n\t\t\t\t\t\t\t\tphase,\n\t\t\t\t\t\t\t\t...failureOf(\n\t\t\t\t\t\t\t\t\toutcome?._tag === \"Failed\"\n\t\t\t\t\t\t\t\t\t\t? Cause.combine(outcome.cause, cause)\n\t\t\t\t\t\t\t\t\t\t: cause,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn Effect.void;\n\t\t\t\t\t\t});\n\n\t\t\t\t\t// Observers hear the outcome once the scope has closed, when a cleanup failure\n\t\t\t\t\t// can no longer change it.\n\t\t\t\t\treturn Effect.andThen(\n\t\t\t\t\t\tinScope(retain, occurrence.id, use, onCleanupFailure),\n\t\t\t\t\t\temitter.settled(occurrence),\n\t\t\t\t\t);\n\t\t\t\t};\n\n\t\t\t\tconst runNode = (node: Node): Effect.Effect<void, never, R> => {\n\t\t\t\t\tswitch (node._tag) {\n\t\t\t\t\t\tcase \"Occurrence\":\n\t\t\t\t\t\t\treturn runOccurrence(node);\n\t\t\t\t\t\tcase \"Sequence\":\n\t\t\t\t\t\t\treturn Effect.forEach(node.children, runNode, { discard: true });\n\t\t\t\t\t}\n\n\t\t\t\t\t// Sibling failures stop admission through `halt`; they never interrupt branches.\n\t\t\t\t\treturn forEachBranch(node.branches, node.concurrency, runNode);\n\t\t\t\t};\n\n\t\t\t\tyield* emitter.runStarted;\n\t\t\t\tfor (const step of plan.steps) {\n\t\t\t\t\t// Migration steps are barriers: a step starts only after the previous one\n\t\t\t\t\t// settled.\n\t\t\t\t\tif (halt.reason !== undefined) break;\n\t\t\t\t\tif (step.omitted) continue;\n\t\t\t\t\tyield* emitter.stepStarted(step);\n\t\t\t\t\tyield* runNode(step.node);\n\t\t\t\t\tyield* emitter.stepSettled(step);\n\t\t\t\t}\n\n\t\t\t\tconst reason = halt.reason;\n\t\t\t\tconst status =\n\t\t\t\t\treason === undefined\n\t\t\t\t\t\t? \"completed\"\n\t\t\t\t\t\t: reason === \"failure\"\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"interrupted\";\n\t\t\t\tyield* emitter.runFinished(status);\n\t\t\t\tconst result = report(\n\t\t\t\t\tplan,\n\t\t\t\t\t\"execute\",\n\t\t\t\t\tstatus,\n\t\t\t\t\toutcomes,\n\t\t\t\t\tbodiesStarted,\n\t\t\t\t\temitter.failures,\n\t\t\t\t);\n\t\t\t\tif (reason === undefined) return result;\n\t\t\t\tif (reason === \"failure\") {\n\t\t\t\t\treturn yield* new ExecutionFailed({\n\t\t\t\t\t\tfailures: result.occurrences.filter(\n\t\t\t\t\t\t\t(entry) => entry.outcome._tag === \"Failed\",\n\t\t\t\t\t\t),\n\t\t\t\t\t\tdeclined: result.occurrences.filter(\n\t\t\t\t\t\t\t(entry) => entry.outcome._tag === \"Declined\",\n\t\t\t\t\t\t),\n\t\t\t\t\t\treport: result,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn yield* new ExecutionInterrupted({ reason, report: result });\n\t\t\t}),\n\t\t);\n\t});\n\nconst dryRun = <A extends Action.Any, E, R>(\n\tplan: Plan.Plan<A, Plan.Coverage>,\n\tresolved: Resolved<E, R>,\n\tobservation: Observation<R>,\n\toptions: ControlOptions,\n\tsubscribe: Subscribe | undefined,\n\tretain: Retain,\n): Effect.Effect<Report<A, E>, ExecutionInterrupted<A, E>, R> =>\n\tEffect.gen(function* () {\n\t\tconst outcomes = new Map<string, Outcome<E>>();\n\t\tconst control = yield* makeControl(options, subscribe);\n\t\tconst { halt, stop, runPhase } = control;\n\t\tlet failedAt: string | undefined;\n\n\t\treturn yield* observed(plan, \"dry-run\", observation, control, outcomes, retain, (emitter) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst settle = (occurrence: Occurrence, outcome: Outcome<E>) => {\n\t\t\t\t\toutcomes.set(occurrence.id, outcome);\n\n\t\t\t\t\treturn emitter.settled(occurrence);\n\t\t\t\t};\n\n\t\t\t\t/** Runs a prepare phase in the occurrence's scope and records what it predicts. */\n\t\t\t\tconst prepare = (occurrence: Occurrence, handler: Internal<E, R>) => {\n\t\t\t\t\tconst id = occurrence.id;\n\t\t\t\t\tconst end = (outcome: Outcome<E>) => {\n\t\t\t\t\t\toutcomes.set(id, outcome);\n\n\t\t\t\t\t\treturn exitOf(outcome);\n\t\t\t\t\t};\n\t\t\t\t\tconst use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tyield* emitter.phaseStarted(occurrence, \"prepare\");\n\t\t\t\t\t\t\t// Observers are awaited, so the run may have stopped while they heard it.\n\t\t\t\t\t\t\tif (halt.reason !== undefined) return Exit.void;\n\t\t\t\t\t\t\tconst preparation = yield* runPhase(handler.prepare(scope), unsettled);\n\t\t\t\t\t\t\tconst stopped = unsuccessful(\"prepare\", preparation, stop);\n\t\t\t\t\t\t\tif (stopped !== undefined) return end(stopped);\n\t\t\t\t\t\t\tif (preparation._tag !== \"Done\") return Exit.void;\n\t\t\t\t\t\t\tif (Exit.isFailure(preparation.exit)) {\n\t\t\t\t\t\t\t\tfailedAt = id;\n\n\t\t\t\t\t\t\t\treturn end({\n\t\t\t\t\t\t\t\t\t_tag: \"PreparationFailed\",\n\t\t\t\t\t\t\t\t\t...failureOf(preparation.exit.cause),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// A dry run never applies: the prepared value is discarded.\n\t\t\t\t\t\t\tconst step = preparation.exit.value;\n\n\t\t\t\t\t\t\treturn end(\n\t\t\t\t\t\t\t\tstep._tag === \"Skip\"\n\t\t\t\t\t\t\t\t\t? { _tag: \"WouldSkip\", reason: step.reason }\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t_tag: \"WouldExecute\",\n\t\t\t\t\t\t\t\t\t\t\tevaluated: true,\n\t\t\t\t\t\t\t\t\t\t\tperformer: handler.performer,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\tconst onCleanupFailure = (cause: Cause.Cause<never>) =>\n\t\t\t\t\t\tEffect.suspend(() => {\n\t\t\t\t\t\t\tconst outcome = outcomes.get(id);\n\t\t\t\t\t\t\tif (outcome?._tag === \"Interrupted\") {\n\t\t\t\t\t\t\t\treturn logCleanupFailure({ occurrence: id })(cause);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfailedAt ??= id;\n\t\t\t\t\t\t\toutcomes.set(id, {\n\t\t\t\t\t\t\t\t_tag: \"PreparationFailed\",\n\t\t\t\t\t\t\t\t...failureOf(\n\t\t\t\t\t\t\t\t\toutcome?._tag === \"PreparationFailed\"\n\t\t\t\t\t\t\t\t\t\t? Cause.combine(outcome.cause, cause)\n\t\t\t\t\t\t\t\t\t\t: cause,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn Effect.void;\n\t\t\t\t\t\t});\n\n\t\t\t\t\treturn Effect.andThen(\n\t\t\t\t\t\tinScope(retain, id, use, onCleanupFailure),\n\t\t\t\t\t\temitter.settled(occurrence),\n\t\t\t\t\t);\n\t\t\t\t};\n\n\t\t\t\t/** Returns whether the node would or might change state. */\n\t\t\t\tconst visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tif (node._tag === \"Sequence\") {\n\t\t\t\t\t\t\tlet current = dirty;\n\t\t\t\t\t\t\tfor (const child of node.children)\n\t\t\t\t\t\t\t\tcurrent = yield* visit(child, current);\n\n\t\t\t\t\t\t\treturn current;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (node._tag === \"Parallel\") {\n\t\t\t\t\t\t\t// Branches are independent: each starts from the state before the group.\n\t\t\t\t\t\t\t// They are evaluated one at a time so the report is deterministic.\n\t\t\t\t\t\t\tlet changed = dirty;\n\t\t\t\t\t\t\tfor (const branch of node.branches)\n\t\t\t\t\t\t\t\tchanged = (yield* visit(branch, dirty)) || changed;\n\n\t\t\t\t\t\t\treturn changed;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst handler = resolved.get(node.id);\n\t\t\t\t\t\tif (handler === undefined || halt.reason !== undefined) return dirty;\n\t\t\t\t\t\tif (failedAt !== undefined) {\n\t\t\t\t\t\t\tyield* settle(node, {\n\t\t\t\t\t\t\t\t_tag: \"Undetermined\",\n\t\t\t\t\t\t\t\treason: `Execution would stop at the failed preparation of \"${failedAt}\".`,\n\t\t\t\t\t\t\t\tperformer: handler.performer,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!handler.prepares) {\n\t\t\t\t\t\t\tyield* settle(node, {\n\t\t\t\t\t\t\t\t_tag: \"WouldExecute\",\n\t\t\t\t\t\t\t\tevaluated: false,\n\t\t\t\t\t\t\t\tperformer: handler.performer,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (dirty) {\n\t\t\t\t\t\t\tyield* settle(node, {\n\t\t\t\t\t\t\t\t_tag: \"Undetermined\",\n\t\t\t\t\t\t\t\treason: \"The prepare phase depends on earlier actions that a dry run does not apply.\",\n\t\t\t\t\t\t\t\tperformer: handler.performer,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tyield* prepare(node, handler);\n\n\t\t\t\t\t\treturn outcomes.get(node.id)?._tag !== \"WouldSkip\";\n\t\t\t\t\t});\n\n\t\t\t\tyield* emitter.runStarted;\n\t\t\t\t// Later migrations conservatively depend on every earlier migration.\n\t\t\t\tlet dirty = false;\n\t\t\t\tfor (const step of plan.steps) {\n\t\t\t\t\tif (halt.reason !== undefined) break;\n\t\t\t\t\tif (step.omitted) continue;\n\t\t\t\t\tyield* emitter.stepStarted(step);\n\t\t\t\t\tdirty = yield* visit(step.node, dirty);\n\t\t\t\t\tyield* emitter.stepSettled(step);\n\t\t\t\t}\n\n\t\t\t\tconst reason = halt.reason;\n\t\t\t\tif (reason !== undefined && reason !== \"failure\") {\n\t\t\t\t\tyield* emitter.runFinished(\"interrupted\");\n\n\t\t\t\t\treturn yield* new ExecutionInterrupted({\n\t\t\t\t\t\treason,\n\t\t\t\t\t\treport: report(\n\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\"dry-run\",\n\t\t\t\t\t\t\t\"interrupted\",\n\t\t\t\t\t\t\toutcomes,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\temitter.failures,\n\t\t\t\t\t\t),\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst status = failedAt === undefined ? \"would-complete\" : \"would-fail\";\n\t\t\t\tyield* emitter.runFinished(status);\n\n\t\t\t\treturn report(plan, \"dry-run\", status, outcomes, false, emitter.failures);\n\t\t\t}),\n\t\t);\n\t});\n\nconst run = <\n\tA extends Action.Any,\n\tC extends Plan.Coverage,\n\tH extends Handler.Any,\n\tI extends Interaction.Any,\n\tO extends Observer.Any,\n>(\n\tplan: Plan.Plan<A, C>,\n\toptions: Options<H, I, O>,\n\tsubscribe: Subscribe | undefined,\n\tretain: Retain,\n): Effect.Effect<\n\tReport<A, Errors<H, I>>,\n\tExecutionError<A, Errors<H, I>>,\n\tRequirements<H, I, O>\n> => {\n\t// Handlers, interactions, and observers are covariant in their errors and services,\n\t// and `Errors<H, I>` and `Requirements<H, I, O>` collect them from each handler in `H`,\n\t// from `I`, and from each observer in `O`, so all of them fit these shapes. From here\n\t// on the compiler checks both channels.\n\tconst handlers: ReadonlyArray<Internal<Errors<H, I>, Requirements<H, I, O>>> =\n\t\toptions.handlers ?? [];\n\tconst interaction: Interaction.Interaction<Errors<H, I>, Requirements<H, I, O>> | undefined =\n\t\toptions.interaction;\n\tconst observation: Observation<Requirements<H, I, O>> = {\n\t\tobservers: options.observers ?? [],\n\t\trunId: options.runId,\n\t};\n\n\treturn Effect.gen(function* () {\n\t\tconst checked = coverage(plan, handlers);\n\t\tif (checked.issues.length > 0) {\n\t\t\treturn yield* new HandlerCoverageError({\n\t\t\t\tissues: checked.issues,\n\t\t\t\treport: report(\n\t\t\t\t\tplan,\n\t\t\t\t\toptions.dryRun === true ? \"dry-run\" : \"execute\",\n\t\t\t\t\t\"not-started\",\n\t\t\t\t\tnew Map<string, Outcome<never>>(),\n\t\t\t\t\tfalse,\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\n\t\tif (options.dryRun === true) {\n\t\t\treturn yield* dryRun(plan, checked.resolved, observation, options, subscribe, retain);\n\t\t}\n\n\t\t// Nobody can answer for manual work, so the run must not start and stop halfway.\n\t\tconst manual = plan.occurrences.filter(\n\t\t\t(occurrence) => checked.resolved.get(occurrence.id)?.performer === \"manual\",\n\t\t);\n\t\tif (manual.length > 0 && interaction === undefined) {\n\t\t\treturn yield* new InteractionUnavailable({\n\t\t\t\toccurrences: manual,\n\t\t\t\treport: report(\n\t\t\t\t\tplan,\n\t\t\t\t\t\"execute\",\n\t\t\t\t\t\"not-started\",\n\t\t\t\t\tnew Map<string, Outcome<never>>(),\n\t\t\t\t\tfalse,\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\n\t\treturn yield* execute(\n\t\t\tplan,\n\t\t\tchecked.resolved,\n\t\t\tinteraction,\n\t\t\tobservation,\n\t\t\toptions,\n\t\t\tsubscribe,\n\t\t\tretain,\n\t\t);\n\t});\n};\n\n/**\n * Runs a plan as an Effect. Coverage, and the interaction that manual handlers need,\n * are checked before any handler phase runs. Steps\n * are sequential barriers; parallel groups run their branches concurrently. On failure,\n * no new action starts, and actions already running settle before the effect fails\n * with the partial report.\n *\n * Each occurrence has its own scope, shared by its phases and closed when it ends. An\n * interrupted Promise that has not settled keeps its occurrence's scope open until it\n * settles, after the effect has ended. Services that the caller provides stay the\n * caller's to release.\n *\n * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the\n * signal passed to Promise callbacks. The effect then ends as interrupted, without a\n * report. Observers receive a final `RunFinished` event without a report, delivered\n * within `settleTimeout`.\n *\n * @since 0.0.1\n */\nexport const effect = <\n\tA extends Action.Any,\n\tC extends Plan.Coverage,\n\tH extends Handler.Any = never,\n\tI extends Interaction.Any = never,\n\tO extends Observer.Any = never,\n>(\n\tplan: Plan.Plan<A, C>,\n\toptions: Options<H, I, O> & CoverageCheck<A, H, C>,\n): Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>>, Requirements<H, I, O>> =>\n\trun(plan, options, undefined, () => {});\n\ntype ServicesOption<R, LE> = [R] extends [never]\n\t? {\n\t\t\t/** Handlers, interactions, and observers without Effect services need none. */\n\t\t\treadonly services?: Context.Context<never> | Layer.Layer<never, LE>;\n\t\t}\n\t: {\n\t\t\t/** Supplies the Effect services of the handlers, the interaction, and the observers. */\n\t\t\treadonly services: Context.Context<R> | Layer.Layer<R, LE>;\n\t\t};\n\n/** @since 0.0.1 */\nexport type PromiseOptions<\n\tH extends Handler.Any,\n\tI extends Interaction.Any = never,\n\tO extends Observer.Any = never,\n> = Options<H, I, O> & {\n\t/**\n\t * Explicit cancellation. Aborting stops admission, interrupts running actions and\n\t * pending confirmations, and rejects with `ExecutionInterrupted` and the partial\n\t * report.\n\t */\n\treadonly signal?: AbortSignal;\n};\n\n/**\n * Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,\n * `InteractionUnavailable`, `ExecutionFailed`, or `ExecutionInterrupted`, each carrying\n * the partial report.\n * Building a supplied services layer can also reject with the layer's own error,\n * without a report.\n *\n * A services layer is built for this run. A services context stays owned by the\n * caller. A Promise callback that ignores its signal can keep running after\n * cancellation or a timeout, beyond `settleTimeout`; the report marks it as possibly\n * still running. Its occurrence's scope and the run's services layer then stay open\n * until it settles, possibly forever, and close in that order. A cleanup failure after\n * the Promise resolved is logged through Effect.\n *\n * @since 0.0.1\n */\nexport const runPromise = <\n\tA extends Action.Any,\n\tC extends Plan.Coverage,\n\tH extends Handler.Any = never,\n\tI extends Interaction.Any = never,\n\t// After `LE`, so explicit type arguments written for earlier releases keep their meaning.\n\tLE = never,\n\tO extends Observer.Any = never,\n>(\n\tplan: Plan.Plan<A, C>,\n\toptions: PromiseOptions<H, I, O> &\n\t\tServicesOption<Requirements<H, I, O>, LE> &\n\t\tCoverageCheck<A, H, C>,\n): Promise<Report<A, Errors<H, I>>> => {\n\tconst { signal } = options;\n\tconst notStarted = () =>\n\t\tnew ExecutionInterrupted({\n\t\t\treason: \"cancelled\",\n\t\t\treport: report(\n\t\t\t\tplan,\n\t\t\t\toptions.dryRun === true ? \"dry-run\" : \"execute\",\n\t\t\t\t\"interrupted\",\n\t\t\t\tnew Map<string, Outcome<Errors<H, I>>>(),\n\t\t\t\tfalse,\n\t\t\t),\n\t\t});\n\tif (signal?.aborted === true) return Promise.reject(notStarted());\n\n\t// Until the run installs its own cancellation, an abort stops building the services\n\t// layer. Afterwards the run stops admission and reports partial progress.\n\tconst abortedBeforeRun = Deferred.makeUnsafe<void>();\n\tlet cancelRun: (() => void) | undefined;\n\tconst onAbort = () => {\n\t\tif (cancelRun === undefined) Deferred.doneUnsafe(abortedBeforeRun, Effect.void);\n\t\telse cancelRun();\n\t};\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\tconst subscribe: Subscribe | undefined =\n\t\tsignal === undefined\n\t\t\t? undefined\n\t\t\t: (cancel) => {\n\t\t\t\t\tcancelRun = cancel;\n\t\t\t\t\tif (signal.aborted) cancel();\n\t\t\t\t};\n\tconst retained: Array<Fiber.Fiber<void>> = [];\n\tconst program = run(plan, options, subscribe, (fiber) => retained.push(fiber));\n\tconst services: Context.Context<never> | Layer.Layer<never, LE> | undefined = options.services;\n\tconst provided =\n\t\tservices === undefined\n\t\t\t? program\n\t\t\t: Context.isContext(services)\n\t\t\t\t? Effect.provideContext(program, services)\n\t\t\t\t: // runPromise is the entry point: the caller's layer is built for this one run,\n\t\t\t\t\t// in a scope that outlives the run while retained occurrence scopes are open.\n\t\t\t\t\tEffect.uninterruptibleMask((restore) =>\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tconst scope = yield* Scope.make();\n\t\t\t\t\t\t\tconst built = yield* Effect.exit(\n\t\t\t\t\t\t\t\trestore(Layer.buildWithScope(services, scope)),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (Exit.isFailure(built)) {\n\t\t\t\t\t\t\t\tyield* Scope.close(scope, built);\n\n\t\t\t\t\t\t\t\treturn yield* built;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst exit = yield* Effect.exit(\n\t\t\t\t\t\t\t\trestore(Effect.provideContext(program, built.value)),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (retained.length === 0) yield* Scope.close(scope, exit);\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tyield* Effect.forkDetach(\n\t\t\t\t\t\t\t\t\tFiber.awaitAll(retained).pipe(\n\t\t\t\t\t\t\t\t\t\tEffect.andThen(Scope.close(scope, exit)),\n\t\t\t\t\t\t\t\t\t\tEffect.catchCause(\n\t\t\t\t\t\t\t\t\t\t\tlogCleanupFailure({ owner: \"services layer\" }),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treturn yield* exit;\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\tconst cancellable =\n\t\tsignal === undefined\n\t\t\t? provided\n\t\t\t: Effect.raceFirst(\n\t\t\t\t\tprovided,\n\t\t\t\t\tEffect.andThen(Deferred.await(abortedBeforeRun), Effect.fail(notStarted())),\n\t\t\t\t);\n\n\treturn Effect.runPromiseExit(\n\t\t// `ServicesOption` requires services that cover every requirement. A layer that\n\t\t// fails to build rejects with its own error.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion, effecttsgo/unsafe-effect-type-assertion\n\t\tcancellable as Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>> | LE>,\n\t)\n\t\t.finally(() => signal?.removeEventListener(\"abort\", onAbort))\n\t\t.then((exit) => {\n\t\t\tif (Exit.isSuccess(exit)) return exit.value;\n\n\t\t\tthrow Cause.squash(exit.cause);\n\t\t});\n};\n","import { Data, Effect, Predicate } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type { Occurrence } from \"../../foundation/plan.ts\";\nimport type * as Callback from \"./promise-callback.ts\";\nimport { adaptPromise } from \"./promise-callback.ts\";\n\n/**\n * What a person says about manual work. There is no other answer: free-form input never\n * reaches a report.\n *\n * @since 0.2.0\n */\nexport type Answer = \"confirmed\" | \"declined\";\n\n/**\n * A request to confirm manual work. The occurrence carries the action, its description,\n * and the migration instruction that declared it, which is what to show the person.\n *\n * @since 0.2.0\n */\nexport type Request<A extends Action.Any = Action.Any> = {\n\treadonly occurrence: Occurrence<A>;\n};\n\n/**\n * A Promise interaction rejected with a value that none of its declared error guards\n * recognized (`rejected`), or an interaction answered with something other than\n * `\"confirmed\"` or `\"declined\"` (`invalid-answer`). An invalid answer is never kept: it\n * may be text that the person typed.\n *\n * @since 0.2.0\n */\nexport class UnexpectedInteractionError extends Data.TaggedError(\"UnexpectedInteractionError\")<{\n\treadonly occurrenceId: string;\n\treadonly reason: \"rejected\" | \"invalid-answer\";\n\t/** The rejection. Always `undefined` for an invalid answer. */\n\treadonly cause: unknown;\n}> {\n\toverride get message() {\n\t\treturn this.reason === \"rejected\"\n\t\t\t? `The interaction failed unexpectedly while confirming \"${this.occurrenceId}\"`\n\t\t\t: `The interaction answered neither \"confirmed\" nor \"declined\" for \"${this.occurrenceId}\"`;\n\t}\n}\n\nconst isAnswer = (value: unknown): value is Answer => value === \"confirmed\" || value === \"declined\";\n\nconst checkAnswer = (request: Request) => (answer: unknown) =>\n\tisAnswer(answer)\n\t\t? Effect.succeed(answer)\n\t\t: Effect.fail(\n\t\t\t\tnew UnexpectedInteractionError({\n\t\t\t\t\toccurrenceId: request.occurrence.id,\n\t\t\t\t\treason: \"invalid-answer\",\n\t\t\t\t\tcause: undefined,\n\t\t\t\t}),\n\t\t\t);\n\nconst TypeId = \"~deltafold/Interaction\";\n\n/**\n * Asks a person to confirm the manual work of a plan. The executor has no terminal or\n * user interface of its own: the consumer running the plan supplies one of these.\n *\n * Parallel branches can ask at the same time. An interaction that owns one terminal\n * serializes its own prompts. A failure or a decline elsewhere stops new actions but\n * does not withdraw a request that was already made; only cancellation does.\n *\n * @since 0.2.0\n */\nexport type Interaction<out E = never, out R = never> = {\n\treadonly [TypeId]: typeof TypeId;\n\treadonly confirm: (request: Request) => Effect.Effect<Answer, E, R>;\n};\n\n/**\n * Any interaction.\n *\n * @since 0.2.0\n */\nexport type Any = Interaction<any, any>;\n\n/**\n * The errors of an interaction.\n *\n * @since 0.2.0\n */\nexport type Error<I> = I extends Interaction<infer E, any> ? E : never;\n\n/**\n * The Effect services of an interaction.\n *\n * @since 0.2.0\n */\nexport type Services<I> = I extends Interaction<any, infer R> ? R : never;\n\n/** @since 0.2.0 */\nexport const isInteraction = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId);\n\n/** @since 0.2.0 */\nexport type PromiseOptions<\n\tS extends Callback.ServiceMap,\n\tG extends ReadonlyArray<Callback.ErrorGuard>,\n> = {\n\t/** Effect services resolved for the callback and added to the run's requirements. */\n\treadonly services?: S;\n\t/** Guards for rejections that keep their own type. */\n\treadonly errors?: G;\n};\n\n/**\n * Confirms manual work with a Promise callback. It receives `{ signal, services }`: an\n * `AbortSignal` that aborts when the run is cancelled, so it can stop asking, and the\n * declared services.\n *\n * @example\n * ```ts\n * // The migration's instruction for this action, or the action's description.\n * const textOf = ({ action, instruction }: Plan.Occurrence) =>\n * \tinstruction?.content\n * \t\t.map((part) => (part._tag === \"Text\" ? part.text : part.action.description))\n * \t\t.join(\"\") ?? action.description;\n *\n * const interaction = Interaction.promise(async ({ occurrence }, { signal }) =>\n * \t(await ask(textOf(occurrence), { signal })) ? \"confirmed\" : \"declined\",\n * );\n * ```\n *\n * @since 0.2.0\n */\nexport const promise = <\n\tconst S extends Callback.ServiceMap = Callback.NoServices,\n\tconst G extends ReadonlyArray<Callback.ErrorGuard> = [],\n>(\n\tconfirm: (request: Request, context: Callback.PromiseContext<S>) => PromiseLike<Answer>,\n\toptions?: PromiseOptions<S, G>,\n): Interaction<\n\tCallback.GuardedError<G[number]> | UnexpectedInteractionError,\n\tCallback.ServiceIds<S>\n> => {\n\tconst adapt = adaptPromise(options ?? {});\n\n\treturn {\n\t\t[TypeId]: TypeId,\n\t\tconfirm: (request) =>\n\t\t\tadapt<unknown, UnexpectedInteractionError>(\n\t\t\t\t(context) => confirm(request, context),\n\t\t\t\t(cause) =>\n\t\t\t\t\tnew UnexpectedInteractionError({\n\t\t\t\t\t\toccurrenceId: request.occurrence.id,\n\t\t\t\t\t\treason: \"rejected\",\n\t\t\t\t\t\tcause,\n\t\t\t\t\t}),\n\t\t\t).pipe(Effect.flatMap(checkAnswer(request))),\n\t};\n};\n\n/**\n * Confirms manual work with an Effect, which keeps its own errors and services and\n * stops through Effect interruption when the run is cancelled.\n *\n * @since 0.2.0\n */\nexport const effect = <E = never, R = never>(\n\tconfirm: (request: Request) => Effect.Effect<Answer, E, R>,\n): Interaction<E | UnexpectedInteractionError, R> => ({\n\t[TypeId]: TypeId,\n\tconfirm: (request) =>\n\t\tEffect.flatMap(\n\t\t\tEffect.suspend(() => confirm(request)),\n\t\t\tcheckAnswer(request),\n\t\t),\n});\n","import { Data } from \"effect\";\n\nimport type { RequestDirection } from \"../../foundation/plan.ts\";\nimport type { Issue } from \"./validate.ts\";\n\n/**\n * A candidate route, summarized for diagnostics and explicit selection.\n *\n * @since 0.0.1\n */\nexport type RouteSummary = {\n\t/** Pass this as the `route` option to select the route. */\n\treadonly id: string;\n\treadonly migrations: ReadonlyArray<string>;\n\treadonly shortcuts: ReadonlyArray<string>;\n\t/** Optimized action count, or `undefined` when the route failed to optimize. */\n\treadonly actions: number | undefined;\n\treadonly cost: number;\n\t/** Why the route cannot be planned, if it cannot. */\n\treadonly failure: string | undefined;\n};\n\n/**\n * An ancestry hop with no declared route in the requested direction.\n *\n * @since 0.0.1\n */\nexport type Blocker = {\n\treadonly from: string;\n\treadonly to: string;\n\treadonly reason: string;\n};\n\n/**\n * The history's declarations are invalid. Resolution needs a valid history.\n *\n * @since 0.0.1\n */\nexport class InvalidHistory extends Data.TaggedError(\"InvalidHistory\")<{\n\treadonly issues: ReadonlyArray<Issue>;\n}> {\n\toverride get message() {\n\t\treturn `The history has ${this.issues.length} declaration issue(s): ${this.issues\n\t\t\t.map((issue) => issue.message)\n\t\t\t.join(\" \")}`;\n\t}\n}\n\n/** @since 0.0.1 */\nexport class UnknownVersion extends Data.TaggedError(\"UnknownVersion\")<{\n\treadonly version: string;\n\treadonly known: ReadonlyArray<string>;\n}> {\n\toverride get message() {\n\t\treturn `Version \"${this.version}\" is not registered in the history.`;\n\t}\n}\n\n/**\n * No declared route connects the versions. This never means that no work is needed:\n * declare `Migration.noop` for a supported zero-work transition.\n *\n * @since 0.0.1\n */\nexport class UnsupportedRoute extends Data.TaggedError(\"UnsupportedRoute\")<{\n\treadonly from: string;\n\treadonly to: string;\n\treadonly direction: RequestDirection;\n\t/** Versions that are reachable from `from` in the requested direction. */\n\treadonly reachable: ReadonlyArray<string>;\n\t/** Reachable versions closest to `to` along release ancestry. Ties are all listed. */\n\treadonly closest: ReadonlyArray<string>;\n\treadonly blockers: ReadonlyArray<Blocker>;\n}> {\n\toverride get message() {\n\t\tconst closest =\n\t\t\tthis.closest.length === 0 ? \"\" : ` Closest reachable: ${this.closest.join(\", \")}.`;\n\n\t\treturn `No declared ${this.direction} route from \"${this.from}\" to \"${this.to}\".${closest}`;\n\t}\n}\n\n/**\n * Several routes connect the versions and no selection or policy chose one.\n *\n * @since 0.0.1\n */\nexport class AmbiguousRoute extends Data.TaggedError(\"AmbiguousRoute\")<{\n\treadonly from: string;\n\treadonly to: string;\n\treadonly candidates: ReadonlyArray<RouteSummary>;\n\treadonly policy: string | undefined;\n}> {\n\toverride get message() {\n\t\tconst ids = this.candidates.map((candidate) => `\"${candidate.id}\"`).join(\", \");\n\t\tconst reason =\n\t\t\tthis.policy === undefined ? \"\" : ` after applying the \"${this.policy}\" policy`;\n\n\t\treturn `${this.candidates.length} routes connect \"${this.from}\" and \"${this.to}\"${reason}: ${ids}. Select one with the \\`route\\` option, or choose a route policy.`;\n\t}\n}\n\n/**\n * The `route` option names no candidate route.\n *\n * @since 0.0.1\n */\nexport class UnknownRoute extends Data.TaggedError(\"UnknownRoute\")<{\n\treadonly route: string;\n\treadonly candidates: ReadonlyArray<RouteSummary>;\n}> {\n\toverride get message() {\n\t\treturn `No candidate route has the identifier \"${this.route}\". Candidates: ${this.candidates\n\t\t\t.map((candidate) => `\"${candidate.id}\"`)\n\t\t\t.join(\", \")}.`;\n\t}\n}\n\n/**\n * Rules rewrite a sequence back into itself.\n *\n * @since 0.0.1\n */\nexport class RewriteCycle extends Data.TaggedError(\"RewriteCycle\")<{\n\treadonly route: string;\n\treadonly rules: ReadonlyArray<string>;\n\treadonly actions: string;\n}> {\n\toverride get message() {\n\t\treturn `Rules ${this.rules.map((rule) => `\"${rule}\"`).join(\", \")} rewrite a sequence back into itself on route \"${this.route}\".`;\n\t}\n}\n\n/**\n * Rules can produce different results depending on which applies first.\n *\n * @since 0.0.1\n */\nexport class ConflictingRewrites extends Data.TaggedError(\"ConflictingRewrites\")<{\n\treadonly route: string;\n\treadonly outcomes: ReadonlyArray<{\n\t\treadonly actions: string;\n\t\treadonly rules: ReadonlyArray<string>;\n\t}>;\n}> {\n\toverride get message() {\n\t\treturn `Rules produce ${this.outcomes.length} different results on route \"${this.route}\", depending on the order they apply in.`;\n\t}\n}\n\n/**\n * Optimization explored too many states or chained too many rule applications, for\n * example because a rule keeps growing the sequence.\n *\n * @since 0.0.1\n */\nexport class RewriteLimitExceeded extends Data.TaggedError(\"RewriteLimitExceeded\")<{\n\treadonly route: string;\n\treadonly limit: \"states\" | \"depth\";\n\treadonly value: number;\n}> {\n\toverride get message() {\n\t\treturn this.limit === \"states\"\n\t\t\t? `Optimizing route \"${this.route}\" explored more than ${this.value} states.`\n\t\t\t: `Optimizing route \"${this.route}\" chained more than ${this.value} rule applications.`;\n\t}\n}\n\n/**\n * More candidate routes exist than the resolver enumerates.\n *\n * @since 0.0.1\n */\nexport class TooManyRoutes extends Data.TaggedError(\"TooManyRoutes\")<{\n\treadonly from: string;\n\treadonly to: string;\n\treadonly limit: number;\n}> {\n\toverride get message() {\n\t\treturn `More than ${this.limit} routes connect \"${this.from}\" and \"${this.to}\".`;\n\t}\n}\n\n/** @since 0.0.1 */\nexport type RewriteError = RewriteCycle | ConflictingRewrites | RewriteLimitExceeded;\n\n/**\n * Why a plan could not be resolved. `UnsupportedRoute` lists the reachable versions, the\n * closest ones by release ancestry, and blockers. `AmbiguousRoute` lists the candidate\n * routes: pass one as `route`, or choose a `policy`.\n *\n * @since 0.0.1\n */\nexport type ResolveError =\n\t| InvalidHistory\n\t| UnknownVersion\n\t| UnsupportedRoute\n\t| AmbiguousRoute\n\t| UnknownRoute\n\t| TooManyRoutes\n\t| RewriteError;\n","import type * as Action from \"../../foundation/action.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { GuideItem, Occurrence } from \"../../foundation/plan.ts\";\n\n/** The declared occurrence a retained occurrence is rendered at. */\nconst anchorOf = (occurrence: Occurrence): Occurrence => {\n\tif (occurrence.origin._tag === \"Declared\") return occurrence;\n\n\tconst first = occurrence.origin.replaces[0];\n\n\treturn first === undefined ? occurrence : anchorOf(first);\n};\n\n/**\n * Resolves a migration's content against the occurrences that survived optimization.\n * Removed occurrences disappear with their instruction blocks. Replacements render at\n * the position of the first occurrence they replaced, using their own instruction or\n * description. Unassociated prose stays.\n */\nexport const resolveGuide = (\n\tcontent: Migration.Content,\n\tretained: ReadonlyArray<Occurrence>,\n\tdeclaredId: (action: Action.Any) => string,\n): ReadonlyArray<GuideItem> => {\n\tconst byAnchor = new Map<string, Array<Occurrence>>();\n\tfor (const occurrence of retained) {\n\t\tconst anchor = anchorOf(occurrence).id;\n\t\tconst list = byAnchor.get(anchor) ?? [];\n\t\tlist.push(occurrence);\n\t\tbyAnchor.set(anchor, list);\n\t}\n\n\tconst renderStep = (step: Action.Step): ReadonlyArray<GuideItem> => {\n\t\tif (step._tag === \"Action\" || step._tag === \"Instruction\") {\n\t\t\tconst action = step._tag === \"Action\" ? step : step.action;\n\n\t\t\treturn (byAnchor.get(declaredId(action)) ?? []).map((occurrence) => ({\n\t\t\t\t_tag: \"Occurrence\",\n\t\t\t\toccurrence,\n\t\t\t}));\n\t\t}\n\n\t\tconst children = (step._tag === \"Sequence\" ? step.children : step.branches)\n\t\t\t.map((child) => renderStep(child))\n\t\t\t.filter((items) => items.length > 0);\n\t\tif (children.length === 0) return [];\n\n\t\treturn [{ _tag: \"Group\", kind: step._tag, children }];\n\t};\n\n\treturn content.flatMap((fragment): ReadonlyArray<GuideItem> => {\n\t\tif (fragment._tag === \"Text\" || fragment._tag === \"ActionRef\") return [fragment];\n\n\t\treturn renderStep(fragment);\n\t});\n};\n","import type * as Action from \"../../foundation/action.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { Direction, Occurrence } from \"../../foundation/plan.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\n\n// Author identifiers may contain any character. Each format escapes its own separators,\n// and the backslash itself, so distinct components never produce the same identifier.\nconst escape = (value: string, separators: RegExp) => value.replace(separators, \"\\\\$&\");\n\nconst occurrencePart = (id: string) => escape(id, /[\\\\/()+]/g);\n\nconst routePart = (id: string) => escape(id, /[\\\\>[\\]]/g);\n\n/** A plan step: `<migration>` forward, `<migration>/revert` in reverse. */\nexport const stepId = (migration: Migration.Any, direction: Direction): string =>\n\tdirection === \"forward\"\n\t\t? occurrencePart(migration.id)\n\t\t: `${occurrencePart(migration.id)}/revert`;\n\n/** `<migration>/<action>` forward, `<migration>/revert/<action>` in reverse. */\nexport const declaredOccurrenceId = (\n\tmigration: Migration.Any,\n\tdirection: Direction,\n\taction: Action.Any,\n): string => `${stepId(migration, direction)}/${occurrencePart(action.id)}`;\n\n/**\n * `<rule>(<replaced>+<replaced>)/<action>`. Replaced identifiers are complete occurrence\n * identifiers, so they nest without further escaping.\n */\nexport const replacementOccurrenceId = (\n\trule: Rule.Any,\n\treplaced: ReadonlyArray<Occurrence>,\n\taction: Action.Any,\n): string =>\n\t`${occurrencePart(rule.id)}(${replaced.map((occurrence) => occurrence.id).join(\"+\")})/${occurrencePart(action.id)}`;\n\n/** The first version of a route identifier. */\nexport const routeStart = (version: string): string => routePart(version);\n\n/** A migration hop: `>` and the target version. */\nexport const routeHop = (to: string): string => `>${routePart(to)}`;\n\n/** A shortcut hop: `>[shortcut]>` and the target version. */\nexport const routeShortcut = (shortcut: string, to: string): string =>\n\t`>[${routePart(shortcut)}]>${routePart(to)}`;\n","import { Array as Arr, Order } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { Occurrence } from \"../../foundation/plan.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\nimport { replacementOccurrenceId } from \"./identifiers.ts\";\n\n/**\n * A top-level element of a route's sequential spine, or of one parallel branch. `step`\n * is the index of the plan step that owns the element.\n */\nexport type Item =\n\t| { readonly _tag: \"Occ\"; readonly occurrence: Occurrence; readonly step: number }\n\t| {\n\t\t\treadonly _tag: \"Par\";\n\t\t\treadonly branches: ReadonlyArray<ReadonlyArray<Item>>;\n\t\t\treadonly concurrency: Action.Concurrency;\n\t\t\treadonly step: number;\n\t }\n\t/** A text-only migration: prose instructions that rules must not match around. */\n\t| { readonly _tag: \"Barrier\"; readonly step: number };\n\nexport type Application = {\n\treadonly rule: Rule.Any;\n\treadonly removed: ReadonlyArray<Occurrence>;\n\treadonly produced: ReadonlyArray<Occurrence>;\n};\n\nexport type Outcome = {\n\treadonly items: ReadonlyArray<Item>;\n\treadonly trace: ReadonlyArray<Application>;\n};\n\nexport type Failure =\n\t| {\n\t\t\treadonly _tag: \"RewriteCycle\";\n\t\t\t/** Rules applied around the cycle, in order. */\n\t\t\treadonly rules: ReadonlyArray<string>;\n\t\t\t/** The action sequence that repeats. */\n\t\t\treadonly actions: string;\n\t }\n\t| {\n\t\t\treadonly _tag: \"ConflictingRewrites\";\n\t\t\treadonly outcomes: ReadonlyArray<{\n\t\t\t\treadonly actions: string;\n\t\t\t\treadonly rules: ReadonlyArray<string>;\n\t\t\t}>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"RewriteLimitExceeded\";\n\t\t\treadonly limit: \"states\" | \"depth\";\n\t\t\treadonly value: number;\n\t };\n\nclass RewriteFailure {\n\treadonly failure: Failure;\n\n\tconstructor(failure: Failure) {\n\t\tthis.failure = failure;\n\t}\n}\n\n/** The largest number of distinct states explored while normalizing one sequence. */\nexport const stateLimit = 10_000;\n\n/** The largest number of rule applications in one chain of rewrites. */\nexport const depthLimit = 256;\n\nconst occurrencesOf = (items: ReadonlyArray<Item>): ReadonlyArray<Occurrence> =>\n\titems.flatMap((item) => {\n\t\tif (item._tag === \"Occ\") return [item.occurrence];\n\t\tif (item._tag === \"Par\") return item.branches.flatMap(occurrencesOf);\n\n\t\treturn [];\n\t});\n\nexport { occurrencesOf };\n\nconst groupKey = (branches: ReadonlyArray<string>) =>\n\t`{${Arr.sort(\n\t\tbranches.map((branch) => `[${branch}]`),\n\t\tOrder.String,\n\t).join(\"|\")}}`;\n\n/** A key that identifies a sequence by its action structure. Branch order is ignored. */\nexport const keyOf = (items: ReadonlyArray<Item>): string =>\n\titems\n\t\t.map((item) => {\n\t\t\tif (item._tag === \"Occ\") return JSON.stringify(item.occurrence.action.id);\n\t\t\tif (item._tag === \"Barrier\") return \"#\";\n\n\t\t\treturn groupKey(item.branches.map(keyOf));\n\t\t})\n\t\t.join(\",\");\n\n/** A key that identifies declared steps by their action structure. Branch order is ignored. */\nexport const stepKey = (steps: ReadonlyArray<Action.Step>): string =>\n\tsteps\n\t\t.map((step) => {\n\t\t\tswitch (step._tag) {\n\t\t\t\tcase \"Action\":\n\t\t\t\t\treturn JSON.stringify(step.id);\n\t\t\t\tcase \"Instruction\":\n\t\t\t\t\treturn JSON.stringify(step.action.id);\n\t\t\t\tcase \"Sequence\":\n\t\t\t\t\treturn stepKey(step.children);\n\t\t\t}\n\t\t\tconst branches = step.branches.map((branch) => stepKey([branch]));\n\t\t\tif (branches.length === 1) return branches[0];\n\n\t\t\treturn groupKey(branches);\n\t\t})\n\t\t.filter((key) => key !== \"\")\n\t\t.join(\",\");\n\nexport type MakeOccurrence = (\n\taction: Action.Any,\n\tinstruction: Migration.Instruction | undefined,\n) => Occurrence;\n\n/** Converts declared steps to items. Sequences flatten; single-branch groups flatten. */\nexport const itemsOf = (\n\tsteps: ReadonlyArray<Action.Step>,\n\tmake: MakeOccurrence,\n\tstep: number,\n): ReadonlyArray<Item> =>\n\tsteps.flatMap((declared): ReadonlyArray<Item> => {\n\t\tswitch (declared._tag) {\n\t\t\tcase \"Action\":\n\t\t\t\treturn [{ _tag: \"Occ\", occurrence: make(declared, undefined), step }];\n\t\t\tcase \"Instruction\":\n\t\t\t\treturn [{ _tag: \"Occ\", occurrence: make(declared.action, declared), step }];\n\t\t\tcase \"Sequence\":\n\t\t\t\treturn itemsOf(declared.children, make, step);\n\t\t}\n\n\t\treturn parallelOf(\n\t\t\tdeclared.branches.map((branch) => itemsOf([branch], make, step)),\n\t\t\tdeclared.concurrency,\n\t\t\tstep,\n\t\t);\n\t});\n\n/** Drops empty branches and flattens a group that has a single branch left. */\nconst parallelOf = (\n\tbranches: ReadonlyArray<ReadonlyArray<Item>>,\n\tconcurrency: Action.Concurrency,\n\tstep: number,\n): ReadonlyArray<Item> => {\n\tconst nonEmpty = branches.filter((branch) => branch.length > 0);\n\tif (nonEmpty.length === 0) return [];\n\tif (nonEmpty.length === 1) return nonEmpty[0] ?? [];\n\n\treturn [{ _tag: \"Par\", branches: nonEmpty, concurrency, step }];\n};\n\nconst matchesAt = (\n\tpattern: ReadonlyArray<Rule.Pattern>,\n\titems: ReadonlyArray<Item>,\n\tposition: number,\n): boolean =>\n\tpattern.every((expected, offset) => {\n\t\tconst item = items[position + offset];\n\t\tif (item === undefined) return false;\n\t\tif (expected._tag === \"Action\") {\n\t\t\treturn item._tag === \"Occ\" && item.occurrence.action.id === expected.id;\n\t\t}\n\n\t\treturn item._tag === \"Par\" && keyOf([item]) === stepKey([expected]);\n\t});\n\ntype Transition = {\n\treadonly next: ReadonlyArray<Item>;\n\treadonly application: Application;\n};\n\n/** Replaces the match of a rule at a position with occurrences that record their provenance. */\nconst replace = (rule: Rule.Any, items: ReadonlyArray<Item>, position: number): Transition => {\n\tconst matched = items.slice(position, position + rule.match.length);\n\tconst removed = occurrencesOf(matched);\n\tconst first = removed[0];\n\t// A non-empty match always covers at least one occurrence.\n\tif (first === undefined) throw new Error(`Rule \"${rule.id}\" matched no occurrences`);\n\tconst step = matched[0]?.step ?? 0;\n\tconst produced: Array<Occurrence> = [];\n\tconst make: MakeOccurrence = (action, instruction) => {\n\t\tconst occurrence: Occurrence = {\n\t\t\t_tag: \"Occurrence\",\n\t\t\tid: replacementOccurrenceId(rule, removed, action),\n\t\t\taction,\n\t\t\tmigration: first.migration,\n\t\t\tdirection: first.direction,\n\t\t\tinstruction,\n\t\t\torigin: { _tag: \"Replacement\", rule, replaces: removed },\n\t\t};\n\t\tproduced.push(occurrence);\n\n\t\treturn occurrence;\n\t};\n\tconst next = [\n\t\t...items.slice(0, position),\n\t\t...itemsOf(rule.replacement, make, step),\n\t\t...items.slice(position + rule.match.length),\n\t];\n\n\treturn { next, application: { rule, removed, produced } };\n};\n\nconst makeNormalizer = (rules: ReadonlyArray<Rule.Any>) => {\n\tconst ordered = Arr.sort(\n\t\trules,\n\t\tOrder.mapInput(Order.String, (rule: Rule.Any) => rule.id),\n\t);\n\n\t/**\n\t * Every single rule application available in a sequence: at any position of the\n\t * sequence itself, or inside any branch of its groups. Branch-local and whole-group\n\t * rewrites compete as transitions from the same state.\n\t */\n\tconst transitions = (items: ReadonlyArray<Item>): ReadonlyArray<Transition> => {\n\t\tconst found: Array<Transition> = [];\n\t\tfor (let position = 0; position < items.length; position++) {\n\t\t\tfor (const rule of ordered) {\n\t\t\t\tif (rule.match.length > 0 && matchesAt(rule.match, items, position)) {\n\t\t\t\t\tfound.push(replace(rule, items, position));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst item = items[position];\n\t\t\tif (item?._tag !== \"Par\") continue;\n\t\t\tfor (const [index, branch] of item.branches.entries()) {\n\t\t\t\tfor (const inner of transitions(branch)) {\n\t\t\t\t\tconst branches = item.branches.map((other, otherIndex) =>\n\t\t\t\t\t\totherIndex === index ? inner.next : other,\n\t\t\t\t\t);\n\t\t\t\t\tfound.push({\n\t\t\t\t\t\tnext: [\n\t\t\t\t\t\t\t...items.slice(0, position),\n\t\t\t\t\t\t\t...parallelOf(branches, item.concurrency, item.step),\n\t\t\t\t\t\t\t...items.slice(position + 1),\n\t\t\t\t\t\t],\n\t\t\t\t\t\tapplication: inner.application,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn found;\n\t};\n\n\t/**\n\t * Explores every rewrite order of the whole sequence, nested groups included, under\n\t * one shared state and depth budget.\n\t */\n\tconst normalize = (input: ReadonlyArray<Item>): Outcome => {\n\t\tconst seen = new Set<string>();\n\t\tconst onPath = new Map<string, number>();\n\t\tconst normals = new Map<string, Outcome>();\n\n\t\tconst visit = (items: ReadonlyArray<Item>, trace: ReadonlyArray<Application>): void => {\n\t\t\tconst key = keyOf(items);\n\t\t\tconst entered = onPath.get(key);\n\t\t\tif (entered !== undefined) {\n\t\t\t\tthrow new RewriteFailure({\n\t\t\t\t\t_tag: \"RewriteCycle\",\n\t\t\t\t\trules: trace.slice(entered).map((application) => application.rule.id),\n\t\t\t\t\tactions: key,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (seen.has(key)) return;\n\n\t\t\tseen.add(key);\n\t\t\tif (seen.size > stateLimit) {\n\t\t\t\tthrow new RewriteFailure({\n\t\t\t\t\t_tag: \"RewriteLimitExceeded\",\n\t\t\t\t\tlimit: \"states\",\n\t\t\t\t\tvalue: stateLimit,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (trace.length > depthLimit) {\n\t\t\t\tthrow new RewriteFailure({\n\t\t\t\t\t_tag: \"RewriteLimitExceeded\",\n\t\t\t\t\tlimit: \"depth\",\n\t\t\t\t\tvalue: depthLimit,\n\t\t\t\t});\n\t\t\t}\n\t\t\tonPath.set(key, trace.length);\n\n\t\t\tconst available = transitions(items);\n\t\t\tfor (const { next, application } of available) visit(next, [...trace, application]);\n\t\t\tif (available.length === 0) normals.set(key, { items, trace });\n\n\t\t\tonPath.delete(key);\n\t\t};\n\n\t\tvisit(input, []);\n\n\t\tif (normals.size > 1) {\n\t\t\tthrow new RewriteFailure({\n\t\t\t\t_tag: \"ConflictingRewrites\",\n\t\t\t\toutcomes: [...normals.entries()].map(([actions, outcome]) => ({\n\t\t\t\t\tactions,\n\t\t\t\t\trules: outcome.trace.map((application) => application.rule.id),\n\t\t\t\t})),\n\t\t\t});\n\t\t}\n\n\t\tconst [outcome] = normals.values();\n\n\t\treturn outcome ?? { items: input, trace: [] };\n\t};\n\n\treturn { normalize };\n};\n\n/** Applies rules to a sequence until no rule matches. */\nexport const rewrite = (\n\titems: ReadonlyArray<Item>,\n\trules: ReadonlyArray<Rule.Any>,\n):\n\t| { readonly _tag: \"Success\"; readonly outcome: Outcome }\n\t| { readonly _tag: \"Failure\"; readonly failure: Failure } => {\n\ttry {\n\t\treturn { _tag: \"Success\", outcome: makeNormalizer(rules).normalize(items) };\n\t} catch (error) {\n\t\tif (error instanceof RewriteFailure) return { _tag: \"Failure\", failure: error.failure };\n\n\t\tthrow error;\n\t}\n};\n","import { Array as Arr, Equal, Graph, Option, Order } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Change from \"../../foundation/change.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\nimport type * as Shortcut from \"../../foundation/shortcut.ts\";\nimport type { Version } from \"../../foundation/version.ts\";\nimport { stepKey } from \"./rewrite.ts\";\n\n/**\n * A problem in a history's declarations.\n *\n * @since 0.0.1\n */\nexport type Issue = {\n\treadonly _tag:\n\t\t| \"DuplicateVersion\"\n\t\t| \"UnregisteredVersion\"\n\t\t| \"AncestryCycle\"\n\t\t| \"ConflictingChange\"\n\t\t| \"ConflictingAction\"\n\t\t| \"DuplicateMigration\"\n\t\t| \"DuplicateEdge\"\n\t\t| \"SelfMigration\"\n\t\t| \"EmptyMigration\"\n\t\t| \"DuplicateOccurrence\"\n\t\t| \"DuplicateRule\"\n\t\t| \"InvalidRule\"\n\t\t| \"DuplicateShortcut\"\n\t\t| \"InvalidShortcut\";\n\t/** The identifier of the declaration the issue is about. */\n\treadonly subject: string;\n\treadonly message: string;\n};\n\nexport type Declarations = {\n\treadonly versions: ReadonlyArray<Version>;\n\treadonly migrations: ReadonlyArray<Migration.Any>;\n\treadonly rules: ReadonlyArray<Rule.Any>;\n\treadonly shortcuts: ReadonlyArray<Shortcut.Any>;\n};\n\nconst issueOrder = Order.combine(\n\tOrder.combine(\n\t\tOrder.mapInput(Order.String, (issue: Issue) => issue._tag),\n\t\tOrder.mapInput(Order.String, (issue: Issue) => issue.subject),\n\t),\n\tOrder.mapInput(Order.String, (issue: Issue) => issue.message),\n);\n\n/** Action instances declared by steps, in declaration order. */\nexport const actionsOfSteps = (steps: ReadonlyArray<Action.Step>): ReadonlyArray<Action.Any> =>\n\tsteps.flatMap((step): ReadonlyArray<Action.Any> => {\n\t\tswitch (step._tag) {\n\t\t\tcase \"Action\":\n\t\t\t\treturn [step];\n\t\t\tcase \"Instruction\":\n\t\t\t\treturn [step.action];\n\t\t\tcase \"Sequence\":\n\t\t\t\treturn actionsOfSteps(step.children);\n\t\t}\n\n\t\treturn actionsOfSteps(step.branches);\n\t});\n\nexport const stepsOf = (content: Migration.Content): ReadonlyArray<Action.Step> =>\n\tcontent.flatMap((fragment) =>\n\t\tfragment._tag === \"Text\" || fragment._tag === \"ActionRef\" ? [] : [fragment],\n\t);\n\n/** Whether two definitions with the same identifier describe the same change. */\nconst sameDefinition = (self: Change.Any, that: Change.Any): boolean =>\n\tself === that ||\n\t(self.id === that.id &&\n\t\tEqual.equals(self.metadata, that.metadata) &&\n\t\tself.description === that.description &&\n\t\tself.backportOf?.id === that.backportOf?.id &&\n\t\tself.reverts.length === that.reverts.length &&\n\t\tself.reverts.every((change, index) => change.id === that.reverts[index]?.id));\n\n/** Whether content declares at least one occurrence. Empty groups declare none. */\nconst hasOccurrences = (content: Migration.Content): boolean =>\n\tactionsOfSteps(stepsOf(content)).length > 0;\n\n/** Whether content has prose or mentions. */\nexport const hasProse = (content: Migration.Content): boolean =>\n\tcontent.some(\n\t\t(fragment) =>\n\t\t\tfragment._tag === \"ActionRef\" ||\n\t\t\t(fragment._tag === \"Text\" && fragment.text.trim() !== \"\"),\n\t);\n\nconst sameAction = (self: Action.Any, that: Action.Any) =>\n\tself === that || (self.kind === that.kind && Equal.equals(self.payload, that.payload));\n\n/** Collects every distinct migration: registered ones and those inside shortcuts. */\nexport const allMigrations = (declarations: Declarations): ReadonlyArray<Migration.Any> => {\n\tconst result: Array<Migration.Any> = [...declarations.migrations];\n\tfor (const shortcut of declarations.shortcuts) {\n\t\tfor (const migration of shortcut.migrations) {\n\t\t\tif (!result.includes(migration)) result.push(migration);\n\t\t}\n\t}\n\n\treturn result;\n};\n\nconst isChain = (migrations: ReadonlyArray<Migration.Any>, from: Version, to: Version): boolean => {\n\tlet current = from.id;\n\tfor (const migration of migrations) {\n\t\tif (migration.from.id !== current) return false;\n\t\tcurrent = migration.to.id;\n\t}\n\n\treturn migrations.length > 0 && current === to.id;\n};\n\nexport const validate = (declarations: Declarations): ReadonlyArray<Issue> => {\n\tconst issues: Array<Issue> = [];\n\tconst issue = (tag: Issue[\"_tag\"], subject: string, message: string) =>\n\t\tissues.push({ _tag: tag, subject, message });\n\n\t// Versions and ancestry.\n\tconst versions = new Map<string, Version>();\n\tfor (const version of declarations.versions) {\n\t\tif (versions.has(version.id)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateVersion\",\n\t\t\t\tversion.id,\n\t\t\t\t`Version \"${version.id}\" is registered more than once.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tversions.set(version.id, version);\n\t}\n\tconst unregistered = new Map<string, Array<string>>();\n\tconst requireVersion = (version: Version, referencedBy: string) => {\n\t\tif (versions.get(version.id) !== undefined) return;\n\n\t\tconst referrers = unregistered.get(version.id) ?? [];\n\t\tif (!referrers.includes(referencedBy)) referrers.push(referencedBy);\n\t\tunregistered.set(version.id, referrers);\n\t};\n\tfor (const version of versions.values()) {\n\t\tif (version.previous !== undefined)\n\t\t\trequireVersion(version.previous, `version \"${version.id}\"`);\n\t}\n\tconst ancestry = Graph.directed<string, undefined>((graph) => {\n\t\tconst nodes = new Map<string, Graph.NodeIndex>();\n\t\tfor (const id of versions.keys()) nodes.set(id, Graph.addNode(graph, id));\n\t\tfor (const version of versions.values()) {\n\t\t\tconst source = nodes.get(version.id);\n\t\t\tconst target =\n\t\t\t\tversion.previous === undefined ? undefined : nodes.get(version.previous.id);\n\t\t\tif (source !== undefined && target !== undefined)\n\t\t\t\tGraph.addEdge(graph, source, target, undefined);\n\t\t}\n\t});\n\tconst cycle = Graph.findCycle(ancestry);\n\tif (Option.isSome(cycle)) {\n\t\tconst ids = cycle.value.path.flatMap((index) =>\n\t\t\tOption.toArray(Graph.getNode(ancestry, index)),\n\t\t);\n\t\tissue(\n\t\t\t\"AncestryCycle\",\n\t\t\tids[0] ?? \"\",\n\t\t\t`Release ancestry contains a cycle: ${ids.join(\" -> \")}.`,\n\t\t);\n\t}\n\n\t// Change definitions.\n\tconst changes = new Map<string, Change.Any>();\n\t// Every distinct object is compared and has its relationships followed, so a repeated\n\t// definition cannot hide a conflict between the changes it refers to.\n\tconst visited = new Set<Change.Any>();\n\tconst conflictingChanges = new Set<string>();\n\tconst visitChange = (change: Change.Any) => {\n\t\tif (visited.has(change)) return;\n\t\tvisited.add(change);\n\t\tconst known = changes.get(change.id);\n\t\tif (known === undefined) changes.set(change.id, change);\n\t\telse if (!sameDefinition(known, change) && !conflictingChanges.has(change.id)) {\n\t\t\tconflictingChanges.add(change.id);\n\t\t\tissue(\n\t\t\t\t\"ConflictingChange\",\n\t\t\t\tchange.id,\n\t\t\t\t`Change \"${change.id}\" has conflicting definitions.`,\n\t\t\t);\n\t\t}\n\t\tfor (const reverted of change.reverts) visitChange(reverted);\n\t\tif (change.backportOf !== undefined) visitChange(change.backportOf);\n\t};\n\tfor (const version of declarations.versions) {\n\t\tfor (const change of version.changes) visitChange(change);\n\t}\n\n\t// Action identities.\n\tconst actions = new Map<string, Action.Any>();\n\tconst conflicting = new Set<string>();\n\tconst visitAction = (action: Action.Any) => {\n\t\tconst known = actions.get(action.id);\n\t\tif (known === undefined) {\n\t\t\tactions.set(action.id, action);\n\n\t\t\treturn;\n\t\t}\n\t\tif (!sameAction(known, action) && !conflicting.has(action.id)) {\n\t\t\tconflicting.add(action.id);\n\t\t\tissue(\n\t\t\t\t\"ConflictingAction\",\n\t\t\t\taction.id,\n\t\t\t\t`Action \"${action.id}\" has conflicting definitions; action identifiers must be unique.`,\n\t\t\t);\n\t\t}\n\t};\n\n\t// Migrations.\n\tconst migrations = allMigrations(declarations);\n\tconst migrationIds = new Map<string, Migration.Any>();\n\tconst registered = new Set<Migration.Any>();\n\tfor (const migration of declarations.migrations) {\n\t\tif (registered.has(migration) || migrationIds.has(migration.id)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateMigration\",\n\t\t\t\tmigration.id,\n\t\t\t\t`Migration \"${migration.id}\" is registered more than once. Register a migration once; register the result of Migration.withRevert in place of the original.`,\n\t\t\t);\n\t\t}\n\t\tregistered.add(migration);\n\t\tmigrationIds.set(migration.id, migration);\n\t}\n\tfor (const migration of migrations) {\n\t\tconst known = migrationIds.get(migration.id);\n\t\tif (known !== undefined && known !== migration && !registered.has(migration)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateMigration\",\n\t\t\t\tmigration.id,\n\t\t\t\t`Migration \"${migration.id}\" has another definition inside a shortcut.`,\n\t\t\t);\n\t\t}\n\t\tif (known === undefined) migrationIds.set(migration.id, migration);\n\n\t\trequireVersion(migration.from, `migration \"${migration.id}\"`);\n\t\trequireVersion(migration.to, `migration \"${migration.id}\"`);\n\t\tif (migration.from.id === migration.to.id) {\n\t\t\tissue(\n\t\t\t\t\"SelfMigration\",\n\t\t\t\tmigration.id,\n\t\t\t\t`Migration \"${migration.id}\" starts and ends at the same version.`,\n\t\t\t);\n\t\t}\n\t\tfor (const change of migration.addresses) visitChange(change);\n\n\t\tconst sides: ReadonlyArray<[string, Migration.Content | undefined]> = [\n\t\t\t[\"forward\", migration.content],\n\t\t\t[\"revert\", migration.revert],\n\t\t];\n\t\tfor (const [direction, content] of sides) {\n\t\t\tif (content === undefined) continue;\n\t\t\tif (!migration.noop && !hasOccurrences(content) && !hasProse(content)) {\n\t\t\t\tissue(\n\t\t\t\t\t\"EmptyMigration\",\n\t\t\t\t\tmigration.id,\n\t\t\t\t\t`The ${direction} side of migration \"${migration.id}\" is empty. Use Migration.noop to declare a zero-work transition.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst counts = new Map<string, number>();\n\t\t\tfor (const action of actionsOfSteps(stepsOf(content))) {\n\t\t\t\tvisitAction(action);\n\t\t\t\tcounts.set(action.id, (counts.get(action.id) ?? 0) + 1);\n\t\t\t}\n\t\t\tfor (const [actionId, count] of counts) {\n\t\t\t\tif (count < 2) continue;\n\n\t\t\t\tissue(\n\t\t\t\t\t\"DuplicateOccurrence\",\n\t\t\t\t\tmigration.id,\n\t\t\t\t\t`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.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Edges. Each pair of versions has at most one migration side, so a transition's work\n\t// lives in one migration.\n\tconst edgeSides = new Map<\n\t\tstring,\n\t\t{ readonly from: string; readonly to: string; readonly labels: Array<string> }\n\t>();\n\tconst addSide = (from: Version, to: Version, label: string) => {\n\t\tconst key = JSON.stringify([from.id, to.id]);\n\t\tconst side = edgeSides.get(key) ?? { from: from.id, to: to.id, labels: [] };\n\t\tside.labels.push(label);\n\t\tedgeSides.set(key, side);\n\t};\n\t// A migration registered twice is already a DuplicateMigration issue.\n\tfor (const migration of new Set(migrationIds.values())) {\n\t\tif (!registered.has(migration)) continue;\n\t\taddSide(migration.from, migration.to, `\"${migration.id}\"`);\n\t\tif (migration.revert !== undefined)\n\t\t\taddSide(migration.to, migration.from, `the revert of \"${migration.id}\"`);\n\t}\n\tfor (const { from, to, labels } of edgeSides.values()) {\n\t\tif (labels.length < 2) continue;\n\n\t\tissue(\n\t\t\t\"DuplicateEdge\",\n\t\t\t`${from} -> ${to}`,\n\t\t\t`${labels.join(\" and \")} both go from \"${from}\" to \"${to}\". Merge them into one migration.`,\n\t\t);\n\t}\n\n\t// Rules.\n\tconst rules = new Set<string>();\n\tfor (const rule of declarations.rules) {\n\t\tif (rules.has(rule.id)) {\n\t\t\tissue(\"DuplicateRule\", rule.id, `Rule \"${rule.id}\" is registered more than once.`);\n\t\t}\n\t\trules.add(rule.id);\n\t\tif (rule.match.length === 0) {\n\t\t\tissue(\"InvalidRule\", rule.id, `Rule \"${rule.id}\" matches nothing.`);\n\t\t}\n\t\tconst patternActions = actionsOfSteps(rule.match);\n\t\tconst replacementActions = actionsOfSteps(rule.replacement);\n\t\tfor (const action of [...patternActions, ...replacementActions]) visitAction(action);\n\t\tconst unique = new Set(replacementActions.map((action) => action.id));\n\t\tif (unique.size !== replacementActions.length) {\n\t\t\tissue(\n\t\t\t\t\"InvalidRule\",\n\t\t\t\trule.id,\n\t\t\t\t`Rule \"${rule.id}\" repeats an action in its replacement.`,\n\t\t\t);\n\t\t}\n\t\t// Same actions in a different structure, such as a sequence made parallel, is a\n\t\t// real replacement.\n\t\tif (rule.match.length > 0 && stepKey(rule.match) === stepKey(rule.replacement)) {\n\t\t\tissue(\"InvalidRule\", rule.id, `Rule \"${rule.id}\" replaces its match with itself.`);\n\t\t}\n\t}\n\n\t// Shortcuts.\n\tconst shortcuts = new Set<string>();\n\tfor (const shortcut of declarations.shortcuts) {\n\t\tif (shortcuts.has(shortcut.id)) {\n\t\t\tissue(\n\t\t\t\t\"DuplicateShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`Shortcut \"${shortcut.id}\" is registered more than once.`,\n\t\t\t);\n\t\t}\n\t\tshortcuts.add(shortcut.id);\n\t\trequireVersion(shortcut.from, `shortcut \"${shortcut.id}\"`);\n\t\trequireVersion(shortcut.to, `shortcut \"${shortcut.id}\"`);\n\t\tconst unknown = shortcut.replaces.filter((migration) => !registered.has(migration));\n\t\tif (unknown.length > 0) {\n\t\t\tissue(\n\t\t\t\t\"InvalidShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`Shortcut \"${shortcut.id}\" replaces unregistered migrations: ${unknown.map((migration) => migration.id).join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\tif (!isChain(shortcut.replaces, shortcut.from, shortcut.to)) {\n\t\t\tissue(\n\t\t\t\t\"InvalidShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`Shortcut \"${shortcut.id}\" must replace a consecutive route from \"${shortcut.from.id}\" to \"${shortcut.to.id}\".`,\n\t\t\t);\n\t\t}\n\t\tif (!isChain(shortcut.migrations, shortcut.from, shortcut.to)) {\n\t\t\tissue(\n\t\t\t\t\"InvalidShortcut\",\n\t\t\t\tshortcut.id,\n\t\t\t\t`The migrations of shortcut \"${shortcut.id}\" must form a route from \"${shortcut.from.id}\" to \"${shortcut.to.id}\".`,\n\t\t\t);\n\t\t}\n\t}\n\n\tfor (const [id, referrers] of unregistered) {\n\t\tissue(\n\t\t\t\"UnregisteredVersion\",\n\t\t\tid,\n\t\t\t`Version \"${id}\" is referenced by ${referrers.join(\", \")} but is not registered.`,\n\t\t);\n\t}\n\n\treturn Arr.sort(issues, issueOrder);\n};\n","import { Array as Arr, Graph, Order, Result, SemVer } from \"effect\";\n\nimport type * as Change from \"../../foundation/change.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type {\n\tDirection,\n\tExplanation,\n\tHop,\n\tNode,\n\tPlan,\n\tRequestDirection,\n\tRoute,\n\tStep,\n} from \"../../foundation/plan.ts\";\nimport type * as Shortcut from \"../../foundation/shortcut.ts\";\nimport type { Version } from \"../../foundation/version.ts\";\nimport { resolveGuide } from \"./guide.ts\";\nimport {\n\tdeclaredOccurrenceId,\n\trouteHop,\n\trouteShortcut,\n\trouteStart,\n\tstepId,\n} from \"./identifiers.ts\";\nimport {\n\tAmbiguousRoute,\n\tConflictingRewrites,\n\tRewriteCycle,\n\tRewriteLimitExceeded,\n\tTooManyRoutes,\n\tUnknownRoute,\n\tUnknownVersion,\n\tUnsupportedRoute,\n\ttype Blocker,\n\ttype ResolveError,\n\ttype RewriteError,\n\ttype RouteSummary,\n} from \"./resolve-error.ts\";\nimport { itemsOf, occurrencesOf, rewrite, type Item, type MakeOccurrence } from \"./rewrite.ts\";\nimport { actionsOfSteps, hasProse, stepsOf, type Declarations } from \"./validate.ts\";\n\n/**\n * Route policies for choosing between candidate routes. Each one is opt-in, and a policy\n * that leaves a tie still fails as ambiguous.\n *\n * - `fewest-actions`: the fewest action occurrences after optimization.\n * - `fewest-migrations`: the fewest migration steps.\n * - `lowest-cost`: the lowest total cost. A migration costs 1 unless it declares\n * `cost`; a shortcut costs its declared `cost` or the total of its migrations.\n * - `prefer-shortcuts`: a route through a shortcut over the route the shortcut replaces.\n *\n * @since 0.0.1\n */\nexport type RoutePolicy =\n\t| \"fewest-actions\"\n\t| \"fewest-migrations\"\n\t| \"lowest-cost\"\n\t| \"prefer-shortcuts\";\n\n/** The largest number of candidate routes enumerated between two versions. */\nexport const routeLimit = 100;\n\ntype Member = { readonly migration: Migration.Any; readonly direction: Direction };\n\ntype Edge = {\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly members: ReadonlyArray<Member>;\n\treadonly shortcut: Shortcut.Any | undefined;\n\treadonly cost: number;\n\treadonly class: \"up\" | \"down\" | \"cross\";\n};\n\ntype Candidate = {\n\treadonly route: Route;\n\treadonly edges: ReadonlyArray<Edge>;\n\treadonly plan: Result.Result<Plan, RewriteError>;\n\treadonly cost: number;\n};\n\nexport type Context = {\n\treadonly declarations: Declarations;\n\treadonly versions: ReadonlyMap<string, Version>;\n\t/** Strict ancestors of each version, by identifier. */\n\treadonly ancestors: ReadonlyMap<string, ReadonlySet<string>>;\n\treadonly edges: ReadonlyArray<Edge>;\n};\n\nconst memberCost = (migration: Migration.Any) => migration.cost ?? 1;\n\nexport const makeContext = (declarations: Declarations): Context => {\n\tconst versions = new Map(declarations.versions.map((version) => [version.id, version]));\n\tconst ancestors = new Map<string, ReadonlySet<string>>();\n\tconst ancestorsOf = (id: string): ReadonlySet<string> => {\n\t\tconst known = ancestors.get(id);\n\t\tif (known !== undefined) return known;\n\n\t\tconst result = new Set<string>();\n\t\tlet current = versions.get(id)?.previous;\n\t\twhile (current !== undefined && !result.has(current.id)) {\n\t\t\tresult.add(current.id);\n\t\t\tcurrent = versions.get(current.id)?.previous;\n\t\t}\n\t\tancestors.set(id, result);\n\n\t\treturn result;\n\t};\n\tfor (const id of versions.keys()) ancestorsOf(id);\n\n\tconst classOf = (from: string, to: string): Edge[\"class\"] => {\n\t\tif (ancestorsOf(to).has(from)) return \"up\";\n\t\tif (ancestorsOf(from).has(to)) return \"down\";\n\n\t\treturn \"cross\";\n\t};\n\n\t// Validation guarantees at most one migration side per pair of versions.\n\tconst edges: Array<Edge> = declarations.migrations.flatMap((migration): Array<Edge> => {\n\t\tconst forward: Edge = {\n\t\t\tfrom: migration.from,\n\t\t\tto: migration.to,\n\t\t\tmembers: [{ migration, direction: \"forward\" }],\n\t\t\tshortcut: undefined,\n\t\t\tcost: memberCost(migration),\n\t\t\tclass: classOf(migration.from.id, migration.to.id),\n\t\t};\n\t\tif (migration.revert === undefined) return [forward];\n\n\t\treturn [\n\t\t\tforward,\n\t\t\t{\n\t\t\t\tfrom: migration.to,\n\t\t\t\tto: migration.from,\n\t\t\t\tmembers: [{ migration, direction: \"revert\" }],\n\t\t\t\tshortcut: undefined,\n\t\t\t\tcost: memberCost(migration),\n\t\t\t\tclass: classOf(migration.to.id, migration.from.id),\n\t\t\t},\n\t\t];\n\t});\n\tfor (const shortcut of declarations.shortcuts) {\n\t\tedges.push({\n\t\t\tfrom: shortcut.from,\n\t\t\tto: shortcut.to,\n\t\t\tmembers: shortcut.migrations.map((migration) => ({ migration, direction: \"forward\" })),\n\t\t\tshortcut,\n\t\t\tcost:\n\t\t\t\tshortcut.cost ??\n\t\t\t\tshortcut.migrations.reduce((total, migration) => total + memberCost(migration), 0),\n\t\t\tclass: classOf(shortcut.from.id, shortcut.to.id),\n\t\t});\n\t}\n\n\treturn { declarations, versions, ancestors, edges };\n};\n\nconst requestDirection = (context: Context, from: string, to: string): RequestDirection => {\n\tif (from === to) return \"none\";\n\tif (context.ancestors.get(to)?.has(from)) return \"upgrade\";\n\tif (context.ancestors.get(from)?.has(to)) return \"downgrade\";\n\n\treturn \"cross-branch\";\n};\n\n/**\n * Edge classes allowed together in one route. A route never mixes moves toward\n * ancestors with moves toward descendants, so sharing an ancestor does not authorize a\n * downgrade-and-upgrade detour. Explicit cross-branch migrations fit either family.\n */\nconst families: ReadonlyArray<ReadonlySet<Edge[\"class\"]>> = [\n\tnew Set([\"up\", \"cross\"]),\n\tnew Set([\"down\", \"cross\"]),\n];\n\nconst routeCost = (edges: ReadonlyArray<Edge>) =>\n\tedges.reduce((total, edge) => total + edge.cost, 0);\n\nconst routeOf = (from: Version, edges: ReadonlyArray<Edge>): Route => {\n\tlet id = routeStart(from.id);\n\tconst hops: Array<Hop> = [];\n\tfor (const edge of edges) {\n\t\tif (edge.shortcut === undefined) {\n\t\t\tid += routeHop(edge.to.id);\n\t\t\thops.push({\n\t\t\t\t_tag: \"Migrations\",\n\t\t\t\tfrom: edge.from,\n\t\t\t\tto: edge.to,\n\t\t\t\tmigrations: edge.members,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tid += routeShortcut(edge.shortcut.id, edge.to.id);\n\t\thops.push({ _tag: \"Shortcut\", from: edge.from, to: edge.to, shortcut: edge.shortcut });\n\t}\n\n\treturn { id, hops };\n};\n\nconst graphOf = (context: Context, family: ReadonlySet<Edge[\"class\"]>) => {\n\tconst nodes = new Map<string, Graph.NodeIndex>();\n\tconst graph = Graph.directed<string, Edge>((mutable) => {\n\t\tfor (const id of context.versions.keys()) nodes.set(id, Graph.addNode(mutable, id));\n\t\tfor (const edge of context.edges) {\n\t\t\tif (!family.has(edge.class)) continue;\n\n\t\t\tconst source = nodes.get(edge.from.id);\n\t\t\tconst target = nodes.get(edge.to.id);\n\t\t\tif (source !== undefined && target !== undefined)\n\t\t\t\tGraph.addEdge(mutable, source, target, edge);\n\t\t}\n\t});\n\n\treturn { graph, nodes };\n};\n\ntype Enumerated = {\n\t/** At most `routeLimit` routes, in search order. */\n\treadonly routes: ReadonlyArray<ReadonlyArray<Edge>>;\n\t/** Whether the search stopped because more routes exist. */\n\treadonly overLimit: boolean;\n};\n\nconst enumerateRoutes = (context: Context, from: Version, to: Version): Enumerated => {\n\tconst routes = new Map<string, ReadonlyArray<Edge>>();\n\tfor (const family of families) {\n\t\tconst { graph, nodes } = graphOf(context, family);\n\t\tconst source = nodes.get(from.id);\n\t\tconst target = nodes.get(to.id);\n\t\tif (source === undefined || target === undefined) continue;\n\n\t\tfor (const path of Graph.simplePaths(graph, { source, target, limit: routeLimit + 1 })) {\n\t\t\troutes.set(routeOf(from, path.costs).id, path.costs);\n\t\t}\n\t}\n\tconst found = [...routes.values()];\n\n\treturn { routes: found.slice(0, routeLimit), overLimit: found.length > routeLimit };\n};\n\nconst toNode = (items: ReadonlyArray<Item>): ReadonlyArray<Node> =>\n\titems.flatMap((item): ReadonlyArray<Node> => {\n\t\tif (item._tag === \"Occ\") return [item.occurrence];\n\t\tif (item._tag === \"Barrier\") return [];\n\n\t\treturn [\n\t\t\t{\n\t\t\t\t_tag: \"Parallel\",\n\t\t\t\tbranches: item.branches.map((branch) => {\n\t\t\t\t\tconst children = toNode(branch);\n\t\t\t\t\tconst [only] = children;\n\n\t\t\t\t\treturn children.length === 1 && only !== undefined\n\t\t\t\t\t\t? only\n\t\t\t\t\t\t: { _tag: \"Sequence\", children };\n\t\t\t\t}),\n\t\t\t\tconcurrency: item.concurrency,\n\t\t\t},\n\t\t];\n\t});\n\nconst contentOf = (member: Member): Migration.Content =>\n\t(member.direction === \"forward\" ? member.migration.content : member.migration.revert) ?? [];\n\nconst buildPlan = (\n\tcontext: Context,\n\tfrom: Version,\n\tto: Version,\n\tdirection: RequestDirection,\n\tedges: ReadonlyArray<Edge>,\n): Result.Result<Plan, RewriteError> => {\n\tconst route = routeOf(from, edges);\n\tconst members = edges.flatMap((edge) => edge.members);\n\n\tconst items = members.flatMap((member, index): ReadonlyArray<Item> => {\n\t\tconst content = contentOf(member);\n\t\tconst make: MakeOccurrence = (action, instruction) => ({\n\t\t\t_tag: \"Occurrence\",\n\t\t\tid: declaredOccurrenceId(member.migration, member.direction, action),\n\t\t\taction,\n\t\t\tmigration: member.migration,\n\t\t\tdirection: member.direction,\n\t\t\tinstruction,\n\t\t\torigin: { _tag: \"Declared\" },\n\t\t});\n\t\tconst declared = itemsOf(stepsOf(content), make, index);\n\t\tif (declared.length === 0 && hasProse(content)) return [{ _tag: \"Barrier\", step: index }];\n\n\t\treturn declared;\n\t});\n\n\tconst rewritten = rewrite(items, context.declarations.rules);\n\tif (rewritten._tag === \"Failure\") {\n\t\tconst failure = rewritten.failure;\n\t\tswitch (failure._tag) {\n\t\t\tcase \"RewriteCycle\":\n\t\t\t\treturn Result.fail(\n\t\t\t\t\tnew RewriteCycle({\n\t\t\t\t\t\troute: route.id,\n\t\t\t\t\t\trules: failure.rules,\n\t\t\t\t\t\tactions: failure.actions,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\tcase \"ConflictingRewrites\":\n\t\t\t\treturn Result.fail(\n\t\t\t\t\tnew ConflictingRewrites({ route: route.id, outcomes: failure.outcomes }),\n\t\t\t\t);\n\t\t}\n\n\t\treturn Result.fail(\n\t\t\tnew RewriteLimitExceeded({\n\t\t\t\troute: route.id,\n\t\t\t\tlimit: failure.limit,\n\t\t\t\tvalue: failure.value,\n\t\t\t}),\n\t\t);\n\t}\n\tconst { items: optimized, trace } = rewritten.outcome;\n\n\tconst explanations: Array<Explanation> = trace.map((application) => ({\n\t\t_tag: \"Rewrite\",\n\t\trule: application.rule,\n\t\tremoved: application.removed,\n\t\tproduced: application.produced,\n\t}));\n\n\tconst steps = members.map((member, index): Step => {\n\t\tconst stepItems = optimized.filter((item) => item.step === index);\n\t\tconst content = contentOf(member);\n\t\tconst declaredCount = actionsOfSteps(stepsOf(content)).length;\n\t\tconst retained = occurrencesOf(stepItems);\n\t\tconst guide = resolveGuide(content, retained, (action) =>\n\t\t\tdeclaredOccurrenceId(member.migration, member.direction, action),\n\t\t);\n\t\tconst allRemoved = declaredCount > 0 && retained.length === 0;\n\t\t// `noop` describes the zero-work sides. A revert added to a noop migration is work.\n\t\tconst noop = member.migration.noop && content.length === 0;\n\t\tconst omitted = noop || allRemoved;\n\t\tif (omitted) {\n\t\t\texplanations.push({\n\t\t\t\t_tag: \"OmittedStep\",\n\t\t\t\tmigration: member.migration,\n\t\t\t\tdirection: member.direction,\n\t\t\t\treason: noop ? \"noop\" : \"all-actions-removed\",\n\t\t\t});\n\t\t}\n\t\tconst [stepFrom, stepTo] =\n\t\t\tmember.direction === \"forward\"\n\t\t\t\t? [member.migration.from, member.migration.to]\n\t\t\t\t: [member.migration.to, member.migration.from];\n\n\t\treturn {\n\t\t\t_tag: \"Step\",\n\t\t\tid: stepId(member.migration, member.direction),\n\t\t\tmigration: member.migration,\n\t\t\tdirection: member.direction,\n\t\t\tfrom: stepFrom,\n\t\t\tto: stepTo,\n\t\t\tnode: { _tag: \"Sequence\", children: toNode(stepItems) },\n\t\t\tguide: omitted ? [] : guide,\n\t\t\tomitted,\n\t\t};\n\t});\n\n\tconst changes: Array<Change.Any> = [];\n\tfor (const member of members) {\n\t\tfor (const change of member.migration.addresses) {\n\t\t\tif (!changes.some((known) => known.id === change.id)) changes.push(change);\n\t\t}\n\t}\n\n\treturn Result.succeed({\n\t\t_tag: \"Plan\",\n\t\tfrom,\n\t\tto,\n\t\tdirection,\n\t\troute,\n\t\tsteps,\n\t\toccurrences: occurrencesOf(optimized),\n\t\tchanges,\n\t\texplanations,\n\t\tcoverage: \"static\",\n\t});\n};\n\nconst summaryOf = (candidate: Candidate): RouteSummary => ({\n\tid: candidate.route.id,\n\tmigrations: candidate.edges.flatMap((edge) =>\n\t\tedge.members.map((member) => member.migration.id),\n\t),\n\tshortcuts: candidate.edges.flatMap((edge) =>\n\t\tedge.shortcut === undefined ? [] : [edge.shortcut.id],\n\t),\n\tactions: Result.isSuccess(candidate.plan)\n\t\t? candidate.plan.success.occurrences.length\n\t\t: undefined,\n\tcost: candidate.cost,\n\tfailure: Result.isFailure(candidate.plan) ? candidate.plan.failure.message : undefined,\n});\n\n/** Migration tokens of a route, with shortcut hops expanded to the route they replace. */\nconst canonicalTokens = (candidate: Candidate) =>\n\tJSON.stringify(\n\t\tcandidate.edges.flatMap((edge) =>\n\t\t\tedge.shortcut === undefined\n\t\t\t\t? edge.members.map((member) => [member.direction, member.migration.id])\n\t\t\t\t: edge.shortcut.replaces.map((migration) => [\"forward\", migration.id]),\n\t\t),\n\t);\n\nconst shortcutCount = (candidate: Candidate) =>\n\tcandidate.edges.filter((edge) => edge.shortcut !== undefined).length;\n\nconst minimal = (\n\tcandidates: ReadonlyArray<Candidate>,\n\tmeasure: (candidate: Candidate) => number | undefined,\n): ReadonlyArray<Candidate> => {\n\tconst measured = candidates.flatMap((candidate) => {\n\t\tconst value = measure(candidate);\n\n\t\treturn value === undefined ? [] : [{ candidate, value }];\n\t});\n\tconst best = Math.min(...measured.map((entry) => entry.value));\n\n\treturn measured.filter((entry) => entry.value === best).map((entry) => entry.candidate);\n};\n\nconst applyPolicy = (\n\tpolicy: RoutePolicy,\n\tcandidates: ReadonlyArray<Candidate>,\n): ReadonlyArray<Candidate> => {\n\tswitch (policy) {\n\t\tcase \"fewest-actions\":\n\t\t\treturn minimal(candidates, (candidate) =>\n\t\t\t\tResult.isSuccess(candidate.plan)\n\t\t\t\t\t? candidate.plan.success.occurrences.length\n\t\t\t\t\t: undefined,\n\t\t\t);\n\t\tcase \"fewest-migrations\":\n\t\t\treturn minimal(candidates, (candidate) =>\n\t\t\t\tcandidate.edges.reduce((total, edge) => total + edge.members.length, 0),\n\t\t\t);\n\t\tcase \"lowest-cost\":\n\t\t\treturn minimal(candidates, (candidate) => candidate.cost);\n\t}\n\n\t// prefer-shortcuts: drop a route when another candidate is the same canonical route\n\t// with more of it replaced by shortcuts. Unrelated routes stay ambiguous.\n\treturn candidates.filter(\n\t\t(candidate) =>\n\t\t\t!candidates.some(\n\t\t\t\t(other) =>\n\t\t\t\t\tother !== candidate &&\n\t\t\t\t\tcanonicalTokens(other) === canonicalTokens(candidate) &&\n\t\t\t\t\tshortcutCount(other) > shortcutCount(candidate),\n\t\t\t),\n\t);\n};\n\nconst depthOf = (context: Context, id: string) => context.ancestors.get(id)?.size ?? 0;\n\n/** Distance between two versions in the release ancestry tree. */\nconst ancestryDistance = (context: Context, self: string, that: string): number => {\n\tconst selfLine = [self, ...ancestorsInOrder(context, self)];\n\tconst thatLine = new Set([that, ...ancestorsInOrder(context, that)]);\n\tconst common = selfLine.find((id) => thatLine.has(id));\n\tif (common === undefined) return Number.POSITIVE_INFINITY;\n\n\treturn depthOf(context, self) + depthOf(context, that) - 2 * depthOf(context, common);\n};\n\nconst ancestorsInOrder = (context: Context, id: string): ReadonlyArray<string> => {\n\tconst result: Array<string> = [];\n\tlet current = context.versions.get(id)?.previous;\n\twhile (current !== undefined && !result.includes(current.id)) {\n\t\tresult.push(current.id);\n\t\tcurrent = context.versions.get(current.id)?.previous;\n\t}\n\n\treturn result;\n};\n\n/** The ancestry path between two versions, through their closest common ancestor. */\nconst ancestryPath = (context: Context, from: string, to: string): ReadonlyArray<string> => {\n\tconst fromLine = [from, ...ancestorsInOrder(context, from)];\n\tconst toLine = [to, ...ancestorsInOrder(context, to)];\n\tconst common = fromLine.find((id) => toLine.includes(id));\n\tif (common === undefined) return [];\n\n\treturn [\n\t\t...fromLine.slice(0, fromLine.indexOf(common) + 1),\n\t\t...Arr.reverse(toLine.slice(0, toLine.indexOf(common))),\n\t];\n};\n\nexport const reachable = (\n\tcontext: Context,\n\tfrom: string,\n\tfamily: ReadonlySet<Edge[\"class\"]>,\n): ReadonlyArray<string> => {\n\tconst seen = new Set([from]);\n\tconst queue = [from];\n\tfor (let current = queue.shift(); current !== undefined; current = queue.shift()) {\n\t\tfor (const edge of context.edges) {\n\t\t\tif (edge.from.id !== current || !family.has(edge.class) || seen.has(edge.to.id))\n\t\t\t\tcontinue;\n\n\t\t\tseen.add(edge.to.id);\n\t\t\tqueue.push(edge.to.id);\n\t\t}\n\t}\n\tseen.delete(from);\n\n\treturn [...seen];\n};\n\nconst familiesFor = (direction: RequestDirection) => {\n\tif (direction === \"upgrade\") return [families[0]];\n\tif (direction === \"downgrade\") return [families[1]];\n\n\treturn families;\n};\n\nconst unsupported = (context: Context, from: string, to: string, direction: RequestDirection) => {\n\tconst allowed = familiesFor(direction).flatMap((family) =>\n\t\tfamily === undefined ? [] : [family],\n\t);\n\tconst reachableIds = Arr.sort(\n\t\tnew Set(allowed.flatMap((family) => reachable(context, from, family))),\n\t\tOrder.String,\n\t);\n\tconst distances = reachableIds.map((id) => ({\n\t\tid,\n\t\tdistance: ancestryDistance(context, id, to),\n\t}));\n\tconst best = Math.min(...distances.map((entry) => entry.distance));\n\tconst closest = Number.isFinite(best)\n\t\t? distances.filter((entry) => entry.distance === best).map((entry) => entry.id)\n\t\t: [];\n\n\tconst path = ancestryPath(context, from, to);\n\tconst blockers: Array<Blocker> = [];\n\tfor (let index = 0; index + 1 < path.length; index++) {\n\t\tconst hopFrom = path[index];\n\t\tconst hopTo = path[index + 1];\n\t\tif (hopFrom === undefined || hopTo === undefined) continue;\n\t\tif (context.edges.some((edge) => edge.from.id === hopFrom && edge.to.id === hopTo))\n\t\t\tcontinue;\n\n\t\tblockers.push({\n\t\t\tfrom: hopFrom,\n\t\t\tto: hopTo,\n\t\t\treason: `No migration is declared from \"${hopFrom}\" to \"${hopTo}\".`,\n\t\t});\n\t}\n\n\t// The common ancestor where an ancestry path turns from moving down to moving up.\n\tconst turn = path.find(\n\t\t(id) =>\n\t\t\tcontext.ancestors.get(from)?.has(id) === true &&\n\t\t\tcontext.ancestors.get(to)?.has(id) === true,\n\t);\n\tif (blockers.length === 0 && turn !== undefined) {\n\t\tblockers.push({\n\t\t\tfrom,\n\t\t\tto,\n\t\t\treason: `A route through \"${turn}\" would combine a downgrade with an upgrade. Declare a migration from \"${from}\" to \"${to}\".`,\n\t\t});\n\t}\n\n\treturn new UnsupportedRoute({\n\t\tfrom,\n\t\tto,\n\t\tdirection,\n\t\treachable: reachableIds,\n\t\tclosest,\n\t\tblockers,\n\t});\n};\n\n/** @since 0.0.1 */\nexport type ResolveOptions = {\n\treadonly from: Version | string;\n\treadonly to: Version | string;\n\t/** Selects a candidate route by identifier. */\n\treadonly route?: string;\n\t/** Chooses between candidate routes. Ties still fail as ambiguous. */\n\treadonly policy?: RoutePolicy;\n};\n\nexport const lookup = (context: Context, reference: Version | string) => {\n\tconst id = typeof reference === \"string\" ? reference : reference.id;\n\tconst version = context.versions.get(id);\n\n\treturn version === undefined\n\t\t? Result.fail(new UnknownVersion({ version: id, known: [...context.versions.keys()] }))\n\t\t: Result.succeed(version);\n};\n\nexport const candidatesBetween = (\n\tcontext: Context,\n\tfrom: Version,\n\tto: Version,\n): Result.Result<ReadonlyArray<Candidate>, TooManyRoutes> => {\n\tconst direction = requestDirection(context, from.id, to.id);\n\tconst { routes, overLimit } = enumerateRoutes(context, from, to);\n\tif (overLimit) {\n\t\treturn Result.fail(new TooManyRoutes({ from: from.id, to: to.id, limit: routeLimit }));\n\t}\n\n\treturn Result.succeed(\n\t\troutes.map((edges) => ({\n\t\t\troute: routeOf(from, edges),\n\t\t\tedges,\n\t\t\tplan: buildPlan(context, from, to, direction, edges),\n\t\t\tcost: routeCost(edges),\n\t\t})),\n\t);\n};\n\nexport const resolve = (\n\tcontext: Context,\n\toptions: ResolveOptions,\n): Result.Result<Plan, ResolveError> =>\n\tResult.gen(function* () {\n\t\tconst from = yield* lookup(context, options.from);\n\t\tconst to = yield* lookup(context, options.to);\n\t\tconst direction = requestDirection(context, from.id, to.id);\n\t\tif (direction === \"none\") {\n\t\t\treturn yield* buildPlan(context, from, to, direction, []);\n\t\t}\n\n\t\tconst candidates = yield* candidatesBetween(context, from, to);\n\t\tif (candidates.length === 0)\n\t\t\treturn yield* Result.fail(unsupported(context, from.id, to.id, direction));\n\n\t\tif (options.route !== undefined) {\n\t\t\tconst selected = candidates.find((candidate) => candidate.route.id === options.route);\n\t\t\tif (selected === undefined) {\n\t\t\t\treturn yield* Result.fail(\n\t\t\t\t\tnew UnknownRoute({\n\t\t\t\t\t\troute: options.route,\n\t\t\t\t\t\tcandidates: candidates.map(summaryOf),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn yield* selected.plan;\n\t\t}\n\n\t\tconst chosen =\n\t\t\toptions.policy === undefined ? candidates : applyPolicy(options.policy, candidates);\n\t\tconst [only] = chosen;\n\t\tif (chosen.length === 1 && only !== undefined) return yield* only.plan;\n\n\t\treturn yield* Result.fail(\n\t\t\tnew AmbiguousRoute({\n\t\t\t\tfrom: from.id,\n\t\t\t\tto: to.id,\n\t\t\t\tcandidates: (chosen.length === 0 ? candidates : chosen).map(summaryOf),\n\t\t\t\tpolicy: options.policy,\n\t\t\t}),\n\t\t);\n\t});\n\n/**\n * A reachable destination and the identifiers of its candidate routes.\n *\n * @since 0.0.1\n */\nexport type Destination = {\n\treadonly version: Version;\n\treadonly routes: ReadonlyArray<string>;\n\t/**\n\t * Present when more routes exist than route search explores. `routes` then lists the\n\t * routes found, cheapest first, and `History.resolve` to this destination fails with\n\t * `TooManyRoutes`.\n\t */\n\treadonly overLimit?: true;\n};\n\nconst semverOrder = (self: string, that: string): number | undefined => {\n\tconst parsedSelf = SemVer.parse(self);\n\tconst parsedThat = SemVer.parse(that);\n\tif (Result.isFailure(parsedSelf) || Result.isFailure(parsedThat)) return undefined;\n\n\treturn SemVer.Order(parsedSelf.success, parsedThat.success);\n};\n\n/**\n * Destinations reachable from a version. Cross-branch destinations are classified by\n * semver order when both identifiers parse, and listed in both directions otherwise.\n * Classification is presentation only; it does not change routing.\n */\nexport const destinations = (\n\tcontext: Context,\n\tfrom: Version,\n\tkind: \"upgrade\" | \"downgrade\",\n): ReadonlyArray<Destination> => {\n\tconst family = kind === \"upgrade\" ? families[0] : families[1];\n\tif (family === undefined) return [];\n\n\treturn reachable(context, from.id, family).flatMap((id) => {\n\t\tconst version = context.versions.get(id);\n\t\tif (version === undefined) return [];\n\n\t\tconst direction = requestDirection(context, from.id, id);\n\t\tif (direction === \"cross-branch\") {\n\t\t\tconst order = semverOrder(id, from.id);\n\t\t\tif (order !== undefined && (kind === \"upgrade\" ? order < 0 : order > 0)) return [];\n\t\t} else if (direction !== kind) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst { routes, overLimit } = enumerateRoutes(context, from, version);\n\t\tif (!overLimit) {\n\t\t\treturn [{ version, routes: routes.map((edges) => routeOf(from, edges).id) }];\n\t\t}\n\t\tconst cheapest = Arr.sort(\n\t\t\troutes,\n\t\t\tOrder.mapInput(Order.Number, (edges: ReadonlyArray<Edge>) => routeCost(edges)),\n\t\t);\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tversion,\n\t\t\t\troutes: cheapest.map((edges) => routeOf(from, edges).id),\n\t\t\t\toverLimit: true as const,\n\t\t\t},\n\t\t];\n\t});\n};\n","import { Predicate, Result } from \"effect\";\n\nimport type * as Action from \"../../foundation/action.ts\";\nimport type * as Change from \"../../foundation/change.ts\";\nimport type * as Migration from \"../../foundation/migration.ts\";\nimport type { Plan } from \"../../foundation/plan.ts\";\nimport type * as Rule from \"../../foundation/rule.ts\";\nimport type * as Shortcut from \"../../foundation/shortcut.ts\";\nimport type { Version } from \"../../foundation/version.ts\";\nimport { InvalidHistory, type ResolveError, type UnknownVersion } from \"./resolve-error.ts\";\nimport {\n\tdestinations,\n\tlookup as lookupVersion,\n\tmakeContext,\n\tresolve as resolveRoute,\n\ttype Context,\n\ttype Destination,\n\ttype ResolveOptions,\n\ttype RoutePolicy,\n} from \"./resolve.ts\";\nimport { validate as validateDeclarations, type Issue } from \"./validate.ts\";\n\nexport * from \"./resolve-error.ts\";\nexport type { Destination, Issue, ResolveOptions, RoutePolicy };\n\n/** @since 0.0.1 */\nexport type History<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"History\";\n\treadonly versions: ReadonlyArray<Version>;\n\treadonly migrations: ReadonlyArray<Migration.Any>;\n\treadonly rules: ReadonlyArray<Rule.Any>;\n\treadonly shortcuts: ReadonlyArray<Shortcut.Any>;\n\t/** Type-level record of every action instance that a plan can contain. */\n\treadonly \"~actions\"?: A;\n\t/** Type-level record of every change that a plan's `changes` can contain. */\n\treadonly \"~changes\"?: C;\n};\n\n/**\n * Any history.\n *\n * @since 0.0.1\n */\nexport type Any = History<any>;\n\n/**\n * Every action instance that a plan resolved from the history can contain.\n *\n * @since 0.0.1\n */\nexport type ActionsOf<H> = H extends History<infer A> ? A : never;\n\n/**\n * Every change that a plan resolved from the history can list in `changes`.\n *\n * @since 0.0.1\n */\nexport type ChangesOf<H> = H extends History<any, infer C> ? C : never;\n\n/**\n * Registers declarations. Migrations are registered independently of versions, so\n * routes can be added later without changing published release definitions.\n *\n * `make` does not throw. Use `History.validate` to list declaration issues;\n * resolution fails with `InvalidHistory` when there are any.\n *\n * @since 0.0.1\n */\nexport const make = <\n\tconst M extends ReadonlyArray<Migration.Any>,\n\tconst R extends ReadonlyArray<Rule.Any> = [],\n\tconst S extends ReadonlyArray<Shortcut.Any> = [],\n>(declarations: {\n\treadonly versions: ReadonlyArray<Version>;\n\treadonly migrations: M;\n\treadonly rules?: R;\n\treadonly shortcuts?: S;\n}): History<\n\tMigration.ActionsOf<M[number]> | Rule.ActionsOf<R[number]> | Shortcut.ActionsOf<S[number]>,\n\tMigration.ChangesOf<M[number]> | Shortcut.ChangesOf<S[number]>\n> => ({\n\t_tag: \"History\",\n\tversions: declarations.versions,\n\tmigrations: declarations.migrations,\n\trules: declarations.rules ?? [],\n\tshortcuts: declarations.shortcuts ?? [],\n});\n\n/** @since 0.0.1 */\nexport const isHistory = (value: unknown): value is Any => Predicate.isTagged(value, \"History\");\n\nconst contexts = new WeakMap<\n\tAny,\n\t{ readonly issues: ReadonlyArray<Issue>; readonly context: Context }\n>();\n\nconst prepare = (history: Any) => {\n\tconst cached = contexts.get(history);\n\tif (cached !== undefined) return cached;\n\n\tconst prepared = { issues: validateDeclarations(history), context: makeContext(history) };\n\tcontexts.set(history, prepared);\n\n\treturn prepared;\n};\n\n/**\n * Lists declaration issues in a deterministic order. An empty list means valid.\n *\n * @since 0.0.1\n */\nexport const validate = (history: Any): ReadonlyArray<Issue> => prepare(history).issues;\n\nconst valid = (history: Any): Result.Result<Context, InvalidHistory> => {\n\tconst { issues, context } = prepare(history);\n\n\treturn issues.length === 0\n\t\t? Result.succeed(context)\n\t\t: Result.fail(new InvalidHistory({ issues }));\n};\n\n/**\n * Resolves an optimized plan between two versions. Planning needs no handlers or\n * execution services, and it never reads or modifies consumer files.\n *\n * When several routes connect the versions, resolution fails with `AmbiguousRoute`\n * unless the `route` option selects one or a route `policy` leaves exactly one.\n *\n * @example\n * ```ts\n * const result = History.resolve(history, { from: \"1.5.3\", to: \"2.0.0\" });\n * if (Result.isSuccess(result)) console.log(result.success.route.id);\n * ```\n *\n * @since 0.0.1\n */\nexport const resolve = <A extends Action.Any, C extends Change.Any>(\n\thistory: History<A, C>,\n\toptions: ResolveOptions,\n): Result.Result<Plan<A, \"static\", C>, ResolveError> =>\n\t// Every occurrence and change comes from the history's declarations, whose unions are\n\t// `A` and `C`.\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion\n\tResult.flatMap(valid(history), (context) => resolveRoute(context, options)) as Result.Result<\n\t\tPlan<A, \"static\", C>,\n\t\tResolveError\n\t>;\n\n/**\n * Destinations reachable by upgrade from a version, with their candidate routes.\n *\n * @since 0.0.1\n */\nexport const upgrades = (\n\thistory: Any,\n\toptions: { readonly from: Version | string },\n): Result.Result<ReadonlyArray<Destination>, InvalidHistory | UnknownVersion> =>\n\treachableFrom(history, options.from, \"upgrade\");\n\n/**\n * Destinations reachable by downgrade from a version, with their candidate routes.\n *\n * @since 0.0.1\n */\nexport const downgrades = (\n\thistory: Any,\n\toptions: { readonly from: Version | string },\n): Result.Result<ReadonlyArray<Destination>, InvalidHistory | UnknownVersion> =>\n\treachableFrom(history, options.from, \"downgrade\");\n\nconst reachableFrom = (history: Any, from: Version | string, kind: \"upgrade\" | \"downgrade\") =>\n\tResult.flatMap(valid(history), (context) =>\n\t\tResult.map(lookupVersion(context, from), (version) => destinations(context, version, kind)),\n\t);\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\nimport { isAction, isRef } from \"./action.ts\";\nimport { describeValue, dedent, isScalar, type Scalar } from \"./template.ts\";\n\n/**\n * Literal prose.\n *\n * @since 0.0.1\n */\nexport type Text = {\n\treadonly _tag: \"Text\";\n\treadonly text: string;\n};\n\n/**\n * Prose content: text and action mentions.\n *\n * @since 0.0.1\n */\nexport type Prose = ReadonlyArray<Text | Action.Ref>;\n\n/**\n * Values accepted inside prose templates.\n *\n * @since 0.0.1\n */\nexport type ProseValue = Scalar | Action.Ref;\n\n/**\n * Prose associated with exactly one action occurrence. The block declares that\n * occurrence; when optimization removes the action, the block leaves the resolved guide\n * with it.\n *\n * @since 0.0.1\n */\nexport type Instruction<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Instruction\";\n\treadonly action: A;\n\treadonly content: Prose;\n};\n\nexport const isInstruction = (value: unknown): value is Instruction =>\n\tPredicate.isTagged(value, \"Instruction\");\n\n/** Builds prose from a tagged template. Throws on values that are not text or mentions. */\nexport const prose = (\n\tstrings: ReadonlyArray<string>,\n\tvalues: ReadonlyArray<unknown>,\n\tcontext: string,\n): Prose => {\n\tconst literals = dedent(strings);\n\tconst content: Array<Text | Action.Ref> = [];\n\n\tconst pushText = (text: string) => {\n\t\tif (text === \"\") return;\n\n\t\tconst last = content.at(-1);\n\t\tif (last?._tag === \"Text\") {\n\t\t\tcontent[content.length - 1] = { _tag: \"Text\", text: last.text + text };\n\n\t\t\treturn;\n\t\t}\n\t\tcontent.push({ _tag: \"Text\", text });\n\t};\n\n\tfor (const [index, literal] of literals.entries()) {\n\t\tpushText(literal);\n\t\tif (index >= values.length) continue;\n\n\t\tconst value = values[index];\n\t\tif (isScalar(value)) {\n\t\t\tpushText(String(value));\n\t\t\tcontinue;\n\t\t}\n\t\tif (isRef(value)) {\n\t\t\tcontent.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isAction(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${context}: action \"${value.id}\" cannot be interpolated here because it would declare another occurrence. Use Action.ref(action) to mention it.`,\n\t\t\t);\n\t\t}\n\t\tthrow new TypeError(`${context}: cannot interpolate ${describeValue(value)}.`);\n\t}\n\n\treturn content;\n};\n\n/**\n * Associates prose with one action occurrence.\n *\n * @example\n * ```ts\n * Migration.instruction(renameTimeout)`\n * \tRename the timeout option, keeping its existing value.\n * `;\n * ```\n *\n * @since 0.0.1\n */\nexport const instruction =\n\t<A extends Action.Any>(action: A) =>\n\t(strings: TemplateStringsArray, ...values: ReadonlyArray<ProseValue>): Instruction<A> => ({\n\t\t_tag: \"Instruction\",\n\t\taction,\n\t\tcontent: prose(strings, values, `Instruction for \"${action.id}\"`),\n\t});\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\nimport { isAction, isParallel, isRef, isSequence } from \"./action.ts\";\nimport type * as Change from \"./change.ts\";\nimport { instruction, isInstruction, type Text } from \"./instruction.ts\";\nimport { describeValue, dedent, isScalar, type Scalar } from \"./template.ts\";\nimport type { Version } from \"./version.ts\";\n\nexport { instruction };\nexport type { Instruction, Prose, ProseValue, Text } from \"./instruction.ts\";\n\n/**\n * Prose, mentions, and occurrence-declaring steps in template order.\n *\n * @since 0.0.1\n */\nexport type Content<A extends Action.Any = Action.Any> = ReadonlyArray<\n\tText | Action.Ref | Action.Step<A>\n>;\n\n/**\n * Values accepted in migration templates.\n *\n * @since 0.0.1\n */\nexport type Interpolation = Scalar | Action.Ref | Action.Step;\n\n/** @since 0.0.1 */\nexport type Migration<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"Migration\";\n\treadonly id: string;\n\treadonly from: Version;\n\treadonly to: Version;\n\t/** The logical changes this transition handles. */\n\treadonly addresses: ReadonlyArray<C>;\n\t/** Whether this is an explicit zero-work transition. */\n\treadonly noop: boolean;\n\t/** Author-declared cost, used only by the `lowest-cost` route policy. */\n\treadonly cost: number | undefined;\n\treadonly content: Content;\n\t/** The reverse transition, from `to` back to `from`. Absent means no reverse edge. */\n\treadonly revert: Content | undefined;\n\t/** Type-level record of the action instances in `content` and `revert`. */\n\treadonly \"~actions\"?: A;\n};\n\n/**\n * Any migration.\n *\n * @since 0.0.1\n */\nexport type Any = Migration<any>;\n\n/**\n * The action instances a migration can contribute to a plan.\n *\n * @since 0.0.1\n */\nexport type ActionsOf<M> = M extends Migration<infer A> ? A : never;\n\n/**\n * The changes a migration addresses.\n *\n * @since 0.0.1\n */\nexport type ChangesOf<M> = M extends Migration<any, infer C> ? C : never;\n\n/** @since 0.0.1 */\nexport type Options<C extends Change.Any = Change.Any> = {\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly addresses?: ReadonlyArray<C>;\n\treadonly cost?: number;\n};\n\n/** @since 0.0.1 */\nexport const isMigration = (value: unknown): value is Any => Predicate.isTagged(value, \"Migration\");\n\nconst isStep = (value: unknown): value is Action.Step =>\n\tisAction(value) || isInstruction(value) || isSequence(value) || isParallel(value);\n\nconst validateStep = (step: Action.Step, context: string): void => {\n\tif (isSequence(step)) {\n\t\tfor (const child of step.children) checkStep(child, context);\n\n\t\treturn;\n\t}\n\tif (isParallel(step)) {\n\t\tfor (const branch of step.branches) checkStep(branch, context);\n\t}\n};\n\nconst checkStep = (value: unknown, context: string): void => {\n\tif (!isStep(value)) {\n\t\tthrow new TypeError(\n\t\t\t`${context}: a group can only contain actions, instructions, and groups.`,\n\t\t);\n\t}\n\tvalidateStep(value, context);\n};\n\n/** Builds content from a tagged template. */\nconst content = (\n\tstrings: ReadonlyArray<string>,\n\tvalues: ReadonlyArray<unknown>,\n\tcontext: string,\n): Content => {\n\tconst literals = dedent(strings);\n\tconst result: Array<Text | Action.Ref | Action.Step> = [];\n\n\tconst pushText = (text: string) => {\n\t\tif (text === \"\") return;\n\n\t\tconst last = result.at(-1);\n\t\tif (last?._tag === \"Text\") {\n\t\t\tresult[result.length - 1] = { _tag: \"Text\", text: last.text + text };\n\n\t\t\treturn;\n\t\t}\n\t\tresult.push({ _tag: \"Text\", text });\n\t};\n\n\tfor (const [index, literal] of literals.entries()) {\n\t\tpushText(literal);\n\t\tif (index >= values.length) continue;\n\n\t\tconst value = values[index];\n\t\tif (isScalar(value)) {\n\t\t\tpushText(String(value));\n\t\t\tcontinue;\n\t\t}\n\t\tif (isRef(value)) {\n\t\t\tresult.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isStep(value)) {\n\t\t\tvalidateStep(value, context);\n\t\t\tresult.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new TypeError(`${context}: cannot interpolate ${describeValue(value)}.`);\n\t}\n\n\treturn result;\n};\n\n/**\n * Declares a migration between exact versions. Interpolated actions, instruction blocks,\n * and groups declare occurrences; `Action.ref` only mentions an action.\n *\n * @example\n * ```ts\n * const migrate152To200 = Migration.make(\"1.5.2-to-2.0.0\", {\n * \tfrom: v152,\n * \tto: v200,\n * \taddresses: [timeoutRenamed],\n * })`\n * \tUpdate the configuration for export A:\n *\n * \t${renameExportA}\n * `;\n * ```\n *\n * @since 0.0.1\n */\nexport const make =\n\t<C extends Change.Any = never>(id: string, options: Options<C>) =>\n\t<const V extends ReadonlyArray<Interpolation>>(\n\t\tstrings: TemplateStringsArray,\n\t\t...values: V\n\t): Migration<Action.ActionsOf<V[number]>, C> => ({\n\t\t_tag: \"Migration\",\n\t\tid,\n\t\tfrom: options.from,\n\t\tto: options.to,\n\t\taddresses: options.addresses ?? [],\n\t\tnoop: false,\n\t\tcost: options.cost,\n\t\tcontent: content(strings, values, `Migration \"${id}\"`),\n\t\trevert: undefined,\n\t});\n\n/** @since 0.0.1 */\nexport type NoopOptions<C extends Change.Any = Change.Any> = Options<C> & {\n\t/** Also declares the reverse transition as zero-work. */\n\treadonly reversible?: boolean;\n};\n\n/**\n * Declares a supported transition that requires no consumer work. It is a directed edge\n * like any migration. Do not use it to hide missing support for changes that need\n * instructions.\n *\n * @since 0.0.1\n */\nexport const noop = <C extends Change.Any = never>(\n\tid: string,\n\toptions: NoopOptions<C>,\n): Migration<never, C> => ({\n\t_tag: \"Migration\",\n\tid,\n\tfrom: options.from,\n\tto: options.to,\n\taddresses: options.addresses ?? [],\n\tnoop: true,\n\tcost: options.cost,\n\tcontent: [],\n\trevert: options.reversible === true ? [] : undefined,\n});\n\n/**\n * Adds a reverse transition. Register the returned migration in place of the original:\n * both share the same identifier. On a `Migration.noop`, the reverse is real work: only\n * the forward side stays zero-work.\n *\n * @example\n * ```ts\n * const reversible = Migration.withRevert(migrate152To200)`\n * \tRestore the previous configuration:\n *\n * \t${restoreTimeout}\n * `;\n * ```\n *\n * @since 0.0.1\n */\nexport const withRevert =\n\t<A extends Action.Any, C extends Change.Any>(migration: Migration<A, C>) =>\n\t<const V extends ReadonlyArray<Interpolation>>(\n\t\tstrings: TemplateStringsArray,\n\t\t...values: V\n\t): Migration<A | Action.ActionsOf<V[number]>, C> => ({\n\t\t...migration,\n\t\trevert: content(strings, values, `Revert of migration \"${migration.id}\"`),\n\t});\n","import { type Cause, Effect, Exit, Predicate } from \"effect\";\n\nimport type * as Plan from \"../../foundation/plan.ts\";\nimport type { InterruptReason, Outcome, Report } from \"./executor.ts\";\nimport type { Performer, Phase } from \"./handler.ts\";\n\nconst TypeId = \"~deltafold/Observer\";\n\n/**\n * The run that emitted an event.\n *\n * @since 0.2.1\n */\nexport type Run = {\n\t/** The `runId` passed to the executor, if any. Shared observers use it to tell runs apart. */\n\treadonly id: string | undefined;\n\treadonly mode: Report[\"mode\"];\n\treadonly from: string;\n\treadonly to: string;\n\treadonly route: string;\n};\n\n/**\n * Counters at the moment an event was emitted. Counters never decrease during a run.\n *\n * @since 0.2.1\n */\nexport type Progress = {\n\t/** Steps with actions and prose-only steps. Omitted steps are not counted. */\n\treadonly steps: { readonly total: number; readonly finished: number };\n\treadonly actions: {\n\t\treadonly total: number;\n\t\t/** Occurrences whose prepare or apply phase has started and that have not settled. */\n\t\treadonly running: number;\n\t\treadonly finished: number;\n\t};\n};\n\n/**\n * One step of the route, as observers see it.\n *\n * - `execute`: the step has actions after optimization.\n * - `prose`: the step has instruction prose but no actions. The executor runs nothing\n * for it and does not wait at it.\n * - `omitted`: a noop, or a step whose actions rules removed or moved into another step.\n *\n * @since 0.2.1\n */\nexport type StepInfo = {\n\t/** The plan step's `id`. */\n\treadonly id: string;\n\t/** Position in `plan.steps`, including omitted steps. */\n\treadonly index: number;\n\treadonly migration: string;\n\treadonly direction: Plan.Direction;\n\treadonly from: string;\n\treadonly to: string;\n\t/** Occurrence identifiers of the step, in plan order. */\n\treadonly occurrences: ReadonlyArray<string>;\n\t/**\n\t * Other steps whose declared actions this step's replacements stand for. Running this\n\t * step performs work that those steps declared.\n\t */\n\treadonly absorbs: ReadonlyArray<string>;\n} & (\n\t| { readonly kind: \"execute\" | \"prose\" }\n\t| { readonly kind: \"omitted\"; readonly reason: \"noop\" | \"all-actions-removed\" }\n);\n\n/**\n * One occurrence of the plan, as observers see it.\n *\n * @since 0.2.1\n */\nexport type ActionInfo = {\n\treadonly occurrence: string;\n\treadonly action: string;\n\treadonly kind: string;\n\treadonly description: string;\n\treadonly migration: string;\n\treadonly direction: Plan.Direction;\n\t/** The step that runs the occurrence. */\n\treadonly step: string;\n\treadonly origin:\n\t\t| { readonly _tag: \"Declared\" }\n\t\t| {\n\t\t\t\treadonly _tag: \"Replacement\";\n\t\t\t\treadonly rule: string;\n\t\t\t\t/** Identifiers of the replaced occurrences, in order. */\n\t\t\t\treadonly replaces: ReadonlyArray<string>;\n\t\t };\n\t/** Steps that declared the actions behind this occurrence, in plan order. */\n\treadonly sources: ReadonlyArray<string>;\n};\n\n/**\n * An outcome as observers see it. Each variant lists its fields explicitly, so a field\n * added to the report's outcome never reaches observers unreviewed. A failure keeps only\n * the error's string `_tag`; the full error is in the execution's report.\n *\n * @since 0.2.1\n */\nexport type OutcomeSummary =\n\t| { readonly _tag: \"Completed\"; readonly performer: \"automated\" }\n\t| {\n\t\t\treadonly _tag: \"Completed\";\n\t\t\treadonly performer: \"manual\";\n\t\t\treadonly confirmation: \"asserted\" | \"verified\";\n\t }\n\t| { readonly _tag: \"Skipped\"; readonly reason: string }\n\t| { readonly _tag: \"Declined\" }\n\t| {\n\t\t\treadonly _tag: \"Failed\";\n\t\t\treadonly phase: Phase;\n\t\t\treadonly errorTag: string | undefined;\n\t }\n\t| {\n\t\t\treadonly _tag: \"Interrupted\";\n\t\t\treadonly phase: Phase;\n\t\t\treadonly reason: InterruptReason;\n\t\t\treadonly settled: boolean;\n\t }\n\t| { readonly _tag: \"Unattempted\" }\n\t| {\n\t\t\treadonly _tag: \"WouldExecute\";\n\t\t\treadonly evaluated: boolean;\n\t\t\treadonly performer: Performer;\n\t }\n\t| { readonly _tag: \"WouldSkip\"; readonly reason: string }\n\t| {\n\t\t\treadonly _tag: \"Undetermined\";\n\t\t\treadonly reason: string;\n\t\t\treadonly performer: Performer;\n\t }\n\t| { readonly _tag: \"PreparationFailed\"; readonly errorTag: string | undefined };\n\n/**\n * Occurrences by outcome tag. `unsettled` counts interrupted occurrences that may still be\n * running.\n *\n * @since 0.2.1\n */\nexport type Counts = { readonly [K in Outcome[\"_tag\"]]: number } & {\n\treadonly unsettled: number;\n};\n\ntype Base = {\n\treadonly run: Run;\n\t/** Position of the event in its run, starting at 0. */\n\treadonly seq: number;\n\t/** Milliseconds since the Unix epoch, from Effect's `Clock`. */\n\treadonly timestamp: number;\n\treadonly progress: Progress;\n};\n\n/**\n * The run is starting: every action has a handler, and manual work has an interaction to\n * ask with. A run that fails either check emits no events. Lists every step of the route,\n * including omitted ones.\n *\n * @since 0.2.1\n */\nexport type RunStarted = Base & {\n\treadonly _tag: \"RunStarted\";\n\treadonly steps: ReadonlyArray<StepInfo>;\n};\n\n/** @since 0.2.1 */\nexport type StepStarted = Base & { readonly _tag: \"StepStarted\"; readonly step: StepInfo };\n\n/**\n * A phase of an occurrence started: its prepare or apply phase, the confirmation of\n * manual work, or its verification. `prepare` appears only for handlers that have a\n * prepare phase. `confirmation` means the run is waiting for a person. An occurrence\n * emits this once per phase that starts.\n *\n * @since 0.2.1\n */\nexport type ActionPhaseStarted = Base & {\n\treadonly _tag: \"ActionPhaseStarted\";\n\treadonly action: ActionInfo;\n\treadonly phase: Phase;\n};\n\n/**\n * An occurrence has its final outcome. Emitted once for each occurrence whose outcome is\n * known, and as `Unattempted` for an occurrence that started but stopped before applying\n * or asking. It arrives after the occurrence's scope has closed, except when an\n * interrupted Promise has not settled: then the scope stays open until it does, the\n * reported outcome is already final, and a later cleanup failure is only logged. Dry-run\n * outcomes that need no prepare phase arrive without a start.\n *\n * @since 0.2.1\n */\nexport type ActionSettled = Base & {\n\treadonly _tag: \"ActionSettled\";\n\treadonly action: ActionInfo;\n\treadonly outcome: OutcomeSummary;\n};\n\n/**\n * A started step ended. `counts` covers the step's occurrences.\n *\n * @since 0.2.1\n */\nexport type StepSettled = Base & {\n\treadonly _tag: \"StepSettled\";\n\treadonly step: StepInfo;\n\treadonly counts: Counts;\n};\n\n/**\n * The run ended. `status` and `counts` match the execution's report. When the fiber of\n * `Executor.effect` is interrupted, there is no report: `report` is `false`, the status is\n * `\"interrupted\"`, and running occurrences count as unsettled interruptions. If the\n * interruption cuts short the delivery of `RunFinished`, the observers that had not yet\n * received it get the report-less one with the same `seq`, so each observer receives\n * exactly one.\n *\n * @since 0.2.1\n */\nexport type RunFinished = Base & {\n\treadonly _tag: \"RunFinished\";\n\treadonly status: Report[\"status\"];\n\treadonly counts: Counts;\n\treadonly report: boolean;\n};\n\n/**\n * What an observer receives. A run emits `RunStarted`; then, for each step that is not\n * omitted, `StepStarted`, an `ActionPhaseStarted` for each phase that starts, an\n * `ActionSettled` for each occurrence, and `StepSettled`; and finally `RunFinished`. Action\n * events of parallel branches interleave.\n *\n * Events carry identifiers and plain data, never payloads, errors, or causes. Action\n * descriptions are included, so they must not contain secrets.\n *\n * @since 0.2.1\n */\nexport type Event =\n\t| RunStarted\n\t| StepStarted\n\t| ActionPhaseStarted\n\t| ActionSettled\n\t| StepSettled\n\t| RunFinished;\n\n/**\n * An observer that failed, or that was abandoned after cancellation or a timeout because\n * it did not finish within the settlement grace period. An abandoned callback is\n * interrupted but not awaited, so one that cannot be interrupted may keep running. The\n * cause can hold arbitrary values, so do not serialize it as a whole.\n *\n * @since 0.2.1\n */\nexport type ObservationFailure = {\n\t/** Position of the observer in the `observers` array. */\n\treadonly observer: number;\n\treadonly event: Event[\"_tag\"];\n\treadonly seq: number;\n\treadonly reason: \"failed\" | \"abandoned\";\n\treadonly cause: Cause.Cause<unknown>;\n};\n\n/**\n * Receives the events of a run. Pass observers to the executor's `observers` option. `R`\n * is the Effect services an observer requires, which become requirements of the execution.\n *\n * The executor delivers one event at a time, to each observer in array order, and waits\n * for each delivery before it continues, so every observer sees the same order. After\n * cancellation or a timeout, each delivery waits at most `settleTimeout` and is then\n * abandoned. A failed or abandoned delivery is listed in the report's `observation` and\n * never changes an outcome. Observers only receive events: they cannot answer a manual\n * confirmation.\n *\n * @since 0.2.1\n */\nexport type Observer<out R = never> = {\n\treadonly [TypeId]: typeof TypeId;\n\t/** Delivers one event and captures how the delivery ended. It never fails. */\n\treadonly notify: (event: Event) => Effect.Effect<Exit.Exit<unknown, unknown>, never, R>;\n};\n\n/**\n * Any observer.\n *\n * @since 0.2.1\n */\nexport type Any = Observer<any>;\n\n/**\n * The Effect services of an observer or a union of observers.\n *\n * @since 0.2.1\n */\nexport type Services<O> = O extends Observer<infer R> ? R : never;\n\n/** @since 0.2.1 */\nexport const isObserver = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId);\n\nclass AsyncSyncObserver extends Error {\n\toverride readonly name = \"AsyncSyncObserver\";\n\toverride readonly message =\n\t\t\"An Observer.sync callback returned a Promise. Use Observer.promise for asynchronous callbacks.\";\n}\n\n/**\n * Observes with a synchronous callback. A thrown value is recorded as an observation\n * failure.\n *\n * @example\n * ```ts\n * Observer.sync((event) => {\n * \tif (event._tag === \"ActionSettled\") console.error(event.action.occurrence, event.outcome._tag);\n * });\n * ```\n *\n * @since 0.2.1\n */\nexport const sync = (callback: (event: Event) => void): Observer => ({\n\t[TypeId]: TypeId,\n\tnotify: (event) =>\n\t\tEffect.sync((): Exit.Exit<void, unknown> => {\n\t\t\ttry {\n\t\t\t\tconst result: unknown = callback(event);\n\t\t\t\tif (!Predicate.isPromiseLike(result)) return Exit.void;\n\t\t\t\t// Keep a rejection from going unhandled; the misuse is reported instead.\n\t\t\t\tPromise.resolve(result).catch(() => undefined);\n\n\t\t\t\treturn Exit.fail(new AsyncSyncObserver());\n\t\t\t} catch (cause) {\n\t\t\t\t// The thrown value is the failure, exactly as the observer threw it.\n\t\t\t\treturn Exit.fail(cause);\n\t\t\t}\n\t\t}),\n});\n\n/**\n * Observes with a Promise callback. The executor waits for the Promise. The `signal`\n * aborts when the executor stops waiting: after cancellation or a timeout, once the\n * settlement grace period has passed, or when the execution is interrupted. A services\n * layer that `Executor.runPromise` built stays open until an abandoned Promise settles.\n *\n * @since 0.2.1\n */\nexport const promise = (\n\tcallback: (event: Event, context: { readonly signal: AbortSignal }) => PromiseLike<unknown>,\n): Observer => ({\n\t[TypeId]: TypeId,\n\tnotify: (event) =>\n\t\tEffect.suspend(() => {\n\t\t\tlet pending: Promise<unknown> | undefined;\n\n\t\t\t// Declaring `signal` makes Effect.promise allocate an AbortController. The rejection\n\t\t\t// is the failure, exactly as the observer rejected.\n\t\t\treturn Effect.promise((signal): Promise<Exit.Exit<unknown, unknown>> => {\n\t\t\t\tconst settles = new Promise<unknown>((resolve) =>\n\t\t\t\t\tresolve(callback(event, { signal })),\n\t\t\t\t).then(\n\t\t\t\t\t() => Exit.void,\n\t\t\t\t\t(cause: unknown) => Exit.fail(cause),\n\t\t\t\t);\n\t\t\t\tpending = settles;\n\n\t\t\t\treturn settles;\n\t\t\t}).pipe(\n\t\t\t\t// The executor abandons a delivery by interrupting it without waiting, and keeps\n\t\t\t\t// the run's services open until the interruption ends. Ending it only once the\n\t\t\t\t// Promise settles keeps them open for the callback's remaining work.\n\t\t\t\tEffect.onInterrupt(() =>\n\t\t\t\t\tpending === undefined\n\t\t\t\t\t\t? Effect.void\n\t\t\t\t\t\t: Effect.promise(() => pending ?? Promise.resolve()),\n\t\t\t\t),\n\t\t\t);\n\t\t}),\n});\n\n/**\n * Observes with an Effect. Its services become requirements of the execution. Its\n * failures are recorded as observation failures and never fail the execution.\n *\n * @example\n * ```ts\n * Observer.effect((event) => Effect.logDebug(event._tag));\n * ```\n *\n * @since 0.2.1\n */\nexport const effect = <E = never, R = never>(\n\tcallback: (event: Event) => Effect.Effect<unknown, E, R>,\n): Observer<R> => ({\n\t[TypeId]: TypeId,\n\tnotify: (event) => Effect.exit(Effect.suspend(() => callback(event))),\n});\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"../foundation/action.ts\";\nimport type { History } from \"./planning/history.ts\";\n\n/** @since 0.0.1 */\nexport type Package<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Package\";\n\t/** The name of the modeled package, for example `@acme/widgets`. */\n\treadonly name: string;\n\treadonly history: History<A>;\n};\n\n/**\n * Defines the modeled package. It holds no renderer settings, release metadata, or\n * handlers.\n *\n * @example\n * ```ts\n * export const widgets = Package.make(\"@acme/widgets\", { history });\n * ```\n *\n * @since 0.0.1\n */\nexport const make = <A extends Action.Any>(\n\tname: string,\n\toptions: { readonly history: History<A> },\n): Package<A> => ({ _tag: \"Package\", name, history: options.history });\n\n/** @since 0.0.1 */\nexport const isPackage = (value: unknown): value is Package<any> =>\n\tPredicate.isTagged(value, \"Package\");\n","import type * as Action from \"./action.ts\";\nimport type * as Change from \"./change.ts\";\nimport type { Instruction, Text } from \"./instruction.ts\";\nimport type * as Migration from \"./migration.ts\";\nimport type * as Rule from \"./rule.ts\";\nimport type * as Shortcut from \"./shortcut.ts\";\nimport type { Version } from \"./version.ts\";\n\n/**\n * Which side of a migration runs.\n *\n * @since 0.0.1\n */\nexport type Direction = \"forward\" | \"revert\";\n\n/**\n * How an occurrence entered the plan.\n *\n * @since 0.0.1\n */\nexport type Origin =\n\t| { readonly _tag: \"Declared\" }\n\t| {\n\t\t\treadonly _tag: \"Replacement\";\n\t\t\treadonly rule: Rule.Any;\n\t\t\t/** The occurrences the rule replaced, in order. */\n\t\t\treadonly replaces: ReadonlyArray<Occurrence>;\n\t };\n\n/**\n * One execution of an action instance in a plan. Its `id` is stable across prose edits:\n * it combines the migration, direction, and action identifiers, or the rule and the\n * replaced occurrences for a replacement.\n *\n * @since 0.0.1\n */\nexport type Occurrence<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Occurrence\";\n\t/**\n\t * Unique within the plan. Built from the migration, direction, and action identifiers,\n\t * or from the rule and the replaced occurrences. Separator characters in author\n\t * identifiers are escaped with a backslash, so identifiers never collide.\n\t */\n\treadonly id: string;\n\treadonly action: A;\n\t/** The migration whose step contains this occurrence. */\n\treadonly migration: Migration.Any;\n\treadonly direction: Direction;\n\t/** The instruction block that declared this occurrence, if any. */\n\treadonly instruction: Instruction | undefined;\n\treadonly origin: Origin;\n};\n\n/** @since 0.0.1 */\nexport type Sequence<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Sequence\";\n\treadonly children: ReadonlyArray<Node<A>>;\n};\n\n/** @since 0.0.1 */\nexport type Parallel<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Parallel\";\n\treadonly branches: ReadonlyArray<Node<A>>;\n\treadonly concurrency: Action.Concurrency;\n};\n\n/**\n * The declared execution structure.\n *\n * @since 0.0.1\n */\nexport type Node<A extends Action.Any = Action.Any> = Occurrence<A> | Sequence<A> | Parallel<A>;\n\n/**\n * Resolved prose for a guide. Occurrences render as their instruction or description.\n *\n * @since 0.0.1\n */\nexport type GuideItem<A extends Action.Any = Action.Any> =\n\t| Text\n\t| Action.Ref\n\t| { readonly _tag: \"Occurrence\"; readonly occurrence: Occurrence<A> }\n\t| {\n\t\t\treadonly _tag: \"Group\";\n\t\t\treadonly kind: \"Sequence\" | \"Parallel\";\n\t\t\t/** One entry per retained child or branch. */\n\t\t\treadonly children: ReadonlyArray<ReadonlyArray<GuideItem<A>>>;\n\t };\n\n/**\n * One migration in the route. Steps are sequential barriers: a step starts only after\n * the previous step completed.\n *\n * @since 0.0.1\n */\nexport type Step<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Step\";\n\t/**\n\t * Identifies the migration side within the route: the migration identifier, followed by\n\t * `/revert` for a reverse migration. Declared occurrence identifiers start with it.\n\t */\n\treadonly id: string;\n\treadonly migration: Migration.Any;\n\treadonly direction: Direction;\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly node: Sequence<A>;\n\t/** Resolved guide content. Empty when the step is omitted from the guide. */\n\treadonly guide: ReadonlyArray<GuideItem<A>>;\n\t/**\n\t * Whether the normal resolved guide leaves this step out: a noop, or a migration whose\n\t * actions were all removed by rules.\n\t */\n\treadonly omitted: boolean;\n};\n\n/**\n * Why the plan differs from the declared migrations.\n *\n * @since 0.0.1\n */\nexport type Explanation =\n\t| {\n\t\t\treadonly _tag: \"Rewrite\";\n\t\t\treadonly rule: Rule.Any;\n\t\t\treadonly removed: ReadonlyArray<Occurrence>;\n\t\t\treadonly produced: ReadonlyArray<Occurrence>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"OmittedStep\";\n\t\t\treadonly migration: Migration.Any;\n\t\t\treadonly direction: Direction;\n\t\t\treadonly reason: \"noop\" | \"all-actions-removed\";\n\t };\n\n/**\n * A hop in a route: the migrations between two versions, or a shortcut.\n *\n * @since 0.0.1\n */\nexport type Hop =\n\t| {\n\t\t\treadonly _tag: \"Migrations\";\n\t\t\treadonly from: Version;\n\t\t\treadonly to: Version;\n\t\t\t/**\n\t\t\t * The migration side that moves between these versions. Validation allows one\n\t\t\t * side per transition, so this holds exactly one entry.\n\t\t\t */\n\t\t\treadonly migrations: ReadonlyArray<{\n\t\t\t\treadonly migration: Migration.Any;\n\t\t\t\treadonly direction: Direction;\n\t\t\t}>;\n\t }\n\t| {\n\t\t\treadonly _tag: \"Shortcut\";\n\t\t\treadonly from: Version;\n\t\t\treadonly to: Version;\n\t\t\treadonly shortcut: Shortcut.Any;\n\t };\n\n/** @since 0.0.1 */\nexport type Route = {\n\t/**\n\t * Identifies the route for explicit selection: version identifiers joined by `>`,\n\t * with shortcut hops written as `[shortcut-id]`. A backslash escapes `\\`, `>`, `[`,\n\t * and `]` inside identifiers, so a version `a>b` appears as `a\\>b`.\n\t */\n\treadonly id: string;\n\treadonly hops: ReadonlyArray<Hop>;\n};\n\n/**\n * How the requested target relates to the source in release ancestry.\n *\n * @since 0.0.1\n */\nexport type RequestDirection = \"none\" | \"upgrade\" | \"downgrade\" | \"cross-branch\";\n\n/**\n * When executors check handler coverage. Static plans also expose uncovered actions in\n * the execution's type.\n *\n * @since 0.0.1\n */\nexport type Coverage = \"static\" | \"runtime\";\n\n/**\n * A resolved, optimized route between two versions. Every step stays traceable to its\n * migration and the changes that migration addresses.\n *\n * @since 0.0.1\n */\nexport type Plan<\n\tA extends Action.Any = Action.Any,\n\tC extends Coverage = \"static\",\n\tCh extends Change.Any = Change.Any,\n> = {\n\treadonly _tag: \"Plan\";\n\treadonly from: Version;\n\treadonly to: Version;\n\treadonly direction: RequestDirection;\n\treadonly route: Route;\n\treadonly steps: ReadonlyArray<Step<A>>;\n\t/** Occurrences in plan order. */\n\treadonly occurrences: ReadonlyArray<Occurrence<A>>;\n\t/** The changes addressed by the route's migrations. */\n\treadonly changes: ReadonlyArray<Ch>;\n\treadonly explanations: ReadonlyArray<Explanation>;\n\t/**\n\t * Whether executors check handler coverage only at run time. Plans resolved from a\n\t * history are checked statically against its conservative action union.\n\t */\n\treadonly coverage: C;\n};\n\n/**\n * Any plan.\n *\n * @since 0.0.1\n */\nexport type Any = Plan<any, any>;\n\n/**\n * The action instances of a plan.\n *\n * @since 0.0.1\n */\nexport type ActionsOf<P> = P extends Plan<infer A, any> ? A : never;\n\n/**\n * Whether the plan has no action occurrences. An empty plan is valid.\n *\n * @since 0.0.1\n */\nexport const isEmpty = (plan: Any): boolean => plan.occurrences.length === 0;\n\n/**\n * Marks a plan for run-time coverage checks only. Use it for dynamically selected or\n * loaded plans whose action union is not known statically. Executors still reject\n * missing handlers before any action body runs.\n *\n * @since 0.0.1\n */\nexport const withRuntimeCoverage = <A extends Action.Any, Ch extends Change.Any>(\n\tplan: Plan<A, Coverage, Ch>,\n): Plan<A, \"runtime\", Ch> => ({\n\t...plan,\n\tcoverage: \"runtime\",\n});\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\n\n/**\n * What a rule matches: an action instance, or a parallel group matched by its branch\n * structure. Matching a parallel group is an explicit structural rule.\n *\n * @since 0.0.1\n */\nexport type Pattern = Action.Any | Action.Parallel;\n\n/** @since 0.0.1 */\nexport type Rule<A extends Action.Any = Action.Any> = {\n\treadonly _tag: \"Rule\";\n\treadonly id: string;\n\treadonly match: ReadonlyArray<Pattern>;\n\t/** Steps that take the place of the match. An empty replacement cancels it. */\n\treadonly replacement: ReadonlyArray<Action.Step<A>>;\n};\n\n/**\n * Any rule.\n *\n * @since 0.0.1\n */\nexport type Any = Rule<any>;\n\n/**\n * The action instances a rule can contribute to a plan.\n *\n * @since 0.0.1\n */\nexport type ActionsOf<R> = R extends Rule<infer A> ? A : never;\n\n/**\n * Declares a replacement. Cancellation, composition, and supersession all use it.\n *\n * The author asserts that the replacement is equivalent to the matched occurrences.\n * deltafold checks the rule's structure and where it applies, but it cannot prove the\n * equivalence.\n *\n * Ordinary rules match consecutive occurrences inside one sequential branch, including\n * across migration boundaries of a route. They never match across parallel branches.\n *\n * @example\n * ```ts\n * const cancelRoundTrip = Rule.replace(\"cancel-timeout-round-trip\", {\n * \tmatch: [renameTimeout, restoreTimeout],\n * \treplacement: [],\n * });\n * const combineRenames = Rule.replace(\"combine-renames\", {\n * \tmatch: [renameAtoB, renameBtoC],\n * \treplacement: [renameAtoC],\n * });\n * ```\n *\n * @since 0.0.1\n */\nexport const replace = <A extends Action.Any = never>(\n\tid: string,\n\toptions: {\n\t\treadonly match: ReadonlyArray<Pattern>;\n\t\treadonly replacement: ReadonlyArray<Action.Step<A>>;\n\t},\n): Rule<A> => ({\n\t_tag: \"Rule\",\n\tid,\n\tmatch: options.match,\n\treplacement: options.replacement,\n});\n\n/** @since 0.0.1 */\nexport const isRule = (value: unknown): value is Any => Predicate.isTagged(value, \"Rule\");\n","import { Predicate } from \"effect\";\n\nimport type * as Action from \"./action.ts\";\nimport type * as Change from \"./change.ts\";\nimport type * as Migration from \"./migration.ts\";\nimport type { Version } from \"./version.ts\";\n\n/** @since 0.0.1 */\nexport type Shortcut<A extends Action.Any = Action.Any, C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"Shortcut\";\n\treadonly id: string;\n\treadonly from: Version;\n\treadonly to: Version;\n\t/** The canonical route this shortcut replaces, in order. */\n\treadonly replaces: ReadonlyArray<Migration.Any>;\n\t/** The migrations that run instead, in order. */\n\treadonly migrations: ReadonlyArray<Migration.Migration<A, C>>;\n\t/** Author-declared cost, used only by the `lowest-cost` route policy. */\n\treadonly cost: number | undefined;\n};\n\n/**\n * Any shortcut.\n *\n * @since 0.0.1\n */\nexport type Any = Shortcut<any>;\n\n/**\n * The action instances a shortcut can contribute to a plan.\n *\n * @since 0.0.1\n */\nexport type ActionsOf<S> = S extends Shortcut<infer A> ? A : never;\n\n/**\n * The changes addressed by a shortcut's migrations.\n *\n * @since 0.0.1\n */\nexport type ChangesOf<S> = S extends Shortcut<any, infer C> ? C : never;\n\n/**\n * Declares a shortcut. The author asserts that its migrations are equivalent to the\n * canonical route it replaces; deltafold does not prove it.\n *\n * @example\n * ```ts\n * const fastUpgrade = Shortcut.make(\"fast-upgrade\", {\n * \tfrom: v201,\n * \tto: v208,\n * \treplaces: [migrate202, migrate203, migrate204],\n * \tmigrations: [migrateDirectlyTo208],\n * });\n * ```\n *\n * @since 0.0.1\n */\nexport const make = <A extends Action.Any, C extends Change.Any = never>(\n\tid: string,\n\toptions: {\n\t\treadonly from: Version;\n\t\treadonly to: Version;\n\t\treadonly replaces: ReadonlyArray<Migration.Any>;\n\t\treadonly migrations: ReadonlyArray<Migration.Migration<A, C>>;\n\t\treadonly cost?: number;\n\t},\n): Shortcut<A, C> => ({\n\t_tag: \"Shortcut\",\n\tid,\n\tfrom: options.from,\n\tto: options.to,\n\treplaces: options.replaces,\n\tmigrations: options.migrations,\n\tcost: options.cost,\n});\n\n/** @since 0.0.1 */\nexport const isShortcut = (value: unknown): value is Any => Predicate.isTagged(value, \"Shortcut\");\n","import { Predicate } from \"effect\";\n\nimport type * as Change from \"./change.ts\";\n\n/** @since 0.0.1 */\nexport type Version<C extends Change.Any = Change.Any> = {\n\treadonly _tag: \"Version\";\n\treadonly id: string;\n\t/**\n\t * The release this version descends from. Absent for a root such as `0.0.0`. Only\n\t * this field sets ancestry: several versions can share a predecessor, and declaration\n\t * order and semver order have no effect.\n\t */\n\treadonly previous: Version | undefined;\n\t/** The changes that shipped in this release. */\n\treadonly changes: ReadonlyArray<C>;\n};\n\n/** @since 0.0.1 */\nexport type Options<C extends Change.Any = Change.Any> = {\n\treadonly previous?: Version;\n\treadonly changes: ReadonlyArray<C>;\n};\n\n/**\n * Declares a version.\n *\n * @example\n * ```ts\n * const v0 = Version.make(\"0.0.0\", { changes: [] });\n * const v100 = Version.make(\"1.0.0\", { previous: v0, changes: [timeoutRenamed] });\n * ```\n *\n * @since 0.0.1\n */\nexport const make = <C extends Change.Any = never>(\n\tid: string,\n\toptions: Options<C>,\n): Version<C> => ({\n\t_tag: \"Version\",\n\tid,\n\tprevious: options.previous,\n\tchanges: options.changes,\n});\n\n/** @since 0.0.1 */\nexport const isVersion = (value: unknown): value is Version => Predicate.isTagged(value, \"Version\");\n\n/**\n * Release metadata attached to a version by release tooling. It does not modify the\n * version registered in history.\n *\n * @since 0.0.1\n */\nexport type Release<M> = {\n\treadonly _tag: \"Release\";\n\treadonly version: Version;\n\treadonly metadata: M;\n};\n\n/**\n * Annotates a version with release metadata.\n *\n * @example\n * ```ts\n * export const release200 = Version.withMetadata(v200, {\n * \treleasedAt: \"2026-11-06T12:00:00Z\",\n * \tcommit: \"abc123\",\n * });\n * ```\n *\n * @since 0.0.1\n */\nexport const withMetadata = <const M>(version: Version, metadata: M): Release<M> => ({\n\t_tag: \"Release\",\n\tversion,\n\tmetadata,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,MAAaA,YACZ,MACA,UAA0D,CAAC,MAC9C;CACb,MAAM,WAAW,QAAQ,mBAAmB;CAE5C,OAAO;EACN,MAAM;EACN;EACA;EACA,OAAO,IAAI,aAAa;GACvB,MAAM;GACN;GACA;GACA;GACA,aAAa,SAAS,OAAO;EAC9B;CACD;AACD;;;;;;AAOA,MAAa,OAAO,YAAsB;CAAE,MAAM;CAAa;AAAO;;;;;;AAOtE,MAAa,YACZ,cACqC;CAAE,MAAM;CAAY;AAAS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