@orkestrel/workflow 0.0.13 → 0.0.14

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["#sleep","#table","#snapshots","#context","#phase","#workflow","#recompute","#metadata","#emitter","#run","#retries","#timeout","#handler","#abort","#silence","#onSilence","#liveness","#status","#result","#name","#attempts","#expire","#activity","#paused","#gate","#timerSignal","#transition","#stamp","#arm","#escalate","#finish","#record","#touch","#release","#clear","#tasks","#isUpdate","#reorder","#id","#workflow","#escalateUp","#tasks","#functions","#silence","#emitter","#name","#bail","#concurrency","#append","#override","#status","#paused","#gate","#statuses","#force","#release","#mint","#addTo","#emitFor","#recompute","#failure","#create","#phases","#isUpdate","#reorder","#context","#bail","#bailOverride","#functions","#silence","#phases","#emitter","#created","#abort","#updated","#paused","#gate","#destroyed","#append","#override","#status","#statuses","#force","#release","#boundary","#addTo","#mint","#indexOf","#emitFor","#recompute","#failure","#workflows","#opens","#saves","#mutations","#additions","#hydrations","#functions","#store","#invalidate","#generation","#retain","#hydrate","#releaseOpen","#persist","#settle","#owns","#resolve","#register","#releaseHydration","#abort","#spawn","#handler","#entries","#queue","#emitter","#aborts","#order","#values","#dispatched","#queued","#dispatch","#count","#stopped","#accepts","#launch","#started","#running","#drained","#cleanup","#failure","#collect","#abortPromise","#cancel","#settleLifecycle","#destroyPromise","#stopPromise","#stopping","#settleDestroy","#settle","#spawn","#waitDrain","#entity","#report","#pulse","#results","#ancestorTerminal","#race","#gates","#resolve","#workflow","#store","#phases","#tasks","#onWorkflowChange","#onWorkflowAdd","#onWorkflowRemove","#onPhaseChange","#onPhaseAdd","#onPhaseRemove","#onTaskChange","#change","#addPhase","#removePhase","#addTask","#removeTask","#attachWorkflow","#fault","#mark","#stored","#flush","#error","#attached","#detachPhase","#attachPhase","#attachTask","#detachTask","#writing","#drain","#revision","#executions","#scheduler","#isWorkflow","#acquire","#execute","#fold","#abortActive","#stoppable","#skipFrom","#cancelled","#halted","#haltFrom","#raceWait","#runPhase","#pace","#completable","#spawnAdded","#entry","#runUnit","#skip","#runTask","#skipping","#settleCancelled","#taskSignal","#owns","#gate","#raceHandler","#timedOut","#failed","#settleAttempt","#revoke","#resolveHandlerAbort","#resolveWaitAbort"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/Scheduler.ts","../../../src/core/cloners.ts","../../../src/core/shapers.ts","../../../src/core/stores/DatabaseWorkflowStore.ts","../../../src/core/stores/MemoryWorkflowStore.ts","../../../src/core/tasks/Task.ts","../../../src/core/tasks/TaskManager.ts","../../../src/core/phases/Phase.ts","../../../src/core/phases/PhaseManager.ts","../../../src/core/Workflow.ts","../../../src/core/WorkflowManager.ts","../../../src/core/Controller.ts","../../../src/core/Runner.ts","../../../src/core/tasks/TaskController.ts","../../../src/core/WorkflowPersistence.ts","../../../src/core/WorkflowRunner.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { PhaseStatus, TaskStatus, WorkflowStatus } from './types.js'\n\n// Workflow constants — the centralized data the contract, the derivation helpers,\n// and (later) the entities read. UPPER_SNAKE, `Object.freeze`d, every member\n// exported (AGENTS §5). The status-vocabulary arrays are the runtime source of\n// truth for the §10 unions: compose them with the shipped contracts primitives\n// (`literalOf(...)` for a guard, `literalShape(...)` for a contract) instead of a\n// bespoke guard.\n\n/** The default {@link import('./types.js').WorkflowDefinition.bail} — graceful (continue on a leaf failure). */\nexport const DEFAULT_BAIL = false\n\n/**\n * Every {@link TaskStatus} value, frozen — the lifecycle vocabulary of a task.\n *\n * @remarks\n * Ordered pending → running → terminal (`completed` / `failed` / `skipped` /\n * `stopped`). The source of truth for the union; compose guards / shapes from it.\n */\nexport const TASK_STATUSES: readonly TaskStatus[] = Object.freeze([\n\t'pending',\n\t'running',\n\t'completed',\n\t'failed',\n\t'skipped',\n\t'stopped',\n])\n\n/** Every {@link PhaseStatus} value, frozen — the lifecycle vocabulary of a phase. */\nexport const PHASE_STATUSES: readonly PhaseStatus[] = Object.freeze([\n\t'pending',\n\t'running',\n\t'completed',\n\t'failed',\n\t'skipped',\n\t'stopped',\n])\n\n/** Every {@link WorkflowStatus} value, frozen — the lifecycle vocabulary of a workflow. */\nexport const WORKFLOW_STATUSES: readonly WorkflowStatus[] = Object.freeze([\n\t'pending',\n\t'running',\n\t'completed',\n\t'failed',\n\t'skipped',\n\t'stopped',\n])\n\n/**\n * The {@link TaskStatus} values that are TERMINAL — a task in one of these will\n * not transition further, frozen.\n *\n * @remarks\n * The source of truth behind {@link import('./helpers.js').isTerminalStatus}.\n * `pending` and `running` are the only non-terminal members.\n */\nexport const TERMINAL_TASK_STATUSES: readonly TaskStatus[] = Object.freeze([\n\t'completed',\n\t'failed',\n\t'skipped',\n\t'stopped',\n])\n\n/**\n * The legal {@link TaskStatus} transition graph of the live W-b task state machine —\n * each current status mapped to the statuses it may move to directly, frozen.\n *\n * @remarks\n * The source of truth behind {@link import('./helpers.js').canTransitionTask} and the\n * `TRANSITION` guard ({@link import('./errors.js').WorkflowError}). A `pending` task may\n * `start` (→ `running`), `skip` (→ `skipped`), or `stop` (→ `stopped`); a `running` task\n * may `complete` (→ `completed`), `fail` (→ `failed`), `skip` (→ `skipped`), or `stop`\n * (→ `stopped`). Every terminal status maps to an empty list — a settled task never\n * transitions again. So completing a non-`running` task, or starting a settled one, is\n * rejected.\n */\nexport const TASK_TRANSITIONS: Readonly<Record<TaskStatus, readonly TaskStatus[]>> = Object.freeze({\n\tpending: ['running', 'skipped', 'stopped'],\n\trunning: ['completed', 'failed', 'skipped', 'stopped'],\n\tcompleted: [],\n\tfailed: [],\n\tskipped: [],\n\tstopped: [],\n})\n\n/**\n * The default per-phase task concurrency the {@link import('./factories.js').createWorkflowRunner}\n * runner applies when a {@link import('./types.js').PhaseDefinition} omits its `concurrency`\n * throttle — a cap that is effectively unbounded for any realistic phase.\n *\n * @remarks\n * The determinism principle fixes that a phase's tasks run CONCURRENTLY; `concurrency` is\n * only an optional resource throttle (max-in-flight). With none declared, the runner runs\n * all of a phase's tasks at once — modelled as this finite cap so the value flows straight\n * into the substrate {@link import('./types.js').RunnerInterface}'s `concurrency` (which\n * expects a positive integer) without a special unbounded branch. No realistic phase\n * declares enough tasks to reach it, so it behaves as \"run them all\".\n *\n * WHY `1024` and not a huge sentinel like `1_000_000`: the backing `@orkestrel/queue` Runner\n * EAGERLY spawns one parked worker loop per concurrency unit AT CONSTRUCTION, so this default\n * must be a value whose eager allocation cost is negligible for every default-concurrency\n * phase — a million-unit default meant ~1e6 promise/closure allocations per such phase. A\n * phase may still DECLARE a larger explicit `concurrency` and pays that allocation knowingly.\n */\nexport const DEFAULT_PHASE_CONCURRENCY = 1024\n\n/**\n * The largest delay representable by the host timer APIs without overflow or clamping.\n */\nexport const MAX_TIMER_MS = 2_147_483_647\n","import type { WorkflowErrorCode } from './types.js'\n\n// AGENTS §12: an illegal state-machine transition, structurally invalid restore, refused\n// mutation, or refused host schedule carries a machine-readable `code`, so a `catch`\n// branches on `error.code` instead of parsing the message. The `context` bag names the\n// offending node / status / parameter. Optional lookups (`task` / `phase`) return\n// `undefined` — they never throw.\n\n/**\n * An error raised by the workflow runtime.\n *\n * @remarks\n * Carries a {@link WorkflowErrorCode} and an optional `context` bag naming the\n * offending node id / status / parameter. Raised for an illegal lifecycle transition\n * (`TRANSITION`), a structurally invalid {@link import('./types.js').WorkflowSnapshot}\n * boundary (`RESTORE`), a refused structural/activity edit (`MUTATION`), or a host\n * schedule refused before arming because the caller's `signal` is not a native\n * `AbortSignal` (`SCHEDULE`, delivered as a rejected promise).\n */\nexport class WorkflowError extends Error {\n\treadonly code: WorkflowErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: WorkflowErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'WorkflowError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrow an unknown caught value to a {@link WorkflowError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is a {@link WorkflowError}\n *\n * @example\n * ```ts\n * try {\n * \ttask.complete('done')\n * } catch (error) {\n * \tif (isWorkflowError(error) && error.code === 'TRANSITION') retry()\n * }\n * ```\n */\nexport function isWorkflowError(value: unknown): value is WorkflowError {\n\ttry {\n\t\treturn value instanceof WorkflowError\n\t} catch {\n\t\treturn false\n\t}\n}\n","import type {\n\tLifecycleStatus,\n\tTaskActivity,\n\tTaskActivityInput,\n\tTaskFailure,\n\tWorkflowSnapshot,\n} from './types.js'\nimport {\n\tattempt,\n\tcloneJSONValue,\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisInteger,\n\tisJSONValue,\n\tisNonEmptyString,\n\tisRecord,\n} from '@orkestrel/contract'\nimport { MAX_TIMER_MS } from './constants.js'\nimport { derivePhaseStatus, deriveWorkflowStatus, isTaskResult } from './helpers.js'\n\n/** Test the workflow lifecycle vocabulary. */\nexport function isLifecycleStatus(value: unknown): value is LifecycleStatus {\n\treturn (\n\t\tvalue === 'pending' ||\n\t\tvalue === 'running' ||\n\t\tvalue === 'completed' ||\n\t\tvalue === 'failed' ||\n\t\tvalue === 'skipped' ||\n\t\tvalue === 'stopped'\n\t)\n}\n\n/** Test a normalized persisted task failure. */\nexport function isTaskFailure(value: unknown): value is TaskFailure {\n\ttry {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\tObject.keys(value).every((key) => key === 'origin' || key === 'message') &&\n\t\t\t(value.origin === 'handler' || value.origin === 'timeout' || value.origin === 'recovery') &&\n\t\t\tisNonEmptyString(value.message)\n\t\t)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Validate a safe owned JSON graph as a coherent workflow snapshot.\n *\n * @remarks\n * Callers at hostile boundaries use {@link isWorkflowSnapshot}, which owns the\n * graph first so this semantic pass never observes accessors or prototypes.\n */\nexport function isOwnedWorkflowSnapshot(value: unknown): value is WorkflowSnapshot {\n\ttry {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!Object.keys(value).every(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey === 'id' ||\n\t\t\t\t\tkey === 'name' ||\n\t\t\t\t\tkey === 'description' ||\n\t\t\t\t\tkey === 'status' ||\n\t\t\t\t\tkey === 'override' ||\n\t\t\t\t\tkey === 'bail' ||\n\t\t\t\t\tkey === 'phases' ||\n\t\t\t\t\tkey === 'created' ||\n\t\t\t\t\tkey === 'updated',\n\t\t\t) ||\n\t\t\t!isNonEmptyString(value.id) ||\n\t\t\t!isNonEmptyString(value.name) ||\n\t\t\t(value.description !== undefined && typeof value.description !== 'string') ||\n\t\t\t!isLifecycleStatus(value.status) ||\n\t\t\t(value.override !== undefined &&\n\t\t\t\tvalue.override !== 'completed' &&\n\t\t\t\tvalue.override !== 'skipped' &&\n\t\t\t\tvalue.override !== 'stopped') ||\n\t\t\t!isBoolean(value.bail) ||\n\t\t\t!isArray(value.phases) ||\n\t\t\t!isFiniteNumber(value.created) ||\n\t\t\tvalue.created < 0 ||\n\t\t\t!isFiniteNumber(value.updated) ||\n\t\t\tvalue.updated < value.created\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tconst phaseIds = new Set<string>()\n\t\tconst derivations: Array<{ status: LifecycleStatus; bail: boolean }> = []\n\t\tlet frontier = false\n\t\tlet running = false\n\t\tlet vacuous = true\n\t\tfor (const phase of value.phases) {\n\t\t\tif (\n\t\t\t\t!isRecord(phase) ||\n\t\t\t\t!Object.keys(phase).every(\n\t\t\t\t\t(key) =>\n\t\t\t\t\t\tkey === 'id' ||\n\t\t\t\t\t\tkey === 'name' ||\n\t\t\t\t\t\tkey === 'description' ||\n\t\t\t\t\t\tkey === 'status' ||\n\t\t\t\t\t\tkey === 'override' ||\n\t\t\t\t\t\tkey === 'bail' ||\n\t\t\t\t\t\tkey === 'concurrency' ||\n\t\t\t\t\t\tkey === 'tasks',\n\t\t\t\t) ||\n\t\t\t\t!isNonEmptyString(phase.id) ||\n\t\t\t\tphaseIds.has(phase.id) ||\n\t\t\t\t!isNonEmptyString(phase.name) ||\n\t\t\t\t(phase.description !== undefined && typeof phase.description !== 'string') ||\n\t\t\t\t!isLifecycleStatus(phase.status) ||\n\t\t\t\t(phase.override !== undefined &&\n\t\t\t\t\tphase.override !== 'skipped' &&\n\t\t\t\t\tphase.override !== 'stopped') ||\n\t\t\t\t!isBoolean(phase.bail) ||\n\t\t\t\t(phase.concurrency !== undefined &&\n\t\t\t\t\t(!isInteger(phase.concurrency) || phase.concurrency < 1)) ||\n\t\t\t\t!isArray(phase.tasks)\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tconst forced = phase.override === 'skipped' || phase.override === 'stopped'\n\t\t\tconst started =\n\t\t\t\tphase.status === 'running' || phase.status === 'completed' || phase.status === 'failed'\n\t\t\tif ((!forced && frontier && started) || (phase.status === 'running' && running)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif (phase.status === 'running') running = true\n\t\t\tif (\n\t\t\t\t!forced &&\n\t\t\t\t(phase.status === 'pending' ||\n\t\t\t\t\tphase.status === 'running' ||\n\t\t\t\t\t(phase.status === 'failed' && phase.bail))\n\t\t\t) {\n\t\t\t\tfrontier = true\n\t\t\t}\n\t\t\tphaseIds.add(phase.id)\n\t\t\tconst taskIds = new Set<string>()\n\t\t\tconst statuses: LifecycleStatus[] = []\n\t\t\tif (phase.tasks.length > 0) vacuous = false\n\t\t\tfor (const task of phase.tasks) {\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(task) ||\n\t\t\t\t\t!Object.keys(task).every(\n\t\t\t\t\t\t(key) =>\n\t\t\t\t\t\t\tkey === 'id' ||\n\t\t\t\t\t\t\tkey === 'name' ||\n\t\t\t\t\t\t\tkey === 'description' ||\n\t\t\t\t\t\t\tkey === 'status' ||\n\t\t\t\t\t\t\tkey === 'result' ||\n\t\t\t\t\t\t\tkey === 'metadata' ||\n\t\t\t\t\t\t\tkey === 'attempts' ||\n\t\t\t\t\t\t\tkey === 'run' ||\n\t\t\t\t\t\t\tkey === 'retries' ||\n\t\t\t\t\t\t\tkey === 'timeout' ||\n\t\t\t\t\t\t\tkey === 'activity',\n\t\t\t\t\t) ||\n\t\t\t\t\t!isNonEmptyString(task.id) ||\n\t\t\t\t\ttaskIds.has(task.id) ||\n\t\t\t\t\t!isNonEmptyString(task.name) ||\n\t\t\t\t\t(task.description !== undefined && typeof task.description !== 'string') ||\n\t\t\t\t\t!isLifecycleStatus(task.status) ||\n\t\t\t\t\t!isRecord(task.metadata) ||\n\t\t\t\t\t!isJSONValue(task.metadata) ||\n\t\t\t\t\t!isInteger(task.attempts) ||\n\t\t\t\t\ttask.attempts < 0 ||\n\t\t\t\t\t(task.run !== undefined && !isNonEmptyString(task.run)) ||\n\t\t\t\t\t(task.retries !== undefined && (!isInteger(task.retries) || task.retries < 0)) ||\n\t\t\t\t\t(task.timeout !== undefined &&\n\t\t\t\t\t\t(!isInteger(task.timeout) || task.timeout < 0 || task.timeout > MAX_TIMER_MS))\n\t\t\t\t) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tconst budget = (task.retries ?? 0) + 1\n\t\t\t\tif (task.attempts > budget || (task.status === 'pending' && task.attempts >= budget)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tconst activityValid = task.activity === undefined || isTaskActivity(task.activity)\n\t\t\t\tif (!activityValid) return false\n\t\t\t\tif (task.status === 'running' || task.status === 'completed' || task.status === 'failed') {\n\t\t\t\t\tif (task.attempts < 1 || task.activity === undefined) return false\n\t\t\t\t}\n\t\t\t\tif (task.status === 'pending' && task.activity !== undefined) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif (task.status === 'completed' || task.status === 'failed') {\n\t\t\t\t\tif (!isTaskResult(task.result, value, phase, task)) return false\n\t\t\t\t} else if (task.result !== undefined) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\ttaskIds.add(task.id)\n\t\t\t\tstatuses.push(task.status)\n\t\t\t}\n\t\t\tconst derived = derivePhaseStatus(statuses)\n\t\t\tif (\n\t\t\t\tphase.status !== (phase.override ?? derived) ||\n\t\t\t\t(phase.override !== undefined && phase.status !== phase.override)\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tderivations.push({ status: phase.status, bail: phase.bail })\n\t\t}\n\t\tconst derived = deriveWorkflowStatus(derivations)\n\t\tif (value.override === 'completed') {\n\t\t\treturn value.status === 'completed' && derived === 'pending' && vacuous\n\t\t}\n\t\treturn value.status === (value.override ?? derived)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/** Total hostile-boundary workflow snapshot guard. */\nexport function isWorkflowSnapshot(value: unknown): value is WorkflowSnapshot {\n\tconst cloned = attempt(() => cloneJSONValue(value))\n\treturn cloned.success && isOwnedWorkflowSnapshot(cloned.value)\n}\n\n/**\n * Test whether an unknown value is a valid whole-frame activity report.\n */\nexport function isTaskActivityInput(value: unknown): value is TaskActivityInput {\n\ttry {\n\t\tif (!isRecord(value)) return false\n\t\tconst prototype = Object.getPrototypeOf(value)\n\t\tif (\n\t\t\t(prototype !== Object.prototype && prototype !== null) ||\n\t\t\t!Object.keys(value).every(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey === 'note' || key === 'progress' || key === 'operations' || key === 'constraints',\n\t\t\t)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tconst note = value.note\n\t\tconst progress = value.progress\n\t\tconst operations = value.operations\n\t\tconst constraints = value.constraints\n\t\tif (note !== undefined && !isNonEmptyString(note)) return false\n\t\tif (progress !== undefined) {\n\t\t\tif (!isRecord(progress)) return false\n\t\t\tconst progressPrototype = Object.getPrototypeOf(progress)\n\t\t\tif (\n\t\t\t\t(progressPrototype !== Object.prototype && progressPrototype !== null) ||\n\t\t\t\t!Object.keys(progress).every(\n\t\t\t\t\t(key) => key === 'current' || key === 'total' || key === 'unit',\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tconst current = progress.current\n\t\t\tconst total = progress.total\n\t\t\tconst unit = progress.unit\n\t\t\tif (\n\t\t\t\t!isFiniteNumber(current) ||\n\t\t\t\tcurrent < 0 ||\n\t\t\t\t(total !== undefined && (!isFiniteNumber(total) || total < current)) ||\n\t\t\t\t(unit !== undefined && !isNonEmptyString(unit))\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tif (operations !== undefined) {\n\t\t\tif (!isArray(operations)) return false\n\t\t\tconst ids = new Set<string>()\n\t\t\tfor (const operation of operations) {\n\t\t\t\tif (!isRecord(operation)) return false\n\t\t\t\tconst operationPrototype = Object.getPrototypeOf(operation)\n\t\t\t\tif (\n\t\t\t\t\t(operationPrototype !== Object.prototype && operationPrototype !== null) ||\n\t\t\t\t\t!Object.keys(operation).every(\n\t\t\t\t\t\t(key) => key === 'id' || key === 'name' || key === 'started',\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tconst id = operation.id\n\t\t\t\tconst name = operation.name\n\t\t\t\tconst started = operation.started\n\t\t\t\tif (\n\t\t\t\t\t!isNonEmptyString(id) ||\n\t\t\t\t\t!isNonEmptyString(name) ||\n\t\t\t\t\t!isFiniteNumber(started) ||\n\t\t\t\t\tstarted < 0 ||\n\t\t\t\t\tids.has(id)\n\t\t\t\t) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tids.add(id)\n\t\t\t}\n\t\t}\n\t\tif (constraints !== undefined) {\n\t\t\tif (!isArray(constraints)) return false\n\t\t\tconst ids = new Set<string>()\n\t\t\tfor (const constraint of constraints) {\n\t\t\t\tif (!isRecord(constraint)) return false\n\t\t\t\tconst constraintPrototype = Object.getPrototypeOf(constraint)\n\t\t\t\tif (\n\t\t\t\t\t(constraintPrototype !== Object.prototype && constraintPrototype !== null) ||\n\t\t\t\t\t!Object.keys(constraint).every(\n\t\t\t\t\t\t(key) => key === 'id' || key === 'name' || key === 'started',\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tconst id = constraint.id\n\t\t\t\tconst name = constraint.name\n\t\t\t\tconst started = constraint.started\n\t\t\t\tif (\n\t\t\t\t\t!isNonEmptyString(id) ||\n\t\t\t\t\t!isNonEmptyString(name) ||\n\t\t\t\t\t!isFiniteNumber(started) ||\n\t\t\t\t\tstarted < 0 ||\n\t\t\t\t\tids.has(id)\n\t\t\t\t) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tids.add(id)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Test whether an unknown value is valid persisted task activity.\n */\nexport function isTaskActivity(value: unknown): value is TaskActivity {\n\ttry {\n\t\tif (!isRecord(value)) return false\n\t\tconst prototype = Object.getPrototypeOf(value)\n\t\tif (\n\t\t\t(prototype !== Object.prototype && prototype !== null) ||\n\t\t\t!Object.keys(value).every(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey === 'note' ||\n\t\t\t\t\tkey === 'progress' ||\n\t\t\t\t\tkey === 'operations' ||\n\t\t\t\t\tkey === 'constraints' ||\n\t\t\t\t\tkey === 'updated',\n\t\t\t)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tconst note = value.note\n\t\tconst progress = value.progress\n\t\tconst operations = value.operations\n\t\tconst constraints = value.constraints\n\t\tconst updated = value.updated\n\t\tif (\n\t\t\toperations === undefined ||\n\t\t\tconstraints === undefined ||\n\t\t\t!isFiniteNumber(updated) ||\n\t\t\tupdated < 0\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\treturn isTaskActivityInput({\n\t\t\t...(note === undefined ? {} : { note }),\n\t\t\t...(progress === undefined ? {} : { progress }),\n\t\t\toperations,\n\t\t\tconstraints,\n\t\t})\n\t} catch {\n\t\treturn false\n\t}\n}\n","import type {\n\tDeferredInterface,\n\tLifecycleStatus,\n\tPhaseContext,\n\tPhaseDerivation,\n\tPhaseSnapshot,\n\tPhaseStatus,\n\tTaskContext,\n\tTaskResult,\n\tTaskSnapshot,\n\tTaskStatus,\n\tWorkflowContext,\n\tWorkflowDefinition,\n\tWorkflowFunctions,\n\tWorkflowInterface,\n\tWorkflowOptions,\n\tWorkflowSnapshot,\n\tWorkflowStatus,\n} from './types.js'\nimport type { Failure, Success } from '@orkestrel/contract'\nimport { isAbortSignal, linkSignal } from '@orkestrel/abort'\nimport {\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisFunction,\n\tisInteger,\n\tisJSONValue,\n\tisNonEmptyString,\n\tisRecord,\n} from '@orkestrel/contract'\nimport { DEFAULT_BAIL, MAX_TIMER_MS, TASK_TRANSITIONS } from './constants.js'\nimport { WorkflowError } from './errors.js'\nimport { isLifecycleStatus, isTaskFailure } from './validators.js'\n\n/**\n * Capture every top-level {@link WorkflowOptions} value exactly once into an owned plain bag.\n *\n * @remarks\n * Direct property reads preserve inherited and non-enumerable option values while preventing\n * accessor-backed caller bags from shifting policy, handlers, hooks, or nested options between\n * construction stages. Nested bags and the functions registry retain their original identities so\n * entity constructors can snapshot keyed child options and live additions can resolve against the\n * same registry.\n *\n * @param options - The caller-owned workflow construction options\n * @returns An owned top-level options bag containing the captured values\n *\n * @example\n * ```ts\n * const captured = captureWorkflowOptions(options)\n * const workflow = createWorkflow(definition, captured)\n * ```\n */\nexport function captureWorkflowOptions(options?: WorkflowOptions): WorkflowOptions {\n\tconst on = options?.on\n\tconst bail = options?.bail\n\tconst error = options?.error\n\tconst phases = options?.phases\n\tconst functions = options?.functions\n\tconst silence = options?.silence\n\treturn Object.freeze({\n\t\t...(on === undefined ? {} : { on }),\n\t\t...(bail === undefined ? {} : { bail }),\n\t\t...(error === undefined ? {} : { error }),\n\t\t...(phases === undefined ? {} : { phases }),\n\t\t...(functions === undefined ? {} : { functions }),\n\t\t...(silence === undefined ? {} : { silence }),\n\t})\n}\n\n// Workflow derivation helpers — pure, side-effect-free functions (AGENTS §4.3,\n// §14). Every function is exported and unit-tested. The status derivations encode\n// the §10/§14 truth-table logic: a phase status is derived from its tasks'\n// statuses, a workflow status from its phases' statuses UNDER the `bail` policy.\n// Determinism is fixed by design (tasks concurrent, phases sequential), so these\n// derivations are order-insensitive set reductions, never sequencing decisions.\n\n// === Status predicates\n\n/**\n * Test whether a {@link LifecycleStatus} is TERMINAL — a node in this state will not\n * transition further.\n *\n * @remarks\n * The ONE terminal check across all three tiers (AGENTS §4.4 \"one concept = one word\"):\n * a task, a phase, and a workflow share the same {@link LifecycleStatus} vocabulary, so a\n * single predicate covers them — {@link derivePhaseStatus} and {@link deriveWorkflowStatus}\n * both consult it to tell a settled node from an in-flight one. Terminal: `completed` /\n * `failed` / `skipped` / `stopped`; the only non-terminal states are `pending` and\n * `running`.\n *\n * @param status - The lifecycle status to test (a task / phase / workflow status)\n * @returns `true` when the status is terminal\n */\nexport function isTerminalStatus(status: LifecycleStatus): boolean {\n\treturn (\n\t\tstatus === 'completed' || status === 'failed' || status === 'skipped' || status === 'stopped'\n\t)\n}\n\n// === Status derivation\n\n/**\n * Derive a phase's status from its tasks' statuses (tasks are concurrent, so this\n * is an order-insensitive reduction).\n *\n * @remarks\n * The truth table (most-severe terminal wins; `bail`-agnostic — a phase surfaces a\n * task failure as `failed` so the workflow's `bail` policy can decide):\n * - no tasks ⇒ `pending`.\n * - any task `running`, OR a mix of started-and-unsettled tasks (some non-`pending`\n * but not all terminal) ⇒ `running`.\n * - every task `pending` ⇒ `pending`.\n * - all terminal: any `failed` ⇒ `failed`; else any `stopped` ⇒ `stopped`; else any\n * `completed` ⇒ `completed`; else (all `skipped`) ⇒ `skipped`.\n *\n * So an all-`skipped` phase is `skipped`, an all-`stopped` phase is `stopped`, a\n * phase with completed tasks and some skips is `completed`, and a single failed\n * task makes the phase `failed`.\n *\n * @param tasks - The phase's task statuses, in any order\n * @returns The derived {@link PhaseStatus}\n */\nexport function derivePhaseStatus(tasks: readonly TaskStatus[]): PhaseStatus {\n\tif (tasks.length === 0) return 'pending'\n\tif (tasks.every((status) => status === 'pending')) return 'pending'\n\tif (!tasks.every((status) => isTerminalStatus(status))) return 'running'\n\tif (tasks.some((status) => status === 'failed')) return 'failed'\n\tif (tasks.some((status) => status === 'stopped')) return 'stopped'\n\tif (tasks.some((status) => status === 'completed')) return 'completed'\n\treturn 'skipped'\n}\n\n/**\n * Derive a workflow's status from its phases' {@link PhaseDerivation}s — each phase's status\n * paired with the EFFECTIVE `bail` it ran under (`phase.bail ?? workflow.bail`) — so the\n * failure outcome is PER-PHASE-bail-aware (phases are sequential, but the derivation is an\n * order-insensitive reduction over the settled set).\n *\n * @remarks\n * `bail` is now a per-phase override (AGENTS §4.4), so it is carried on each\n * {@link PhaseDerivation} rather than passed as one scalar. It is the ONLY axis that changes\n * the failure outcome, decided per phase:\n * - **A `failed` phase whose effective `bail` is `true` (halt)** propagates ⇒ the workflow is\n * `failed` (the database-transaction halt) — even when the workflow default is graceful.\n * - **A `failed` phase whose effective `bail` is `false` (graceful)** is DATA, not a workflow\n * failure — it folds into completion like a settled phase. A graceful failed phase NEVER\n * makes the workflow `failed` — even when the workflow default is strict.\n *\n * The rest of the table is shared:\n * - no phases ⇒ `pending`.\n * - any phase `running`, OR a mix of started-and-unsettled phases (some non-`pending`\n * but not all terminal) ⇒ `running`.\n * - every phase `pending` ⇒ `pending`.\n * - all terminal (a `failed` phase counts as terminal here): any `stopped` ⇒ `stopped`; else\n * any `completed` (or any graceful-bail `failed`, folded into completion) ⇒ `completed`;\n * else (all `skipped`) ⇒ `skipped`.\n *\n * @param phases - The workflow's per-phase {@link PhaseDerivation}s (status + effective bail), in any order\n * @returns The derived {@link WorkflowStatus}\n */\nexport function deriveWorkflowStatus(phases: readonly PhaseDerivation[]): WorkflowStatus {\n\tif (phases.length === 0) return 'pending'\n\tif (phases.some((phase) => phase.status === 'failed' && phase.bail)) return 'failed'\n\tif (phases.every((phase) => phase.status === 'pending')) return 'pending'\n\tif (!phases.every((phase) => isTerminalStatus(phase.status))) return 'running'\n\tif (phases.some((phase) => phase.status === 'stopped')) return 'stopped'\n\t// A `completed` phase — or a graceful-bail `failed` phase, folded into completion — makes the\n\t// whole workflow complete.\n\tif (\n\t\tphases.some(\n\t\t\t(phase) => phase.status === 'completed' || (phase.status === 'failed' && !phase.bail),\n\t\t)\n\t) {\n\t\treturn 'completed'\n\t}\n\treturn 'skipped'\n}\n\n// === Pending-suffix boundary (bottom-up NATIVE mutation gating)\n\n/**\n * Derive the PENDING SUFFIX boundary of a positional list of {@link LifecycleStatus}es —\n * the index of the first entry in the contiguous trailing run of `pending` entries.\n *\n * @remarks\n * The native, hook-free replacement for a runner-installed cursor (AGENTS §12): a\n * {@link import('./types.js').WorkflowInterface}'s `add` / `remove` / `move` / `update`\n * reads this over its live phases' statuses to decide which positions are safe to edit.\n * Because entries run SEQUENTIALLY (phases sequential, AGENTS determinism), every\n * already-started entry forms a contiguous LEADING prefix and every still-`pending`\n * entry forms the trailing suffix — so the boundary is simply the count of leading\n * non-`pending` entries: the index of the first `pending` entry, or the full length when\n * none is `pending` (nothing is safely editable). A `pending` container's entries are ALL\n * `pending`, so the boundary is `0` and every position is naturally accepted — callers\n * need no special case for that.\n *\n * @param statuses - The positional list of statuses to derive the boundary from\n * @returns The index of the first `pending` entry, or `statuses.length` when none is `pending`\n *\n * @example\n * ```ts\n * deriveBoundary(['completed', 'running', 'pending', 'pending']) // 2\n * deriveBoundary(['pending', 'pending']) // 0\n * deriveBoundary(['completed', 'completed']) // 2 (nothing pending)\n * ```\n */\nexport function deriveBoundary(statuses: readonly LifecycleStatus[]): number {\n\tconst index = statuses.findIndex((status) => status === 'pending')\n\treturn index === -1 ? statuses.length : index\n}\n\n// === Task state-machine guards (the W-b transition graph + override)\n\n/**\n * Test whether the live W-b task state machine may move directly from one\n * {@link TaskStatus} to another — the legal-transition guard.\n *\n * @remarks\n * Reads the {@link import('./constants.js').TASK_TRANSITIONS} graph: `true` only when\n * `to` is listed under `from`. A settled (terminal) `from` has no legal targets, so any\n * transition off it is `false`. The W-b `Task` consults this before every transition and\n * throws a `TRANSITION` {@link import('./errors.js').WorkflowError} when it returns `false`.\n *\n * @param from - The task's current status\n * @param to - The status the transition would move it to\n * @returns `true` when the move is legal\n */\nexport function canTransitionTask(from: TaskStatus, to: TaskStatus): boolean {\n\treturn TASK_TRANSITIONS[from].includes(to)\n}\n\n/**\n * Resolve a task's runtime silence window against its workflow default.\n *\n * @param value - The task-level override; any present non-positive or non-finite value disables\n * @param fallback - The workflow-level default\n * @returns A host-safe effective window (`1..MAX_TIMER_MS`), or `undefined`\n */\nexport function resolveTaskSilence(\n\tvalue: number | undefined,\n\tfallback: number | undefined,\n): number | undefined {\n\tif (value !== undefined) {\n\t\treturn Number.isFinite(value) && value > 0 && value <= MAX_TIMER_MS ? value : undefined\n\t}\n\treturn fallback !== undefined &&\n\t\tNumber.isFinite(fallback) &&\n\t\tfallback > 0 &&\n\t\tfallback <= MAX_TIMER_MS\n\t\t? fallback\n\t\t: undefined\n}\n\n// === Result construction (AGENTS §12 — `@orkestrel/contract` ships the `Result` /\n// `Success` / `Failure` TYPES but no `success`/`failure` constructors, so this module\n// provides the ones every gated Result-constructing site in this package's W-b entities\n// + managers uses instead of a hand-rolled `{ success: true/false, ... }` literal)\n\n/**\n * Box a value as a {@link Success} — the graceful outcome half of a {@link Result}.\n *\n * @typeParam T - The boxed value's type\n * @param value - The value to box\n * @returns A {@link Success} wrapping `value`\n *\n * @example\n * ```ts\n * const result = success(task) // { success: true, value: task }\n * ```\n */\nexport function success<T>(value: T): Success<T> {\n\treturn { success: true, value }\n}\n\n/**\n * Box an error as a {@link Failure} — the graceful outcome half of a {@link Result}.\n *\n * @typeParam E - The boxed error's type\n * @param error - The error to box\n * @returns A {@link Failure} wrapping `error`\n *\n * @example\n * ```ts\n * const result = failure(new WorkflowError('MUTATION', 'refused')) // { success: false, error }\n * ```\n */\nexport function failure<E>(error: E): Failure<E> {\n\treturn { success: false, error }\n}\n\n/**\n * Normalize an unknown thrown value to a non-empty persistence-safe message.\n *\n * @param error - The caught value\n * @returns A non-empty message without stack or cause data\n */\nexport function errorToMessage(error: unknown): string {\n\ttry {\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\treturn typeof message === 'string' && message.length > 0 ? message : 'unknown failure'\n\t} catch {\n\t\treturn 'unknown failure'\n\t}\n}\n\n// === Result-tree collection\n\n/**\n * Find the first {@link TaskResult} in a positional list whose boxed outcome is a\n * `Failure` — the pure scan shared by a phase's and a workflow's derived-`failed`\n * `fail`-event lookup.\n *\n * @remarks\n * The shared leaf behind {@link import('./phases/Phase.js').Phase} and\n * {@link import('./Workflow.js').Workflow}'s own `#failure` — each gathers ITS tier's\n * results (a phase's own settled tasks, a workflow's flattened `results()`) and feeds\n * them here; the tier-local method keeps the §12 invariant throw (a derived `failed`\n * status guarantees a failing result exists) since throwing on `undefined` is\n * orchestration, not a leaf concern.\n *\n * @param results - The results to scan, in any order\n * @returns The first result whose `result.success` is `false`, or `undefined` if none\n *\n * @example\n * ```ts\n * findFailure([completedResult, failedResult]) // failedResult\n * ```\n */\nexport function findFailure(results: readonly TaskResult[]): TaskResult | undefined {\n\treturn results.find((result) => result.result?.success === false)\n}\n\n// === Lineage context builders (the chain carried back UP the tree)\n\n/**\n * Build a {@link WorkflowContext} — the identity every level inherits — from a node's\n * `id` / `name` / optional `description`.\n *\n * @remarks\n * The root of the context chain a live {@link import('./Workflow.js').Workflow} exposes;\n * {@link buildPhaseContext} / {@link buildTaskContext} extend it down the tree. Accepts a\n * structural node (a definition or a snapshot node — both carry the three identity fields).\n *\n * @param node - The node's identity (`id` / `name` / optional `description`)\n * @returns The {@link WorkflowContext}\n */\nexport function buildWorkflowContext(node: WorkflowContext): WorkflowContext {\n\treturn Object.freeze({\n\t\tid: node.id,\n\t\tname: node.name,\n\t\t...(node.description === undefined ? {} : { description: node.description }),\n\t})\n}\n\n/**\n * Build a {@link PhaseContext} — a phase's own identity plus a back-reference to its\n * workflow — from the parent {@link WorkflowContext} and the phase node's identity.\n *\n * @param workflow - The parent workflow context (the lineage pointer UP the tree)\n * @param node - The phase's identity (`id` / `name` / optional `description`)\n * @returns The {@link PhaseContext}\n */\nexport function buildPhaseContext(workflow: WorkflowContext, node: WorkflowContext): PhaseContext {\n\treturn Object.freeze({ ...buildWorkflowContext(node), workflow: buildWorkflowContext(workflow) })\n}\n\n/**\n * Build a {@link TaskContext} — a task's own identity plus a back-reference to its phase\n * (and, transitively, its workflow) — from the parent {@link PhaseContext} and the task\n * node's identity.\n *\n * @param phase - The parent phase context (carrying the full lineage UP the tree)\n * @param node - The task's identity (`id` / `name` / optional `description`)\n * @returns The {@link TaskContext}\n */\nexport function buildTaskContext(phase: PhaseContext, node: WorkflowContext): TaskContext {\n\treturn Object.freeze({\n\t\t...buildWorkflowContext(node),\n\t\tphase: buildPhaseContext(phase.workflow, phase),\n\t})\n}\n\n// === Definition → initial snapshot (the unified construction input)\n\n/**\n * Convert a {@link WorkflowDefinition} into an INITIAL {@link WorkflowSnapshot} — every\n * node `pending`, no results, empty metadata — so the live W-b tree has ONE construction\n * path (snapshot-driven) for both a fresh build and a restore.\n *\n * @remarks\n * The structural fields (`id` / `name` / `description` + the ordered phases / tasks)\n * carry over verbatim, as does each phase's `concurrency` (persisted on the\n * {@link PhaseSnapshot} so a restore reinstates the same throttle) and each task's `run` /\n * `retries` / `timeout` (persisted on the {@link TaskSnapshot}, like `bail` / `concurrency`,\n * so a restore + a {@link import('./types.js').WorkflowOptions.functions} registry resumes\n * real work). The `bail` policy carries over — at the\n * workflow tier AND, per phase, the\n * EFFECTIVE policy (`phase.bail ?? workflowBail`) on each {@link PhaseSnapshot} — so the seeded\n * snapshot is self-contained; a fresh seed has no `override`. `created` / `updated` are stamped now.\n * {@link import('./factories.js').createWorkflow} builds from this.\n *\n * The optional `bail` override is the EFFECTIVE workflow policy the tree will run under\n * (`createWorkflow` / the runner resolve `options.bail ?? definition.bail ?? DEFAULT_BAIL` and\n * pass it here), so an `options.bail` override reaches BOTH the workflow tier AND the\n * inheritance default of every phase that declares no `bail` of its own — otherwise the\n * per-phase seeds would silently ignore the override. Omitted ⇒ the definition's own `bail`\n * (defaulting to the graceful {@link import('./constants.js').DEFAULT_BAIL}).\n *\n * @param definition - The workflow definition to seed from\n * @param bail - The EFFECTIVE workflow bail to seed both tiers with (defaults to the definition's)\n * @returns An initial, all-`pending` {@link WorkflowSnapshot}\n */\nexport function definitionToSnapshot(\n\tdefinition: WorkflowDefinition,\n\tbail?: boolean,\n): WorkflowSnapshot {\n\tconst now = Date.now()\n\t// The effective workflow-level policy each phase inherits when it declares no `bail` of its own\n\t// — the supplied override (an `options.bail`) when given, else the definition's own default. The\n\t// source of the per-phase effective policy persisted on every PhaseSnapshot.\n\tconst workflowBail = bail ?? definition.bail ?? DEFAULT_BAIL\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name,\n\t\t...(definition.description === undefined ? {} : { description: definition.description }),\n\t\tstatus: 'pending',\n\t\tbail: workflowBail,\n\t\tphases: definition.phases.map((phase) => phaseDefinitionToSnapshot(phase, workflowBail)),\n\t\tcreated: now,\n\t\tupdated: now,\n\t}\n}\n\n/**\n * Convert one {@link import('./types.js').PhaseDefinition} into an initial, all-`pending`\n * {@link PhaseSnapshot} — the per-phase step of {@link definitionToSnapshot}.\n *\n * @remarks\n * The snapshot persists the EFFECTIVE failure policy this phase runs under: the phase's own\n * `bail` when it declares one, else the `workflowBail` it inherits — so a restore reinstates\n * the same per-phase policy without a silent default (`effectiveBail = phase.bail ?? workflowBail`).\n * `concurrency` (the resource throttle) carries over verbatim, omitted when undefined.\n *\n * @param phase - The phase definition to seed from\n * @param workflowBail - The workflow-level `bail` default the phase inherits when it declares none\n * @returns An initial {@link PhaseSnapshot}\n */\nexport function phaseDefinitionToSnapshot(\n\tphase: WorkflowDefinition['phases'][number],\n\tworkflowBail: boolean,\n): PhaseSnapshot {\n\treturn {\n\t\tid: phase.id,\n\t\tname: phase.name,\n\t\t...(phase.description === undefined ? {} : { description: phase.description }),\n\t\tstatus: 'pending',\n\t\tbail: phase.bail ?? workflowBail,\n\t\t...(phase.concurrency === undefined ? {} : { concurrency: phase.concurrency }),\n\t\ttasks: phase.tasks.map((task) => taskDefinitionToSnapshot(task)),\n\t}\n}\n\n/**\n * Convert one {@link import('./types.js').TaskDefinition} into an initial, `pending`\n * {@link TaskSnapshot} — the per-task leaf step of {@link definitionToSnapshot} (no\n * result yet, empty metadata).\n *\n * @remarks\n * `run` / `retries` / `timeout` carry over verbatim (persisted declarative config, like a\n * phase's `bail` / `concurrency`) — a restore reinstates the same behavior reference and\n * reliability overrides once paired with a {@link import('./types.js').WorkflowOptions.functions}\n * registry.\n *\n * @param task - The task definition to seed from\n * @returns An initial {@link TaskSnapshot}\n */\nexport function taskDefinitionToSnapshot(\n\ttask: WorkflowDefinition['phases'][number]['tasks'][number],\n): TaskSnapshot {\n\treturn {\n\t\tid: task.id,\n\t\tname: task.name,\n\t\t...(task.description === undefined ? {} : { description: task.description }),\n\t\tstatus: 'pending',\n\t\tmetadata: {},\n\t\tattempts: 0,\n\t\t...(task.run === undefined ? {} : { run: task.run }),\n\t\t...(task.retries === undefined ? {} : { retries: task.retries }),\n\t\t...(task.timeout === undefined ? {} : { timeout: task.timeout }),\n\t}\n}\n\n/**\n * Convert interrupted running work into a recoverable pending suffix or an\n * exhausted recovery failure without replenishing attempts.\n *\n * @param snapshot - A fully validated owned snapshot with no terminal overrides\n * @returns The recovery projection\n */\nexport function recoverWorkflowSnapshot(snapshot: WorkflowSnapshot): WorkflowSnapshot {\n\tconst phases: PhaseSnapshot[] = []\n\tlet halted = false\n\tconst now = Math.max(Date.now(), snapshot.updated)\n\tconst workflow = buildWorkflowContext(snapshot)\n\tfor (const phase of snapshot.phases) {\n\t\tconst exhausted = new Set<string>()\n\t\tfor (const task of phase.tasks) {\n\t\t\tconst budget = (task.retries ?? 0) + 1\n\t\t\tif (task.status === 'running' && task.attempts >= budget) exhausted.add(task.id)\n\t\t}\n\t\tconst strict =\n\t\t\tphase.bail && (exhausted.size > 0 || phase.tasks.some((task) => task.status === 'failed'))\n\t\tconst tasks: TaskSnapshot[] = []\n\t\tfor (const task of phase.tasks) {\n\t\t\tconst eligible = task.status === 'pending' || task.status === 'running'\n\t\t\tif ((halted || strict) && eligible && !exhausted.has(task.id)) {\n\t\t\t\ttasks.push({ ...task, status: 'skipped' })\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (!exhausted.has(task.id)) {\n\t\t\t\tif (task.status === 'running') {\n\t\t\t\t\tconst { activity: _activity, ...pending } = task\n\t\t\t\t\ttasks.push({ ...pending, status: 'pending' })\n\t\t\t\t} else tasks.push(task)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst phaseContext = buildPhaseContext(workflow, phase)\n\t\t\tconst taskContext = buildTaskContext(phaseContext, task)\n\t\t\tconst result: TaskResult = {\n\t\t\t\ttask: taskContext,\n\t\t\t\tphase: phaseContext,\n\t\t\t\tworkflow,\n\t\t\t\tstatus: 'failed',\n\t\t\t\tresult: {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\torigin: 'recovery',\n\t\t\t\t\t\tmessage: `task '${task.id}' exhausted its retry budget during recovery`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\ttimestamp: now,\n\t\t\t}\n\t\t\ttasks.push({ ...task, status: 'failed', result })\n\t\t}\n\t\tconst status = derivePhaseStatus(tasks.map((task) => task.status))\n\t\tphases.push({ ...phase, status, tasks })\n\t\tif (strict) halted = true\n\t}\n\treturn {\n\t\t...snapshot,\n\t\tstatus: deriveWorkflowStatus(\n\t\t\tphases.map((phase) => ({ status: phase.status, bail: phase.bail })),\n\t\t),\n\t\tphases,\n\t\tupdated: now,\n\t}\n}\n\n/** Compare two optional description values. */\nexport function matchesDescription(left: unknown, right: unknown): boolean {\n\treturn left === right && (left === undefined || typeof left === 'string')\n}\n\n/** Test a result's lineage against its containing snapshot nodes. */\nexport function isTaskResult(\n\tvalue: unknown,\n\tworkflow: unknown,\n\tphase: unknown,\n\ttask: unknown,\n): value is TaskResult {\n\ttry {\n\t\tif (\n\t\t\t!isRecord(value) ||\n\t\t\t!isRecord(workflow) ||\n\t\t\t!isRecord(phase) ||\n\t\t\t!isRecord(task) ||\n\t\t\t!Object.keys(value).every(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey === 'task' ||\n\t\t\t\t\tkey === 'phase' ||\n\t\t\t\t\tkey === 'workflow' ||\n\t\t\t\t\tkey === 'status' ||\n\t\t\t\t\tkey === 'result' ||\n\t\t\t\t\tkey === 'timestamp',\n\t\t\t) ||\n\t\t\t!isLifecycleStatus(value.status) ||\n\t\t\tvalue.status !== task.status ||\n\t\t\t!isFiniteNumber(value.timestamp) ||\n\t\t\tvalue.timestamp < 0 ||\n\t\t\t!isRecord(value.task) ||\n\t\t\t!isRecord(value.phase) ||\n\t\t\t!isRecord(value.workflow) ||\n\t\t\t!Object.keys(value.workflow).every(\n\t\t\t\t(key) => key === 'id' || key === 'name' || key === 'description',\n\t\t\t) ||\n\t\t\t!Object.keys(value.phase).every(\n\t\t\t\t(key) => key === 'id' || key === 'name' || key === 'description' || key === 'workflow',\n\t\t\t) ||\n\t\t\t!Object.keys(value.task).every(\n\t\t\t\t(key) => key === 'id' || key === 'name' || key === 'description' || key === 'phase',\n\t\t\t)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (\n\t\t\tvalue.task.id !== task.id ||\n\t\t\tvalue.task.name !== task.name ||\n\t\t\t!matchesDescription(value.task.description, task.description) ||\n\t\t\tvalue.phase.id !== phase.id ||\n\t\t\tvalue.phase.name !== phase.name ||\n\t\t\t!matchesDescription(value.phase.description, phase.description) ||\n\t\t\tvalue.workflow.id !== workflow.id ||\n\t\t\tvalue.workflow.name !== workflow.name ||\n\t\t\t!matchesDescription(value.workflow.description, workflow.description)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (\n\t\t\t!isRecord(value.task.phase) ||\n\t\t\t!isRecord(value.task.phase.workflow) ||\n\t\t\t!isRecord(value.phase.workflow) ||\n\t\t\t!Object.keys(value.task.phase).every(\n\t\t\t\t(key) => key === 'id' || key === 'name' || key === 'description' || key === 'workflow',\n\t\t\t) ||\n\t\t\t!Object.keys(value.task.phase.workflow).every(\n\t\t\t\t(key) => key === 'id' || key === 'name' || key === 'description',\n\t\t\t) ||\n\t\t\t!Object.keys(value.phase.workflow).every(\n\t\t\t\t(key) => key === 'id' || key === 'name' || key === 'description',\n\t\t\t)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (\n\t\t\tvalue.task.phase.id !== phase.id ||\n\t\t\tvalue.task.phase.name !== phase.name ||\n\t\t\t!matchesDescription(value.task.phase.description, phase.description) ||\n\t\t\tvalue.phase.workflow.id !== workflow.id ||\n\t\t\tvalue.phase.workflow.name !== workflow.name ||\n\t\t\t!matchesDescription(value.phase.workflow.description, workflow.description) ||\n\t\t\tvalue.task.phase.workflow.id !== workflow.id ||\n\t\t\tvalue.task.phase.workflow.name !== workflow.name ||\n\t\t\t!matchesDescription(value.task.phase.workflow.description, workflow.description)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (value.status === 'completed') {\n\t\t\treturn (\n\t\t\t\tisRecord(value.result) &&\n\t\t\t\tvalue.result.success === true &&\n\t\t\t\tObject.keys(value.result).every((key) => key === 'success' || key === 'value') &&\n\t\t\t\tisJSONValue(value.result.value)\n\t\t\t)\n\t\t}\n\t\tif (value.status === 'failed') {\n\t\t\treturn (\n\t\t\t\tisRecord(value.result) &&\n\t\t\t\tvalue.result.success === false &&\n\t\t\t\tObject.keys(value.result).every((key) => key === 'success' || key === 'error') &&\n\t\t\t\tisTaskFailure(value.result.error)\n\t\t\t)\n\t\t}\n\t\treturn false\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Test that every named task has a callable runtime handler before dispatch.\n *\n * @remarks\n * A snapshot lookup reads each unique `run` binding at most once from `functions`. A live workflow\n * validates its tasks' already-resolved handlers without consulting the retained registry again.\n *\n * @param workflow - The persisted snapshot or constructed live workflow to validate\n * @returns Whether every named task resolves to a callable handler\n */\nexport function hasWorkflowHandlers(workflow: WorkflowInterface): boolean\nexport function hasWorkflowHandlers(\n\tworkflow: WorkflowSnapshot,\n\tfunctions: WorkflowFunctions | undefined,\n): boolean\nexport function hasWorkflowHandlers(\n\tworkflow: WorkflowInterface | WorkflowSnapshot,\n\tfunctions?: WorkflowFunctions,\n): boolean {\n\tif ('destroyed' in workflow) {\n\t\tfor (const phase of workflow.phases.phases()) {\n\t\t\tfor (const task of phase.tasks.tasks()) {\n\t\t\t\tif (task.run !== undefined && !isFunction(task.handler)) return false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\tconst runs = new Set<string>()\n\tfor (const phase of workflow.phases) {\n\t\tfor (const task of phase.tasks) {\n\t\t\tif (task.run === undefined || runs.has(task.run)) continue\n\t\t\truns.add(task.run)\n\t\t\tif (!isFunction(functions?.[task.run])) return false\n\t\t}\n\t}\n\treturn true\n}\n\n/** Locate the nearest identifiable node for an inconsistent owned snapshot. */\nexport function workflowSnapshotContext(\n\tvalue: unknown,\n): Readonly<Record<string, unknown>> | undefined {\n\tif (!isRecord(value) || !isArray(value.phases)) return undefined\n\tfor (const phase of value.phases) {\n\t\tif (!isRecord(phase)) continue\n\t\tconst phaseContext = isNonEmptyString(phase.id) ? { phase: phase.id } : undefined\n\t\tif (\n\t\t\t!isBoolean(phase.bail) ||\n\t\t\t(phase.concurrency !== undefined &&\n\t\t\t\t(!isInteger(phase.concurrency) || phase.concurrency < 1)) ||\n\t\t\t!isArray(phase.tasks)\n\t\t) {\n\t\t\treturn phaseContext\n\t\t}\n\t\tfor (const task of phase.tasks) {\n\t\t\tif (!isRecord(task)) continue\n\t\t\tif (\n\t\t\t\t(task.run !== undefined && !isNonEmptyString(task.run)) ||\n\t\t\t\t(task.retries !== undefined && (!isInteger(task.retries) || task.retries < 0)) ||\n\t\t\t\t(task.timeout !== undefined &&\n\t\t\t\t\t(!isInteger(task.timeout) || task.timeout < 0 || task.timeout > MAX_TIMER_MS)) ||\n\t\t\t\t!isInteger(task.attempts) ||\n\t\t\t\ttask.attempts < 0\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\t...(phaseContext ?? {}),\n\t\t\t\t\t...(isNonEmptyString(task.id) ? { task: task.id } : {}),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined\n}\n\n/**\n * Flatten a nested list of per-phase {@link TaskResult} lists into one positional list\n * — the workflow tier of the result tree, built from each phase's `results()`.\n *\n * @remarks\n * Pure and order-preserving: phases in order, each phase's task results in order. The\n * W-b `Workflow.results()` calls this over its phases' `results()`; a phase's own\n * `results()` is the per-phase list this consumes.\n *\n * @param phases - The per-phase result lists, in phase order\n * @returns One flattened {@link TaskResult} list, in positional order\n */\nexport function collectResults(\n\tphases: ReadonlyArray<readonly TaskResult[]>,\n): readonly TaskResult[] {\n\treturn phases.flat()\n}\n\n// === Positional-entry array manipulation (the TaskManager/PhaseManager `add`/`move` core)\n\n/**\n * Insert one `[key, value]` entry at a positional index into a readonly entries array —\n * the pure splice-in step behind an insertion-ordered registry's `add`.\n *\n * @remarks\n * Shared by {@link import('./tasks/TaskManager.js').TaskManager} and\n * {@link import('./phases/PhaseManager.js').PhaseManager}: both convert their\n * insertion-ordered `Map` to `[...map.entries()]`, call this to splice the new entry\n * in at the target index, then rebuild the `Map` from the result (a stateful step that\n * stays a `#` private method — this helper does no `Map` construction). Does not\n * mutate `entries`; returns a new array.\n *\n * @typeParam T - The entry's value type\n * @param entries - The current positional entries, in order\n * @param index - The index to insert at (`0` prepends, `entries.length` appends)\n * @param key - The new entry's key\n * @param value - The new entry's value\n * @returns A new entries array with `[key, value]` inserted at `index`\n *\n * @example\n * ```ts\n * insertEntry([['a', 1], ['b', 2]], 1, 'c', 3) // [['a', 1], ['c', 3], ['b', 2]]\n * ```\n */\nexport function insertEntry<T>(\n\tentries: ReadonlyArray<readonly [string, T]>,\n\tindex: number,\n\tkey: string,\n\tvalue: T,\n): ReadonlyArray<readonly [string, T]> {\n\tconst next = [...entries]\n\tnext.splice(index, 0, [key, value])\n\treturn next\n}\n\n/**\n * Reposition the entry keyed `key` to a new positional index in a readonly entries\n * array — the pure remove-then-reinsert step behind an insertion-ordered registry's\n * `move`.\n *\n * @remarks\n * The move counterpart of {@link insertEntry}: finds the entry by `key`, splices it\n * out, then splices it back in at `index`. An absent `key` is a no-op (returns a copy\n * of `entries` unchanged) — the caller (`TaskManager.move` / `PhaseManager.move`)\n * already gates on the target's existence before calling this, so the no-op branch is\n * defensive, never reached in practice. Does not mutate `entries`; returns a new array.\n *\n * @typeParam T - The entry's value type\n * @param entries - The current positional entries, in order\n * @param key - The key of the entry to reposition\n * @param index - The new index for the entry\n * @returns A new entries array with the `key` entry repositioned to `index`\n *\n * @example\n * ```ts\n * moveEntry([['a', 1], ['b', 2], ['c', 3]], 'a', 2) // [['b', 2], ['c', 3], ['a', 1]]\n * ```\n */\nexport function moveEntry<T>(\n\tentries: ReadonlyArray<readonly [string, T]>,\n\tkey: string,\n\tindex: number,\n): ReadonlyArray<readonly [string, T]> {\n\tconst next = [...entries]\n\tconst at = next.findIndex(([entryKey]) => entryKey === key)\n\tif (at === -1) return next\n\tconst [entry] = next.splice(at, 1)\n\tif (entry !== undefined) next.splice(index, 0, entry)\n\treturn next\n}\n\n/**\n * Create a {@link DeferredInterface} — a promise whose settlement is driven\n * externally, so a caller can resolve/reject it from outside the executor.\n *\n * @typeParam T - The value the deferred promise resolves\n * @returns A deferred `promise` plus its `resolve` / `reject`\n */\nexport function createDeferred<T>(): DeferredInterface<T> {\n\treturn Promise.withResolvers<T>()\n}\n\n/**\n * Schedule one cancellable host operation behind an owned settlement signal.\n *\n * @remarks\n * A defined `signal` that is not a native `AbortSignal` is refused before anything is armed, as a\n * rejected promise carrying a {@link import('./errors.js').WorkflowError} with the `SCHEDULE` code.\n * Rejecting rather than throwing keeps every caller on one settlement path, so a backend never has\n * to guard the call itself.\n *\n * The guard is necessary but not sufficient, so linking stays contained. A `Proxy` over a native\n * signal passes the guard and can still make linking throw from a trap, and that escape would be\n * synchronous — the one shape every caller here is built not to expect. Containment turns it into\n * the same `SCHEDULE` rejection, so setup has exactly one failure shape however hostile the input.\n *\n * The completion and failure paths each own an {@link AbortController}; their native composite is\n * linked to the optional caller signal before `start` can arm host work. Scheduler backends attach\n * only to that safe composite, so caller mutation of `addEventListener` or `removeEventListener`\n * cannot strand the operation. The first completion resolves, the first host failure rejects with\n * its exact value, and caller abort rejects with its exact linked reason. Caller abort and host\n * failure cancel an armed handle; synchronous settlement also cancels the handle immediately after\n * `start` returns it. Cancellation is secondary cleanup: if its closure throws, the already-winning\n * completion, exact host failure, or exact caller reason still settles without escape or replacement.\n *\n * @param start - Arm host work and return its cancellation closure\n * @param signal - Optional caller cancellation signal\n * @returns A promise settled exactly once by an invalid-signal refusal, completion, host failure,\n * or caller abort\n */\nexport function scheduleHost(\n\tstart: (complete: () => void, failure: (error: unknown) => void) => () => void,\n\tsignal?: AbortSignal,\n): Promise<void> {\n\tif (signal !== undefined && !isAbortSignal(signal)) {\n\t\treturn Promise.reject(\n\t\t\tnew WorkflowError('SCHEDULE', 'scheduleHost signal must be an AbortSignal', {\n\t\t\t\tsignal: typeof signal,\n\t\t\t}),\n\t\t)\n\t}\n\tconst completion = new AbortController()\n\tconst failed = new AbortController()\n\tlet settled: AbortSignal\n\ttry {\n\t\tsettled = linkSignal(AbortSignal.any([completion.signal, failed.signal]), signal)\n\t} catch {\n\t\treturn Promise.reject(\n\t\t\tnew WorkflowError('SCHEDULE', 'scheduleHost could not link the caller signal', {\n\t\t\t\tsignal: typeof signal,\n\t\t\t}),\n\t\t)\n\t}\n\tif (settled.aborted) return Promise.reject(settled.reason)\n\treturn new Promise<void>((resolve, reject) => {\n\t\tlet cancel: (() => void) | undefined\n\t\tlet hostFailure: unknown\n\t\tsettled.addEventListener(\n\t\t\t'abort',\n\t\t\t() => {\n\t\t\t\tif (completion.signal.aborted) {\n\t\t\t\t\tresolve()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst reason = failed.signal.aborted ? hostFailure : settled.reason\n\t\t\t\ttry {\n\t\t\t\t\tcancel?.()\n\t\t\t\t} catch {}\n\t\t\t\treject(reason)\n\t\t\t},\n\t\t\t{ once: true },\n\t\t)\n\t\ttry {\n\t\t\tcancel = start(\n\t\t\t\t() => completion.abort(),\n\t\t\t\t(error) => {\n\t\t\t\t\thostFailure = error\n\t\t\t\t\tfailed.abort()\n\t\t\t\t},\n\t\t\t)\n\t\t} catch (error) {\n\t\t\thostFailure = error\n\t\t\tfailed.abort()\n\t\t}\n\t\tif (settled.aborted) {\n\t\t\ttry {\n\t\t\t\tcancel?.()\n\t\t\t} catch {}\n\t\t}\n\t})\n}\n\n/**\n * Park until `signal` aborts — a promise-parked wait (AGENTS §21), never a timer or\n * busy-loop, that NEVER rejects.\n *\n * @remarks\n * Resolves IMMEDIATELY when `signal` is already aborted; otherwise attaches a one-shot\n * `abort` listener and resolves when it fires, removing the listener either way. The\n * shared leaf behind the duplicate abort-wiring an execution engine otherwise hand-rolls\n * at every fold point.\n *\n * @param signal - The signal to park on\n * @returns A promise that resolves once `signal` has aborted\n *\n * @example\n * ```ts\n * const controller = new AbortController()\n * const parked = parkSignal(controller.signal)\n * controller.abort()\n * await parked // resolves\n * ```\n */\nexport function parkSignal(signal: AbortSignal): Promise<void> {\n\tif (signal.aborted) return Promise.resolve()\n\treturn new Promise((resolve) => {\n\t\tsignal.addEventListener('abort', () => resolve(), { once: true })\n\t})\n}\n","import type { SchedulerInterface, SchedulerOptions } from './types.js'\nimport { scheduleHost } from './helpers.js'\n\n/**\n * The safe cross-environment cooperative-yield default — a {@link SchedulerInterface}\n * built on `setTimeout` / `clearTimeout` alone, so it runs unchanged in both the\n * browser and Node.\n *\n * @remarks\n * - **Cross-environment.** Uses ONLY `setTimeout` / `clearTimeout` — universally\n * available. It deliberately avoids env-specific fast paths (`setImmediate`,\n * `scheduler.yield`, `requestAnimationFrame`, `node:timers/promises`,\n * `MessageChannel`); those belong to the environment backends, built with the\n * agent loop that consumes them.\n * - **`yield` is a macrotask host-turn, not a microtask.** `yield()` waits on a\n * `setTimeout(0)`, NOT `queueMicrotask`. A microtask drains before the host\n * regains control, so it would not actually let pending I/O, timers, or\n * rendering run — it only defers within the current task. A zero-delay timer is\n * the correct cross-environment \"give the host a turn\".\n * - **Abort-aware.** A pending `yield` / `delay` rejects with `signal.reason` exactly.\n * {@link scheduleHost} links an owned settlement composite to the caller before arming\n * the timer, so pre-abort schedules nothing, caller signal method mutation is harmless,\n * cancellation clears the handle, and native first-settlement wins exactly once.\n * - **Priority is accepted but uniform.** `options.priority` is part of the\n * contract, but a `setTimeout`-based default cannot act on urgency, so it treats\n * every priority the same. Environment backends honour it.\n * - **Event-free.** A pure functional primitive — no Emitter, no events.\n *\n * @example\n * ```ts\n * const scheduler = new Scheduler()\n * while (!signal.aborted) {\n * \tdoSomeWork()\n * \tawait scheduler.yield({ signal }) // let the host run between work units\n * }\n * ```\n */\nexport class Scheduler implements SchedulerInterface {\n\t/**\n\t * Yield control back to the host so other tasks (I/O, timers, rendering) can\n\t * run, then resume — a macrotask turn via `setTimeout(0)` (NOT a microtask,\n\t * which would resume before the host regains control).\n\t */\n\tyield(options?: SchedulerOptions): Promise<void> {\n\t\treturn this.#sleep(0, options?.signal)\n\t}\n\n\t/**\n\t * Resume after at least `ms` milliseconds; abort rejects with `signal.reason`.\n\t *\n\t * @remarks\n\t * `ms` should be a non-negative finite number. The primitive stays minimal and\n\t * does no validation: it passes `ms` straight to the host `setTimeout`, which\n\t * clamps a negative value or `NaN` to ~0 — so an out-of-domain `ms` resolves on\n\t * the next host turn rather than throwing.\n\t */\n\tdelay(ms: number, options?: SchedulerOptions): Promise<void> {\n\t\treturn this.#sleep(ms, options?.signal)\n\t}\n\n\t// The cross-environment timer boundary shared by `yield` and `delay`; `scheduleHost`\n\t// owns listener safety, cancellation races, exact reasons, and once-only settlement.\n\t#sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\t\treturn scheduleHost((complete) => {\n\t\t\tconst handle = setTimeout(complete, ms)\n\t\t\treturn () => clearTimeout(handle)\n\t\t}, signal)\n\t}\n}\n","import type { TaskActivity, WorkflowSnapshot } from './types.js'\nimport { cloneJSONValue, isArray, isContractError, isRecord } from '@orkestrel/contract'\nimport { WorkflowError, isWorkflowError } from './errors.js'\nimport { workflowSnapshotContext } from './helpers.js'\nimport { isOwnedWorkflowSnapshot, isTaskActivity } from './validators.js'\n\n/**\n * Validate and own a workflow snapshot before live construction.\n *\n * @param input - The hostile snapshot boundary\n * @param id - The optional storage key the owned snapshot must match\n * @returns A deeply owned frozen snapshot\n * @throws {WorkflowError} With `RESTORE` when the snapshot is invalid or does not match `id`\n */\nexport function cloneWorkflowSnapshot(input: unknown, id?: string): WorkflowSnapshot {\n\tlet cloned: unknown\n\ttry {\n\t\tcloned = cloneJSONValue(input)\n\t} catch (error) {\n\t\tif (isWorkflowError(error)) throw error\n\t\tif (isContractError(error)) {\n\t\t\tthrow new WorkflowError(\n\t\t\t\t'RESTORE',\n\t\t\t\t`workflow snapshot could not be read safely: ${error.message}`,\n\t\t\t)\n\t\t}\n\t\tthrow new WorkflowError('RESTORE', 'workflow snapshot could not be read safely')\n\t}\n\tif (!isOwnedWorkflowSnapshot(cloned)) {\n\t\tthrow new WorkflowError(\n\t\t\t'RESTORE',\n\t\t\t'workflow snapshot is inconsistent',\n\t\t\tworkflowSnapshotContext(cloned),\n\t\t)\n\t}\n\tif (id !== undefined && cloned.id !== id) {\n\t\tthrow new WorkflowError(\n\t\t\t'RESTORE',\n\t\t\t`workflow snapshot '${cloned.id}' does not match storage key '${id}'`,\n\t\t\t{ requested: id, payload: cloned.id },\n\t\t)\n\t}\n\treturn cloned\n}\n\n/**\n * Validate and clone one complete task activity frame.\n *\n * @remarks\n * This is the hostile boundary behind task reports and snapshot hydration. Supplying\n * `updated` stamps an input frame without reading an `updated` property from it; omitting\n * `updated` restores a stored frame and reads its persisted timestamp exactly once. Every\n * untrusted property is captured once inside one protected boundary. The returned frame,\n * collections, progress, operations, and constraints are copied and frozen.\n *\n * @param input - The untrusted complete activity frame\n * @param updated - An optional accepted timestamp used instead of a persisted `updated`\n * @returns An immutable cloned {@link TaskActivity}\n * @throws {WorkflowError} With `MUTATION` when the frame cannot be read or validated\n */\nexport function cloneTaskActivity(input: unknown, updated?: number): TaskActivity {\n\ttry {\n\t\tif (!isRecord(input)) {\n\t\t\tthrow new WorkflowError('MUTATION', 'task activity must be a record')\n\t\t}\n\t\tconst inputPrototype = Object.getPrototypeOf(input)\n\t\tif (\n\t\t\t(inputPrototype !== Object.prototype && inputPrototype !== null) ||\n\t\t\t!Object.keys(input).every(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey === 'note' ||\n\t\t\t\t\tkey === 'progress' ||\n\t\t\t\t\tkey === 'operations' ||\n\t\t\t\t\tkey === 'constraints' ||\n\t\t\t\t\t(updated === undefined && key === 'updated'),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new WorkflowError('MUTATION', 'task activity must be a record')\n\t\t}\n\t\tconst note = input.note\n\t\tconst progressInput = input.progress\n\t\tconst operationsInput = input.operations\n\t\tconst constraintsInput = input.constraints\n\t\tconst accepted = updated === undefined ? input.updated : updated\n\n\t\tconst operationInputs =\n\t\t\toperationsInput === undefined\n\t\t\t\t? []\n\t\t\t\t: isArray(operationsInput)\n\t\t\t\t\t? [...operationsInput]\n\t\t\t\t\t: undefined\n\t\tif (operationInputs === undefined) {\n\t\t\tthrow new WorkflowError('MUTATION', 'task activity operations must be an array')\n\t\t}\n\t\tconst operations: unknown[] = []\n\t\tfor (const operation of operationInputs) {\n\t\t\tif (!isRecord(operation)) {\n\t\t\t\tthrow new WorkflowError('MUTATION', 'task activity contains an invalid operation')\n\t\t\t}\n\t\t\tconst operationPrototype = Object.getPrototypeOf(operation)\n\t\t\tif (\n\t\t\t\t(operationPrototype !== Object.prototype && operationPrototype !== null) ||\n\t\t\t\t!Object.keys(operation).every((key) => key === 'id' || key === 'name' || key === 'started')\n\t\t\t) {\n\t\t\t\tthrow new WorkflowError('MUTATION', 'task activity contains an invalid operation')\n\t\t\t}\n\t\t\tconst id = operation.id\n\t\t\tconst name = operation.name\n\t\t\tconst started = operation.started\n\t\t\toperations.push(Object.freeze({ id, name, started }))\n\t\t}\n\n\t\tlet progress: unknown\n\t\tif (progressInput !== undefined) {\n\t\t\tif (!isRecord(progressInput)) {\n\t\t\t\tthrow new WorkflowError('MUTATION', 'task activity contains invalid progress')\n\t\t\t}\n\t\t\tconst progressPrototype = Object.getPrototypeOf(progressInput)\n\t\t\tif (\n\t\t\t\t(progressPrototype !== Object.prototype && progressPrototype !== null) ||\n\t\t\t\t!Object.keys(progressInput).every(\n\t\t\t\t\t(key) => key === 'current' || key === 'total' || key === 'unit',\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new WorkflowError('MUTATION', 'task activity contains invalid progress')\n\t\t\t}\n\t\t\tconst current = progressInput.current\n\t\t\tconst total = progressInput.total\n\t\t\tconst unit = progressInput.unit\n\t\t\tprogress = Object.freeze({\n\t\t\t\tcurrent,\n\t\t\t\t...(total === undefined ? {} : { total }),\n\t\t\t\t...(unit === undefined ? {} : { unit }),\n\t\t\t})\n\t\t}\n\n\t\tconst constraintInputs =\n\t\t\tconstraintsInput === undefined\n\t\t\t\t? []\n\t\t\t\t: isArray(constraintsInput)\n\t\t\t\t\t? [...constraintsInput]\n\t\t\t\t\t: undefined\n\t\tif (constraintInputs === undefined) {\n\t\t\tthrow new WorkflowError('MUTATION', 'task activity constraints must be an array')\n\t\t}\n\t\tconst constraints: unknown[] = []\n\t\tfor (const constraint of constraintInputs) {\n\t\t\tif (!isRecord(constraint)) {\n\t\t\t\tthrow new WorkflowError('MUTATION', 'task activity contains an invalid constraint')\n\t\t\t}\n\t\t\tconst constraintPrototype = Object.getPrototypeOf(constraint)\n\t\t\tif (\n\t\t\t\t(constraintPrototype !== Object.prototype && constraintPrototype !== null) ||\n\t\t\t\t!Object.keys(constraint).every((key) => key === 'id' || key === 'name' || key === 'started')\n\t\t\t) {\n\t\t\t\tthrow new WorkflowError('MUTATION', 'task activity contains an invalid constraint')\n\t\t\t}\n\t\t\tconst id = constraint.id\n\t\t\tconst name = constraint.name\n\t\t\tconst started = constraint.started\n\t\t\tconstraints.push(Object.freeze({ id, name, started }))\n\t\t}\n\n\t\tconst activity = Object.freeze({\n\t\t\t...(note === undefined ? {} : { note }),\n\t\t\t...(progress === undefined ? {} : { progress }),\n\t\t\toperations: Object.freeze(operations),\n\t\t\tconstraints: Object.freeze(constraints),\n\t\t\tupdated: accepted,\n\t\t})\n\t\tif (!isTaskActivity(activity)) {\n\t\t\tthrow new WorkflowError('MUTATION', 'task activity is invalid')\n\t\t}\n\t\treturn activity\n\t} catch (error) {\n\t\tif (isWorkflowError(error)) throw error\n\t\tthrow new WorkflowError('MUTATION', 'task activity could not be read safely')\n\t}\n}\n","import {\n\tarrayShape,\n\tintegerShape,\n\tliteralShape,\n\tobjectShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\nimport { MAX_TIMER_MS } from './constants.js'\n\n// Workflow contract shapes — the shape VALUES the contract (factories.ts) compiles\n// into the four lockstep outputs (JSON Schema + guard + parser + generator). These\n// shapes MUST agree with the hand-written definition interfaces (types.ts), which\n// are the source of truth (AGENTS §14): a valid `WorkflowDefinition` is accepted by\n// the compiled `is` / `parse`, and the seeded `generate` produces a valid one.\n//\n// The definition interfaces stay hand-written rather than `Infer`-derived from\n// these shapes — the databases module already hit TS2589 on nested `objectShape`\n// generics, and this tree nests three levels (workflow → phase → task → form), so\n// the shapes are consumed as plain `ContractShape` runtime descriptors and the\n// contract is typed `ContractInterface<WorkflowDefinition>` at the factory.\n//\n// Per-field `description`s ride INSIDE the advertised JSON Schema (compilers.ts\n// `compileSchema` emits a shape's `description` verbatim) — advisory metadata only: it\n// never changes what the guard / parser accept (the contract stays byte-for-byte strict).\n\n// The description-carrying `bail` toggle rides on the shared `literalShape` (the\n// `@orkestrel/contract` module) — a described single-value literal is just\n// `literalShape([value], { description })`, so no module-local helper is needed.\n\n/**\n * The shape of a {@link import('./types.js').TaskDefinition} — identity plus an optional\n * `run` behavior reference (a plain registry-key string, min length 1). `description` is\n * optional prose.\n */\nexport const taskShape = objectShape({\n\tid: stringShape({ min: 1, description: 'Unique task id within its phase.' }),\n\tname: stringShape({ min: 1, description: 'Human-readable task name.' }),\n\tdescription: optionalShape(stringShape({ description: 'Optional task description.' })),\n\trun: optionalShape(\n\t\tstringShape({\n\t\t\tmin: 1,\n\t\t\tdescription:\n\t\t\t\t'The registered behavior name to invoke (a registry key, not a label); omitted has no handler.',\n\t\t}),\n\t),\n\tretries: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 0,\n\t\t\tdescription:\n\t\t\t\t'Extra attempts after the first on failure; overrides the phase default. Omitted means none.',\n\t\t}),\n\t),\n\ttimeout: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 0,\n\t\t\tmax: MAX_TIMER_MS,\n\t\t\tdescription:\n\t\t\t\t'Per-attempt deadline in milliseconds; overrides the phase default. Omitted means no deadline.',\n\t\t}),\n\t),\n})\n\n/**\n * The shape of a {@link import('./types.js').PhaseDefinition} — identity, its ordered\n * {@link taskShape} tasks, and an optional positive-integer `concurrency` throttle\n * (max tasks in flight; omitted ⇒ unbounded).\n */\nexport const phaseShape = objectShape({\n\tid: stringShape({ min: 1, description: 'Unique phase id within the workflow.' }),\n\tname: stringShape({ min: 1, description: 'Human-readable phase name.' }),\n\tdescription: optionalShape(stringShape({ description: 'Optional phase description.' })),\n\ttasks: arrayShape(taskShape, { description: 'The phase tasks; they run CONCURRENTLY.' }),\n\tconcurrency: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 1,\n\t\t\tdescription: 'Max tasks in flight at once (a resource throttle); omitted means unbounded.',\n\t\t}),\n\t),\n\tbail: optionalShape(\n\t\tliteralShape([true, false], {\n\t\t\tdescription: 'Per-phase failure-policy override; omitted inherits the workflow bail.',\n\t\t}),\n\t),\n})\n\n/**\n * The shape of a {@link import('./types.js').WorkflowDefinition} — the contract root:\n * identity, its ordered {@link phaseShape} phases, and the optional `bail` boolean\n * failure policy (the literal pair `true`/`false`, the runtime mirror of the boolean\n * toggle; omitted ⇒ the graceful default).\n */\nexport const workflowShape = objectShape({\n\tid: stringShape({ min: 1, description: 'Unique workflow id.' }),\n\tname: stringShape({ min: 1, description: 'Human-readable workflow name.' }),\n\tdescription: optionalShape(stringShape({ description: 'Optional workflow description.' })),\n\tphases: arrayShape(phaseShape, {\n\t\tdescription: 'The workflow phases; they run SEQUENTIALLY, in order.',\n\t}),\n\tbail: optionalShape(\n\t\tliteralShape([true, false], {\n\t\t\tdescription:\n\t\t\t\t'Failure policy: false (default) continues gracefully, true halts on the first failure.',\n\t\t}),\n\t),\n})\n\n// === Update (patch) shapes — the mutation API's `update` payload validation\n//\n// These shapes validate a {@link import('./types.js').TaskUpdate} /\n// {@link import('./types.js').PhaseUpdate} — a declarative PARTIAL edit to an\n// existing `pending` entity (AGENTS §12), never a full replacement. Every field is\n// therefore optional; a PROVIDED field still carries the same constraint as its\n// creation-time counterpart (`taskShape` / `phaseShape`) so a patch cannot smuggle in\n// an invalid value.\n\n/**\n * The shape of a {@link import('./types.js').TaskUpdate} — a partial edit to a\n * `pending` task's `name` / `description`, both optional.\n *\n * @remarks\n * Mirrors {@link taskShape}'s `name` / `description` constraints exactly (a provided\n * `name` still has `minLength: 1`); never `id` / `run` / `retries` / `timeout` (those\n * are not patchable fields, AGENTS §12).\n */\nexport const taskUpdateShape = objectShape({\n\tname: optionalShape(stringShape({ min: 1, description: 'New task name.' })),\n\tdescription: optionalShape(stringShape({ description: 'New task description.' })),\n})\n\n/**\n * The shape of a {@link import('./types.js').PhaseUpdate} — a partial edit to a\n * `pending` phase's `name` / `description` / `concurrency` / `bail`, all optional.\n *\n * @remarks\n * Mirrors {@link phaseShape}'s corresponding field constraints exactly; never `id` /\n * `tasks` (structural children change through the phase's own `add` / `remove` /\n * `move`, not a patch, AGENTS §12).\n */\nexport const phaseUpdateShape = objectShape({\n\tname: optionalShape(stringShape({ min: 1, description: 'New phase name.' })),\n\tdescription: optionalShape(stringShape({ description: 'New phase description.' })),\n\tconcurrency: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 1,\n\t\t\tdescription:\n\t\t\t\t'Max tasks in flight at once (a resource throttle); omitted leaves it unchanged.',\n\t\t}),\n\t),\n\tbail: optionalShape(\n\t\tliteralShape([true, false], {\n\t\t\tdescription: 'Per-phase failure-policy override; omitted leaves it unchanged.',\n\t\t}),\n\t),\n})\n","import type { TableInterface } from '@orkestrel/database'\nimport type { WorkflowSnapshot, WorkflowSnapshotRow, WorkflowStoreInterface } from '../types.js'\nimport { cloneWorkflowSnapshot } from '../cloners.js'\n\n/**\n * A {@link WorkflowStoreInterface} backed by one table of the `databases` layer — a\n * workflow's durable run-state IS a row, so persistence reduces to keyed point-access\n * (`get` / `set` / `delete`) over a `TableInterface`, the driver-pluggable twin of the\n * plain-`Map` {@link import('./MemoryWorkflowStore.js').MemoryWorkflowStore}.\n *\n * @remarks\n * The store is driver-agnostic: it holds a single {@link TableInterface} whose backend\n * (memory, JSON, SQLite, IndexedDB) is chosen by whoever builds it (the factories), so a\n * JSON / SQLite / IndexedDB backend swaps in WITHOUT touching the runner or the entity tree\n * — the same seam as `@orkestrel/queue`'s `DatabaseQueueStore`.\n * The driver defaults to memory ({@link import('../factories.js').createDatabaseWorkflowStore}\n * passes `createMemoryDriver()`), so it ALSO works in memory out of the box; you opt into the\n * durable plumbing by passing a JSON / SQLite / IndexedDB driver.\n *\n * The {@link WorkflowSnapshot} is stored as ONE OPAQUE JSON COLUMN — the table is a row of\n * `{ id; snapshot }` ({@link WorkflowSnapshotRow}), the snapshot the whole JSON blob (a `rawShape`\n * column the factory builds) — exactly as `DatabaseQueueStore` stores its `input`. The snapshot is\n * already a COMPLETE, self-contained, pure-JSON payload, so storing it whole is lossless AND\n * sidesteps a TS2589 instantiation-depth blow-up: a structured multi-column table would force the\n * contract to `Infer` the deeply-nested snapshot shape (workflow → phases → tasks → results),\n * tripping the compiler — one JSON column keeps the row type flat (`snapshot` reads back as `unknown`).\n *\n * - **`set(snapshot)` upserts under the snapshot's OWN `id`** (no separate id param) — it writes\n * the row `{ id: snapshot.id, snapshot }`.\n * - **`get(id)` resolves the stored snapshot for an id**, narrowing the opaque JSON column back to\n * a {@link WorkflowSnapshot} ({@link import('../helpers.js').isWorkflowSnapshot} — the AGENTS §14\n * boundary narrow for an untrusted storage read), or `undefined` if none is stored. A present\n * snapshot whose own id differs from the requested key rejects with normalized `RESTORE` evidence.\n * - **`delete(id)` drops a snapshot by id**; an absent id is a no-op (no throw).\n *\n * UNLIKE the server package's `SessionStoreInterface` there is NO\n * idle-TTL / eviction — a persisted run-state is durable orchestration state that lives until an\n * explicit `delete`. The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the\n * §22 method bijection with {@link WorkflowStoreInterface}). Restore stays a caller concern: read a\n * snapshot back and rebuild the live tree with {@link import('../factories.js').createRestoredWorkflow}.\n *\n * @example\n * ```ts\n * import { createMemoryDriver } from '@orkestrel/database'\n * import { createDatabaseWorkflowStore, createWorkflow, createRestoredWorkflow } from '@orkestrel/workflow'\n *\n * const store = createDatabaseWorkflowStore(createMemoryDriver()) // a durable driver swaps in here\n * const workflow = createWorkflow(definition)\n * await store.set(workflow.snapshot()) // persist the run state (one JSON column)\n * const snapshot = await store.get(definition.id)\n * const restored = snapshot && createRestoredWorkflow(snapshot) // an identical live tree\n * await store.delete(definition.id) // drop it\n * ```\n */\nexport class DatabaseWorkflowStore implements WorkflowStoreInterface {\n\treadonly #table: TableInterface<WorkflowSnapshotRow>\n\n\t/**\n\t * Wrap a table as a workflow store.\n\t *\n\t * @param table - The {@link TableInterface} holding the snapshots — its row is the\n\t * {@link WorkflowSnapshotRow} `{ id; snapshot }` shape (the snapshot one opaque JSON column)\n\t */\n\tconstructor(table: TableInterface<WorkflowSnapshotRow>) {\n\t\tthis.#table = table\n\t}\n\n\t/** Resolve and key-check the snapshot for `id`, narrowing the opaque column to `WorkflowSnapshot`. */\n\tasync get(id: string): Promise<WorkflowSnapshot | undefined> {\n\t\tconst row = await this.#table.get(id)\n\t\tif (row === undefined) return undefined\n\t\t// The snapshot crosses back as an untrusted storage read. A present malformed row is\n\t\t// corruption, not absence, so preserve cloneWorkflowSnapshot's normalized RESTORE failure.\n\t\treturn cloneWorkflowSnapshot(row.snapshot, id)\n\t}\n\n\t/** Insert or replace under the snapshot's OWN `id` (no separate id param) — the row is `{ id, snapshot }`. */\n\tasync set(snapshot: WorkflowSnapshot): Promise<void> {\n\t\tconst owned = cloneWorkflowSnapshot(snapshot)\n\t\tawait this.#table.set({ id: owned.id, snapshot: owned })\n\t}\n\n\t/** Drop a snapshot by id; an absent id is a no-op (no throw). */\n\tasync delete(id: string): Promise<void> {\n\t\tawait this.#table.remove(id)\n\t}\n}\n","import type { WorkflowSnapshot, WorkflowStoreInterface } from '../types.js'\nimport { cloneWorkflowSnapshot } from '../cloners.js'\n\n/**\n * The in-memory {@link WorkflowStoreInterface} — a process-lifetime `Map` of\n * {@link WorkflowSnapshot}s keyed by workflow id, the DEFAULT store\n * {@link import('../factories.js').createMemoryWorkflowStore} builds.\n *\n * @remarks\n * A plain `Map<string, WorkflowSnapshot>` (AGENTS §21 — the snapshot is already pure,\n * self-contained JSON, so no encoding is needed for the memory tier). UNLIKE the server\n * package's `SessionStoreInterface`'s memory store there is\n * NO idle-TTL and NO eviction: a persisted workflow run-state is durable orchestration state\n * that lives until an explicit `delete`, never silently aging out (a run that vanished\n * mid-flight would be a silent data loss, not a freed session). A durable backend (JSON /\n * SQLite / IndexedDB) swaps in through the SAME interface without touching the runner or the\n * entity tree — its driver-pluggable twin is\n * {@link import('./DatabaseWorkflowStore.js').DatabaseWorkflowStore} (the snapshot as one opaque\n * JSON column), exactly as `@orkestrel/queue`'s `MemoryQueueStore`\n * twins `DatabaseQueueStore`.\n *\n * - **`get` resolves the persisted snapshot for an id**, or `undefined` if none is stored.\n * - **`set` inserts / replaces under the snapshot's OWN `id`** (no separate id param).\n * - **`delete` drops a snapshot by id**; an absent id is a no-op (no throw).\n *\n * The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the §22 method\n * bijection with {@link WorkflowStoreInterface}). Restore is a caller concern: read a snapshot\n * back and rebuild the live tree with {@link import('../factories.js').createRestoredWorkflow}.\n *\n * @example\n * ```ts\n * import { createMemoryWorkflowStore, createWorkflow, createRestoredWorkflow } from '@orkestrel/workflow'\n *\n * const store = createMemoryWorkflowStore()\n * const workflow = createWorkflow(definition)\n * await store.set(workflow.snapshot()) // persist the run state\n * const snapshot = await store.get(definition.id)\n * const restored = snapshot && createRestoredWorkflow(snapshot) // an identical live tree\n * await store.delete(definition.id) // drop it\n * ```\n */\nexport class MemoryWorkflowStore implements WorkflowStoreInterface {\n\treadonly #snapshots = new Map<string, WorkflowSnapshot>()\n\n\tget(id: string): Promise<WorkflowSnapshot | undefined> {\n\t\tconst snapshot = this.#snapshots.get(id)\n\t\treturn Promise.resolve(snapshot === undefined ? undefined : cloneWorkflowSnapshot(snapshot))\n\t}\n\n\tset(snapshot: WorkflowSnapshot): Promise<void> {\n\t\t// Insert / replace under the snapshot's OWN id (no separate id param).\n\t\tconst owned = cloneWorkflowSnapshot(snapshot)\n\t\tthis.#snapshots.set(owned.id, owned)\n\t\treturn Promise.resolve()\n\t}\n\n\tdelete(id: string): Promise<void> {\n\t\t// Drop by id; `Map.delete` of an absent id is already a no-op (no throw).\n\t\tthis.#snapshots.delete(id)\n\t\treturn Promise.resolve()\n\t}\n}\n","import type { AbortInterface } from '@orkestrel/abort'\nimport type { JSONRecord, JSONValue, Result } from '@orkestrel/contract'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { TimeoutInterface } from '@orkestrel/timeout'\nimport type {\n\tDeferredInterface,\n\tPhaseInterface,\n\tTaskActivity,\n\tTaskActivityInput,\n\tTaskContext,\n\tTaskEventMap,\n\tTaskFailure,\n\tTaskInterface,\n\tTaskOptions,\n\tTaskResult,\n\tTaskSnapshot,\n\tTaskStatus,\n\tTaskUpdate,\n\tWorkflowFunction,\n\tWorkflowInterface,\n} from '../types.js'\nimport { createAbort } from '@orkestrel/abort'\nimport { cloneJSONRecord, cloneJSONValue, isContractError } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport { createTimeout } from '@orkestrel/timeout'\nimport { cloneTaskActivity } from '../cloners.js'\nimport { WorkflowError } from '../errors.js'\nimport {\n\tbuildTaskContext,\n\tcanTransitionTask,\n\tcreateDeferred,\n\tfailure,\n\tresolveTaskSilence,\n\tsuccess,\n} from '../helpers.js'\n\n/**\n * The live leaf state machine (W-b) for one task — an observable (AGENTS §13), guarded\n * synchronous task whose explicit {@link TaskStatus} advances through the AGENTS §10\n * transitions, recording a {@link TaskResult} on a terminal outcome.\n *\n * @remarks\n * - **Guarded transitions (AGENTS §10).** `start` (→ `running`), then `complete(value)`\n * (→ `completed`, records a {@link import('@orkestrel/contract').Success}), `fail(error)`\n * (→ `failed`, records a {@link import('@orkestrel/contract').Failure}), `skip` (→ `skipped`),\n * `stop` (→ `stopped`). Each consults {@link canTransitionTask} FIRST and throws a\n * `TRANSITION` {@link WorkflowError} on an illegal move (e.g. completing a non-`running`\n * task) — the legal graph is the single source of truth, so the leaf can never reach an\n * impossible state.\n * - **Snapshot fidelity.** A leaf needs no override: `skipped` / `stopped` are explicit terminal\n * statuses, and restore reinstates the leaf directly from {@link TaskSnapshot.status}.\n * - **The cascade.** Every status change records its boxed result (when any), fires the leaf's\n * OWN event, THEN calls the parent phase's `#recompute` (injected at construction) so the\n * transition propagates UP (Task → Phase → Workflow re-derive). The own-event-before-cascade\n * order means an observer sees the CAUSE (this leaf changed) before the EFFECT (the parents\n * re-derive) — the project precedent (`Runner.#settle` emits its own `fail` before propagating).\n * - **Observable (AGENTS §13).** The owned {@link emitter} ({@link TaskEventMap}) fires the\n * matching event strictly AFTER the state change, BEFORE the cascade; the emitter isolates\n * a listener throw and routes it to its `error` handler (the `error` option), so a buggy\n * observer can never corrupt a transition.\n * - **Declarative config (AGENTS §12).** `run` / `retries` / `timeout` PERSIST in a\n * {@link TaskSnapshot} (like a phase's `bail` / `concurrency`), carried verbatim from the\n * matching {@link import('../types.js').TaskDefinition} / {@link TaskSnapshot} field. `handler`\n * is the RUNTIME-ONLY counterpart — `run` resolved ONCE at construction against the\n * workflow-level {@link import('../types.js').WorkflowOptions.functions} registry — and is\n * NEVER persisted; `undefined` when `run` is omitted or unregistered. Only omission is a\n * deliberate no-op; unresolved named work is rejected before dispatch.\n */\nexport class Task implements TaskInterface {\n\tdeclare readonly description?: string\n\treadonly #context: TaskContext\n\treadonly #phase: PhaseInterface\n\treadonly #workflow: WorkflowInterface\n\t// Propagate a status change UP to the parent phase (which re-derives, then escalates to the\n\t// workflow) — injected by the parent so the leaf needs no back-reference plumbing of its own.\n\treadonly #recompute: () => void\n\treadonly #metadata: JSONRecord\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into a\n\t// transition or the cascade.\n\treadonly #emitter: Emitter<TaskEventMap>\n\t#status: TaskStatus\n\t// The recorded outcome once the task settled with one (`completed` / `failed`), else undefined.\n\t#result: TaskResult | undefined\n\t// `name` / `description` seed from `#context` but live as independent fields (AGENTS §12) so\n\t// `patch` can rename SELF without mutating the immutable lineage `#context` a `TaskResult`\n\t// stamps.\n\t#name: string\n\t// PERSISTED declarative config, carried verbatim from the TaskDefinition / TaskSnapshot.\n\treadonly #run: string | undefined\n\treadonly #retries: number | undefined\n\treadonly #timeout: number | undefined\n\t#attempts: number\n\t// RUNTIME-ONLY (never persisted): `run` resolved ONCE at construction against the\n\t// workflow-level functions registry; `undefined` when `run` is omitted or unregistered.\n\treadonly #handler: WorkflowFunction | undefined\n\treadonly #abort: AbortInterface\n\treadonly #silence: number | undefined\n\treadonly #onSilence: () => void\n\treadonly #liveness: TimeoutInterface | undefined\n\t#activity: TaskActivity | undefined\n\t#paused: boolean\n\t#gate: DeferredInterface<void> | undefined\n\t#timerSignal: AbortSignal | undefined\n\n\tconstructor(\n\t\tcontext: TaskContext,\n\t\tphase: PhaseInterface,\n\t\tworkflow: WorkflowInterface,\n\t\trecompute: () => void,\n\t\toptions?: TaskOptions,\n\t\tstatus: TaskStatus = 'pending',\n\t\tresult?: TaskResult,\n\t\trun?: string,\n\t\tretries?: number,\n\t\ttimeout?: number,\n\t\tmetadata: JSONRecord = {},\n\t\tattempts = 0,\n\t\tactivity?: TaskActivity,\n\t\thandler?: WorkflowFunction,\n\t\tsilence?: number,\n\t) {\n\t\tthis.#context = buildTaskContext(context.phase, context)\n\t\tthis.#phase = phase\n\t\tthis.#workflow = workflow\n\t\tthis.#recompute = recompute\n\t\ttry {\n\t\t\tconst metadataOption = options?.metadata\n\t\t\tthis.#metadata = cloneJSONRecord(metadataOption ?? metadata)\n\t\t} catch (error) {\n\t\t\tif (isContractError(error)) {\n\t\t\t\tthrow new WorkflowError(\n\t\t\t\t\t'RESTORE',\n\t\t\t\t\t`task '${context.id}' metadata could not be read safely: ${error.message}`,\n\t\t\t\t\t{ task: context.id },\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow new WorkflowError('RESTORE', `task '${context.id}' metadata could not be read safely`, {\n\t\t\t\ttask: context.id,\n\t\t\t})\n\t\t}\n\t\tconst on = options?.on\n\t\tconst listenerError = options?.error\n\t\tconst silenceOption = options?.silence\n\t\tthis.#emitter = new Emitter<TaskEventMap>({\n\t\t\t...(on === undefined ? {} : { on }),\n\t\t\t...(listenerError === undefined ? {} : { error: listenerError }),\n\t\t})\n\t\tthis.#status = status\n\t\t// A RESTORE seeds the recorded outcome (present for a `completed` / `failed` leaf), so\n\t\t// the result tree round-trips; a fresh leaf starts with none. A leaf's terminal status\n\t\t// (`skipped` / `stopped`) already encodes a forced state, so the leaf needs no separate\n\t\t// override field — the override round-trip lives on the DERIVED Phase / Workflow nodes.\n\t\tthis.#result = result\n\t\tthis.#name = context.name\n\t\tif (context.description !== undefined) {\n\t\t\tObject.defineProperty(this, 'description', {\n\t\t\t\tconfigurable: true,\n\t\t\t\tvalue: context.description,\n\t\t\t})\n\t\t}\n\t\t// Carried verbatim from the TaskDefinition / TaskSnapshot (declarative, persisted).\n\t\tthis.#run = run\n\t\tthis.#retries = retries\n\t\tthis.#timeout = timeout\n\t\tthis.#attempts = attempts\n\t\t// Resolved ONCE by the caller (Phase) against the functions registry; stored as-is.\n\t\tthis.#handler = handler\n\t\tthis.#abort = createAbort()\n\t\tthis.#silence = resolveTaskSilence(silenceOption, silence)\n\t\tthis.#onSilence = this.#expire.bind(this)\n\t\tthis.#liveness =\n\t\t\tthis.#silence === undefined\n\t\t\t\t? undefined\n\t\t\t\t: createTimeout({ ms: this.#silence, signal: this.#abort.signal })\n\t\tthis.#activity = activity === undefined ? undefined : cloneTaskActivity(activity)\n\t\tthis.#paused = false\n\t\tthis.#gate = undefined\n\t\tthis.#timerSignal = undefined\n\t}\n\n\tget emitter(): EmitterInterface<TaskEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget id(): string {\n\t\treturn this.#context.id\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget context(): TaskContext {\n\t\treturn this.#context\n\t}\n\n\tget phase(): PhaseInterface {\n\t\treturn this.#phase\n\t}\n\n\tget workflow(): WorkflowInterface {\n\t\treturn this.#workflow\n\t}\n\n\tget status(): TaskStatus {\n\t\treturn this.#status\n\t}\n\n\tget result(): TaskResult | undefined {\n\t\treturn this.#result\n\t}\n\n\tget attempts(): number {\n\t\treturn this.#attempts\n\t}\n\n\tget run(): string | undefined {\n\t\treturn this.#run\n\t}\n\n\tget handler(): WorkflowFunction | undefined {\n\t\treturn this.#handler\n\t}\n\n\tget retries(): number | undefined {\n\t\treturn this.#retries\n\t}\n\n\tget timeout(): number | undefined {\n\t\treturn this.#timeout\n\t}\n\n\tget activity(): TaskActivity | undefined {\n\t\treturn this.#activity\n\t}\n\n\tget silence(): number | undefined {\n\t\treturn this.#silence\n\t}\n\n\tget silent(): boolean {\n\t\treturn this.#status === 'running' && this.#liveness?.expired === true\n\t}\n\n\tget paused(): boolean {\n\t\treturn this.#paused\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#abort.signal\n\t}\n\n\tstart(): void {\n\t\tconst budget = Math.max(0, this.#retries ?? 0) + 1\n\t\tif ((this.#status !== 'pending' && this.#status !== 'running') || this.#attempts >= budget) {\n\t\t\tthrow new WorkflowError('TRANSITION', `task '${this.id}' cannot start another attempt`, {\n\t\t\t\ttask: this.id,\n\t\t\t\tstatus: this.#status,\n\t\t\t\tattempts: this.#attempts,\n\t\t\t\tbudget,\n\t\t\t})\n\t\t}\n\t\tif (this.#status === 'pending') this.#transition('running')\n\t\tthis.#attempts += 1\n\t\tthis.#activity = cloneTaskActivity({}, this.#stamp())\n\t\tthis.#arm()\n\t\t// Own event FIRST, THEN the cascade — an observer sees the cause (this task started) before\n\t\t// the effect (the phase / workflow re-derive), mirroring `Runner.#settle` (AGENTS §13).\n\t\tthis.#emitter.emit('start', this.id)\n\t\tthis.#escalate()\n\t}\n\n\tcomplete(value: JSONValue): void {\n\t\tlet owned: JSONValue\n\t\ttry {\n\t\t\towned = cloneJSONValue(value)\n\t\t} catch (error) {\n\t\t\tif (isContractError(error)) {\n\t\t\t\tthrow new WorkflowError(\n\t\t\t\t\t'RESTORE',\n\t\t\t\t\t`task '${this.id}' result could not be read safely: ${error.message}`,\n\t\t\t\t\t{ task: this.id },\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow new WorkflowError('RESTORE', `task '${this.id}' result could not be read safely`, {\n\t\t\t\ttask: this.id,\n\t\t\t})\n\t\t}\n\t\tthis.#transition('completed')\n\t\tthis.#finish()\n\t\t// Box the produced value as a Success (an inline `Result` branch, the codebase idiom) and\n\t\t// RECORD it BEFORE escalating, so the parents' `results()` already see it when the cascade\n\t\t// re-derives. Then observe the leaf's own `complete` FIRST, and escalate the cascade LAST —\n\t\t// so the leaf's own event fires before any parent's cascade event (cause before effect).\n\t\tconst result = this.#record('completed', Object.freeze({ success: true, value: owned }))\n\t\tthis.#emitter.emit('complete', result)\n\t\tthis.#escalate()\n\t}\n\n\tfail(error: TaskFailure): void {\n\t\t// Normalize into the persisted JSON contract before transitioning. Record before escalating\n\t\t// so parent result reads already see the terminal outcome.\n\t\tconst origin =\n\t\t\terror.origin === 'handler' || error.origin === 'timeout' || error.origin === 'recovery'\n\t\t\t\t? error.origin\n\t\t\t\t: 'handler'\n\t\tconst message =\n\t\t\ttypeof error.message === 'string' && error.message.length > 0\n\t\t\t\t? error.message\n\t\t\t\t: 'unknown failure'\n\t\tthis.#transition('failed')\n\t\tthis.#finish()\n\t\tconst result = this.#record(\n\t\t\t'failed',\n\t\t\tObject.freeze({\n\t\t\t\tsuccess: false,\n\t\t\t\terror: Object.freeze({ origin, message }),\n\t\t\t}),\n\t\t)\n\t\tthis.#emitter.emit('fail', result)\n\t\tthis.#escalate()\n\t}\n\n\tskip(): void {\n\t\t// `skip` (AGENTS §10) moves a `pending` / `running` task to the terminal `skipped` state —\n\t\t// the status itself records the forced terminal (no boxed outcome: a skip produced none).\n\t\t// Own event FIRST, THEN the cascade (cause before effect).\n\t\tthis.#transition('skipped')\n\t\tthis.#finish()\n\t\tthis.#abort.abort()\n\t\tthis.#emitter.emit('skip')\n\t\tthis.#escalate()\n\t}\n\n\tstop(): void {\n\t\t// `stop` (AGENTS §10) moves a `pending` / `running` task to the terminal `stopped` state —\n\t\t// same discipline as `skip`; a stop likewise produced no boxed outcome. Own event FIRST,\n\t\t// THEN the cascade.\n\t\tthis.#transition('stopped')\n\t\tthis.#finish()\n\t\tthis.#abort.abort()\n\t\tthis.#emitter.emit('stop')\n\t\tthis.#escalate()\n\t}\n\n\treport(input: TaskActivityInput): Result<TaskActivity, WorkflowError> {\n\t\tif (this.#status !== 'running') {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('TRANSITION', `task '${this.id}' cannot report while '${this.#status}'`, {\n\t\t\t\t\ttask: this.id,\n\t\t\t\t\tstatus: this.#status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\ttry {\n\t\t\tconst activity = cloneTaskActivity(input, this.#stamp())\n\t\t\tthis.#activity = activity\n\t\t\tthis.#arm()\n\t\t\tthis.#emitter.emit('report', activity)\n\t\t\treturn success(activity)\n\t\t} catch (error) {\n\t\t\treturn failure(\n\t\t\t\terror instanceof WorkflowError\n\t\t\t\t\t? error\n\t\t\t\t\t: new WorkflowError('MUTATION', 'task activity report was refused', {\n\t\t\t\t\t\t\ttask: this.id,\n\t\t\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t}\n\n\tpulse(): boolean {\n\t\tif (this.#status !== 'running' || this.#activity === undefined) return false\n\t\tthis.#touch()\n\t\tthis.#arm()\n\t\tconst activity = this.#activity\n\t\tthis.#emitter.emit('pulse', activity)\n\t\treturn true\n\t}\n\n\tpause(): void {\n\t\tif (this.#paused || (this.#status !== 'pending' && this.#status !== 'running')) return\n\t\tthis.#paused = true\n\t\tthis.#gate = createDeferred<void>()\n\t\tthis.#emitter.emit('pause')\n\t}\n\n\tresume(): void {\n\t\tif (!this.#paused) return\n\t\tthis.#paused = false\n\t\tthis.#release()\n\t\tthis.#emitter.emit('resume')\n\t}\n\n\twait(): Promise<void> {\n\t\treturn this.#paused && this.#gate !== undefined ? this.#gate.promise : Promise.resolve()\n\t}\n\n\t/**\n\t * Apply a validated declarative patch to SELF (`name` / `description`).\n\t *\n\t * @remarks\n\t * Defense-in-depth (AGENTS §12): the owning\n\t * {@link import('../types.js').TaskManagerInterface.update} gates FIRST (target\n\t * exists + `pending`), so this is the second, redundant check — it THROWS a\n\t * `MUTATION` {@link WorkflowError} unless this task's own `status` is `pending`.\n\t *\n\t * @param value - The {@link TaskUpdate} fields to apply\n\t * @example\n\t * ```ts\n\t * task.patch({ name: 'Renamed task' })\n\t * ```\n\t */\n\tpatch(value: TaskUpdate): void {\n\t\tif (this.#status !== 'pending') {\n\t\t\tthrow new WorkflowError(\n\t\t\t\t'MUTATION',\n\t\t\t\t`task '${this.id}' cannot be patched while '${this.#status}'`,\n\t\t\t\t{ task: this.id, status: this.#status },\n\t\t\t)\n\t\t}\n\t\tif (value.name !== undefined) this.#name = value.name\n\t\tif (value.description !== undefined) {\n\t\t\tObject.defineProperty(this, 'description', {\n\t\t\t\tconfigurable: true,\n\t\t\t\tvalue: value.description,\n\t\t\t})\n\t\t}\n\t}\n\n\tsnapshot(): TaskSnapshot {\n\t\t// Pure JSON: identity + status + the recorded result + the open metadata bag + the\n\t\t// declarative run/retries/timeout config (like a phase's bail/concurrency). The leaf's\n\t\t// status IS its forced-terminal marker (`skipped` / `stopped`), so restore reinstates the\n\t\t// leaf from `status` directly — no separate override field is needed at the leaf.\n\t\treturn {\n\t\t\tid: this.id,\n\t\t\tname: this.name,\n\t\t\t...(this.description === undefined ? {} : { description: this.description }),\n\t\t\tstatus: this.#status,\n\t\t\t...(this.#result === undefined ? {} : { result: this.#result }),\n\t\t\tmetadata: this.#metadata,\n\t\t\tattempts: this.#attempts,\n\t\t\t...(this.#run === undefined ? {} : { run: this.#run }),\n\t\t\t...(this.#retries === undefined ? {} : { retries: this.#retries }),\n\t\t\t...(this.#timeout === undefined ? {} : { timeout: this.#timeout }),\n\t\t\t...(this.#activity === undefined ? {} : { activity: this.#activity }),\n\t\t}\n\t}\n\n\t// Guard then apply one status move: reject an illegal transition with a `TRANSITION` error\n\t// (naming the offending current status + requested target), else set the new status. The\n\t// cascade is NOT run here — every caller records its boxed result (when any) FIRST, notifies\n\t// its OWN event SECOND, then escalates LAST, so an observer sees cause (this leaf changed)\n\t// before effect (the parents re-derive). See `start` / `complete` / `fail` / `skip` / `stop`.\n\t#transition(to: TaskStatus): void {\n\t\tif (!canTransitionTask(this.#status, to)) {\n\t\t\tthrow new WorkflowError(\n\t\t\t\t'TRANSITION',\n\t\t\t\t`task '${this.id}' cannot transition from '${this.#status}' to '${to}'`,\n\t\t\t\t{ task: this.id, from: this.#status, to },\n\t\t\t)\n\t\t}\n\t\tthis.#status = to\n\t}\n\n\t// Build the lineage-stamped {@link TaskResult} for a terminal outcome, store it as `#result`,\n\t// and return it. The boxed `result` is present only for `completed` / `failed`.\n\t#record(status: TaskStatus, result: TaskResult['result']): TaskResult {\n\t\tconst record: TaskResult = {\n\t\t\ttask: this.#context,\n\t\t\tphase: this.#context.phase,\n\t\t\tworkflow: this.#context.phase.workflow,\n\t\t\tstatus,\n\t\t\t...(result === undefined ? {} : { result }),\n\t\t\ttimestamp: Date.now(),\n\t\t}\n\t\tconst frozen = Object.freeze(record)\n\t\tthis.#result = frozen\n\t\treturn frozen\n\t}\n\n\t// Notify the parent phase that this leaf changed, so it re-derives and escalates to the\n\t// workflow — the single upward step of the cascade.\n\t#escalate(): void {\n\t\tthis.#recompute()\n\t}\n\n\t#touch(): void {\n\t\tif (this.#activity === undefined) return\n\t\tthis.#activity = Object.freeze({\n\t\t\t...this.#activity,\n\t\t\tupdated: this.#stamp(),\n\t\t})\n\t}\n\n\t#stamp(): number {\n\t\treturn Math.max(Date.now(), this.#activity?.updated ?? 0)\n\t}\n\n\t#finish(): void {\n\t\tthis.#clear()\n\t\tthis.#paused = false\n\t\tthis.#release()\n\t}\n\n\t#arm(): void {\n\t\tthis.#clear()\n\t\tconst liveness = this.#liveness\n\t\tif (liveness === undefined || this.#status !== 'running') return\n\t\tliveness.start()\n\t\tconst signal = liveness.signal\n\t\tthis.#timerSignal = signal\n\t\tsignal.addEventListener('abort', this.#onSilence, { once: true })\n\t}\n\n\t#clear(): void {\n\t\tconst signal = this.#timerSignal\n\t\tif (signal !== undefined) signal.removeEventListener('abort', this.#onSilence)\n\t\tthis.#timerSignal = undefined\n\t\tthis.#liveness?.clear()\n\t}\n\n\t#expire(): void {\n\t\tthis.#timerSignal = undefined\n\t\tif (this.#status !== 'running' || this.#liveness?.expired !== true) return\n\t\tthis.#emitter.emit('silence')\n\t}\n\n\t#release(): void {\n\t\tif (this.#gate === undefined) return\n\t\tthis.#gate.resolve()\n\t\tthis.#gate = undefined\n\t}\n}\n","import type { Result } from '@orkestrel/contract'\nimport type { TaskInterface, TaskManagerInterface, TaskUpdate } from '../types.js'\nimport { compileGuard } from '@orkestrel/contract'\nimport { WorkflowError } from '../errors.js'\nimport { failure, insertEntry, moveEntry, success } from '../helpers.js'\nimport { taskUpdateShape } from '../shapers.js'\n\n/**\n * The lean child manager (AGENTS §9) of a {@link import('../phases/Phase.js').Phase}'s live\n * tasks — an insertion-ordered registry keyed by task `id`, so positional order is\n * preserved across an interior `skip` / `remove`.\n *\n * @remarks\n * - **Positional store.** Tasks live in an insertion-ordered `Map` keyed by `id`;\n * `append` adds one at the end (the build-time wiring path), `task(id)` looks one up,\n * `tasks()` lists them in positional order, `count` is the size. A `skip` is a STATUS\n * change on a stored task (never a removal), so order survives it; a snapshot RESTORE\n * re-`append`s in the snapshot's order, reproducing it exactly.\n * - **Gated mutation API (AGENTS §12).** `add` / `remove` / `move` / `update` are the\n * graceful `Result` counterparts to `append`, gating ONLY on the target's OWN\n * existence/status/id/bounds — a duplicate id, an absent/non-`pending` target, an\n * out-of-bounds `index`, or a patch that fails {@link taskUpdateShape} validation all\n * fail gracefully with a `MUTATION` {@link WorkflowError} instead of throwing.\n * - **No batch matrix.** A phase's tasks are a fixed positional set, so AGENTS §9.2 (the\n * bulk verb overloads) is deliberately omitted — there is no `remove` family here.\n * - **Event-free.** A purely structural container — the live {@link TaskInterface}s own\n * their own emitters; the manager observes nothing.\n *\n * @example\n * ```ts\n * const tasks = new TaskManager()\n * tasks.append(task) // a live Task\n * tasks.task(task.id) // the same task\n * tasks.count // 1\n * ```\n */\nexport class TaskManager implements TaskManagerInterface {\n\treadonly #tasks = new Map<string, TaskInterface>()\n\t// The compiled guard validating a `TaskUpdate` patch (AGENTS §14) before it reaches\n\t// `update`'s `task.patch` call.\n\treadonly #isUpdate = compileGuard(taskUpdateShape)\n\n\tget count(): number {\n\t\treturn this.#tasks.size\n\t}\n\n\tappend(task: TaskInterface): void {\n\t\tif (this.#tasks.has(task.id)) {\n\t\t\tthrow new WorkflowError('MUTATION', `duplicate task id '${task.id}'`, { id: task.id })\n\t\t}\n\t\tthis.#tasks.set(task.id, task)\n\t}\n\n\tadd(task: TaskInterface, index?: number): Result<TaskInterface, WorkflowError> {\n\t\tif (this.#tasks.has(task.id)) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `duplicate task id '${task.id}'`, { id: task.id }),\n\t\t\t)\n\t\t}\n\t\tconst at = index ?? this.#tasks.size\n\t\tif (at < 0 || at > this.#tasks.size) {\n\t\t\treturn failure(new WorkflowError('MUTATION', `index '${at}' out of bounds`, { index: at }))\n\t\t}\n\t\tthis.#reorder(insertEntry([...this.#tasks.entries()], at, task.id, task))\n\t\treturn success(task)\n\t}\n\n\tremove(id: string): Result<TaskInterface, WorkflowError> {\n\t\tconst target = this.#tasks.get(id)\n\t\tif (target === undefined || target.status !== 'pending') {\n\t\t\treturn failure(new WorkflowError('MUTATION', `task '${id}' is not a pending task`, { id }))\n\t\t}\n\t\tthis.#tasks.delete(id)\n\t\treturn success(target)\n\t}\n\n\tmove(id: string, index: number): Result<TaskInterface, WorkflowError> {\n\t\tconst target = this.#tasks.get(id)\n\t\tif (target === undefined || target.status !== 'pending') {\n\t\t\treturn failure(new WorkflowError('MUTATION', `task '${id}' is not a pending task`, { id }))\n\t\t}\n\t\tif (index < 0 || index >= this.#tasks.size) {\n\t\t\treturn failure(new WorkflowError('MUTATION', `index '${index}' out of bounds`, { index }))\n\t\t}\n\t\tthis.#reorder(moveEntry([...this.#tasks.entries()], id, index))\n\t\treturn success(target)\n\t}\n\n\tupdate(id: string, patch: TaskUpdate): Result<TaskInterface, WorkflowError> {\n\t\tconst target = this.#tasks.get(id)\n\t\tif (target === undefined || target.status !== 'pending') {\n\t\t\treturn failure(new WorkflowError('MUTATION', `task '${id}' is not a pending task`, { id }))\n\t\t}\n\t\tif (!this.#isUpdate(patch)) {\n\t\t\treturn failure(new WorkflowError('MUTATION', `invalid patch for task '${id}'`, { id }))\n\t\t}\n\t\ttarget.patch(patch)\n\t\treturn success(target)\n\t}\n\n\ttask(id: string): TaskInterface | undefined {\n\t\treturn this.#tasks.get(id)\n\t}\n\n\ttasks(): readonly TaskInterface[] {\n\t\treturn [...this.#tasks.values()]\n\t}\n\n\t// Rebuild the positional store from `entries` — the shared reorder step behind\n\t// `add` (insert) and `move` (reposition), keeping the `Map`'s insertion order the\n\t// single source of positional truth.\n\t#reorder(entries: ReadonlyArray<readonly [string, TaskInterface]>): void {\n\t\tthis.#tasks.clear()\n\t\tfor (const [key, value] of entries) this.#tasks.set(key, value)\n\t}\n}\n","import type { Result } from '@orkestrel/contract'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tDeferredInterface,\n\tPhaseContext,\n\tPhaseEventMap,\n\tPhaseInterface,\n\tPhaseOptions,\n\tPhaseSnapshot,\n\tPhaseStatus,\n\tPhaseUpdate,\n\tTaskDefinition,\n\tTaskInterface,\n\tTaskManagerInterface,\n\tTaskOptions,\n\tTaskResult,\n\tTaskSnapshot,\n\tTaskUpdate,\n\tWorkflowFunction,\n\tWorkflowFunctions,\n\tWorkflowInterface,\n} from '../types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { WorkflowError } from '../errors.js'\nimport {\n\tbuildPhaseContext,\n\tbuildTaskContext,\n\tcreateDeferred,\n\tderivePhaseStatus,\n\tfailure,\n\tfindFailure,\n\tisTerminalStatus,\n\ttaskDefinitionToSnapshot,\n} from '../helpers.js'\nimport { Task } from '../tasks/Task.js'\nimport { TaskManager } from '../tasks/TaskManager.js'\n\n/**\n * The live DERIVED state machine (W-b) for one phase — an observable (AGENTS §13) whose\n * {@link PhaseStatus} is computed from its tasks (never set directly) and recomputed\n * reactively as a task transitions (the middle tier of the cascade).\n *\n * @remarks\n * - **Derived status.** `status` is `#override` when one is in force, else\n * {@link derivePhaseStatus} over the live tasks' statuses. `#recompute` (passed to\n * each child {@link Task}) re-derives on every child transition; a CHANGE emits the matching\n * event AND escalates to the workflow (`#escalate`, the upward step of the cascade).\n * - **Override (AGENTS §10).** `skip` / `stop` FORCE the phase's status (e.g. skipping a whole\n * phase), overriding the derived value; the override is PERSISTED in the snapshot's own\n * `override` field and restored DIRECTLY (no divergence guess), so a forced phase round-trips.\n * - **Children (AGENTS §9).** `tasks` is the lean {@link TaskManager} (an accessor + `count`,\n * no batch matrix); built positionally from the snapshot so order survives an interior `skip`.\n * `results()` collects the settled tasks' {@link TaskResult}s (the phase tier of the result\n * tree); `workflow` navigates UP to the live parent.\n * - **Observable (AGENTS §13).** The owned {@link emitter} ({@link PhaseEventMap}) fires\n * `start` / `complete` / `fail` / `pause` / `resume` / `skip` / `stop` after the\n * corresponding status or runtime-gate change. Status events fire after the phase recomputes\n * and before it escalates to the workflow, preserving child/phase cause before parent effect.\n * The emitter isolates a listener throw and routes it to its `error` handler (the `error`\n * option); `fail` carries the failing task's {@link TaskResult}.\n * - **Structural API (AGENTS §7).** `add` / `remove` / `move` / `update` gate BEFORE\n * delegating to {@link tasks} (the manager gates the target's own existence/status/id/\n * bounds), then emit the matching {@link PhaseEventMap} event on success only. NATIVE\n * gating, purely from this phase's own derived `status` (no runner-installed hook): while\n * `pending`, any valid `index` is accepted; while `running`, `add` accepts ONLY a pure\n * append (a live runner subscribed to the `add` event picks it up), and `remove` / `move` /\n * `update` always fail gracefully (the tasks are already handed to the execution\n * substrate); while terminal, everything is refused.\n * - **Patch (AGENTS §12).** `patch` applies a validated {@link PhaseUpdate} to SELF\n * (`name` / `description` / `concurrency` / `bail`) — defense-in-depth: it throws a\n * `MUTATION` {@link WorkflowError} unless this phase's own `status` is `pending`, mirroring\n * the owning {@link WorkflowInterface.update}'s gate.\n * - **Minting (AGENTS §7).** {@link add} MINTS a live {@link Task} from a {@link TaskDefinition}\n * (converts it to a {@link TaskSnapshot}, builds the task wired to THIS phase) — the same\n * construction path {@link #append} uses at build time, so a live mint and a restored/built\n * task are wired IDENTICALLY. At construction, the workflow-level\n * {@link import('../types.js').WorkflowFunctions} registry (threaded from\n * {@link import('../types.js').WorkflowOptions.functions}) resolves every unique initial `run`\n * name ONCE before any task is built; siblings sharing a name receive the exact same captured\n * runtime {@link import('../types.js').TaskInterface.handler}. A later live {@link add} reads\n * that name once from the retained registry at its own mint moment. An omitted or unregistered\n * `run` resolves to no handler; only omission is a no-op, while an unresolved present name makes\n * the containing tree non-drivable.\n * - **Runtime lifecycle (AGENTS §10).** `pause` / `resume` / `wait` mirror the workflow's own\n * quartet, scoped to this phase — a driving\n * {@link import('../types.js').WorkflowRunnerInterface.execute} gates a task's own\n * pre-dispatch on the workflow's gate FIRST, then this phase's gate, WITHOUT touching\n * {@link status} — `paused` is runtime-only, never persisted. `skip` / `stop` (this phase's\n * own terminal forcing) always release a parked {@link wait} waiter, mirroring\n * {@link import('../Workflow.js').Workflow.destroy}'s cascade — a permanently-ended phase\n * has nothing left to pause for.\n */\nexport class Phase implements PhaseInterface {\n\tdeclare readonly description?: string\n\treadonly #id: string\n\t#name: string\n\treadonly #workflow: WorkflowInterface\n\t// Escalate a derived-status change UP to the parent workflow (which re-derives under `bail`)\n\t// — injected by the parent so the phase needs no back-reference plumbing of its own.\n\treadonly #escalateUp: () => void\n\treadonly #tasks: TaskManager = new TaskManager()\n\t// The workflow-level function registry retained from Workflow. Initial tasks capture one\n\t// binding per unique run name. A later live mint reads its own\n\t// binding from this retained registry; existing handlers never change when the registry does.\n\treadonly #functions: WorkflowFunctions | undefined\n\treadonly #silence: number | undefined\n\t// The EFFECTIVE failure policy this phase runs under (`phase.bail ?? workflow.bail`, resolved\n\t// at seed time and carried on the snapshot) — read by the runner to decide fail-fast vs\n\t// settle-all for THIS phase, and by the workflow's per-phase-bail-aware status derivation.\n\t// Mutable (AGENTS §7): a `pending` phase's `patch` may override it before a run starts.\n\t#bail: boolean\n\t// Max tasks in flight at once (a resource throttle), seeded from the snapshot; mutable via a\n\t// `pending` phase's `patch` (AGENTS §7). `undefined` ⇒ unbounded.\n\t#concurrency: number | undefined\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), never the cascade.\n\treadonly #emitter: Emitter<PhaseEventMap>\n\t// The last computed status — the baseline a recompute diffs against to detect a CHANGE.\n\t#status: PhaseStatus\n\t// The forced status of a `skip` / `stop`, overriding the derived value; `undefined` ⇒ derived.\n\t#override: PhaseStatus | undefined\n\t// RUNTIME-ONLY (never persisted): whether the phase is currently paused.\n\t#paused: boolean\n\t// The parked `wait()` gate while paused; `undefined` when not paused — released (resolved) by\n\t// `resume` / `stop` / `skip`.\n\t#gate: DeferredInterface<void> | undefined\n\n\tconstructor(\n\t\tsnapshot: PhaseSnapshot,\n\t\tworkflow: WorkflowInterface,\n\t\tescalate: () => void,\n\t\toptions?: PhaseOptions,\n\t\tbail?: boolean,\n\t\tfunctions?: WorkflowFunctions,\n\t\tsilence?: number,\n\t) {\n\t\tconst on = options?.on\n\t\tconst error = options?.error\n\t\tconst tasks = options?.tasks\n\t\tthis.#id = snapshot.id\n\t\tthis.#name = snapshot.name\n\t\tif (snapshot.description !== undefined) {\n\t\t\tObject.defineProperty(this, 'description', {\n\t\t\t\tconfigurable: true,\n\t\t\t\tvalue: snapshot.description,\n\t\t\t})\n\t\t}\n\t\tthis.#workflow = workflow\n\t\tthis.#escalateUp = escalate\n\t\tthis.#functions = functions\n\t\tthis.#silence = silence\n\t\tconst handlers = new Map<string, WorkflowFunction | undefined>()\n\t\tfor (const task of snapshot.tasks) {\n\t\t\tif (task.run !== undefined && !handlers.has(task.run)) {\n\t\t\t\thandlers.set(task.run, functions?.[task.run])\n\t\t\t}\n\t\t}\n\t\t// The effective per-phase policy: the explicit workflow `bail` OVERRIDE when supplied (a\n\t\t// deliberate \"re-run the whole tree under THIS uniform policy\" knob — `createWorkflow` /\n\t\t// `createRestoredWorkflow` thread `options.bail` here), else the snapshot's persisted per-phase `bail`\n\t\t// (so an option-less restore is IDENTICAL — each phase's own persisted policy governs). The\n\t\t// snapshot already resolved `phase.bail ?? workflowBail` at seed time, mirroring how Workflow\n\t\t// reads its own `#bail`.\n\t\tthis.#bail = bail ?? snapshot.bail\n\t\tthis.#concurrency = snapshot.concurrency\n\t\tthis.#emitter = new Emitter<PhaseEventMap>({\n\t\t\t...(on === undefined ? {} : { on }),\n\t\t\t...(error === undefined ? {} : { error }),\n\t\t})\n\t\t// Build the live tasks positionally from the snapshot — each wired to recompute THIS phase\n\t\t// on a transition, carrying its own restore state and the once-captured handler for its run.\n\t\tfor (const task of snapshot.tasks) {\n\t\t\tconst taskOptions = tasks?.[task.id]\n\t\t\tconst handler = task.run === undefined ? undefined : handlers.get(task.run)\n\t\t\tthis.#append(task, taskOptions, handler)\n\t\t}\n\t\t// Restore the override DIRECTLY from the snapshot's own field (present only when a whole-\n\t\t// phase skip / stop forced it) — no fragile status-divergence guess. Then seed the baseline\n\t\t// from the EFFECTIVE status so a recompute diffs against the right value.\n\t\tthis.#override = snapshot.override\n\t\tthis.#status = this.status\n\t\tthis.#paused = false\n\t\tthis.#gate = undefined\n\t}\n\n\tget emitter(): EmitterInterface<PhaseEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget id(): string {\n\t\treturn this.#id\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget context(): PhaseContext {\n\t\t// Computed fresh so a renamed phase's context reflects its CURRENT identity — the phase's\n\t\t// own id/name/description plus the live parent workflow context.\n\t\treturn buildPhaseContext(this.#workflow.context, {\n\t\t\tid: this.#id,\n\t\t\tname: this.#name,\n\t\t\t...(this.description === undefined ? {} : { description: this.description }),\n\t\t})\n\t}\n\n\tget workflow(): WorkflowInterface {\n\t\treturn this.#workflow\n\t}\n\n\tget bail(): boolean {\n\t\treturn this.#bail\n\t}\n\n\tget concurrency(): number | undefined {\n\t\treturn this.#concurrency\n\t}\n\n\tget paused(): boolean {\n\t\treturn this.#paused\n\t}\n\n\tget status(): PhaseStatus {\n\t\t// The override wins when forced; otherwise the status is derived from the live tasks.\n\t\treturn this.#override ?? derivePhaseStatus(this.#statuses())\n\t}\n\n\tget tasks(): TaskManagerInterface {\n\t\treturn this.#tasks\n\t}\n\n\ttask(id: string): TaskInterface | undefined {\n\t\treturn this.#tasks.task(id)\n\t}\n\n\tresults(): readonly TaskResult[] {\n\t\t// The phase tier of the result tree — every settled task's recorded result, in positional\n\t\t// order. A `pending` / `running` task (or a forced skip / stop) contributed none.\n\t\tconst results: TaskResult[] = []\n\t\tfor (const task of this.#tasks.tasks()) {\n\t\t\tif (task.result !== undefined) results.push(task.result)\n\t\t}\n\t\treturn results\n\t}\n\n\tskip(): void {\n\t\t// `skip` (AGENTS §10) FORCES the phase to `skipped`, overriding the derived value — then\n\t\t// recompute so the change is detected, emitted, and escalated.\n\t\t// IDEMPOTENT / NO-OP once `status` is already terminal (a settled phase cannot be\n\t\t// re-forced) — but a parked `wait()` waiter is ALWAYS released regardless (a terminal\n\t\t// phase must never hold one; kept unconditional for safety).\n\t\tif (!isTerminalStatus(this.status)) this.#force('skipped')\n\t\tthis.#paused = false\n\t\tthis.#release()\n\t}\n\n\tstop(): void {\n\t\t// `stop` (AGENTS §10) FORCES the phase to `stopped` — same override discipline as `skip`;\n\t\t// `stopped` IS a PhaseEventMap event, so this emit fires. NO-OP once `status` is already\n\t\t// terminal (a settled phase cannot be re-forced). Always releases a parked `wait()`\n\t\t// waiter (AGENTS §10 — a permanently-ended phase has nothing left to pause for), even on\n\t\t// the no-op branch, for safety.\n\t\tif (!isTerminalStatus(this.status)) this.#force('stopped')\n\t\tthis.#paused = false\n\t\tthis.#release()\n\t}\n\n\tpause(): void {\n\t\t// Idempotent: a no-op when already paused or terminal — pausing a settled phase has\n\t\t// nothing to suspend.\n\t\tif (this.#paused || isTerminalStatus(this.status)) return\n\t\tthis.#paused = true\n\t\tthis.#gate = createDeferred<void>()\n\t\tthis.#emitter.emit('pause')\n\t}\n\n\tresume(): void {\n\t\t// Idempotent: a no-op unless currently paused.\n\t\tif (!this.#paused) return\n\t\tthis.#paused = false\n\t\tthis.#release()\n\t\tthis.#emitter.emit('resume')\n\t}\n\n\twait(): Promise<void> {\n\t\t// Promise-parked (AGENTS §21), never a timer or busy-loop — resolves immediately when not\n\t\t// paused; while paused, the shared gate resolves on `resume` / `stop` / `skip`.\n\t\treturn this.#paused && this.#gate !== undefined ? this.#gate.promise : Promise.resolve()\n\t}\n\n\tadd(definition: TaskDefinition, index?: number): Result<TaskInterface, WorkflowError> {\n\t\tconst status = this.status\n\t\tif (isTerminalStatus(status)) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `phase '${this.#id}' is terminal`, {\n\t\t\t\t\tid: this.#id,\n\t\t\t\t\tstatus,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst created = this.#mint(definition)\n\t\tif (status === 'running') {\n\t\t\t// Running: only a pure append is eligible — a live runner subscribed to the `add`\n\t\t\t// event picks the new task up for same-run execution.\n\t\t\tconst at = index ?? this.#tasks.count\n\t\t\tif (at !== this.#tasks.count) {\n\t\t\t\treturn failure(\n\t\t\t\t\tnew WorkflowError(\n\t\t\t\t\t\t'MUTATION',\n\t\t\t\t\t\t`phase '${this.#id}' only accepts an append while executing`,\n\t\t\t\t\t\t{ id: this.#id, index: at },\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn this.#addTo(created, index, at)\n\t\t}\n\t\treturn this.#addTo(created, index, index ?? this.#tasks.count)\n\t}\n\n\tremove(id: string): Result<TaskInterface, WorkflowError> {\n\t\tif (this.status !== 'pending') {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `phase '${this.#id}' is not pending`, {\n\t\t\t\t\tid: this.#id,\n\t\t\t\t\tstatus: this.status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst result = this.#tasks.remove(id)\n\t\tif (result.success) this.#emitter.emit('remove', result.value)\n\t\treturn result\n\t}\n\n\tmove(id: string, index: number): Result<TaskInterface, WorkflowError> {\n\t\tif (this.status !== 'pending') {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `phase '${this.#id}' is not pending`, {\n\t\t\t\t\tid: this.#id,\n\t\t\t\t\tstatus: this.status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst result = this.#tasks.move(id, index)\n\t\tif (result.success) this.#emitter.emit('move', result.value, index)\n\t\treturn result\n\t}\n\n\tupdate(id: string, patch: TaskUpdate): Result<TaskInterface, WorkflowError> {\n\t\tif (this.status !== 'pending') {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `phase '${this.#id}' is not pending`, {\n\t\t\t\t\tid: this.#id,\n\t\t\t\t\tstatus: this.status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst result = this.#tasks.update(id, patch)\n\t\tif (result.success) this.#emitter.emit('update', result.value)\n\t\treturn result\n\t}\n\n\tpatch(value: PhaseUpdate): void {\n\t\t// Defense-in-depth (AGENTS §12): the owning WorkflowInterface.update gates FIRST, so a\n\t\t// direct call here THROWS unless this phase is genuinely `pending`.\n\t\tif (this.status !== 'pending') {\n\t\t\tthrow new WorkflowError('MUTATION', `phase '${this.#id}' can only be patched while pending`, {\n\t\t\t\tid: this.#id,\n\t\t\t\tstatus: this.status,\n\t\t\t})\n\t\t}\n\t\tif (value.name !== undefined) this.#name = value.name\n\t\tif (value.description !== undefined) {\n\t\t\tObject.defineProperty(this, 'description', {\n\t\t\t\tconfigurable: true,\n\t\t\t\tvalue: value.description,\n\t\t\t})\n\t\t}\n\t\tif (value.concurrency !== undefined) this.#concurrency = value.concurrency\n\t\tif (value.bail !== undefined) this.#bail = value.bail\n\t}\n\n\tsnapshot(): PhaseSnapshot {\n\t\t// Pure JSON: identity + the EFFECTIVE status (override-or-derived) + the ACTUAL override\n\t\t// (emitted only when one is in force) + the effective `bail` this phase ran under (always —\n\t\t// a REQUIRED field, like Workflow's) + the concurrency throttle (when set) + the tasks'\n\t\t// snapshots in positional order. Persisting the override + bail + concurrency directly lets a\n\t\t// restore reinstate them without guessing from a divergence.\n\t\treturn {\n\t\t\tid: this.id,\n\t\t\tname: this.name,\n\t\t\t...(this.description === undefined ? {} : { description: this.description }),\n\t\t\tstatus: this.status,\n\t\t\t...(this.#override === undefined ? {} : { override: this.#override }),\n\t\t\tbail: this.#bail,\n\t\t\t...(this.#concurrency === undefined ? {} : { concurrency: this.#concurrency }),\n\t\t\ttasks: this.#tasks.tasks().map((task) => task.snapshot()),\n\t\t}\n\t}\n\n\t// Recompute the derived status after a child transition (the callback wired into each Task):\n\t// diff the new effective status against the baseline; on a CHANGE, advance the baseline, emit\n\t// the matching event, and escalate to the workflow. An override pins the status, so a forced\n\t// phase ignores further child churn. The phase event precedes the parent effect.\n\t#recompute(): void {\n\t\tconst next = this.status\n\t\tif (next === this.#status) {\n\t\t\t// No phase-level change, but a child still transitioned — escalate so the workflow can\n\t\t\t// re-derive (its own diff decides whether the workflow itself changed + emits).\n\t\t\tthis.#escalateUp()\n\t\t\treturn\n\t\t}\n\t\tthis.#status = next\n\t\tif (isTerminalStatus(next)) {\n\t\t\tthis.#paused = false\n\t\t\tthis.#release()\n\t\t}\n\t\tthis.#emitFor(next)\n\t\tthis.#escalateUp()\n\t}\n\n\t// Apply a forced status (skip / stop): set the override, then recompute so the change is\n\t// detected, emitted (when the status maps to an event), and escalated.\n\t#force(status: PhaseStatus): void {\n\t\tthis.#override = status\n\t\tthis.#recompute()\n\t}\n\n\t// Emit the PhaseEventMap event matching a newly-entered status. `running` ⇒ `start`,\n\t// `completed` ⇒ `complete`, `failed` ⇒ `fail` (with the failing task's result), `stopped`\n\t// ⇒ `stop`, `skipped` ⇒ `skip`. `pending` has no event.\n\t#emitFor(status: PhaseStatus): void {\n\t\tif (status === 'running') this.#emitter.emit('start', this.id)\n\t\telse if (status === 'completed') this.#emitter.emit('complete')\n\t\telse if (status === 'failed') this.#emitter.emit('fail', this.#failure())\n\t\telse if (status === 'skipped') this.#emitter.emit('skip')\n\t\telse if (status === 'stopped') this.#emitter.emit('stop')\n\t}\n\n\t// The failing task's REAL recorded {@link TaskResult} — the first task whose result is a\n\t// Failure — so the `fail` event carries the true cause. A phase derives `failed` ONLY when a\n\t// child failed with a `Failure` result, so one always exists when `#emitFor('failed')` calls\n\t// this: assert that invariant (§12 programmer-error guard, mirroring `Runner.#dispatch`) rather\n\t// than fabricating a synthetic result — a fake, lineage-degenerate `TaskResult` would mask the\n\t// true cause while still type-checking.\n\t#failure(): TaskResult {\n\t\tconst found = findFailure(this.results())\n\t\tif (found === undefined) {\n\t\t\tthrow new Error(`phase '${this.id}' derived failed with no failing task result`)\n\t\t}\n\t\treturn found\n\t}\n\n\t// Resolve the parked `wait()` gate (when one exists) and clear it — the shared release step\n\t// behind `resume` / `stop` / `skip` (all three always release a parked waiter).\n\t#release(): void {\n\t\tif (this.#gate === undefined) return\n\t\tthis.#gate.resolve()\n\t\tthis.#gate = undefined\n\t}\n\n\t// Delegate an `add` to the task manager and emit `add` (the inserted task + its final\n\t// `at` index) on success — the shared tail of the hooked and un-hooked `add` branches.\n\t#addTo(\n\t\ttask: TaskInterface,\n\t\tindex: number | undefined,\n\t\tat: number,\n\t): Result<TaskInterface, WorkflowError> {\n\t\tconst result = this.#tasks.add(task, index)\n\t\tif (result.success) this.#emitter.emit('add', result.value, at)\n\t\treturn result\n\t}\n\n\t// Build one live task from its snapshot, threading its per-task options (its own `on` /\n\t// `metadata`, keyed by id under the phase options) and its restore state (including its\n\t// declarative `run` / `retries` / `timeout`), then append it.\n\t#append(\n\t\ttask: TaskSnapshot,\n\t\toptions: TaskOptions | undefined,\n\t\thandler: WorkflowFunction | undefined,\n\t): void {\n\t\tconst created = this.#create(task, options, handler)\n\t\tthis.#tasks.append(created)\n\t}\n\n\t// Build one live task wired to THIS phase — the shared construction step behind both\n\t// `#append` (build-time wiring, from a TaskSnapshot's restore state) and `#mint` (a live\n\t// `add`, from a freshly-converted TaskDefinition snapshot) — so a mint and a built/restored\n\t// task are wired IDENTICALLY (recompute cascade, emitter hooks, context stamping). The caller\n\t// supplies the once-resolved runtime handler for the construction moment it owns.\n\t#create(\n\t\tsnapshot: TaskSnapshot,\n\t\toptions: TaskOptions | undefined,\n\t\thandler: WorkflowFunction | undefined,\n\t): Task {\n\t\tconst context = buildTaskContext(this.context, snapshot)\n\t\treturn new Task(\n\t\t\tcontext,\n\t\t\tthis,\n\t\t\tthis.#workflow,\n\t\t\t() => this.#recompute(),\n\t\t\toptions,\n\t\t\tsnapshot.status,\n\t\t\tsnapshot.result,\n\t\t\tsnapshot.run,\n\t\t\tsnapshot.retries,\n\t\t\tsnapshot.timeout,\n\t\t\tsnapshot.metadata,\n\t\t\tsnapshot.attempts,\n\t\t\tsnapshot.activity,\n\t\t\thandler,\n\t\t\tthis.#silence,\n\t\t)\n\t}\n\n\t// MINT a live task from a TaskDefinition for a live `add` — converts it to an initial\n\t// TaskSnapshot (definitionToSnapshot's per-task step, carrying its `run` / `retries` /\n\t// `timeout`) then resolves its handler once against the retained registry for this live mint.\n\t#mint(definition: TaskDefinition): Task {\n\t\tconst snapshot = taskDefinitionToSnapshot(definition)\n\t\tconst handler = snapshot.run === undefined ? undefined : this.#functions?.[snapshot.run]\n\t\treturn this.#create(snapshot, undefined, handler)\n\t}\n\n\t// The live tasks' statuses, in positional order — the input to `derivePhaseStatus`.\n\t#statuses(): readonly PhaseStatus[] {\n\t\treturn this.#tasks.tasks().map((task) => task.status)\n\t}\n}\n","import type { Result } from '@orkestrel/contract'\nimport type { PhaseInterface, PhaseManagerInterface, PhaseUpdate } from '../types.js'\nimport { compileGuard } from '@orkestrel/contract'\nimport { WorkflowError } from '../errors.js'\nimport { failure, insertEntry, moveEntry, success } from '../helpers.js'\nimport { phaseUpdateShape } from '../shapers.js'\n\n/**\n * The lean child manager (AGENTS §9) of a {@link import('../Workflow.js').Workflow}'s\n * live phases — an insertion-ordered registry keyed by phase `id`, the phase analogue\n * of {@link import('../tasks/TaskManager.js').TaskManager}.\n *\n * @remarks\n * - **Positional store.** Phases live in an insertion-ordered `Map` keyed by `id`;\n * `append` adds one at the end, `phase(id)` looks one up, `phases()` lists them in\n * positional order, `count` is the size. A snapshot RESTORE re-`append`s in the\n * snapshot's order, reproducing it exactly.\n * - **Gated mutation API (AGENTS §12).** `add` / `remove` / `move` / `update` are the\n * graceful `Result` counterparts to `append`, gating ONLY on the target's OWN\n * existence/status/id/bounds — a duplicate id, an absent/non-`pending` target, an\n * out-of-bounds `index`, or a patch that fails {@link phaseUpdateShape} validation\n * all fail gracefully with a `MUTATION` {@link WorkflowError} instead of throwing.\n * - **No batch matrix.** A workflow's phases are a fixed positional set, so AGENTS §9.2\n * is deliberately omitted.\n * - **Event-free.** A purely structural container — the live {@link PhaseInterface}s own\n * their own emitters.\n *\n * @example\n * ```ts\n * const phases = new PhaseManager()\n * phases.append(phase) // a live Phase\n * phases.phase(phase.id) // the same phase\n * phases.count // 1\n * ```\n */\nexport class PhaseManager implements PhaseManagerInterface {\n\treadonly #phases = new Map<string, PhaseInterface>()\n\t// The compiled guard validating a `PhaseUpdate` patch (AGENTS §14) before it reaches\n\t// `update`'s `phase.patch` call.\n\treadonly #isUpdate = compileGuard(phaseUpdateShape)\n\n\tget count(): number {\n\t\treturn this.#phases.size\n\t}\n\n\tappend(phase: PhaseInterface): void {\n\t\tif (this.#phases.has(phase.id)) {\n\t\t\tthrow new WorkflowError('MUTATION', `duplicate phase id '${phase.id}'`, { id: phase.id })\n\t\t}\n\t\tthis.#phases.set(phase.id, phase)\n\t}\n\n\tadd(phase: PhaseInterface, index?: number): Result<PhaseInterface, WorkflowError> {\n\t\tif (this.#phases.has(phase.id)) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `duplicate phase id '${phase.id}'`, { id: phase.id }),\n\t\t\t)\n\t\t}\n\t\tconst at = index ?? this.#phases.size\n\t\tif (at < 0 || at > this.#phases.size) {\n\t\t\treturn failure(new WorkflowError('MUTATION', `index '${at}' out of bounds`, { index: at }))\n\t\t}\n\t\tthis.#reorder(insertEntry([...this.#phases.entries()], at, phase.id, phase))\n\t\treturn success(phase)\n\t}\n\n\tremove(id: string): Result<PhaseInterface, WorkflowError> {\n\t\tconst target = this.#phases.get(id)\n\t\tif (target === undefined || target.status !== 'pending') {\n\t\t\treturn failure(new WorkflowError('MUTATION', `phase '${id}' is not a pending phase`, { id }))\n\t\t}\n\t\tthis.#phases.delete(id)\n\t\treturn success(target)\n\t}\n\n\tmove(id: string, index: number): Result<PhaseInterface, WorkflowError> {\n\t\tconst target = this.#phases.get(id)\n\t\tif (target === undefined || target.status !== 'pending') {\n\t\t\treturn failure(new WorkflowError('MUTATION', `phase '${id}' is not a pending phase`, { id }))\n\t\t}\n\t\tif (index < 0 || index >= this.#phases.size) {\n\t\t\treturn failure(new WorkflowError('MUTATION', `index '${index}' out of bounds`, { index }))\n\t\t}\n\t\tthis.#reorder(moveEntry([...this.#phases.entries()], id, index))\n\t\treturn success(target)\n\t}\n\n\tupdate(id: string, patch: PhaseUpdate): Result<PhaseInterface, WorkflowError> {\n\t\tconst target = this.#phases.get(id)\n\t\tif (target === undefined || target.status !== 'pending') {\n\t\t\treturn failure(new WorkflowError('MUTATION', `phase '${id}' is not a pending phase`, { id }))\n\t\t}\n\t\tif (!this.#isUpdate(patch)) {\n\t\t\treturn failure(new WorkflowError('MUTATION', `invalid patch for phase '${id}'`, { id }))\n\t\t}\n\t\ttarget.patch(patch)\n\t\treturn success(target)\n\t}\n\n\tphase(id: string): PhaseInterface | undefined {\n\t\treturn this.#phases.get(id)\n\t}\n\n\tphases(): readonly PhaseInterface[] {\n\t\treturn [...this.#phases.values()]\n\t}\n\n\t// Rebuild the positional store from `entries` — the shared reorder step behind\n\t// `add` (insert) and `move` (reposition), keeping the `Map`'s insertion order the\n\t// single source of positional truth.\n\t#reorder(entries: ReadonlyArray<readonly [string, PhaseInterface]>): void {\n\t\tthis.#phases.clear()\n\t\tfor (const [key, value] of entries) this.#phases.set(key, value)\n\t}\n}\n","import type { Result } from '@orkestrel/contract'\nimport type { AbortInterface } from '@orkestrel/abort'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tDeferredInterface,\n\tPhaseDefinition,\n\tPhaseDerivation,\n\tPhaseInterface,\n\tPhaseManagerInterface,\n\tPhaseOptions,\n\tPhaseSnapshot,\n\tPhaseUpdate,\n\tTaskResult,\n\tWorkflowContext,\n\tWorkflowEventMap,\n\tWorkflowFunctions,\n\tWorkflowInterface,\n\tWorkflowOptions,\n\tWorkflowSnapshot,\n\tWorkflowStatus,\n} from './types.js'\nimport { createAbort } from '@orkestrel/abort'\nimport { Emitter } from '@orkestrel/emitter'\nimport { cloneWorkflowSnapshot } from './cloners.js'\nimport { WorkflowError } from './errors.js'\nimport {\n\tbuildWorkflowContext,\n\tcaptureWorkflowOptions,\n\tcollectResults,\n\tcreateDeferred,\n\tderiveBoundary,\n\tderiveWorkflowStatus,\n\tfailure,\n\tfindFailure,\n\tisTerminalStatus,\n\tphaseDefinitionToSnapshot,\n} from './helpers.js'\nimport { Phase } from './phases/Phase.js'\nimport { PhaseManager } from './phases/PhaseManager.js'\n\n/**\n * The live DERIVED state machine (W-b) for a whole workflow — the observable (AGENTS §13)\n * ROOT whose {@link WorkflowStatus} is computed from its phases under the `bail` policy and\n * recomputed reactively as the cascade propagates up from a task transition.\n *\n * @remarks\n * - **Construction.** Built from a {@link WorkflowSnapshot} (the unified input —\n * {@link import('./factories.js').createWorkflow} seeds an initial snapshot from a\n * {@link import('./types.js').WorkflowDefinition}, {@link import('./factories.js').createRestoredWorkflow}\n * passes a persisted one). Each child {@link Phase} is wired to escalate to `#recompute`.\n * - **Derived status.** `status` is `#override` when forced, else\n * {@link deriveWorkflowStatus} over the live phases' statuses feeding `bail`. `failed` is\n * reachable ONLY under `bail: true` (a single failed task halts the workflow); under\n * `bail: false` a failed phase folds into `completed`. `#recompute` diffs on each phase\n * change; a CHANGE emits.\n * - **Override (AGENTS §10).** `skip` / `stop` FORCE the status; an executed task-free pending tree\n * may also be force-completed vacuously. The override is PERSISTED in the snapshot's own\n * `override` field and restored DIRECTLY (no divergence guess). The snapshot also persists\n * `bail`, so a restore re-derives status identically without a silent policy default.\n * - **Result tree.** `results()` flattens every phase's `results()` ({@link collectResults}) — the\n * workflow tier; `phase(id)` + each `phase.task(id)` navigate DOWN, a task's `phase` / `workflow`\n * navigate UP.\n * - **Snapshot.** `snapshot()` serializes the whole live tree to a {@link WorkflowSnapshot} (pure\n * JSON); {@link import('./factories.js').createRestoredWorkflow} rebuilds an equivalent live tree.\n * - **Observable (AGENTS §13).** The owned {@link emitter} ({@link WorkflowEventMap}) fires\n * `start` / `complete` / `fail` / `pause` / `resume` / `skip` / `stop` after the\n * corresponding status or runtime-gate change; the emitter isolates a listener throw and\n * routes it to its `error` handler (the `error` option); `fail` carries the failing task's\n * {@link TaskResult}.\n * - **Structural API (AGENTS §7).** `add` / `remove` / `move` / `update` gate BEFORE\n * delegating to {@link phases} (the manager gates the target's own existence/status/id/\n * bounds), then emit the matching {@link WorkflowEventMap} event on success only. NATIVE,\n * bottom-up gating (no runner-installed hook): refused outright while this workflow's own\n * `status` is terminal; otherwise a target position must fall within the PENDING SUFFIX —\n * the contiguous trailing run of `pending` phases — whose boundary is\n * {@link import('./helpers.js').deriveBoundary} over the live phases' statuses. A `pending`\n * workflow's phases are all `pending`, so the boundary is `0` and every position is\n * naturally accepted.\n * - **Runtime lifecycle (AGENTS §10).** `pause` / `resume` / `wait` gate execution at the runner's\n * phase/task boundaries WITHOUT touching {@link status} — `paused` is runtime-only, never\n * persisted. `destroy` is a terminal teardown: it `stop`s every non-terminal task and\n * phase (releasing their gates and liveness resources), aborts {@link signal}, forces the\n * workflow `stop` override when needed, releases its parked waiter, and marks\n * {@link destroyed} — all idempotent.\n */\nexport class Workflow implements WorkflowInterface {\n\tdeclare readonly description?: string\n\treadonly #context: WorkflowContext\n\treadonly #bail: boolean\n\t// The EXPLICIT workflow `bail` override (`options.bail`), when one was supplied — a deliberate\n\t// \"re-run the whole tree under THIS uniform policy\" knob threaded down to each phase so it\n\t// overrides the phase's persisted per-phase bail. `undefined` ⇒ no override (each phase keeps its\n\t// own persisted policy, so an option-less restore is identical). Distinct from `#bail` (the\n\t// resolved default), which is ALWAYS defined.\n\treadonly #bailOverride: boolean | undefined\n\t// The `function`-task behavior registry each live task's `run` name resolves against ONCE at\n\t// construction — threaded to every Phase (and, transitively, every Task). Read at RESOLVE\n\t// time (construction / a later live `add`'s mint), so mutating the object passed in AFTER\n\t// construction changes only later mints, never tasks already resolved — do not mutate it.\n\treadonly #functions: WorkflowFunctions | undefined\n\treadonly #silence: number | undefined\n\treadonly #phases: PhaseManager = new PhaseManager()\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), never the cascade.\n\treadonly #emitter: Emitter<WorkflowEventMap>\n\t// Creation / update stamps carried verbatim through a snapshot round-trip.\n\treadonly #created: number\n\t#updated: number\n\t// The last computed status — the baseline a recompute diffs against to detect a CHANGE.\n\t#status: WorkflowStatus\n\t// The forced status of `skip` / `stop` or vacuous completion; `undefined` ⇒ derived.\n\t#override: WorkflowStatus | undefined\n\t// This workflow's own cancellation handle (AGENTS core precedent) — `signal` fires on `destroy`.\n\treadonly #abort: AbortInterface\n\t// RUNTIME-ONLY (never persisted): whether the workflow is currently paused.\n\t#paused: boolean\n\t// The parked `wait()` gate while paused; `undefined` when not paused — released (resolved) by\n\t// `resume` / `stop` / `destroy`.\n\t#gate: DeferredInterface<void> | undefined\n\t// RUNTIME-ONLY (never persisted): whether `destroy` has torn this workflow down.\n\t#destroyed: boolean\n\n\tconstructor(snapshot: WorkflowSnapshot, options?: WorkflowOptions) {\n\t\tconst captured = captureWorkflowOptions(options)\n\t\tconst on = captured.on\n\t\tconst bail = captured.bail\n\t\tconst error = captured.error\n\t\tconst phases = captured.phases\n\t\tconst functions = captured.functions\n\t\tconst silence = captured.silence\n\t\tthis.#context = buildWorkflowContext(snapshot)\n\t\tif (snapshot.description !== undefined) {\n\t\t\tObject.defineProperty(this, 'description', { value: snapshot.description })\n\t\t}\n\t\t// The snapshot carries the policy it ran under (the self-contained durable payload), so the\n\t\t// snapshot's `bail` is the source of truth; an explicit `options.bail` still wins when given.\n\t\tthis.#bail = bail ?? snapshot.bail\n\t\t// The explicit override (only when supplied) — cascaded to every phase so it overrides their\n\t\t// persisted per-phase bail; omitted ⇒ each phase keeps its own persisted policy (identical restore).\n\t\tthis.#bailOverride = bail\n\t\tthis.#functions = functions\n\t\tthis.#silence = silence\n\t\tthis.#emitter = new Emitter<WorkflowEventMap>({\n\t\t\t...(on === undefined ? {} : { on }),\n\t\t\t...(error === undefined ? {} : { error }),\n\t\t})\n\t\tthis.#created = snapshot.created\n\t\tthis.#updated = snapshot.updated\n\t\tthis.#abort = createAbort()\n\t\tthis.#paused = false\n\t\tthis.#gate = undefined\n\t\tthis.#destroyed = false\n\t\t// Build the live phases positionally from the snapshot — each wired to recompute THIS\n\t\t// workflow on a derived-status change, carrying its own per-phase options + restore state,\n\t\t// and the workflow-level `#functions` registry, so each of its tasks resolves its `run`\n\t\t// name into a runtime handler ONCE at construction.\n\t\tfor (const phase of snapshot.phases) {\n\t\t\tconst phaseOptions = phases?.[phase.id]\n\t\t\tthis.#append(phase, phaseOptions)\n\t\t}\n\t\t// Restore the override DIRECTLY from the snapshot's own field (present when whole-workflow\n\t\t// skip / stop or vacuous completion forced it) — no fragile status-divergence guess. Then\n\t\t// seed the baseline from the EFFECTIVE status so a recompute diffs against the right value.\n\t\tthis.#override = snapshot.override\n\t\tthis.#status = this.status\n\t}\n\n\tget emitter(): EmitterInterface<WorkflowEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget id(): string {\n\t\treturn this.#context.id\n\t}\n\n\tget name(): string {\n\t\treturn this.#context.name\n\t}\n\n\tget context(): WorkflowContext {\n\t\treturn this.#context\n\t}\n\n\tget bail(): boolean {\n\t\treturn this.#bail\n\t}\n\n\tget paused(): boolean {\n\t\treturn this.#paused\n\t}\n\n\tget destroyed(): boolean {\n\t\treturn this.#destroyed\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.#abort.signal\n\t}\n\n\tget status(): WorkflowStatus {\n\t\t// The override wins when forced; otherwise the status is derived from the live phases'\n\t\t// derivations — each phase's status paired with the EFFECTIVE `bail` it ran under, so the\n\t\t// failure outcome is per-phase-bail-aware (a strict phase halts even under a graceful workflow).\n\t\treturn this.#override ?? deriveWorkflowStatus(this.#statuses())\n\t}\n\n\tget phases(): PhaseManagerInterface {\n\t\treturn this.#phases\n\t}\n\n\tphase(id: string): PhaseInterface | undefined {\n\t\treturn this.#phases.phase(id)\n\t}\n\n\tresults(): readonly TaskResult[] {\n\t\t// The workflow tier of the result tree — every settled task's result across all phases, in\n\t\t// positional order (phases in order, each phase's task results in order).\n\t\treturn collectResults(this.#phases.phases().map((phase) => phase.results()))\n\t}\n\n\tskip(): void {\n\t\t// `skip` (AGENTS §10) FORCES the workflow to `skipped`, overriding the derived value — then\n\t\t// recompute so the change is detected and the `skip` event is emitted. IDEMPOTENT /\n\t\t// NO-OP once `status` is already terminal (a settled workflow cannot be re-forced) — but a\n\t\t// parked `wait()` waiter is ALWAYS released regardless (a terminal workflow must never hold\n\t\t// one; kept unconditional for safety even though a terminal entity should have none parked).\n\t\tif (!isTerminalStatus(this.status)) this.#force('skipped')\n\t\tthis.#paused = false\n\t\tthis.#release()\n\t}\n\n\tstop(): void {\n\t\t// `stop` (AGENTS §10) FORCES the workflow to `stopped` — `stopped` IS a WorkflowEventMap\n\t\t// event, so this emit fires. NO-OP once `status` is already terminal (mirrors `skip` and\n\t\t// `destroy`'s own `if (!isTerminalStatus(...))` guard) — a settled workflow cannot be\n\t\t// re-forced. Always releases a parked `wait()` waiter (AGENTS §10 — a permanently-ended\n\t\t// workflow has nothing left to pause for), even on the no-op branch, for safety.\n\t\tif (!isTerminalStatus(this.status)) this.#force('stopped')\n\t\tthis.#paused = false\n\t\tthis.#release()\n\t}\n\n\tcomplete(): void {\n\t\t// Forces the workflow to `completed` (overriding the derived value), reusing the same #force\n\t\t// override machinery as skip/stop. `completed` IS a WorkflowEventMap event, so the emit fires.\n\t\t// Used by the runner to settle an EXECUTED no-op tree (no work happened ⇒ vacuously done) —\n\t\t// its ONLY legitimate use, so this is a NO-OP unless `status` is still `pending` AND the\n\t\t// whole tree contains no tasks. Empty phases remain vacuous; any pending task is real work\n\t\t// and cannot be erased by a root override.\n\t\tif (\n\t\t\tthis.status === 'pending' &&\n\t\t\tthis.#phases.phases().every((phase) => phase.tasks.count === 0)\n\t\t) {\n\t\t\tthis.#force('completed')\n\t\t}\n\t}\n\n\tpause(): void {\n\t\t// Idempotent: a no-op when already paused, terminal, or destroyed — pausing a settled or\n\t\t// torn-down workflow has nothing to suspend.\n\t\tif (this.#paused || isTerminalStatus(this.status) || this.#destroyed) return\n\t\tthis.#paused = true\n\t\tthis.#gate = createDeferred<void>()\n\t\tthis.#emitter.emit('pause')\n\t}\n\n\tresume(): void {\n\t\t// Idempotent: a no-op unless currently paused.\n\t\tif (!this.#paused) return\n\t\tthis.#paused = false\n\t\tthis.#release()\n\t\tthis.#emitter.emit('resume')\n\t}\n\n\tdestroy(): void {\n\t\t// Idempotent terminal teardown — calling `destroy` twice never throws.\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tconst phases = this.#phases.phases()\n\t\tif (!isTerminalStatus(this.status)) this.stop()\n\t\tfor (const phase of phases) phase.stop()\n\t\tfor (const phase of phases) {\n\t\t\tfor (const task of phase.tasks.tasks()) {\n\t\t\t\tif (!isTerminalStatus(task.status)) task.stop()\n\t\t\t}\n\t\t}\n\t\tthis.#paused = false\n\t\tthis.#release()\n\t\tthis.#abort.abort()\n\t\tfor (const phase of phases) {\n\t\t\tfor (const task of phase.tasks.tasks()) task.emitter.destroy()\n\t\t\tphase.emitter.destroy()\n\t\t}\n\t\tthis.#emitter.destroy()\n\t}\n\n\twait(): Promise<void> {\n\t\t// Promise-parked (AGENTS §21), never a timer or busy-loop — resolves immediately when not\n\t\t// paused; while paused, the shared gate resolves on `resume` / `skip` / `stop` / `destroy`.\n\t\treturn this.#paused && this.#gate !== undefined ? this.#gate.promise : Promise.resolve()\n\t}\n\n\tadd(definition: PhaseDefinition, index?: number): Result<PhaseInterface, WorkflowError> {\n\t\tif (isTerminalStatus(this.status)) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `workflow '${this.id}' is terminal`, {\n\t\t\t\t\tid: this.id,\n\t\t\t\t\tstatus: this.status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst at = index ?? this.#phases.count\n\t\tif (at < this.#boundary()) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `workflow '${this.id}' add index precedes boundary`, {\n\t\t\t\t\tid: this.id,\n\t\t\t\t\tindex: at,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\treturn this.#addTo(this.#mint(definition), index, at)\n\t}\n\n\tremove(id: string): Result<PhaseInterface, WorkflowError> {\n\t\tif (isTerminalStatus(this.status)) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `workflow '${this.id}' is terminal`, {\n\t\t\t\t\tid: this.id,\n\t\t\t\t\tstatus: this.status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst at = this.#indexOf(id)\n\t\tif (at === -1 || at < this.#boundary()) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `workflow '${this.id}' cannot remove '${id}'`, {\n\t\t\t\t\tid: this.id,\n\t\t\t\t\tphase: id,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst result = this.#phases.remove(id)\n\t\tif (result.success) this.#emitter.emit('remove', result.value)\n\t\treturn result\n\t}\n\n\tmove(id: string, index: number): Result<PhaseInterface, WorkflowError> {\n\t\tif (isTerminalStatus(this.status)) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `workflow '${this.id}' is terminal`, {\n\t\t\t\t\tid: this.id,\n\t\t\t\t\tstatus: this.status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst at = this.#indexOf(id)\n\t\tconst boundary = this.#boundary()\n\t\tif (at === -1 || at < boundary || index < boundary) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `workflow '${this.id}' cannot move '${id}'`, {\n\t\t\t\t\tid: this.id,\n\t\t\t\t\tphase: id,\n\t\t\t\t\tindex,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst result = this.#phases.move(id, index)\n\t\tif (result.success) this.#emitter.emit('move', result.value, index)\n\t\treturn result\n\t}\n\n\tupdate(id: string, patch: PhaseUpdate): Result<PhaseInterface, WorkflowError> {\n\t\tif (isTerminalStatus(this.status)) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `workflow '${this.id}' is terminal`, {\n\t\t\t\t\tid: this.id,\n\t\t\t\t\tstatus: this.status,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst at = this.#indexOf(id)\n\t\tif (at === -1 || at < this.#boundary()) {\n\t\t\treturn failure(\n\t\t\t\tnew WorkflowError('MUTATION', `workflow '${this.id}' cannot update '${id}'`, {\n\t\t\t\t\tid: this.id,\n\t\t\t\t\tphase: id,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst result = this.#phases.update(id, patch)\n\t\tif (result.success) this.#emitter.emit('update', result.value)\n\t\treturn result\n\t}\n\n\tsnapshot(): WorkflowSnapshot {\n\t\t// Pure JSON: identity + the EFFECTIVE status + the ACTUAL override (emitted only when one is\n\t\t// in force) + the `bail` policy this tree ran under + the phases' snapshots in positional\n\t\t// order + the creation / update stamps. Persisting `override` and `bail` makes the payload\n\t\t// self-contained, so a restore reinstates the override directly and re-derives identically.\n\t\treturn cloneWorkflowSnapshot({\n\t\t\tid: this.id,\n\t\t\tname: this.name,\n\t\t\t...(this.description === undefined ? {} : { description: this.description }),\n\t\t\tstatus: this.status,\n\t\t\t...(this.#override === undefined ? {} : { override: this.#override }),\n\t\t\tbail: this.#bail,\n\t\t\tphases: this.#phases.phases().map((phase) => phase.snapshot()),\n\t\t\tcreated: this.#created,\n\t\t\tupdated: this.#updated,\n\t\t})\n\t}\n\n\t// The top of the cascade: recompute the derived status after a phase change (the callback\n\t// wired into each Phase). Diff the new effective status against the baseline; on a CHANGE,\n\t// advance the baseline + the `updated` stamp, then emit the matching event. The workflow is\n\t// the root, so there is nothing further to escalate to.\n\t#recompute(): void {\n\t\tconst next = this.status\n\t\tif (next === this.#status) return\n\t\tthis.#status = next\n\t\tif (isTerminalStatus(next)) {\n\t\t\tthis.#paused = false\n\t\t\tthis.#release()\n\t\t}\n\t\tthis.#updated = Math.max(Date.now(), this.#updated)\n\t\tthis.#emitFor(next)\n\t}\n\n\t// Apply a forced status (skip / stop / vacuous complete): set the override, then recompute so\n\t// the change is detected + emitted (when the status maps to an event).\n\t#force(status: WorkflowStatus): void {\n\t\tthis.#override = status\n\t\tthis.#recompute()\n\t}\n\n\t// Emit the WorkflowEventMap event matching a newly-entered status. `running` ⇒ `start`,\n\t// `completed` ⇒ `complete`, `failed` ⇒ `fail` (with the failing task's result, reachable only\n\t// under `bail: true`), `skipped` ⇒ `skip`, `stopped` ⇒ `stop`. `pending` has no event.\n\t#emitFor(status: WorkflowStatus): void {\n\t\tif (status === 'running') this.#emitter.emit('start', this.id)\n\t\telse if (status === 'completed') this.#emitter.emit('complete')\n\t\telse if (status === 'failed') this.#emitter.emit('fail', this.#failure())\n\t\telse if (status === 'skipped') this.#emitter.emit('skip')\n\t\telse if (status === 'stopped') this.#emitter.emit('stop')\n\t}\n\n\t// Delegate an `add` to the phase manager and emit `add` (the inserted phase + its final\n\t// `at` index) on success — the shared tail of the hooked and un-hooked `add` branches.\n\t#addTo(\n\t\tphase: PhaseInterface,\n\t\tindex: number | undefined,\n\t\tat: number,\n\t): Result<PhaseInterface, WorkflowError> {\n\t\tconst result = this.#phases.add(phase, index)\n\t\tif (result.success) this.#emitter.emit('add', result.value, at)\n\t\treturn result\n\t}\n\n\t// The positional index of the live phase `id`, or `-1` when absent — the shared lookup\n\t// behind the NATIVE `remove` / `move` / `update` boundary gate.\n\t#indexOf(id: string): number {\n\t\treturn this.#phases.phases().findIndex((phase) => phase.id === id)\n\t}\n\n\t// The NATIVE pending-suffix boundary over the live phases' CURRENT statuses — reads\n\t// instance state, so it stays a method; the pure reduction itself is `deriveBoundary`.\n\t#boundary(): number {\n\t\treturn deriveBoundary(this.#phases.phases().map((phase) => phase.status))\n\t}\n\n\t// The failing task's REAL recorded {@link TaskResult} — the first failed result across every\n\t// phase — so the `fail` event carries the true cause. A workflow derives `failed` ONLY under\n\t// `bail` when some task failed with a `Failure` result, so one always exists when\n\t// `#emitFor('failed')` calls this: assert that invariant (§12 programmer-error guard, mirroring\n\t// `Runner.#dispatch`) rather than fabricating a synthetic, lineage-degenerate result that would\n\t// mask the true cause while still type-checking.\n\t#failure(): TaskResult {\n\t\tconst found = findFailure(this.results())\n\t\tif (found === undefined) {\n\t\t\tthrow new Error(`workflow '${this.id}' derived failed with no failing task result`)\n\t\t}\n\t\treturn found\n\t}\n\n\t// Build one live phase from its snapshot, threading its per-phase options (keyed by id under\n\t// the workflow options) + the explicit workflow bail override (when one was supplied — it\n\t// overrides the phase's persisted per-phase bail) + THIS workflow's `#functions` registry\n\t// (so the phase's own tasks resolve their `run` name into a runtime handler) and wiring it\n\t// to recompute THIS workflow on a derived-status change.\n\t#append(phase: PhaseSnapshot, options: PhaseOptions | undefined): void {\n\t\tconst created = new Phase(\n\t\t\tphase,\n\t\t\tthis,\n\t\t\t() => this.#recompute(),\n\t\t\toptions,\n\t\t\tthis.#bailOverride,\n\t\t\tthis.#functions,\n\t\t\tthis.#silence,\n\t\t)\n\t\tthis.#phases.append(created)\n\t}\n\n\t// MINT a live phase (and its tasks) from a PhaseDefinition for a live `add` — converts it to\n\t// an initial PhaseSnapshot (`phaseDefinitionToSnapshot`'s per-phase step, resolving effective\n\t// bail as `definition.bail ?? this.#bail`, carrying each task's `run` / `retries` / `timeout`)\n\t// then builds it via the Phase constructor's OWN `#functions` resolution, so a live mint and a\n\t// built/restored phase are wired IDENTICALLY — same recompute cascade, same emitter hooks,\n\t// same handler resolution.\n\t#mint(definition: PhaseDefinition): Phase {\n\t\treturn new Phase(\n\t\t\tphaseDefinitionToSnapshot(definition, this.#bail),\n\t\t\tthis,\n\t\t\t() => this.#recompute(),\n\t\t\tundefined,\n\t\t\tthis.#bailOverride,\n\t\t\tthis.#functions,\n\t\t\tthis.#silence,\n\t\t)\n\t}\n\n\t// Resolve the parked `wait()` gate (when one exists) and clear it — the shared release step\n\t// behind `resume` / `stop` / `destroy` (all three always release a parked waiter).\n\t#release(): void {\n\t\tif (this.#gate === undefined) return\n\t\tthis.#gate.resolve()\n\t\tthis.#gate = undefined\n\t}\n\n\t// The live phases' derivations, in positional order — each phase's status paired with its\n\t// EFFECTIVE `bail` (phase override or the workflow default) — the input to\n\t// `deriveWorkflowStatus` (per-phase-bail-aware).\n\t#statuses(): readonly PhaseDerivation[] {\n\t\treturn this.#phases.phases().map((phase) => ({ status: phase.status, bail: phase.bail }))\n\t}\n}\n","import type {\n\tWorkflowDefinition,\n\tWorkflowFunctions,\n\tWorkflowInterface,\n\tWorkflowManagerInterface,\n\tWorkflowManagerOptions,\n\tWorkflowSnapshot,\n\tWorkflowStoreInterface,\n} from './types.js'\nimport { isArray } from '@orkestrel/contract'\nimport { cloneWorkflowSnapshot } from './cloners.js'\nimport { createRestoredWorkflow, createWorkflow } from './factories.js'\n\n/**\n * The store-backed registry of {@link WorkflowInterface}s keyed by `id`, in insertion order —\n * the additive manager tier mirroring the `@orkestrel/agent` line's `ConversationManager` /\n * `WorkspaceManager`. Event-free (a registry, like its twins); the observability lives on each\n * {@link WorkflowInterface}.\n *\n * @remarks\n * - **Registry.** Workflows live in an insertion-ordered `Map` keyed by `id`. `add(definition)`\n * mints a live {@link WorkflowInterface} through {@link createWorkflow} (flowing the manager's\n * `functions` registry in) and stores it under `definition.id` — an already-present id\n * OVERWRITES (last write wins). `count` is the map size, `workflow(id)` looks one up,\n * `workflows()` lists them in insertion order.\n * - **Durable open / save.** `open(id)` returns an already-registered workflow directly; same-id\n * misses share one hydration. A concurrent `add` wins, while `remove` / `clear` invalidate\n * earlier reads; wrong-key payloads reject with `RESTORE`. `save(id)` captures a registered\n * workflow's snapshot at invocation and serializes same-id writes without coupling other ids.\n * Both remain lenient without a store or registered id.\n * - **Removal.** `remove` drops one by id, or a batch (§9.2, array overload FIRST) — `true` when\n * any was removed. `clear` empties the registry.\n * - **No active pointer.** Unlike its `ConversationManager` / `WorkspaceManager` twins, there is\n * no `active` / `switch` — nothing in the workflow domain renders \"the current workflow\".\n *\n * @example\n * ```ts\n * const manager = new WorkflowManager({\n * \tfunctions: { compile: async (controller) => `built ${controller.task.id}` },\n * })\n * const workflow = manager.add(definition) // minted, registered, RUNNABLE\n * manager.workflow(workflow.id) // the same workflow\n * manager.count // 1\n * ```\n */\nexport class WorkflowManager implements WorkflowManagerInterface {\n\treadonly #workflows = new Map<string, WorkflowInterface>()\n\treadonly #opens = new Map<string, Promise<WorkflowInterface | undefined>>()\n\treadonly #saves = new Map<string, Promise<void>>()\n\treadonly #mutations = new Map<string, symbol>()\n\treadonly #additions = new Map<string, symbol>()\n\treadonly #hydrations = new Map<string, Set<symbol>>()\n\t#generation = Symbol()\n\t// The functions registry flowed into every workflow this manager mints or hydrates, so\n\t// each live task's `run` resolves to a real `handler` (RUNNABLE) rather than the\n\t// inspectable unresolved state; the runner rejects it until matching functions are supplied.\n\treadonly #functions: WorkflowFunctions | undefined\n\t// The optional durable store backing `open` / `save`; `undefined` ⇒ registry-only (both lenient).\n\treadonly #store: WorkflowStoreInterface | undefined\n\n\tconstructor(options?: WorkflowManagerOptions) {\n\t\tthis.#functions = options?.functions\n\t\tthis.#store = options?.store\n\t}\n\n\tget count(): number {\n\t\treturn this.#workflows.size\n\t}\n\n\tworkflow(id: string): WorkflowInterface | undefined {\n\t\treturn this.#workflows.get(id)\n\t}\n\n\tworkflows(): readonly WorkflowInterface[] {\n\t\treturn [...this.#workflows.values()]\n\t}\n\n\tadd(definition: WorkflowDefinition): WorkflowInterface {\n\t\t// Mints keyed by the definition's own id — a re-add under the same id overwrites,\n\t\t// exactly as `createWorkflow` keys the live tree by `definition.id`.\n\t\tconst workflow = createWorkflow(definition, {\n\t\t\t...(this.#functions === undefined ? {} : { functions: this.#functions }),\n\t\t})\n\t\tconst mutation = this.#invalidate(workflow.id)\n\t\tif (mutation === undefined) this.#additions.delete(workflow.id)\n\t\telse this.#additions.set(workflow.id, mutation)\n\t\tthis.#workflows.set(workflow.id, workflow)\n\t\treturn workflow\n\t}\n\n\topen(id: string): Promise<WorkflowInterface | undefined> {\n\t\t// Already registered ⇒ the registry is the live source, no store hit.\n\t\tconst existing = this.#workflows.get(id)\n\t\tif (existing !== undefined) return Promise.resolve(existing)\n\t\t// No store ⇒ a registry miss resolves nothing (lenient).\n\t\tif (this.#store === undefined) return Promise.resolve(undefined)\n\t\tconst pending = this.#opens.get(id)\n\t\tif (pending !== undefined) return pending\n\t\tconst mutation = this.#mutations.get(id)\n\t\tconst generation = this.#generation\n\t\tconst lease = this.#retain(id)\n\t\tconst reservation = Promise.withResolvers<WorkflowInterface | undefined>()\n\t\tconst opening = reservation.promise\n\t\t// Reserve identity before hydration can synchronously cross the external store boundary.\n\t\tthis.#opens.set(id, opening)\n\t\tvoid this.#hydrate(id, mutation, generation, lease, this.#store).then(\n\t\t\treservation.resolve,\n\t\t\treservation.reject,\n\t\t)\n\t\tvoid opening.then(\n\t\t\t() => this.#releaseOpen(id, opening),\n\t\t\t() => this.#releaseOpen(id, opening),\n\t\t)\n\t\treturn opening\n\t}\n\n\tsave(id: string): Promise<boolean> {\n\t\t// Lenient: persist only when a store is set AND the id is registered; otherwise a no-op.\n\t\tconst workflow = this.#workflows.get(id)\n\t\tif (this.#store === undefined || workflow === undefined) return Promise.resolve(false)\n\t\tconst snapshot = workflow.snapshot()\n\t\tconst previous = this.#saves.get(id)\n\t\tconst reservation = Promise.withResolvers<void>()\n\t\tconst saving = reservation.promise\n\t\t// Reserve the serialization predecessor before persistence can synchronously reenter.\n\t\tthis.#saves.set(id, saving)\n\t\tvoid this.#persist(this.#store, previous, snapshot).then(\n\t\t\treservation.resolve,\n\t\t\treservation.reject,\n\t\t)\n\t\tvoid saving.then(\n\t\t\t() => this.#settle(id, saving),\n\t\t\t() => this.#settle(id, saving),\n\t\t)\n\t\treturn saving.then(() => true)\n\t}\n\n\t// §9.2: the array overload FIRST, so a list resolves to the batch form.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(ids: string | readonly string[]): boolean {\n\t\tif (isArray(ids)) {\n\t\t\tlet removed = false\n\t\t\tfor (const id of ids) {\n\t\t\t\tthis.#invalidate(id)\n\t\t\t\tthis.#additions.delete(id)\n\t\t\t\tif (this.#workflows.delete(id)) removed = true\n\t\t\t}\n\t\t\treturn removed\n\t\t}\n\t\tthis.#invalidate(ids)\n\t\tthis.#additions.delete(ids)\n\t\treturn this.#workflows.delete(ids)\n\t}\n\n\tclear(): void {\n\t\tthis.#generation = Symbol()\n\t\tthis.#mutations.clear()\n\t\tthis.#additions.clear()\n\t\tthis.#opens.clear()\n\t\tthis.#workflows.clear()\n\t}\n\n\tasync #hydrate(\n\t\tid: string,\n\t\tmutation: symbol | undefined,\n\t\tgeneration: symbol,\n\t\tlease: symbol,\n\t\tstore: WorkflowStoreInterface,\n\t): Promise<WorkflowInterface | undefined> {\n\t\ttry {\n\t\t\tconst snapshot = await store.get(id)\n\t\t\tif (!this.#owns(id, mutation, generation)) return this.#resolve(id, generation)\n\t\t\tif (snapshot === undefined) return undefined\n\t\t\tlet owned: WorkflowSnapshot\n\t\t\ttry {\n\t\t\t\towned = cloneWorkflowSnapshot(snapshot, id)\n\t\t\t} catch (error) {\n\t\t\t\tif (!this.#owns(id, mutation, generation)) return this.#resolve(id, generation)\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tif (!this.#owns(id, mutation, generation)) return this.#resolve(id, generation)\n\t\t\tlet workflow: WorkflowInterface\n\t\t\ttry {\n\t\t\t\tworkflow = createRestoredWorkflow(owned, {\n\t\t\t\t\t...(this.#functions === undefined ? {} : { functions: this.#functions }),\n\t\t\t\t})\n\t\t\t} catch (error) {\n\t\t\t\tif (!this.#owns(id, mutation, generation)) return this.#resolve(id, generation)\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tif (!this.#owns(id, mutation, generation)) return this.#resolve(id, generation)\n\t\t\treturn this.#register(id, workflow, mutation, generation)\n\t\t} finally {\n\t\t\tthis.#releaseHydration(id, lease)\n\t\t}\n\t}\n\n\t#owns(id: string, mutation: symbol | undefined, generation: symbol): boolean {\n\t\treturn this.#generation === generation && this.#mutations.get(id) === mutation\n\t}\n\n\t#resolve(id: string, generation: symbol): WorkflowInterface | undefined {\n\t\tif (this.#generation !== generation) return undefined\n\t\tconst mutation = this.#mutations.get(id)\n\t\tconst workflow = this.#workflows.get(id)\n\t\treturn workflow !== undefined && this.#additions.get(id) === mutation ? workflow : undefined\n\t}\n\n\t#register(\n\t\tid: string,\n\t\tworkflow: WorkflowInterface,\n\t\tmutation: symbol | undefined,\n\t\tgeneration: symbol,\n\t): WorkflowInterface | undefined {\n\t\tif (!this.#owns(id, mutation, generation)) return this.#resolve(id, generation)\n\t\tthis.#workflows.set(id, workflow)\n\t\treturn workflow\n\t}\n\n\tasync #persist(\n\t\tstore: WorkflowStoreInterface,\n\t\tprevious: Promise<void> | undefined,\n\t\tsnapshot: WorkflowSnapshot,\n\t): Promise<void> {\n\t\tif (previous !== undefined) {\n\t\t\ttry {\n\t\t\t\tawait previous\n\t\t\t} catch {\n\t\t\t\t// The prior caller owns its rejection; this invocation still reaches the store.\n\t\t\t}\n\t\t}\n\t\tawait store.set(snapshot)\n\t}\n\n\t#invalidate(id: string): symbol | undefined {\n\t\tthis.#opens.delete(id)\n\t\tif (!this.#hydrations.has(id)) {\n\t\t\tthis.#mutations.delete(id)\n\t\t\tthis.#additions.delete(id)\n\t\t\treturn undefined\n\t\t}\n\t\tconst mutation = Symbol()\n\t\tthis.#mutations.set(id, mutation)\n\t\treturn mutation\n\t}\n\n\t#retain(id: string): symbol {\n\t\tconst lease = Symbol()\n\t\tconst hydrations = this.#hydrations.get(id)\n\t\tif (hydrations === undefined) this.#hydrations.set(id, new Set([lease]))\n\t\telse hydrations.add(lease)\n\t\treturn lease\n\t}\n\n\t#releaseOpen(id: string, opening: Promise<WorkflowInterface | undefined>): void {\n\t\tif (this.#opens.get(id) === opening) this.#opens.delete(id)\n\t}\n\n\t#releaseHydration(id: string, lease: symbol): void {\n\t\tconst hydrations = this.#hydrations.get(id)\n\t\tif (hydrations === undefined) return\n\t\thydrations.delete(lease)\n\t\tif (hydrations.size !== 0) return\n\t\tthis.#hydrations.delete(id)\n\t\tthis.#mutations.delete(id)\n\t\tthis.#additions.delete(id)\n\t}\n\n\t#settle(id: string, saving: Promise<void>): void {\n\t\tif (this.#saves.get(id) === saving) this.#saves.delete(id)\n\t}\n}\n","import type { AbortInterface } from '@orkestrel/abort'\nimport type { ControllerInterface } from './types.js'\nimport { parkSignal } from './helpers.js'\n\n/**\n * The per-unit handle a runner handler receives — wraps the unit's identity,\n * input, cancellation, and the run controls (`wait` / `spawn` / `abort`).\n *\n * @remarks\n * - **Built by the Runner per unit.** The runner constructs one `Controller` per\n * unit it dispatches, handing it the unit's `id`, `input`, the unit's `Abort`\n * handle, the queue attempt's `signal`, and a `spawn` callback that launches a\n * sibling through the same queue.\n * - **Signal.** `signal` is the queue attempt's signal, which ANY-combines the\n * unit's own abort, the runner-level abort (the runner aborts every unit), and\n * the per-attempt timeout — so it fires on any of the three. `aborted` and\n * `abort(reason)` delegate to the unit's `Abort` (the cancellation source of\n * truth); since the attempt signal ANY-includes that abort, `abort()` fires\n * `signal` too.\n * - **`wait` promise-parks (never a timer).** It resolves the instant the unit's\n * `signal` fires (immediately if already aborted) via a one-shot listener — no\n * `setTimeout`, no polling, no busy-yield — so a parked unit costs no CPU.\n * - **`spawn` is fire-and-track.** It delegates to the runner's launch-a-sibling\n * callback, which routes the sibling through the queue; the runner's `execute`\n * awaits the spawn closure, so the sibling runs whether or not its promise is\n * awaited. (Inline-awaiting a spawn from a slot-holding handler on a bounded\n * runner can deadlock — fan out instead; see {@link ControllerInterface.spawn}.)\n * - **Event-free by design.** The per-unit handle carries no Emitter; observe the\n * {@link RunnerInterface.emitter} instead (`unit` / `spawn` / `settle` / `fail` carry the id).\n */\nexport class Controller<TInput, TResult> implements ControllerInterface<TInput, TResult> {\n\treadonly id: string\n\treadonly input: TInput\n\treadonly signal: AbortSignal\n\t// The unit's cancellation handle — the source of truth for `aborted` / `abort`.\n\treadonly #abort: AbortInterface\n\t// The runner's launch-a-sibling callback — routes a spawn through the queue.\n\treadonly #spawn: (input: TInput) => Promise<TResult>\n\n\tconstructor(\n\t\tid: string,\n\t\tinput: TInput,\n\t\tabort: AbortInterface,\n\t\tsignal: AbortSignal,\n\t\tspawn: (input: TInput) => Promise<TResult>,\n\t) {\n\t\tthis.id = id\n\t\tthis.input = input\n\t\tthis.#abort = abort\n\t\tthis.signal = signal\n\t\tthis.#spawn = spawn\n\t}\n\n\tget aborted(): boolean {\n\t\treturn this.#abort.aborted\n\t}\n\n\twait(): Promise<void> {\n\t\t// Promise-park on the unit's signal — the shared `parkSignal` leaf (resolves immediately\n\t\t// if already aborted, else on the one-shot 'abort' event). No timer, no poll (the B1 fix).\n\t\treturn parkSignal(this.signal)\n\t}\n\n\tspawn(input: TInput): Promise<TResult> {\n\t\treturn this.#spawn(input)\n\t}\n\n\tabort(reason?: unknown): void {\n\t\tthis.#abort.abort(reason)\n\t}\n}\n","import type { AbortInterface } from '@orkestrel/abort'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { QueueExecution, QueueInterface } from '@orkestrel/queue'\nimport type {\n\tDeferredInterface,\n\tRunnerEventMap,\n\tRunnerInterface,\n\tRunnerOptions,\n\tRunnerUnit,\n\tUnitOutcome,\n} from './types.js'\nimport { createAbort } from '@orkestrel/abort'\nimport { createQueue } from '@orkestrel/queue'\nimport { Emitter } from '@orkestrel/emitter'\nimport { createDeferred } from './helpers.js'\nimport { Controller } from './Controller.js'\n\n/**\n * A thin generic orchestrator that drives declared units — and any they `spawn` —\n * through a bounded-concurrency {@link createQueue}, collecting ordered results.\n *\n * @remarks\n * - **Drives the Queue (no reimplemented concurrency).** Every unit (declared or\n * spawned) is `enqueue`d on one internal `Queue`, so backpressure, FIFO ordering,\n * bounded concurrency, retries, and the per-attempt timeout are all the Queue's —\n * the Runner adds only orchestration (launching, ordering, draining, fail-fast).\n * - **Spawns actually run, results stay ordered (the B2 fix).** Declared inputs and\n * `spawn`ed siblings flow through the SAME `#launch`, which appends the unit's `id`\n * to an ordered `#order` list and records its settled value into `#values` by `id`.\n * Results are read back as `#order.map(id => #values.get(id))` — declared first (in\n * input order), then spawns (in spawn order). There is no one-time task snapshot,\n * so a unit spawned mid-handler is run and ordered like any other.\n * - **`execute` awaits the full spawn closure via a count gate.** `#launch` increments\n * an outstanding-unit `#count` BEFORE enqueuing and every settle decrements it,\n * resolving the `#drained` deferred at zero. Because `spawn` calls `#launch` (so\n * `#count += 1`) before the parent handler returns, the count never reaches zero\n * mid-run — `execute` parks on `#drained` and so awaits the entire transitive\n * closure, not just the declared units.\n * - **`spawn` is fire-and-track.** A spawned unit runs through the queue regardless of\n * whether its promise is awaited; the Runner never awaits a spawned promise from\n * within a handler's slot (it awaits the count gate instead), so a slot-holding\n * handler can fan out without the Runner deadlocking it. (An inline `await` of a\n * spawn by a bounded handler can still deadlock — that caveat is the caller's.)\n * - **Per-unit Controller + signal.** Each unit gets a `Controller` carrying its `id`,\n * `input`, the unit's `Abort` (so `aborted` / `abort` delegate to it), and the queue\n * attempt's `signal` (which ANY-combines the unit abort + runner abort + timeout). A\n * `spawn` callback is injected so `controller.spawn(input)` delegates to `#launch`.\n * - **One-shot + fail-fast.** `execute` runs once (a second call throws). The first\n * unit failure (after its retries) records the error and `abort()`s the run, so every\n * sibling's signal fires; later failures are ignored and `execute` rejects with the\n * first error. A user `abort(reason)` likewise rejects a running `execute`.\n * - **`pause` / `resume` / `stop` (§10) ride the backing Queue.** `pause` / `resume`\n * delegate straight to the Queue's own pause/resume (holding/releasing the NEXT\n * dispatch while an in-flight unit finishes); `paused` mirrors the Queue's. `stop` is a\n * GRACEFUL permanent end, distinct from `abort`: still-pending (never-dispatched)\n * units are rejected by the Queue's own stop WITHOUT their handler ever running, and\n * `#settle` reads that fact (`#dispatched`) to treat the rejection as a stop artifact —\n * not a failure, never tripping fail-fast — while an in-flight unit still runs to\n * completion and settles normally. `execute` RESOLVES (never rejects) once every unit\n * has settled, with whatever results actually completed.\n * - **Observable (§13).** The owned {@link emitter} ({@link RunnerEventMap}) carries the run\n * lifecycle — `start` / `unit` / `spawn` / `settle` / `fail` / `finish` / `abort` — for\n * fire-and-forget observers. Every event is emitted directly, strictly AFTER the relevant\n * launch / settle / drain transition; the emitter isolates a listener throw and routes it\n * to its `error` handler (the `error` option), so a buggy observer can NEVER reorder, throw\n * into, or corrupt the one-shot / fail-fast / spawn-tracking engine: the outstanding-unit\n * count gate stays balanced and fail-fast still fires regardless of what a listener does.\n * Observation is purely a side-channel.\n */\nexport class Runner<TInput, TResult> implements RunnerInterface<TInput, TResult> {\n\treadonly #handler: RunnerOptions<TInput, TResult>['handler']\n\t// The per-entry reliability resolver — spread into each enqueue so a unit's `retries` /\n\t// `timeout` OVERRIDE the queue-level defaults (the Queue resolves default→override). Optional:\n\t// with none supplied, the enqueue is byte-identical to the no-resolver path.\n\treadonly #entries: RunnerOptions<TInput, TResult>['entries']\n\treadonly #queue: QueueInterface<RunnerUnit<TInput>, TResult>\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// count gate / fail-fast / spawn tracking.\n\treadonly #emitter: Emitter<RunnerEventMap<TResult>>\n\t// Each unit's cancellation handle, by id — aborted en masse on a runner abort.\n\treadonly #aborts = new Map<string, AbortInterface>()\n\t// The launch order of every unit (declared, then spawns) — the result ordering.\n\treadonly #order: string[] = []\n\t// Each unit's settled value, by id — boxed so presence is tracked by map membership\n\t// (not by an `undefined` sentinel), correct even when `TResult` includes `undefined`.\n\treadonly #values = new Map<string, { readonly value: TResult }>()\n\t// The ids whose handler was actually DISPATCHED (`#dispatch` invoked) — the settlement-path\n\t// distinguisher a graceful `stop` needs: a never-dispatched unit's enqueue rejection (the\n\t// queue's own \"queue is stopped\" error for a still-PENDING entry) is a stop artifact, never a\n\t// unit failure; a dispatched unit's rejection is a genuine failure even while stopping.\n\treadonly #dispatched = new Set<string>()\n\treadonly #queued = new Set<string>()\n\t// Outstanding (launched-but-unsettled) units; `#drained` resolves when it hits 0.\n\t#count = 0\n\t#drained: DeferredInterface<void> | undefined\n\t#started = false\n\t#running = false\n\t#stopped = false\n\t// Set the moment a GRACEFUL `stop()` is requested — read by `#settle` to classify a\n\t// never-dispatched unit's rejection as a stop artifact rather than a failure.\n\t#stopping = false\n\t// The first unit failure (fail-fast) — `execute` rejects with it once drained.\n\t#failure: { readonly error: unknown } | undefined\n\t#stopPromise: Promise<void> | undefined\n\t#abortPromise: Promise<void> | undefined\n\t#destroyPromise: Promise<void> | undefined\n\n\tconstructor(options: RunnerOptions<TInput, TResult>) {\n\t\tconst handler = options.handler\n\t\tconst entries = options.entries\n\t\tconst on = options.on\n\t\tconst error = options.error\n\t\tconst concurrency = options.concurrency\n\t\tconst retries = options.retries\n\t\tconst timeout = options.timeout\n\t\tthis.#handler = handler\n\t\tthis.#entries = entries\n\t\tthis.#emitter = new Emitter<RunnerEventMap<TResult>>({\n\t\t\t...(on === undefined ? {} : { on }),\n\t\t\t...(error === undefined ? {} : { error }),\n\t\t})\n\t\tthis.#queue = createQueue<RunnerUnit<TInput>, TResult>({\n\t\t\thandler: this.#dispatch.bind(this),\n\t\t\t...(concurrency === undefined ? {} : { concurrency }),\n\t\t\t...(retries === undefined ? {} : { retries }),\n\t\t\t...(timeout === undefined ? {} : { timeout }),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<RunnerEventMap<TResult>> {\n\t\treturn this.#emitter\n\t}\n\n\tget active(): number {\n\t\treturn this.#count\n\t}\n\n\tget stopped(): boolean {\n\t\treturn this.#stopped\n\t}\n\n\tget paused(): boolean {\n\t\treturn this.#queue.paused\n\t}\n\n\t/**\n\t * Inject one more unit into an IN-FLIGHT `execute` run — a LIVE counterpart to a\n\t * `Controller.spawn`, called from OUTSIDE any unit's handler.\n\t *\n\t * @remarks\n\t * Returns `undefined` synchronously (graceful, non-throwing — AGENTS §12) unless the\n\t * runner is currently mid-`execute` and not yet stopped — covering \"never started\",\n\t * \"already drained\", \"aborted\", and \"destroyed\". Otherwise the unit is routed through\n\t * the SAME backing queue as a declared/`spawn`ed unit via `#launch` — the outstanding-\n\t * unit count gate increments BEFORE this call returns, so an in-flight `execute`\n\t * keeps awaiting it (the drain race: `#running` flips to `false` as the very first\n\t * step after `execute`'s `await drained.promise` settles, so a `spawn` reaching this\n\t * method after the run has fully drained is cleanly rejected with `undefined` —\n\t * never silently dropped, never hangs `execute`). Emits {@link RunnerEventMap.spawn}\n\t * with a `parent` of `undefined` (this call has no spawning unit) once accepted.\n\t *\n\t * @param input - The unit's work payload\n\t * @returns The unit's result promise, or `undefined` when no in-flight run can accept it\n\t * @example\n\t * ```ts\n\t * const runner = createRunner({ handler: (c) => c.input })\n\t * const result = runner.execute([1, 2])\n\t * const extra = runner.spawn(3) // Promise<number> | undefined\n\t * await result\n\t * ```\n\t */\n\tspawn(input: TInput): Promise<TResult> | undefined {\n\t\tif (!this.#accepts()) return undefined\n\t\treturn this.#launch(input, undefined, true)\n\t}\n\n\tasync execute(inputs: readonly TInput[]): Promise<readonly TResult[]> {\n\t\tif (this.#started) throw new Error('runner has already executed')\n\t\tif (this.#stopped) throw new Error('runner is stopped')\n\t\tthis.#started = true\n\t\tthis.#running = true\n\t\tconst drained = createDeferred<void>()\n\t\tthis.#drained = drained\n\t\tfor (const input of inputs) {\n\t\t\tif (!this.#accepts()) break\n\t\t\tvoid this.#launch(input)\n\t\t}\n\t\t// Every declared unit is reserved before observation begins, so a start-listener public\n\t\t// spawn is accepted after the declared order. Queue dispatch remains asynchronous, so the\n\t\t// start event still precedes every unit handler.\n\t\tthis.#emitter.emit('start')\n\t\tif (this.#count === 0) drained.resolve()\n\t\tawait drained.promise\n\t\tthis.#running = false\n\t\tconst cleanup = await this.#cleanup()\n\t\tif (this.#failure !== undefined) throw this.#failure.error\n\t\tif (cleanup !== undefined) throw cleanup.error\n\t\t// The batch drained successfully — observe `finish` with the ordered results, AFTER the\n\t\t// drained gate resolved and the fail-fast check passed (a failed run throws above and\n\t\t// emits no `finish`; its per-unit `fail` + run-level `abort` already fired).\n\t\tconst results = this.#collect()\n\t\tthis.#emitter.emit('finish', results)\n\t\tconst finishing = await this.#cleanup()\n\t\tif (finishing !== undefined) throw finishing.error\n\t\treturn results\n\t}\n\n\tabort(reason?: unknown): Promise<void> {\n\t\tif (this.#abortPromise !== undefined) return this.#abortPromise\n\t\tconst barrier = createDeferred<void>()\n\t\tthis.#abortPromise = barrier.promise\n\t\tvoid barrier.promise.catch(() => {})\n\t\t// Record an abort as the run's failure (if none yet) so a parked `execute` rejects\n\t\t// rather than returning partial results. Preserve the caller's `reason` verbatim —\n\t\t// it is the same value the unit signals carry (the abort flows to each unit's\n\t\t// signal), and symmetric with `#settle`, which stores `outcome.error` as-is — only\n\t\t// synthesizing an Error when no reason was given. The `#failure === undefined` guard\n\t\t// keeps the FIRST failure (a fail-fast handler error recorded in `#settle` before its\n\t\t// own `this.abort(...)` call) from being overwritten by the abort's write.\n\t\tif (this.#running && this.#failure === undefined) {\n\t\t\tthis.#failure = { error: reason === undefined ? new Error('runner aborted') : reason }\n\t\t}\n\t\tthis.#cancel(reason)\n\t\tthis.#stopped = true\n\t\tconst cleanup = this.#queue.abort(reason)\n\t\tvoid this.#settleLifecycle(barrier, cleanup)\n\t\t// Observe the abort — AFTER every unit's signal fired, the backing queue was aborted,\n\t\t// and the run was marked stopped, so a swallowed listener throw can't perturb the\n\t\t// cancel. Idempotent at the top (a second `abort` returns early), so this fires once.\n\t\tthis.#emitter.emit('abort', reason)\n\t\treturn barrier.promise\n\t}\n\n\t/**\n\t * Suspend dispatch (AGENTS §10 — resumable): delegates to the backing queue's own\n\t * `pause`, which holds the NEXT dispatch while any in-flight unit finishes.\n\t *\n\t * @remarks\n\t * A no-op once the runner is `stopped` — a stopped runner has no dispatch left to\n\t * suspend, mirroring the guard `stop()` itself applies. Also a no-op when already\n\t * `paused` (the queue's own `pause` is idempotent), so calling it repeatedly is safe.\n\t */\n\tpause(): void {\n\t\tif (this.#stopped || this.#queue.paused) return\n\t\tthis.#queue.pause()\n\t}\n\n\t/**\n\t * Continue a paused runner (AGENTS §10); delegates to the backing queue's `resume`.\n\t *\n\t * @remarks\n\t * A no-op once the runner is `stopped` (nothing left to resume) and a no-op when the\n\t * runner is not currently `paused`, so calling it repeatedly or on a never-paused\n\t * runner is safe.\n\t */\n\tresume(): void {\n\t\tif (this.#stopped || !this.#queue.paused) return\n\t\tthis.#queue.resume()\n\t}\n\n\t/**\n\t * Permanently end the runner (AGENTS §10) — a GRACEFUL stop, distinct from `abort`.\n\t * Marks the runner `stopping` + `stopped`, then stops the backing queue: every\n\t * still-PENDING (never-dispatched) unit is rejected by the queue with its own\n\t * \"queue is stopped\" error, WITHOUT running its handler; every already-in-flight unit\n\t * keeps running to completion and settles normally. `#settle` reads `#stopping` to\n\t * classify a never-dispatched unit's rejection as a stop artifact (decrement the count\n\t * gate, no recorded failure, no fail-fast trip) rather than a genuine failure — a\n\t * dispatched unit's rejection while stopping is still a real failure. Idempotent.\n\t */\n\tstop(): Promise<void> {\n\t\tif (this.#destroyPromise !== undefined) {\n\t\t\treturn this.#destroyPromise\n\t\t}\n\t\tif (this.#abortPromise !== undefined) {\n\t\t\treturn this.#abortPromise\n\t\t}\n\t\tif (this.#stopPromise !== undefined) return this.#stopPromise\n\t\tconst barrier = createDeferred<void>()\n\t\tthis.#stopPromise = barrier.promise\n\t\tvoid barrier.promise.catch(() => {})\n\t\tthis.#stopping = true\n\t\tthis.#stopped = true\n\t\tconst cleanup = this.#queue.stop()\n\t\tvoid this.#settleLifecycle(barrier, cleanup)\n\t\treturn barrier.promise\n\t}\n\n\tdestroy(): Promise<void> {\n\t\tif (this.#destroyPromise !== undefined) return this.#destroyPromise\n\t\tconst barrier = createDeferred<void>()\n\t\tthis.#destroyPromise = barrier.promise\n\t\tvoid barrier.promise.catch(() => {})\n\t\tthis.#stopped = true\n\t\tvoid this.abort()\n\t\tconst cleanup = this.#queue.destroy()\n\t\tvoid this.#settleDestroy(barrier, cleanup)\n\t\treturn barrier.promise\n\t}\n\n\t// Launch one unit (a declared input, a handler-spawned sibling, or a live external\n\t// `spawn`) through the shared queue. Increments `#count` BEFORE enqueuing — so a\n\t// spawn keeps the count above zero until the spawned unit itself settles, making\n\t// `execute` await the full closure (B2). The settle bookkeeping records the value /\n\t// first failure and drains at zero. A `parent` (present only for a handler `spawn`)\n\t// means this is a sub-unit; `announce` (defaulted from `parent` but forced `true` by\n\t// the public `spawn`, whose caller has no parent unit) decides whether to observe\n\t// this launch as a `spawn` event — AFTER the unit's id is minted, tracked, and the\n\t// count incremented (so the gate already accounts for it), BEFORE enqueuing. A\n\t// declared launch (no parent, default `announce`) emits no `spawn`.\n\t#launch(input: TInput, parent?: string, announce = parent !== undefined): Promise<TResult> {\n\t\tconst id = crypto.randomUUID()\n\t\tconst abort = createAbort()\n\t\tthis.#aborts.set(id, abort)\n\t\tthis.#order.push(id)\n\t\tthis.#count += 1\n\t\tif (announce) this.#emitter.emit('spawn', id, parent)\n\t\tlet promise: Promise<TResult>\n\t\ttry {\n\t\t\tconst entry = this.#entries?.(input)\n\t\t\tconst retries = entry?.retries\n\t\t\tconst timeout = entry?.timeout\n\t\t\t// Only a fully resolved entry is queued. Reserve that classification before enqueue so\n\t\t\t// a resolver-triggered graceful stop remains never-dispatched stop work; a resolver or\n\t\t\t// property failure never enters this set and remains a genuine unit failure.\n\t\t\tthis.#queued.add(id)\n\t\t\tpromise = this.#queue.enqueue(\n\t\t\t\t{ id, input },\n\t\t\t\t{\n\t\t\t\t\tid,\n\t\t\t\t\tsignal: abort.signal,\n\t\t\t\t\t...(retries === undefined ? {} : { retries }),\n\t\t\t\t\t...(timeout === undefined ? {} : { timeout }),\n\t\t\t\t},\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tpromise = Promise.reject(error)\n\t\t}\n\t\tvoid promise.then(\n\t\t\t(value) => this.#settle(id, { ok: true, value }),\n\t\t\t(error: unknown) => this.#settle(id, { ok: false, error }),\n\t\t)\n\t\treturn promise\n\t}\n\n\t// The queue handler for one unit: build its Controller over the attempt signal and\n\t// run the user handler against it. The unit's own `Abort` was passed as the entry\n\t// signal, so `execution.signal` already fires on unit abort, runner abort, or timeout\n\t// — expose THAT as `controller.signal` (covering all three); `abort` / `aborted`\n\t// delegate to the unit `Abort` via the Controller.\n\t#dispatch(unit: RunnerUnit<TInput>, execution: QueueExecution): Promise<TResult> | TResult {\n\t\t// `#launch` always stores the unit's `Abort` BEFORE enqueuing, so this lookup is an\n\t\t// invariant, never optional. Assert it (§12 programmer-error guard — narrows to a\n\t\t// defined `Abort` without `!`) rather than fabricating a fresh, unlinked abort: a\n\t\t// fallback `Abort` would be divorced from this entry's `execution.signal`, silently\n\t\t// severing the unit's cancellation while the type still type-checked.\n\t\tconst abort = this.#aborts.get(unit.id)\n\t\tif (abort === undefined) throw new Error('unit abort missing')\n\t\t// Record that this unit's handler was actually dispatched — the settlement-path\n\t\t// distinguisher `#settle` reads to tell a graceful `stop`'s never-dispatched rejection\n\t\t// (this branch never ran) from a genuine in-flight failure (this branch DID run).\n\t\tthis.#dispatched.add(unit.id)\n\t\tconst controller = new Controller<TInput, TResult>(\n\t\t\tunit.id,\n\t\t\tunit.input,\n\t\t\tabort,\n\t\t\texecution.signal,\n\t\t\t(input) => this.#spawn(input, unit.id),\n\t\t)\n\t\t// Observe the unit beginning — the queue has dequeued it and is about to run its\n\t\t// handler (mirrors the Queue's own `start`); AFTER the invariant abort lookup, BEFORE\n\t\t// the user handler runs, so a swallowed listener throw can't perturb the dispatch.\n\t\tthis.#emitter.emit('unit', unit.id)\n\t\treturn this.#handler(controller)\n\t}\n\n\t// `controller.spawn(input)` — only valid DURING a run; routes the sibling through\n\t// the same `#launch` (and thus the queue), so it actually runs and is ordered. The\n\t// spawning unit's `parent` id flows through so `#launch` can observe the `spawn`.\n\t#spawn(input: TInput, parent: string): Promise<TResult> {\n\t\tif (!this.#accepts()) throw new Error('spawn is unavailable outside an active run')\n\t\treturn this.#launch(input, parent)\n\t}\n\n\t// Record one unit's outcome, then decrement the outstanding count and drain at zero.\n\t// The FIRST failure is fail-fast: store it and `abort()` so every sibling's signal\n\t// fires; later failures (incl. the abort-induced rejections) are ignored. A success\n\t// boxes its value by id (presence by membership, so `undefined` is a valid result). A\n\t// GRACEFUL `stop()`'s never-dispatched rejection (the handler never ran — `#dispatched`\n\t// lacks `id`) is neither a success nor a failure: it settles the count gate silently,\n\t// with no recorded failure and no fail-fast trip, so `execute` still resolves with\n\t// whatever DID settle rather than rejecting.\n\t#settle(id: string, outcome: UnitOutcome<TResult>): void {\n\t\tif (outcome.ok) {\n\t\t\tthis.#values.set(id, { value: outcome.value })\n\t\t\t// Observe the successful unit — AFTER its value is recorded (the unit is settled);\n\t\t\t// the emit only OBSERVES it and runs before the count decrement, so it cannot\n\t\t\t// perturb the drain that follows.\n\t\t\tthis.#emitter.emit('settle', id)\n\t\t} else if (this.#stopping && this.#queued.has(id) && !this.#dispatched.has(id)) {\n\t\t\t// A graceful stop's pending-entry rejection — the handler never ran, so this is not\n\t\t\t// a unit failure. Fall through to the count decrement below with no other bookkeeping.\n\t\t} else if (this.#failure === undefined) {\n\t\t\tthis.#failure = { error: outcome.error }\n\t\t\t// Observe the FIRST (fail-fast) failure — AFTER the error is recorded, BEFORE the\n\t\t\t// cascade `abort()` (so observers see cause `fail` then effect `abort`). Only the\n\t\t\t// first failure emits `fail`; the abort-induced sibling rejections are ignored\n\t\t\t// (they fall through neither branch), matching fail-fast's \"later failures ignored\".\n\t\t\tthis.#emitter.emit('fail', id, outcome.error)\n\t\t\tvoid this.abort(outcome.error)\n\t\t}\n\t\tthis.#count -= 1\n\t\t// `#count` is incremented once per launch and decremented once per settle, so it\n\t\t// reaches exactly 0 — assert that honestly. `<= 0` would mask an over-decrement\n\t\t// regression (a double-settle) as a silent early drain; `=== 0` surfaces it instead.\n\t\tif (this.#count === 0) this.#drained?.resolve()\n\t}\n\n\t// Read every settled value back in launch order (declared first, then spawns) — by\n\t// map membership, so a `TResult` of `undefined` is preserved (not treated as absent).\n\t#collect(): readonly TResult[] {\n\t\tconst results: TResult[] = []\n\t\tfor (const id of this.#order) {\n\t\t\tconst box = this.#values.get(id)\n\t\t\tif (box !== undefined) results.push(box.value)\n\t\t}\n\t\treturn results\n\t}\n\n\t#accepts(): boolean {\n\t\treturn this.#running && !this.#stopped\n\t}\n\n\tasync #cleanup(): Promise<{ readonly error: unknown } | undefined> {\n\t\tconst cleanup = this.#destroyPromise ?? this.#abortPromise ?? this.#stopPromise\n\t\tif (cleanup === undefined) return undefined\n\t\ttry {\n\t\t\tawait cleanup\n\t\t\treturn undefined\n\t\t} catch (error) {\n\t\t\treturn { error }\n\t\t}\n\t}\n\n\tasync #settleLifecycle(barrier: DeferredInterface<void>, cleanup: Promise<void>): Promise<void> {\n\t\tlet failure: { readonly error: unknown } | undefined\n\t\ttry {\n\t\t\tawait cleanup\n\t\t} catch (error) {\n\t\t\tfailure = { error }\n\t\t}\n\t\tawait this.#waitDrain()\n\t\tif (failure === undefined) barrier.resolve()\n\t\telse barrier.reject(failure.error)\n\t}\n\n\tasync #settleDestroy(barrier: DeferredInterface<void>, cleanup: Promise<void>): Promise<void> {\n\t\tlet failure: { readonly error: unknown } | undefined\n\t\ttry {\n\t\t\tawait cleanup\n\t\t} catch (error) {\n\t\t\tfailure = { error }\n\t\t}\n\t\tawait this.#waitDrain()\n\t\tthis.#emitter.destroy()\n\t\tif (failure === undefined) barrier.resolve()\n\t\telse barrier.reject(failure.error)\n\t}\n\n\tasync #waitDrain(): Promise<void> {\n\t\tif (this.#count === 0) return\n\t\tawait this.#drained?.promise\n\t}\n\n\t// Abort every tracked unit's cancellation handle (fires each Controller's signal).\n\t#cancel(reason: unknown): void {\n\t\tfor (const abort of this.#aborts.values()) abort.abort(reason)\n\t}\n}\n","import type {\n\tTaskActivity,\n\tTaskActivityInput,\n\tTaskContext,\n\tTaskControllerInterface,\n\tTaskInterface,\n\tTaskResult,\n} from '../types.js'\nimport type { JSONRecord, Result } from '@orkestrel/contract'\nimport type { WorkflowError } from '../errors.js'\nimport { isTerminalStatus } from '../helpers.js'\n\n/**\n * The attempt-scoped handle a {@link import('./types.js').WorkflowFunction} receives.\n *\n * @remarks\n * - **A leaf handle, NOT the runner `Controller`.** A workflow task is a leaf of the\n * declarative W-b tree, not a fan-out unit, so it has no `spawn`; its `wait` instead\n * checkpoints the workflow, phase, and task cooperative gates.\n * - **Folded signal.** `signal` is the cancellation folded for THIS attempt: its per-attempt\n * deadline, task stop/skip, workflow abort/timeout/budget/destroy, or a sibling fail-fast.\n * A handler races its work against it; `aborted` reads it.\n * - **Attempt ownership.** `report` / `pulse` are closures supplied by the runner and refuse\n * after this signal aborts or a retry token supersedes this handle.\n * - **Input + lineage.** `input` is the task's open `metadata` bag (its\n * {@link import('./types.js').TaskInput} payload, `{}` when none); `task` is the full\n * {@link TaskContext}, so `task.phase` / `task.phase.workflow` navigate UP the lineage.\n * - **Read-up results.** `results()` returns every settled task's {@link TaskResult} across\n * the phases that have already finished (a closure over the live\n * {@link import('./types.js').WorkflowInterface}), so a `function` task can read an earlier\n * phase's output. Read-only — a task records its OWN outcome by returning / throwing, not\n * by mutating the tree.\n * - **Event-free.** Like the runner `Controller`, the per-task handle carries no Emitter;\n * observe the W-b entities' own emitters (`task.emitter` / `phase.emitter`) instead.\n */\nexport class TaskController implements TaskControllerInterface {\n\treadonly signal: AbortSignal\n\treadonly input: JSONRecord\n\treadonly task: TaskContext\n\treadonly attempt: number\n\treadonly #entity: TaskInterface\n\treadonly #report: (input: TaskActivityInput) => Result<TaskActivity, WorkflowError>\n\treadonly #pulse: () => boolean\n\t// Read the live workflow's settled results on demand — a closure injected by the runner,\n\t// so the handle reaches UP the tree without holding a back-reference to the workflow entity.\n\treadonly #results: () => readonly TaskResult[]\n\n\tconstructor(\n\t\tsignal: AbortSignal,\n\t\tinput: JSONRecord,\n\t\ttask: TaskInterface,\n\t\tattempt: number,\n\t\tresults: () => readonly TaskResult[],\n\t\treport: (input: TaskActivityInput) => Result<TaskActivity, WorkflowError>,\n\t\tpulse: () => boolean,\n\t) {\n\t\tthis.signal = signal\n\t\tthis.input = input\n\t\tthis.task = task.context\n\t\tthis.attempt = attempt\n\t\tthis.#entity = task\n\t\tthis.#results = results\n\t\tthis.#report = report\n\t\tthis.#pulse = pulse\n\t}\n\n\tget aborted(): boolean {\n\t\treturn this.signal.aborted\n\t}\n\n\tget paused(): boolean {\n\t\tif (this.#ancestorTerminal()) return false\n\t\treturn (\n\t\t\tthis.#entity.workflow.paused ||\n\t\t\tthis.#entity.phase.paused ||\n\t\t\t(!isTerminalStatus(this.#entity.status) && this.#entity.paused)\n\t\t)\n\t}\n\n\treport(input: TaskActivityInput): Result<TaskActivity, WorkflowError> {\n\t\treturn this.#report(input)\n\t}\n\n\tpulse(): boolean {\n\t\treturn this.#pulse()\n\t}\n\n\tasync wait(): Promise<void> {\n\t\twhile (this.paused && !this.signal.aborted) {\n\t\t\tawait this.#race(this.#gates())\n\t\t}\n\t}\n\n\tresults(): readonly TaskResult[] {\n\t\treturn this.#results()\n\t}\n\n\t#gates(): ReadonlyArray<Promise<void>> {\n\t\tif (this.#ancestorTerminal()) return []\n\t\tconst gates: Array<Promise<void>> = []\n\t\tif (this.#entity.workflow.paused) gates.push(this.#entity.workflow.wait())\n\t\tif (this.#entity.phase.paused) gates.push(this.#entity.phase.wait())\n\t\tif (!isTerminalStatus(this.#entity.status) && this.#entity.paused) {\n\t\t\tgates.push(this.#entity.wait())\n\t\t}\n\t\treturn gates\n\t}\n\n\tasync #race(gates: ReadonlyArray<Promise<void>>): Promise<void> {\n\t\tif (this.signal.aborted || gates.length === 0) return\n\t\tconst deferred = Promise.withResolvers<void>()\n\t\tconst onAbort = this.#resolve.bind(this, deferred)\n\t\tconst onTerminal = this.#resolve.bind(this, deferred)\n\t\tthis.signal.addEventListener('abort', onAbort, { once: true })\n\t\tthis.#entity.workflow.emitter.on('skip', onTerminal)\n\t\tthis.#entity.workflow.emitter.on('stop', onTerminal)\n\t\tthis.#entity.phase.emitter.on('skip', onTerminal)\n\t\tthis.#entity.phase.emitter.on('stop', onTerminal)\n\t\ttry {\n\t\t\tif (this.#ancestorTerminal()) deferred.resolve()\n\t\t\tawait Promise.race([Promise.all(gates), deferred.promise])\n\t\t} finally {\n\t\t\tthis.signal.removeEventListener('abort', onAbort)\n\t\t\tthis.#entity.workflow.emitter.off('skip', onTerminal)\n\t\t\tthis.#entity.workflow.emitter.off('stop', onTerminal)\n\t\t\tthis.#entity.phase.emitter.off('skip', onTerminal)\n\t\t\tthis.#entity.phase.emitter.off('stop', onTerminal)\n\t\t}\n\t}\n\n\t#ancestorTerminal(): boolean {\n\t\treturn (\n\t\t\tisTerminalStatus(this.#entity.workflow.status) || isTerminalStatus(this.#entity.phase.status)\n\t\t)\n\t}\n\n\t#resolve(deferred: PromiseWithResolvers<void>): void {\n\t\tdeferred.resolve()\n\t}\n}\n","import type {\n\tPhaseInterface,\n\tTaskInterface,\n\tWorkflowCheckpoint,\n\tWorkflowFault,\n\tWorkflowInterface,\n\tWorkflowPersistenceInterface,\n\tWorkflowStoreInterface,\n} from './types.js'\nimport { errorToMessage } from './helpers.js'\n\n/**\n * Advanced run-local snapshot persistence with one writer and one coalesced latest obligation.\n *\n * @remarks\n * Normally composed by `WorkflowRunner.execute({ store })`; exported for hosts that need to\n * coordinate the same required boundaries around their own runner integration.\n */\nexport class WorkflowPersistence implements WorkflowPersistenceInterface {\n\treadonly #workflow: WorkflowInterface\n\treadonly #store: WorkflowStoreInterface\n\treadonly #phases = new Set<PhaseInterface>()\n\treadonly #tasks = new Set<TaskInterface>()\n\treadonly #onWorkflowChange: () => void\n\treadonly #onWorkflowAdd: (phase: PhaseInterface) => void\n\treadonly #onWorkflowRemove: (phase: PhaseInterface) => void\n\treadonly #onPhaseChange: () => void\n\treadonly #onPhaseAdd: (task: TaskInterface) => void\n\treadonly #onPhaseRemove: (task: TaskInterface) => void\n\treadonly #onTaskChange: () => void\n\t#writing: Promise<void> | undefined\n\t#error: string | undefined\n\t#fault: WorkflowFault | undefined\n\t#attached = true\n\t#revision = 0\n\t#stored = 0\n\n\tconstructor(workflow: WorkflowInterface, store: WorkflowStoreInterface) {\n\t\tthis.#workflow = workflow\n\t\tthis.#store = store\n\t\tthis.#onWorkflowChange = this.#change.bind(this)\n\t\tthis.#onWorkflowAdd = this.#addPhase.bind(this)\n\t\tthis.#onWorkflowRemove = this.#removePhase.bind(this)\n\t\tthis.#onPhaseChange = this.#change.bind(this)\n\t\tthis.#onPhaseAdd = this.#addTask.bind(this)\n\t\tthis.#onPhaseRemove = this.#removeTask.bind(this)\n\t\tthis.#onTaskChange = this.#change.bind(this)\n\t\tthis.#attachWorkflow()\n\t}\n\n\tget fault(): WorkflowFault | undefined {\n\t\treturn this.#fault\n\t}\n\n\t/**\n\t * Persist every change through this required boundary.\n\t *\n\t * @param checkpoint - The boundary being made durable\n\t * @param task - The task owning an attempt or settlement\n\t * @param attempt - The persisted attempt number\n\t * @returns Whether the latest state reached the store\n\t */\n\tasync checkpoint(\n\t\tcheckpoint: WorkflowCheckpoint,\n\t\ttask?: TaskInterface,\n\t\tattempt?: number,\n\t): Promise<boolean> {\n\t\tconst revision = this.#mark()\n\t\twhile (this.#stored < revision) await this.#flush()\n\t\tif (this.#error === undefined) return true\n\t\tif (this.#fault === undefined) {\n\t\t\tthis.#fault = Object.freeze({\n\t\t\t\torigin: 'persistence',\n\t\t\t\tcheckpoint,\n\t\t\t\tmessage: this.#error,\n\t\t\t\t...(task === undefined ? {} : { task: task.id }),\n\t\t\t\t...(attempt === undefined ? {} : { attempt }),\n\t\t\t})\n\t\t}\n\t\treturn false\n\t}\n\n\t/**\n\t * Stop observing the live tree and persist its final state.\n\t *\n\t * @returns Whether the final snapshot reached the store\n\t */\n\tasync finalize(): Promise<boolean> {\n\t\tthis.detach()\n\t\treturn this.checkpoint('final')\n\t}\n\n\t/** Stop observing the live tree. */\n\tdetach(): void {\n\t\tif (!this.#attached) return\n\t\tthis.#attached = false\n\t\tthis.#workflow.emitter.off('start', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.off('complete', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.off('fail', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.off('skip', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.off('stop', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.off('move', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.off('update', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.off('add', this.#onWorkflowAdd)\n\t\tthis.#workflow.emitter.off('remove', this.#onWorkflowRemove)\n\t\tfor (const phase of this.#phases) this.#detachPhase(phase)\n\t}\n\n\t#attachWorkflow(): void {\n\t\tthis.#workflow.emitter.on('start', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.on('complete', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.on('fail', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.on('skip', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.on('stop', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.on('move', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.on('update', this.#onWorkflowChange)\n\t\tthis.#workflow.emitter.on('add', this.#onWorkflowAdd)\n\t\tthis.#workflow.emitter.on('remove', this.#onWorkflowRemove)\n\t\tfor (const phase of this.#workflow.phases.phases()) this.#attachPhase(phase)\n\t}\n\n\t#attachPhase(phase: PhaseInterface): void {\n\t\tif (this.#phases.has(phase)) return\n\t\tthis.#phases.add(phase)\n\t\tphase.emitter.on('start', this.#onPhaseChange)\n\t\tphase.emitter.on('complete', this.#onPhaseChange)\n\t\tphase.emitter.on('fail', this.#onPhaseChange)\n\t\tphase.emitter.on('skip', this.#onPhaseChange)\n\t\tphase.emitter.on('stop', this.#onPhaseChange)\n\t\tphase.emitter.on('move', this.#onPhaseChange)\n\t\tphase.emitter.on('update', this.#onPhaseChange)\n\t\tphase.emitter.on('add', this.#onPhaseAdd)\n\t\tphase.emitter.on('remove', this.#onPhaseRemove)\n\t\tfor (const task of phase.tasks.tasks()) this.#attachTask(task)\n\t}\n\n\t#detachPhase(phase: PhaseInterface): void {\n\t\tif (!this.#phases.delete(phase)) return\n\t\tphase.emitter.off('start', this.#onPhaseChange)\n\t\tphase.emitter.off('complete', this.#onPhaseChange)\n\t\tphase.emitter.off('fail', this.#onPhaseChange)\n\t\tphase.emitter.off('skip', this.#onPhaseChange)\n\t\tphase.emitter.off('stop', this.#onPhaseChange)\n\t\tphase.emitter.off('move', this.#onPhaseChange)\n\t\tphase.emitter.off('update', this.#onPhaseChange)\n\t\tphase.emitter.off('add', this.#onPhaseAdd)\n\t\tphase.emitter.off('remove', this.#onPhaseRemove)\n\t\tfor (const task of phase.tasks.tasks()) this.#detachTask(task)\n\t}\n\n\t#attachTask(task: TaskInterface): void {\n\t\tif (this.#tasks.has(task)) return\n\t\tthis.#tasks.add(task)\n\t\ttask.emitter.on('start', this.#onTaskChange)\n\t\ttask.emitter.on('complete', this.#onTaskChange)\n\t\ttask.emitter.on('fail', this.#onTaskChange)\n\t\ttask.emitter.on('skip', this.#onTaskChange)\n\t\ttask.emitter.on('stop', this.#onTaskChange)\n\t\ttask.emitter.on('report', this.#onTaskChange)\n\t\ttask.emitter.on('pulse', this.#onTaskChange)\n\t}\n\n\t#detachTask(task: TaskInterface): void {\n\t\tif (!this.#tasks.delete(task)) return\n\t\ttask.emitter.off('start', this.#onTaskChange)\n\t\ttask.emitter.off('complete', this.#onTaskChange)\n\t\ttask.emitter.off('fail', this.#onTaskChange)\n\t\ttask.emitter.off('skip', this.#onTaskChange)\n\t\ttask.emitter.off('stop', this.#onTaskChange)\n\t\ttask.emitter.off('report', this.#onTaskChange)\n\t\ttask.emitter.off('pulse', this.#onTaskChange)\n\t}\n\n\t#addPhase(phase: PhaseInterface): void {\n\t\tthis.#attachPhase(phase)\n\t\tthis.#change()\n\t}\n\n\t#removePhase(phase: PhaseInterface): void {\n\t\tthis.#detachPhase(phase)\n\t\tthis.#change()\n\t}\n\n\t#addTask(task: TaskInterface): void {\n\t\tthis.#attachTask(task)\n\t\tthis.#change()\n\t}\n\n\t#removeTask(task: TaskInterface): void {\n\t\tthis.#detachTask(task)\n\t\tthis.#change()\n\t}\n\n\t#change(): void {\n\t\tthis.#mark()\n\t\tvoid this.#flush()\n\t}\n\n\tasync #flush(): Promise<void> {\n\t\tif (this.#writing !== undefined) {\n\t\t\tawait this.#writing\n\t\t\treturn\n\t\t}\n\t\tconst reservation = Promise.withResolvers<void>()\n\t\tconst writing = reservation.promise\n\t\t// Reserve the writer before the drain can synchronously enter external store code.\n\t\tthis.#writing = writing\n\t\tvoid this.#drain().then(reservation.resolve, reservation.reject)\n\t\ttry {\n\t\t\tawait writing\n\t\t} finally {\n\t\t\tif (this.#writing === writing) this.#writing = undefined\n\t\t\tif (this.#stored < this.#revision) void this.#flush()\n\t\t}\n\t}\n\n\tasync #drain(): Promise<void> {\n\t\twhile (this.#stored < this.#revision) {\n\t\t\tconst revision = this.#revision\n\t\t\ttry {\n\t\t\t\tawait this.#store.set(this.#workflow.snapshot())\n\t\t\t\tthis.#error = undefined\n\t\t\t} catch (error) {\n\t\t\t\tthis.#error = errorToMessage(error)\n\t\t\t}\n\t\t\tthis.#stored = revision\n\t\t}\n\t}\n\n\t#mark(): number {\n\t\tthis.#revision += 1\n\t\treturn this.#revision\n\t}\n}\n","import type { JSONValue } from '@orkestrel/contract'\nimport type { TimeoutInterface } from '@orkestrel/timeout'\nimport type {\n\tControllerInterface,\n\tPhaseInterface,\n\tRunnerEntryOptions,\n\tRunnerInterface,\n\tSchedulerInterface,\n\tTaskInterface,\n\tWorkflowDefinition,\n\tWorkflowInterface,\n\tWorkflowOptions,\n\tWorkflowResult,\n\tWorkflowRunOptions,\n\tWorkflowRunnerInterface,\n} from './types.js'\nimport { createTimeout } from '@orkestrel/timeout'\nimport { DEFAULT_BAIL, DEFAULT_PHASE_CONCURRENCY, MAX_TIMER_MS } from './constants.js'\nimport { WorkflowError } from './errors.js'\nimport {\n\tcaptureWorkflowOptions,\n\tdefinitionToSnapshot,\n\terrorToMessage,\n\tfailure,\n\thasWorkflowHandlers,\n\tisTerminalStatus,\n} from './helpers.js'\nimport { Runner } from './Runner.js'\nimport { TaskController } from './tasks/TaskController.js'\nimport { Workflow } from './Workflow.js'\nimport { WorkflowPersistence } from './WorkflowPersistence.js'\n\n// A unit of phase work is one live `TaskInterface` — the substrate Runner's `TInput`. Its\n// handler's resolved value is irrelevant (the OUTCOME is recorded on the live task via\n// `complete` / `fail` / `skip`, NOT in the Runner's ordered results), so the Runner's\n// `TResult` is `void`: the runner DRIVES the entity, the substrate only sequences + bounds.\n//\n// The run-level cancel reads the active phase Runner through a LOCAL per-`#execute` cell (an\n// inline `{ runner }` holder threaded into `#runPhase`), NOT a shared `#active` field — so a\n// NESTED `execute` through application composition gets its OWN cell and can never clobber the\n// outer run's while it is suspended awaiting that handler. Each run cancels exactly its own\n// phase Runner.\n\n/**\n * The thin orchestrator that EXECUTES a live W-b workflow tree by COMPOSING the shipped\n * substrate — phases sequential, tasks concurrent — dispatching each task through its OWN\n * resolved handler under the `bail` policy.\n *\n * @remarks\n * - **Composes, never re-implements.** Per-phase bounded concurrency is one\n * {@link createRunner} per phase (the substrate {@link RunnerInterface} over the workers\n * `Queue`); `bail` maps onto that Runner's fail-fast vs settle-all; the run-level abort /\n * timeout / budget / entity `signal` fold through the `@orkestrel/abort` signal contract,\n * {@link createTimeout}, and `AbortSignal.any` (exactly as the agent runtime folds its bounds);\n * pacing is the shipped\n * {@link SchedulerInterface}. The runner writes ZERO concurrency / retry / abort logic of\n * its own — it only sequences phases, dispatches a task's own handler, and drives the live\n * entity. The workflow layer owns per-task deadlines because timeout settlement must\n * update the live leaf under the phase's `bail` policy before the substrate unit settles.\n * - **Pure engine — no integration registry.** The runner carries no behavior or provider\n * registry: each live {@link TaskInterface} already\n * resolved its own {@link import('./types.js').WorkflowFunction} into\n * {@link import('./types.js').TaskInterface.handler} ONCE at construction (build, restore,\n * or a live mint all resolve it identically, from {@link WorkflowOptions.functions}), so\n * dispatch is simply \"invoke the task's own handler\". Provider, protocol, and tool\n * integrations remain application-owned {@link import('./types.js').WorkflowFunction}s\n * composed into {@link WorkflowOptions.functions}. This module imports none of them.\n * - **Two `execute` forms, one engine.** `execute(definition, options)` BUILDS the live tree\n * from a {@link WorkflowDefinition} (single source of truth for the `run` / `concurrency`\n * metadata); `execute(workflow, options)` DRIVES a caller-owned, ALREADY-BUILT\n * {@link WorkflowInterface} instead — the entity-native control surface (AGENTS §10:\n * `pause` / `resume` / `add` / `stop` / `destroy` live on the entity itself). Both forms\n * converge on the SAME `#execute` engine: neither reads a `WorkflowDefinition` once the tree\n * exists — `#runTask` reads each task's OWN {@link import('./types.js').TaskInterface.handler}\n * / `retries` / `timeout`, and `#runPhase` reads each phase's OWN\n * {@link PhaseInterface.concurrency} / `bail`, so a live `add`-minted phase or task (V5)\n * runs under EXACTLY the same rules as one built from the original definition.\n * - **Phases sequential, tasks concurrent — LIVE continuity.** `#execute` drives the phases in\n * order, RE-READING `workflow.phases.phases()` every iteration (a cursor over the live\n * manager, not a one-time snapshot) so a caller's `workflow.add(phaseDefinition)` mid-run is\n * picked up. Within a phase, `#runPhase` subscribes to that phase's `add` event BEFORE\n * capturing its task list, then `spawn`s any task added mid-phase onto the SAME substrate\n * Runner (so it is actually dispatched, under the same `concurrency`); a task added too late\n * for `spawn` to accept (the runner already drained) is swept `skip`ped afterward so the\n * phase always reaches a coherent terminal state.\n * - **Dispatch by handler.** `#runTask` invokes the live task's own\n * {@link import('./types.js').TaskInterface.handler} directly. An omitted `run` deliberately\n * auto-completes with JSON `null`; a present unresolved name is rejected by the synchronous\n * execution claim and never false-completes.\n * - **`bail` → substrate.** Under `bail: true` (halt) a genuine task failure `fail`s the leaf\n * THEN re-throws, so the substrate Runner fail-fasts — it aborts the in-flight siblings\n * (their `controller.signal` fires; a mid-flight sibling `skip`s) and rejects the phase run;\n * `#execute` then `skip`s the remaining tasks / phases (the workflow derives `failed`).\n * Under `bail: false` (graceful) a failure `fail`s the leaf and RESOLVES (never throws), so\n * the Runner settles every unit (allSettled) and the run finishes (the workflow derives\n * `completed`, the failure recorded in the result tree).\n * - **Pause / stop / destroy gates.** Workflow, phase, and task gates are checked before\n * dispatch, and a running handler can checkpoint their folded state through\n * {@link import('./types.js').TaskControllerInterface.wait}. Because the substrate acquires\n * concurrency before this handler gate, a paused task occupies one phase slot until resume;\n * already-running siblings continue and its per-attempt timeout keeps counting. A GRACEFUL\n * `workflow.stop()` (no signal involved) is caught at\n * those same gates: not-yet-started work is `skip`ped, in-flight work finishes naturally. A\n * HARD `workflow.destroy()` aborts {@link WorkflowInterface.signal}, which `#fold` has folded\n * into the run's composed signal — so it cancels the active phase Runner (and every\n * in-flight task) exactly like an external abort / timeout / budget fire. EVERY park on a\n * `wait()` gate is RACED against that same run signal (`#raceWait`, S2) — so a cancel firing\n * WHILE parked unparks the engine promptly instead of hanging until `resume`; the existing\n * halt / abort re-checks after the gate then decide the outcome.\n * - **Abort / Timeout / Budget / entity-signal fold.** `#execute` folds the live workflow's\n * own {@link WorkflowInterface.signal}, the run's external `signal`, a\n * {@link TimeoutInterface}, and the `@orkestrel/budget` package's `BudgetInterface`'s\n * `signal` into one `runSignal` (`AbortSignal.any`); a fire aborts the active phase's Runner\n * (cancelling every in-flight task) and HALTS the run — the remaining tasks / phases `skip`\n * and the workflow is force-`stop`ped (settles `stopped`). Each task's\n * {@link TaskController} signal `AbortSignal.any`-combines the substrate per-unit signal with\n * `runSignal`, so a handler observes either cause directly.\n * - **Re-entrant-safe.** No shared per-run mutable field: the active-Runner holder is LOCAL to\n * each `#execute`, so a nested application-level `execute` cannot clobber the outer run's\n * state.\n */\nexport class WorkflowRunner implements WorkflowRunnerInterface {\n\tstatic readonly #executions = new WeakSet<WorkflowInterface>()\n\treadonly #scheduler: SchedulerInterface\n\n\tconstructor(scheduler: SchedulerInterface) {\n\t\tthis.#scheduler = scheduler\n\t}\n\n\t/**\n\t * Execute a workflow definition to completion — BUILD its live tree, run the phases\n\t * sequentially with each phase's tasks concurrent — resolving its terminal\n\t * {@link WorkflowResult} (whose `workflow` is the freshly-built live tree).\n\t *\n\t * @remarks\n\t * One-shot. The runner BUILDS the live tree from `definition` internally (one source of\n\t * truth — the per-task `run` and per-phase `concurrency` come from the same definition\n\t * the tree is constructed from, so the executed tree can never drift from the metadata).\n\t * The {@link WorkflowOptions} part of `options` (initial `on` listeners, a `bail` override,\n\t * the per-node `phases` bag, the {@link WorkflowOptions.functions} registry each task's\n\t * `run` resolves against) is forwarded to the build. Under `bail: false` (graceful) every\n\t * task settles (a failure is recorded on its {@link TaskInterface}) and the workflow\n\t * reaches `completed`; under `bail: true` (halt) the first failure aborts the in-flight\n\t * sibling tasks AND `skip`s the remaining tasks / phases, settling the workflow `failed`. A\n\t * {@link WorkflowRunOptions} abort / timeout / budget fires every in-flight task's signal\n\t * and `stop`s the run. `execute` resolves (never rejects) on a cancel — the partial outcome\n\t * is read from the returned {@link WorkflowResult} (its `workflow` / `status` / `results`).\n\t * An unexpected scheduler or engine-infrastructure failure rejects after remaining work is\n\t * stopped, swept, and final persistence is attempted.\n\t *\n\t * @param definition - The {@link WorkflowDefinition} to build the live tree from and drive\n\t * @param options - The construction options ({@link WorkflowOptions}: `on` / `bail` /\n\t * `phases` / `functions`) PLUS the per-run bounds (`signal` / `timeout` / `budget`)\n\t * @returns The run's terminal {@link WorkflowResult} (its `workflow` is the built tree)\n\t * @example\n\t * ```ts\n\t * const result = await runner.execute(definition, { timeout: 5_000 })\n\t * result.status // 'completed' | 'failed' | 'stopped'\n\t * ```\n\t */\n\texecute(definition: WorkflowDefinition, options?: WorkflowRunOptions): Promise<WorkflowResult>\n\t/**\n\t * Drive an ALREADY-BUILT, CALLER-OWNED live {@link WorkflowInterface} — the entity-native\n\t * counterpart to the definition-building {@link execute} overload.\n\t *\n\t * @remarks\n\t * `createWorkflow` mints the live tree, this overload drives it, and the caller controls\n\t * the SAME entity mid-run via its own `pause` / `resume` / `add` / `stop` / `destroy`\n\t * (AGENTS §10). Requires `workflow.status === 'pending'`, `!workflow.destroyed`, and no\n\t * prior execution claim. A process-local object-identity claim shared by all runner instances\n\t * is acquired synchronously and never released, so a same-object second call throws a `TRANSITION`\n\t * {@link WorkflowError} before any asynchronous status change. Once accepted, observable\n\t * semantics are byte-identical to the `definition` form —\n\t * except the phase loop RE-READS the live tree every iteration, so a caller's live `add`\n\t * mid-run is picked up and actually dispatched. `options` carries only the per-run bounds\n\t * (`signal` / `timeout` / `budget`) — the construction half of {@link WorkflowRunOptions}\n\t * does not apply, since the tree already exists.\n\t *\n\t * @param workflow - The live {@link WorkflowInterface} to drive\n\t * @param options - The per-run bounds (`signal` / `timeout` / `budget`)\n\t * @returns The run's terminal {@link WorkflowResult} (its `workflow` is the SAME entity passed in)\n\t * @example\n\t * ```ts\n\t * const workflow = createWorkflow(definition)\n\t * const run = runner.execute(workflow)\n\t * workflow.pause()\n\t * workflow.resume()\n\t * await run\n\t * ```\n\t */\n\texecute(\n\t\tworkflow: WorkflowInterface,\n\t\toptions?: Omit<WorkflowRunOptions, keyof WorkflowOptions>,\n\t): Promise<WorkflowResult>\n\texecute(\n\t\ttarget: WorkflowDefinition | WorkflowInterface,\n\t\toptions?: WorkflowRunOptions,\n\t): Promise<WorkflowResult> {\n\t\tif (this.#isWorkflow(target)) {\n\t\t\tconst signal = options?.signal\n\t\t\tconst timeout = options?.timeout\n\t\t\tconst budget = options?.budget\n\t\t\tconst store = options?.store\n\t\t\tthis.#acquire(target)\n\t\t\treturn this.#execute(target, signal, timeout, budget, store)\n\t\t}\n\t\tconst captured = captureWorkflowOptions(options)\n\t\tconst signal = options?.signal\n\t\tconst timeout = options?.timeout\n\t\tconst budget = options?.budget\n\t\tconst store = options?.store\n\t\t// SINGLE SOURCE OF TRUTH: build the live tree from the SAME definition we drive, so the\n\t\t// executed entity can never drift from the `run` / `concurrency` metadata. The\n\t\t// WorkflowOptions half (initial `on` listeners + a `bail` override + the per-node `phases`\n\t\t// bag + the `functions` registry) is applied to the constructed `Workflow` (resolving\n\t\t// `bail` as `options.bail ?? definition.bail ?? DEFAULT_BAIL`); the run-control bounds\n\t\t// (signal/timeout/budget) feed the fold in `#execute`. The tree is built DIRECTLY (not via\n\t\t// `createWorkflow`) so the runner never imports its own module's factory — preserving this\n\t\t// codebase's factories→classes direction (no class↔factory cycle).\n\t\tconst bail = captured.bail ?? target.bail ?? DEFAULT_BAIL\n\t\t// Seed BOTH tiers of the snapshot with the effective bail (`definitionToSnapshot`'s 2nd arg) so\n\t\t// an `options.bail` override reaches each INHERITING phase's snapshot (a per-phase `bail` still\n\t\t// wins). The captured `options.bail` value is preserved (NOT overwritten with the resolved\n\t\t// `bail`): the snapshot already carries the resolved bail at both tiers, so `Workflow` reads\n\t\t// `#bail` from it; injecting a resolved `bail` would make `Workflow` treat it as an EXPLICIT\n\t\t// uniform override and clobber the per-phase overrides. A caller's genuine `options.bail` stays\n\t\t// as given and cascades uniformly. The owned top-level `captured` bag is forwarded — `Workflow`\n\t\t// resolves each task's `handler` from its retained `functions` registry at construction (V-c),\n\t\t// so a definition run and a `createWorkflow` build follow the SAME construction path.\n\t\tconst workflow = new Workflow(definitionToSnapshot(target, bail), captured)\n\t\tthis.#acquire(workflow)\n\t\treturn this.#execute(workflow, signal, timeout, budget, store)\n\t}\n\n\t#acquire(workflow: WorkflowInterface): void {\n\t\tconst tasks = workflow.phases.phases().flatMap((phase) => phase.tasks.tasks())\n\t\tconst runnable =\n\t\t\t(workflow.status === 'pending' || workflow.status === 'running') &&\n\t\t\ttasks.every((task) => task.status !== 'running') &&\n\t\t\t(tasks.length === 0 || tasks.some((task) => task.status === 'pending')) &&\n\t\t\thasWorkflowHandlers(workflow)\n\t\tif (!runnable || workflow.destroyed || WorkflowRunner.#executions.has(workflow)) {\n\t\t\tthrow new WorkflowError('TRANSITION', `workflow '${workflow.id}' is not drivable`, {\n\t\t\t\tid: workflow.id,\n\t\t\t\tstatus: workflow.status,\n\t\t\t\tdestroyed: workflow.destroyed,\n\t\t\t})\n\t\t}\n\t\tWorkflowRunner.#executions.add(workflow)\n\t}\n\n\t// Drive the whole tree: arm the run-level bounds (the folded abort), run the phases\n\t// SEQUENTIALLY — re-reading the live phase list every iteration (live continuity, V7) — then\n\t// assemble the terminal result. A run-level cancel (incl. `workflow.destroy()`, folded into\n\t// `runSignal`) halts the loop and force-`stop`s the workflow; a graceful `workflow.stop()`\n\t// (no signal) is caught at the same halt check without forcing anything (it is already the\n\t// terminal status). The active-Runner `holder` is LOCAL (re-entrant-safe).\n\tasync #execute(\n\t\tworkflow: WorkflowInterface,\n\t\tsignal: AbortSignal | undefined,\n\t\tms: number | undefined,\n\t\tbudget: WorkflowRunOptions['budget'],\n\t\tstore: WorkflowRunOptions['store'],\n\t): Promise<WorkflowResult> {\n\t\t// Arm the deadline + budget and fold every present bound — INCLUDING the live workflow's\n\t\t// own `signal` (fires on `destroy`) — into ONE run signal the tasks race against, the same\n\t\t// fold the agent runtime uses. A fire of any cancels every in-flight task.\n\t\t// Arm only a host-safe deadline. Non-positive, non-finite, and over-max values disable\n\t\t// the bound instead of clamping into an immediate host-timer cancellation.\n\t\t// On a run-level cancel, abort the ACTIVE phase's Runner (cancelling its in-flight tasks).\n\t\t// The active Runner is swapped per phase via the LOCAL holder; a closure over it always\n\t\t// fires the current one. A one-shot listener (the run halts once); cleared in the `finally`.\n\t\tconst holder: { runner: RunnerInterface<TaskInterface, void> | undefined } = {\n\t\t\trunner: undefined,\n\t\t}\n\t\tlet timeout: TimeoutInterface | undefined\n\t\tlet persistence: WorkflowPersistence | undefined\n\t\tlet runSignal: AbortSignal | undefined\n\t\tlet onCancel: (() => void) | undefined\n\t\ttry {\n\t\t\ttimeout =\n\t\t\t\tms !== undefined && Number.isFinite(ms) && ms > 0 && ms <= MAX_TIMER_MS\n\t\t\t\t\t? createTimeout({ ms })\n\t\t\t\t\t: undefined\n\t\t\ttimeout?.start()\n\t\t\tbudget?.start()\n\t\t\trunSignal = this.#fold(workflow, signal, budget, timeout)\n\t\t\tpersistence = store === undefined ? undefined : new WorkflowPersistence(workflow, store)\n\t\t\tonCancel = this.#abortActive.bind(this, holder, runSignal)\n\t\t\tif (runSignal.aborted) onCancel()\n\t\t\telse runSignal.addEventListener('abort', onCancel, { once: true })\n\t\t\tif (persistence !== undefined && !(await persistence.checkpoint('initial'))) {\n\t\t\t\tif (this.#stoppable(workflow)) workflow.stop()\n\t\t\t\tthis.#skipFrom(workflow.phases.phases(), 0)\n\t\t\t}\n\t\t\tlet index = 0\n\t\t\tfor (;;) {\n\t\t\t\t// Re-read the live phase list every iteration (a cursor, not a one-time snapshot) —\n\t\t\t\t// a caller's `workflow.add(phaseDefinition)` mid-run extends this and is picked up.\n\t\t\t\tconst phases = workflow.phases.phases()\n\t\t\t\tif (index >= phases.length) break\n\t\t\t\tconst phase = phases[index]\n\t\t\t\tif (phase === undefined) {\n\t\t\t\t\tindex += 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// A run-level cancel, OR the workflow already reached a terminal status (a prior\n\t\t\t\t// bail-true failure, or a GRACEFUL `workflow.stop()` the caller invoked directly):\n\t\t\t\t// HALT the loop — skip THIS and every remaining phase's tasks, then break.\n\t\t\t\tif (this.#cancelled(runSignal) || this.#halted(workflow)) {\n\t\t\t\t\tthis.#haltFrom(phases, index, workflow, runSignal)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t// The phase-boundary pause gate (AGENTS §10, workflow-only): park until resumed /\n\t\t\t\t// stopped / destroyed, RACED against a run-level cancel (an abort/timeout/budget/\n\t\t\t\t// destroy firing while parked unparks promptly rather than hanging until resume),\n\t\t\t\t// then re-check the halt state fresh (a `stop` / `destroy` may have landed while\n\t\t\t\t// parked) before starting the phase.\n\t\t\t\tif (workflow.paused) await this.#raceWait(workflow.wait(), runSignal, undefined, workflow)\n\t\t\t\tif (this.#cancelled(runSignal) || this.#halted(workflow)) {\n\t\t\t\t\tthis.#haltFrom(workflow.phases.phases(), index, workflow, runSignal)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif (phase.status === 'skipped' || phase.status === 'stopped') {\n\t\t\t\t\tthis.#skipFrom([phase], 0)\n\t\t\t\t\tindex += 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Run the phase to settlement. Under bail-true it REJECTS on the first failure\n\t\t\t\t// (fail-fast) — skip the remaining phases; otherwise it settles all and continues.\n\t\t\t\tconst failed = await this.#runPhase(workflow, phase, runSignal, holder, persistence)\n\t\t\t\tif (failed) {\n\t\t\t\t\tthis.#skipFrom(workflow.phases.phases(), index + 1)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tindex += 1\n\t\t\t\t// Pace BETWEEN phases (never after the last, read from the LIVE count) — the\n\t\t\t\t// cooperative host yield, the shipped scheduler racing the run signal. Only an\n\t\t\t\t// abort-caused rejection is swallowed (the halt guard handles it next iteration);\n\t\t\t\t// any other scheduler error is a genuine fault and re-thrown.\n\t\t\t\tconst remaining = workflow.phases.phases()\n\t\t\t\tif (index < remaining.length && !this.#cancelled(runSignal)) {\n\t\t\t\t\tawait this.#pace(runSignal)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// A run-level cancel makes the run STOPPED — `#haltFrom` forces `stop` BEFORE sweeping\n\t\t\t// (F1-CRITICAL) so the override is set before any per-task skip can drive the derived\n\t\t\t// status to `skipped` first. The substrate RACES an in-flight handler out on abort (its\n\t\t\t// result discarded), so a slow-settling task may still read `running` at this point; the\n\t\t\t// detached handler's own later `skip` is then a guarded no-op.\n\t\t\tif (this.#cancelled(runSignal)) {\n\t\t\t\tthis.#haltFrom(workflow.phases.phases(), 0, workflow, runSignal)\n\t\t\t} else if (this.#completable(workflow)) {\n\t\t\t\tworkflow.complete()\n\t\t\t}\n\t\t\tconst durable = await persistence?.finalize()\n\t\t\treturn {\n\t\t\t\tworkflow,\n\t\t\t\tstatus: workflow.status,\n\t\t\t\tresults: workflow.results(),\n\t\t\t\t...(durable === undefined ? {} : { durable }),\n\t\t\t\t...(persistence?.fault === undefined ? {} : { fault: persistence.fault }),\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.#stoppable(workflow)) workflow.stop()\n\t\t\tthis.#skipFrom(workflow.phases.phases(), 0)\n\t\t\tawait persistence?.finalize()\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tpersistence?.detach()\n\t\t\ttimeout?.clear()\n\t\t\tif (runSignal !== undefined && onCancel !== undefined) {\n\t\t\t\trunSignal.removeEventListener('abort', onCancel)\n\t\t\t}\n\t\t}\n\t}\n\n\tasync #pace(signal: AbortSignal): Promise<void> {\n\t\ttry {\n\t\t\tawait this.#scheduler.yield({ signal })\n\t\t} catch (error) {\n\t\t\tif (!signal.aborted) throw error\n\t\t}\n\t}\n\n\t// Run ONE phase's tasks CONCURRENTLY through a single substrate Runner. Returns whether the\n\t// phase failed under bail-true (so `#execute` skips the rest) — `false` for a graceful\n\t// settle-all AND for a run-level cancel (which is NOT a phase failure; `#execute`'s halt\n\t// guard handles the skip + the workflow `stop`). The Runner provides bounded concurrency +\n\t// the fail-fast abort cascade; this handler only drives the live task entity.\n\t//\n\t// LIVE continuity (V7): subscribes to the phase's `add` event BEFORE capturing its task\n\t// list, so a task minted onto this phase mid-run (`phase.add`) is picked up — `spawn`ed onto\n\t// the SAME substrate Runner the declared tasks run on, under the same `concurrency`. A\n\t// `spawn` that the Runner can no longer accept (the tight drain-race window its own doc\n\t// describes) returns `undefined`, tolerated here — the `finally` sweep below `skip`s any\n\t// task STILL `pending` after the phase settles, so the phase always reaches a coherent\n\t// terminal state regardless of that race.\n\tasync #runPhase(\n\t\tworkflow: WorkflowInterface,\n\t\tphase: PhaseInterface,\n\t\trunSignal: AbortSignal,\n\t\tholder: { runner: RunnerInterface<TaskInterface, void> | undefined },\n\t\tpersistence: WorkflowPersistence | undefined,\n\t): Promise<boolean> {\n\t\tconst launched = new Set<string>()\n\t\tconst onAdd = this.#spawnAdded.bind(this, launched, holder)\n\t\tphase.emitter.on('add', onAdd)\n\t\ttry {\n\t\t\tconst tasks = phase.tasks.tasks()\n\t\t\tfor (const task of tasks) launched.add(task.id)\n\t\t\tif (tasks.length === 0) return false\n\t\t\t// The EFFECTIVE per-phase failure policy and resource throttle are read straight off the\n\t\t\t// LIVE phase (V7): `phase.bail` is already the resolved `phase.bail ?? workflow.bail`, and\n\t\t\t// `phase.concurrency` mirrors the definition/mint it was built from — no definition\n\t\t\t// correlation needed. Clamp a non-positive concurrency (unbounded / not validated) to the\n\t\t\t// default — a non-positive throttle means \"no throttle declared\" ⇒ run them all.\n\t\t\tconst bail = phase.bail\n\t\t\tconst concurrency =\n\t\t\t\tphase.concurrency !== undefined && phase.concurrency > 0\n\t\t\t\t\t? phase.concurrency\n\t\t\t\t\t: DEFAULT_PHASE_CONCURRENCY\n\t\t\t// The substrate Queue retries a failed task by RE-INVOKING its handler (`#runTask`), so the\n\t\t\t// leaf must survive a failed attempt to recover on a later one. This run-local map counts each\n\t\t\t// task's attempts (by id) so `#runTask` can DEFER the leaf `fail` until the FINAL attempt\n\t\t\t// (`attempt > retries`) — an intermediate failure re-throws (driving the Queue's retry) WITHOUT\n\t\t\t// terminating the leaf, so a subsequent success can still `complete` it. A no-retry task's first\n\t\t\t// attempt IS its final one, so this reduces to today's behavior exactly. Fresh per phase run.\n\t\t\tconst attempts = new Map<string, number>()\n\t\t\tfor (const task of tasks) attempts.set(task.id, task.attempts)\n\t\t\tconst owners = new Map<string, number>()\n\t\t\tconst created = new Runner<TaskInterface, void>({\n\t\t\t\tconcurrency,\n\t\t\t\t// Thread retries into the substrate unit. Per-attempt deadlines stay in this workflow\n\t\t\t\t// layer so timeout settlement follows the phase's bail policy before the unit resolves.\n\t\t\t\tentries: this.#entry.bind(this),\n\t\t\t\thandler: this.#runUnit.bind(this, workflow, runSignal, bail, attempts, owners, persistence),\n\t\t\t})\n\t\t\tholder.runner = created\n\t\t\ttry {\n\t\t\t\t// The Runner sequences + bounds the work; its ordered results are unused (the OUTCOME\n\t\t\t\t// lives on each live task). Under bail-true the FIRST failure rejects this — fail-fast.\n\t\t\t\tawait created.execute(tasks)\n\t\t\t\treturn false\n\t\t\t} catch {\n\t\t\t\t// The phase Runner rejected. Two causes reject it: a bail-true fail-fast (a task threw,\n\t\t\t\t// so the Runner aborted the siblings) — a genuine phase failure, report `true` so\n\t\t\t\t// `#execute` skips the rest (the failing leaf already `fail`ed). OR a run-level cancel I\n\t\t\t\t// forwarded (`onCancel` → `runner.abort`) — NOT a phase failure: report `false` and let\n\t\t\t\t// `#execute`'s halt guard skip the remaining phases + force the workflow `stop`.\n\t\t\t\treturn !this.#cancelled(runSignal)\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tawait created.destroy()\n\t\t\t\t} finally {\n\t\t\t\t\tholder.runner = undefined\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tphase.emitter.off('add', onAdd)\n\t\t\t// F1-CRITICAL: on a GENUINE run-level cancel, force the workflow `stop` BEFORE this\n\t\t\t// sweep — the sweep below can itself skip every non-terminal task and drive the derived\n\t\t\t// workflow status to `skipped` first, and `stop()` (F1) is a NO-OP once `status` is\n\t\t\t// already terminal. Forcing here (this `finally` runs BEFORE `#execute` regains control)\n\t\t\t// is required — `#execute`'s own halt guard would otherwise find the workflow already\n\t\t\t// terminal by the time it runs. Not a signal cancel (e.g. a normal phase settle, or a\n\t\t\t// bail-true fail-fast the caller already `fail`ed): no forcing, just the coherent sweep.\n\t\t\tif (this.#cancelled(runSignal) && this.#stoppable(workflow)) workflow.stop()\n\t\t\t// Coherent terminal state (V7): a task minted too late for `spawn` to accept (the\n\t\t\t// drain-race window) is left `pending` with nothing driving it — sweep it `skip`ped now.\n\t\t\t// A no-op for every task the substrate already settled (terminal statuses ignore `skip`).\n\t\t\tfor (const task of phase.tasks.tasks()) this.#skip(task)\n\t\t}\n\t}\n\n\t#abortActive(\n\t\tholder: { runner: RunnerInterface<TaskInterface, void> | undefined },\n\t\trunSignal: AbortSignal,\n\t): void {\n\t\tvoid holder.runner?.abort(runSignal.reason)\n\t}\n\n\t#spawnAdded(\n\t\tlaunched: Set<string>,\n\t\tholder: { runner: RunnerInterface<TaskInterface, void> | undefined },\n\t\ttask: TaskInterface,\n\t): void {\n\t\tif (launched.has(task.id)) return\n\t\tlaunched.add(task.id)\n\t\tvoid holder.runner?.spawn(task)\n\t}\n\n\t#entry(task: TaskInterface): RunnerEntryOptions {\n\t\tconst retries = Math.max(0, (task.retries ?? 0) - task.attempts)\n\t\treturn retries === 0 ? {} : { retries }\n\t}\n\n\t#runUnit(\n\t\tworkflow: WorkflowInterface,\n\t\trunSignal: AbortSignal,\n\t\tbail: boolean,\n\t\tattempts: Map<string, number>,\n\t\towners: Map<string, number>,\n\t\tpersistence: WorkflowPersistence | undefined,\n\t\tcontroller: ControllerInterface<TaskInterface, void>,\n\t): Promise<void> {\n\t\treturn this.#runTask(\n\t\t\tworkflow,\n\t\t\tcontroller.input,\n\t\t\tcontroller,\n\t\t\trunSignal,\n\t\t\tbail,\n\t\t\tattempts,\n\t\t\towners,\n\t\t\tpersistence,\n\t\t)\n\t}\n\n\t// Run ONE task: drive the live entity through its transitions around its OWN resolved\n\t// handler. `start` (once), invoke `task.handler` (or auto-complete an omitted `run`), then\n\t// `complete(value)` on a returned value or `fail(error)` on a FINAL-attempt failure. A\n\t// genuine CANCEL (`#skipping` — a run-level bound, or a sibling's fail-fast under bail-true)\n\t// `skip`s the task instead; a GRACEFUL `workflow.stop()` reaching this pre-dispatch gate\n\t// likewise `skip`s a not-yet-started task (V7) without touching an in-flight one (checked\n\t// ONLY here, before `task.start()` — never in the post-dispatch checks below, so a task\n\t// already running when `stop()` lands finishes naturally).\n\t//\n\t// THREE abort causes reach this task's signal and MUST be told apart:\n\t// • a workflow-owned per-attempt TIMEOUT — fires ONLY the folded attempt signal, never\n\t// the unit `Abort` (`controller.aborted`) nor `runSignal`;\n\t// • a SIBLING fail-fast under bail (the Runner aborts in-flight siblings on a failure) — aborts\n\t// the unit `Abort` ⇒ `controller.aborted`;\n\t// • a run-level CANCEL (abort / timeout / budget / `workflow.destroy()`, all folded into\n\t// `runSignal`) — fires `runSignal` (and, forwarded through the phase Runner's abort, the unit\n\t// `Abort` too).\n\t// So `#skipping` (`controller.aborted || runSignal.aborted`) is the genuine-cancel discriminator,\n\t// and a BARE timeout is `signal.aborted && !#skipping` — a RETRYABLE FAILURE of this attempt, NOT\n\t// a skip: it joins the retry-cooperative path below (non-final ⇒ leaf stays `running` for the\n\t// Queue's own retry; final ⇒ `task.fail` so the leaf is `failed`, visible to `bail` /\n\t// `deriveWorkflowStatus`), never `#skip` (which would lose a recovered result and hide the fault).\n\t//\n\t// RETRIES: the substrate Queue re-invokes this handler per attempt (threaded `retries`), so the\n\t// leaf must survive an intermediate failure to recover. `attempts` counts this task's invocations;\n\t// an attempt that is NOT the last (`attempt <= retries`) re-throws on a thrown failure to DRIVE the\n\t// Queue's retry WITHOUT failing the leaf (it stays `running`, so a later attempt can still\n\t// `complete`); a non-final TIMEOUT likewise leaves the leaf `running` and rejects to request\n\t// the substrate retry. Only the FINAL attempt records the leaf `fail`. A no-retry\n\t// task's first attempt is its final one, so the no-timeout path is byte-identical to before. On the\n\t// FINAL thrown failure: bail-true re-throws so the substrate Runner fail-fasts (aborts siblings +\n\t// rejects the phase run); bail-false swallows (the failure is recorded and the run settles all).\n\tasync #runTask(\n\t\tworkflow: WorkflowInterface,\n\t\ttask: TaskInterface,\n\t\tcontroller: ControllerInterface<TaskInterface, void>,\n\t\trunSignal: AbortSignal,\n\t\tbail: boolean,\n\t\tattempts: Map<string, number>,\n\t\towners: Map<string, number>,\n\t\tpersistence: WorkflowPersistence | undefined,\n\t): Promise<void> {\n\t\t// The task's folded cancellation handed to the handler: the substrate per-unit ATTEMPT signal\n\t\t// (fires on this Runner's abort — a sibling fail-fast or a run-level cancel I forwarded — OR on\n\t\t// the per-attempt deadline) ANY-combined with the run signal directly, so a handler observes\n\t\t// any cause. `createAbort` does the fold. NOTE this is broader than the genuine-cancel test:\n\t\t// `signal.aborted` is true for a bare timeout too, which is why `#skipping` (the unit-abort /\n\t\t// run-cancel discriminator) — not `signal.aborted` — gates the skip path.\n\t\t// This attempt's 1-based number, and whether it is the LAST the Queue will make (the per-task\n\t\t// `retries` + 1 total; the substrate floors negative retries at 0). The leaf is failed only on\n\t\t// the final attempt, so an earlier failure/timeout leaves the leaf `running` to retry.\n\t\tconst attempt = (attempts.get(task.id) ?? 0) + 1\n\t\tattempts.set(task.id, attempt)\n\t\tconst retries = Math.max(0, task.retries ?? 0)\n\t\tconst last = attempt > retries\n\t\tif (task.status !== 'pending' && task.status !== 'running') return\n\t\t// Pre-existing cancellation wins before this attempt claims a running slot.\n\t\tif (this.#skipping(task, controller, runSignal) || this.#halted(workflow, task.phase)) {\n\t\t\tthis.#settleCancelled(task, workflow, runSignal)\n\t\t\treturn\n\t\t}\n\t\tconst ms = task.timeout\n\t\tconst deadline =\n\t\t\tms !== undefined && Number.isFinite(ms) && ms > 0 && ms <= MAX_TIMER_MS\n\t\t\t\t? createTimeout({ ms })\n\t\t\t\t: undefined\n\t\tconst signal = this.#taskSignal(task, controller.signal, runSignal, deadline)\n\t\ttry {\n\t\t\t// Once the attempt owns its slot, start/reset activity before racing every pause gate\n\t\t\t// against the folded attempt/task/run signal. A deadline can therefore retry/fail a paused\n\t\t\t// attempt without dispatching its external handler.\n\t\t\ttask.start()\n\t\t\tif (task.attempts !== attempt) return\n\t\t\towners.set(task.id, attempt)\n\t\t\tdeadline?.start()\n\t\t\tconst durable =\n\t\t\t\tpersistence === undefined ? true : await persistence.checkpoint('attempt', task, attempt)\n\t\t\tif (!this.#owns(owners, task, attempt)) return\n\t\t\tif (!durable) {\n\t\t\t\tif (this.#stoppable(workflow)) workflow.stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (task.run !== undefined && task.handler === undefined) {\n\t\t\t\tconst error = new WorkflowError(\n\t\t\t\t\t'TRANSITION',\n\t\t\t\t\t`task '${task.id}' has an unresolved run '${task.run}'`,\n\t\t\t\t\t{ task: task.id, run: task.run },\n\t\t\t\t)\n\t\t\t\ttask.fail({ origin: 'handler', message: error.message })\n\t\t\t\tif (bail) throw error\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (\n\t\t\t\tawait this.#gate(\n\t\t\t\t\tworkflow.paused ? workflow.wait() : undefined,\n\t\t\t\t\ttask,\n\t\t\t\t\tworkflow,\n\t\t\t\t\tcontroller,\n\t\t\t\t\trunSignal,\n\t\t\t\t\tsignal,\n\t\t\t\t\tattempts,\n\t\t\t\t\towners,\n\t\t\t\t\tattempt,\n\t\t\t\t\tlast,\n\t\t\t\t\tbail,\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn\n\t\t\tif (\n\t\t\t\tawait this.#gate(\n\t\t\t\t\ttask.phase.paused ? task.phase.wait() : undefined,\n\t\t\t\t\ttask,\n\t\t\t\t\tworkflow,\n\t\t\t\t\tcontroller,\n\t\t\t\t\trunSignal,\n\t\t\t\t\tsignal,\n\t\t\t\t\tattempts,\n\t\t\t\t\towners,\n\t\t\t\t\tattempt,\n\t\t\t\t\tlast,\n\t\t\t\t\tbail,\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn\n\t\t\tif (\n\t\t\t\tawait this.#gate(\n\t\t\t\t\ttask.paused ? task.wait() : undefined,\n\t\t\t\t\ttask,\n\t\t\t\t\tworkflow,\n\t\t\t\t\tcontroller,\n\t\t\t\t\trunSignal,\n\t\t\t\t\tsignal,\n\t\t\t\t\tattempts,\n\t\t\t\t\towners,\n\t\t\t\t\tattempt,\n\t\t\t\t\tlast,\n\t\t\t\t\tbail,\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn\n\t\t\t// A genuine CANCEL that landed BEFORE dispatch (a run-level bound, or a sibling fail-fast), OR\n\t\t\t// a GRACEFUL `workflow.stop()` the caller invoked directly (V7 — no signal involved): skip\n\t\t\t// without running the handler. A bare per-attempt timeout cannot precede dispatch (its\n\t\t\t// deadline is armed as the attempt begins), so it is excluded from this skip.\n\t\t\tif (this.#skipping(task, controller, runSignal) || this.#halted(workflow, task.phase)) {\n\t\t\t\tthis.#settleCancelled(task, workflow, runSignal)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (task.status !== 'running') return\n\t\t\t// The task's open `metadata` bag is on its snapshot (the live `TaskContext` carries only\n\t\t\t// lineage), so read it from there — the task's input the handler may inspect.\n\t\t\tconst handle = new TaskController(\n\t\t\t\tsignal,\n\t\t\t\ttask.snapshot().metadata,\n\t\t\t\ttask,\n\t\t\t\tattempt,\n\t\t\t\t() => workflow.results(),\n\t\t\t\t(input) =>\n\t\t\t\t\tthis.#owns(owners, task, attempt) && !signal.aborted\n\t\t\t\t\t\t? task.report(input)\n\t\t\t\t\t\t: failure(\n\t\t\t\t\t\t\t\tnew WorkflowError(\n\t\t\t\t\t\t\t\t\t'TRANSITION',\n\t\t\t\t\t\t\t\t\t`task '${task.id}' attempt '${attempt}' no longer owns activity`,\n\t\t\t\t\t\t\t\t\t{ task: task.id, attempt },\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t() => this.#owns(owners, task, attempt) && !signal.aborted && task.pulse(),\n\t\t\t)\n\t\t\tlet outcome:\n\t\t\t\t| readonly [settled: true, value: JSONValue]\n\t\t\t\t| readonly [settled: false, value: undefined, genuine?: boolean]\n\t\t\ttry {\n\t\t\t\t// Invoke the task's OWN resolved handler directly. `undefined` is reachable here only\n\t\t\t\t// for an omitted `run`, the deliberate JSON-null no-op form.\n\t\t\t\toutcome =\n\t\t\t\t\ttask.handler === undefined\n\t\t\t\t\t\t? [true, null]\n\t\t\t\t\t\t: await this.#raceHandler(\n\t\t\t\t\t\t\t\tPromise.resolve(task.handler(handle)),\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tthis.#skipping.bind(this, task, controller, runSignal),\n\t\t\t\t\t\t\t)\n\t\t\t} catch (error) {\n\t\t\t\tif (!this.#owns(owners, task, attempt)) return\n\t\t\t\t// A handler threw. If the runner already swept this task terminal, or a genuine cancel\n\t\t\t\t// fired, treat it as a halt — `#skip` (guarded).\n\t\t\t\tif (task.status !== 'running' || this.#skipping(task, controller, runSignal)) {\n\t\t\t\t\tthis.#settleCancelled(task, workflow, runSignal)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// A bare per-attempt TIMEOUT surfaced as a throw (a signal-aware handler threw on the\n\t\t\t\t// deadline): the retryable-failure path, same as the resolve branch above.\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tthis.#timedOut(owners, task, attempt, last, bail)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tthis.#failed(owners, task, attempt, error, last, bail)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (!this.#owns(owners, task, attempt)) return\n\t\t\tif (!outcome[0]) {\n\t\t\t\tthis.#settleAttempt(\n\t\t\t\t\ttask,\n\t\t\t\t\tworkflow,\n\t\t\t\t\tcontroller,\n\t\t\t\t\trunSignal,\n\t\t\t\t\tsignal,\n\t\t\t\t\tattempts,\n\t\t\t\t\towners,\n\t\t\t\t\tattempt,\n\t\t\t\t\tlast,\n\t\t\t\t\tbail,\n\t\t\t\t\toutcome[2],\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (task.status !== 'running') return\n\t\t\tif (this.#skipping(task, controller, runSignal)) {\n\t\t\t\tthis.#settleCancelled(task, workflow, runSignal)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (signal.aborted) {\n\t\t\t\tthis.#timedOut(owners, task, attempt, last, bail)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (!this.#owns(owners, task, attempt)) return\n\t\t\ttry {\n\t\t\t\ttask.complete(outcome[1])\n\t\t\t} catch (error) {\n\t\t\t\tif (!this.#owns(owners, task, attempt)) return\n\t\t\t\tif (task.status !== 'running') throw error\n\t\t\t\tthis.#failed(owners, task, attempt, error, last, bail)\n\t\t\t}\n\t\t} finally {\n\t\t\tdeadline?.clear()\n\t\t\tif (\n\t\t\t\tpersistence !== undefined &&\n\t\t\t\tthis.#owns(owners, task, attempt) &&\n\t\t\t\tisTerminalStatus(task.status) &&\n\t\t\t\t!(await persistence.checkpoint('settlement', task, attempt)) &&\n\t\t\t\tthis.#stoppable(workflow)\n\t\t\t) {\n\t\t\t\tworkflow.stop()\n\t\t\t}\n\t\t\tthis.#revoke(owners, task.id, attempt)\n\t\t}\n\t}\n\n\t// Check one cooperative gate and settle any cancellation or timeout that won its race.\n\tasync #gate(\n\t\twait: Promise<void> | undefined,\n\t\ttask: TaskInterface,\n\t\tworkflow: WorkflowInterface,\n\t\tcontroller: ControllerInterface<TaskInterface, void>,\n\t\trunSignal: AbortSignal,\n\t\tsignal: AbortSignal,\n\t\tattempts: Map<string, number>,\n\t\towners: Map<string, number>,\n\t\tattempt: number,\n\t\tlast: boolean,\n\t\tbail: boolean,\n\t): Promise<boolean> {\n\t\tconst genuine =\n\t\t\twait === undefined\n\t\t\t\t? undefined\n\t\t\t\t: await this.#raceWait(\n\t\t\t\t\t\twait,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tthis.#skipping.bind(this, task, controller, runSignal),\n\t\t\t\t\t\tworkflow,\n\t\t\t\t\t\ttask.phase,\n\t\t\t\t\t)\n\t\treturn this.#settleAttempt(\n\t\t\ttask,\n\t\t\tworkflow,\n\t\t\tcontroller,\n\t\t\trunSignal,\n\t\t\tsignal,\n\t\t\tattempts,\n\t\t\towners,\n\t\t\tattempt,\n\t\t\tlast,\n\t\t\tbail,\n\t\t\tgenuine,\n\t\t)\n\t}\n\n\t#settleAttempt(\n\t\ttask: TaskInterface,\n\t\tworkflow: WorkflowInterface,\n\t\tcontroller: ControllerInterface<TaskInterface, void>,\n\t\trunSignal: AbortSignal,\n\t\tsignal: AbortSignal,\n\t\tattempts: Map<string, number>,\n\t\towners: Map<string, number>,\n\t\tattempt: number,\n\t\tlast: boolean,\n\t\tbail: boolean,\n\t\tgenuine?: boolean,\n\t): boolean {\n\t\tif (attempts.get(task.id) !== attempt || !this.#owns(owners, task, attempt)) return true\n\t\tif (signal.aborted) {\n\t\t\tif (genuine ?? this.#skipping(task, controller, runSignal)) {\n\t\t\t\tthis.#settleCancelled(task, workflow, runSignal)\n\t\t\t} else {\n\t\t\t\tthis.#timedOut(owners, task, attempt, last, bail)\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t\tif (this.#skipping(task, controller, runSignal) || this.#halted(workflow, task.phase)) {\n\t\t\tthis.#settleCancelled(task, workflow, runSignal)\n\t\t\treturn true\n\t\t}\n\t\treturn task.status !== 'running'\n\t}\n\n\tasync #raceHandler(\n\t\thandler: Promise<JSONValue>,\n\t\tsignal: AbortSignal,\n\t\tcancelled: () => boolean,\n\t): Promise<\n\t\t| readonly [settled: true, value: JSONValue]\n\t\t| readonly [settled: false, value: undefined, genuine?: boolean]\n\t> {\n\t\tif (signal.aborted) return [false, undefined, cancelled()]\n\t\tconst deferred = Promise.withResolvers<\n\t\t\t| readonly [settled: true, value: JSONValue]\n\t\t\t| readonly [settled: false, value: undefined, genuine?: boolean]\n\t\t>()\n\t\tconst onAbort = this.#resolveHandlerAbort.bind(this, deferred, cancelled)\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\ttry {\n\t\t\treturn await Promise.race([\n\t\t\t\thandler.then((value): readonly [true, JSONValue] => [true, value]),\n\t\t\t\tdeferred.promise,\n\t\t\t])\n\t\t} finally {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t}\n\t}\n\n\t#resolveHandlerAbort(\n\t\tdeferred: PromiseWithResolvers<\n\t\t\t| readonly [settled: true, value: JSONValue]\n\t\t\t| readonly [settled: false, value: undefined, genuine?: boolean]\n\t\t>,\n\t\tcancelled: () => boolean,\n\t): void {\n\t\tdeferred.resolve([false, undefined, cancelled()])\n\t}\n\n\t// Settle a timed-out attempt. A non-final timeout rejects to drive the substrate retry.\n\t// A final timeout always fails the leaf, then rejects only when the phase is fail-fast.\n\t#timedOut(\n\t\towners: Map<string, number>,\n\t\ttask: TaskInterface,\n\t\tattempt: number,\n\t\tlast: boolean,\n\t\tbail: boolean,\n\t): void {\n\t\tif (!this.#owns(owners, task, attempt)) return\n\t\tconst error = new Error(`task '${task.id}' timed out`)\n\t\tif (last) task.fail({ origin: 'timeout', message: error.message })\n\t\tif (!last || bail) throw error\n\t}\n\n\t#failed(\n\t\towners: Map<string, number>,\n\t\ttask: TaskInterface,\n\t\tattempt: number,\n\t\terror: unknown,\n\t\tlast: boolean,\n\t\tbail: boolean,\n\t): void {\n\t\tif (!this.#owns(owners, task, attempt)) return\n\t\tif (!last) throw error\n\t\ttask.fail({ origin: 'handler', message: errorToMessage(error) })\n\t\tif (bail) throw error\n\t}\n\n\t#owns(owners: Map<string, number>, task: TaskInterface, attempt: number): boolean {\n\t\treturn owners.get(task.id) === attempt && task.attempts === attempt\n\t}\n\n\t#revoke(owners: Map<string, number>, id: string, attempt: number): void {\n\t\tif (owners.get(id) === attempt) owners.delete(id)\n\t}\n\n\t// RACE a parked entity `wait()` against a run-level cancel (S2 — the gate/signal race fix): an\n\t// external abort / timeout / budget / `workflow.destroy()` firing WHILE the engine is parked on\n\t// `workflow.wait()` / `phase.wait()` must unpark it PROMPTLY rather than leaving it hung until\n\t// `resume` — the entity's own `wait()` never rejects and is only ever released by\n\t// resume/stop/skip/destroy, so the runner (not the entity) is responsible for racing it against\n\t// the run signal. A one-shot abort listener is wrapped in a promise and ALWAYS removed after the\n\t// race settles (never leaked) — no polling either way. An already-aborted signal short-circuits.\n\t//\n\t// NOT rewritten onto `helpers.parkSignal`: `parkSignal` has no mechanism to detach its own\n\t// listener early when `wait()` wins the race — it self-removes only via its `{ once: true }`\n\t// firing on `runSignal`'s eventual abort, which for a run with many pause gates (each call site\n\t// adding its own listener) would accumulate listeners on `runSignal` for the run's whole\n\t// lifetime instead of one-at-a-time. The hand-rolled promise here keeps the SAME one-shot-abort\n\t// shape as `parkSignal` but stays REMOVABLE, so it is cleaned up the instant the race settles\n\t// either way — correctness over reuse.\n\tasync #raceWait(\n\t\twait: Promise<void>,\n\t\tsignal: AbortSignal,\n\t\tcancelled?: () => boolean,\n\t\tworkflow?: WorkflowInterface,\n\t\tphase?: PhaseInterface,\n\t): Promise<boolean | undefined> {\n\t\tif (signal.aborted) return cancelled?.()\n\t\tconst deferred = Promise.withResolvers<boolean | undefined>()\n\t\tconst onAbort = this.#resolveWaitAbort.bind(this, deferred, cancelled)\n\t\tconst onTerminal = this.#resolveWaitAbort.bind(this, deferred, undefined)\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\tworkflow?.emitter.on('skip', onTerminal)\n\t\tworkflow?.emitter.on('stop', onTerminal)\n\t\tphase?.emitter.on('skip', onTerminal)\n\t\tphase?.emitter.on('stop', onTerminal)\n\t\ttry {\n\t\t\tif (workflow !== undefined && this.#halted(workflow, phase)) deferred.resolve(undefined)\n\t\t\tconst outcome = await Promise.race([wait, deferred.promise])\n\t\t\treturn typeof outcome === 'boolean' ? outcome : undefined\n\t\t} finally {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\tworkflow?.emitter.off('skip', onTerminal)\n\t\t\tworkflow?.emitter.off('stop', onTerminal)\n\t\t\tphase?.emitter.off('skip', onTerminal)\n\t\t\tphase?.emitter.off('stop', onTerminal)\n\t\t}\n\t}\n\n\t#resolveWaitAbort(\n\t\tdeferred: PromiseWithResolvers<boolean | undefined>,\n\t\tcancelled: (() => boolean) | undefined,\n\t): void {\n\t\tdeferred.resolve(cancelled?.())\n\t}\n\n\t// The per-task folded signal: ANY-combine the substrate per-unit signal with the run signal via\n\t// the native `AbortSignal.any`. No hand-rolled listener wiring, no extra wrapping — `AbortSignal.any`\n\t// already returns a plain `AbortSignal`. `runSignal` is always present (V7 — it always folds in the\n\t// live workflow's own signal), so there is no longer a bare-`unitSignal` shortcut to take.\n\t#taskSignal(\n\t\ttask: TaskInterface,\n\t\tunitSignal: AbortSignal,\n\t\trunSignal: AbortSignal,\n\t\ttimeout: TimeoutInterface | undefined,\n\t): AbortSignal {\n\t\tconst signals = [task.signal, unitSignal, runSignal]\n\t\tif (timeout !== undefined) signals.push(timeout.signal)\n\t\treturn AbortSignal.any(signals)\n\t}\n\n\t// Fold the run-level bounds into ONE signal — the LIVE workflow's own `signal` (fires on\n\t// `destroy`, V7), the run's external `signal`, the deadline, and the budget, combined via\n\t// `AbortSignal.any` (the agent runtime's `#parents` pattern). The workflow's signal is always\n\t// present, so this always returns a defined signal (never `undefined`) — a workflow that is\n\t// never `destroy`ed simply never fires it, so a bounds-free run is unaffected.\n\t#fold(\n\t\tworkflow: WorkflowInterface,\n\t\tsignal: AbortSignal | undefined,\n\t\tbudget: WorkflowRunOptions['budget'],\n\t\ttimeout: TimeoutInterface | undefined,\n\t): AbortSignal {\n\t\tconst signals: AbortSignal[] = [workflow.signal]\n\t\tif (signal !== undefined) signals.push(signal)\n\t\tif (timeout !== undefined) signals.push(timeout.signal)\n\t\tif (budget !== undefined) signals.push(budget.signal)\n\t\treturn signals.length === 1 ? workflow.signal : AbortSignal.any(signals)\n\t}\n\n\t// HALT from `index`: when the halt is a GENUINE run-level CANCEL (F1-CRITICAL), force the\n\t// workflow `stop` BEFORE sweeping — `stop()` is a NO-OP once `status` is already terminal\n\t// (F1), so forcing it FIRST (while the derived status is still non-terminal) is the only\n\t// ordering that survives the sweep driving every remaining task to `skipped`; sweeping first\n\t// would silently turn the intended `stopped` into a derived `skipped`. When the halt is NOT a\n\t// signal cancel (a prior bail-true `failed`, or a caller's own direct `workflow.stop()` /\n\t// `skip()`), the workflow is ALREADY validly terminal — no forcing needed, just sweep.\n\t#haltFrom(\n\t\tphases: readonly PhaseInterface[],\n\t\tindex: number,\n\t\tworkflow: WorkflowInterface,\n\t\trunSignal: AbortSignal,\n\t): void {\n\t\tif (this.#cancelled(runSignal) && this.#stoppable(workflow)) workflow.stop()\n\t\tthis.#skipFrom(phases, index)\n\t}\n\n\t// Skip every not-yet-settled task across phases `index..end` — the halt path (a run-level\n\t// cancel, or the remaining phases after a bail-true failure). Only a `pending` / `running`\n\t// task can `skip` (a settled one ignores it), so this is safe over already-finished phases.\n\t#skipFrom(phases: readonly PhaseInterface[], index: number): void {\n\t\tfor (let cursor = index; cursor < phases.length; cursor += 1) {\n\t\t\tconst phase = phases[cursor]\n\t\t\tif (phase === undefined) continue\n\t\t\tfor (const task of phase.tasks.tasks()) this.#skip(task)\n\t\t}\n\t}\n\n\t// F1-CRITICAL: the same stop-before-skip ordering as `#haltFrom`, applied to a SINGLE task\n\t// skip inside `#runTask`. A per-task skip on a genuine run-level cancel can itself drive the\n\t// derived workflow status to `skipped` before `#execute` / `#runPhase` ever get control back\n\t// (this call happens INSIDE the substrate's per-unit handler) — so force the workflow `stop`\n\t// FIRST (while `#stoppable`) whenever the skip is due to `#cancelled(runSignal)`, then skip.\n\t// A skip caused ONLY by a sibling fail-fast (`controller.aborted` under bail, no run-level\n\t// signal fired) does NOT force anything — that path is a genuine phase failure, not a cancel.\n\t#settleCancelled(task: TaskInterface, workflow: WorkflowInterface, runSignal: AbortSignal): void {\n\t\tif (this.#cancelled(runSignal) && this.#stoppable(workflow)) workflow.stop()\n\t\tthis.#skip(task)\n\t}\n\n\t// Skip one task iff it is not already terminal — a settled leaf has no legal `skip`\n\t// transition (it would throw a `TRANSITION` WorkflowError), so guard on the live status.\n\t#skip(task: TaskInterface): void {\n\t\tif (task.status === 'pending' || task.status === 'running') task.skip()\n\t}\n\n\t// Whether an in-flight task is being GENUINELY CANCELLED (and so should `skip`), as opposed to\n\t// merely TIMED OUT (which retries / fails). Two causes fire a task's attempt signal as a genuine\n\t// cancel: the unit `Abort` — `controller.aborted` — fired by a SIBLING fail-fast under bail OR by\n\t// a run-level cancel I forwarded through the phase Runner's abort; and the run signal directly\n\t// (`runSignal.aborted`, which now also covers `workflow.destroy()`, V7). A per-attempt TIMEOUT\n\t// fires NEITHER (it aborts only the deadline portion of the attempt signal, never the unit `Abort`\n\t// nor the run signal), so it is excluded — the precise discriminator that keeps a timeout off the\n\t// skip path. A fresh read each call so it reflects a cancel that landed mid-dispatch.\n\t#skipping(\n\t\ttask: TaskInterface,\n\t\tcontroller: ControllerInterface<TaskInterface, void>,\n\t\trunSignal: AbortSignal,\n\t): boolean {\n\t\treturn task.signal.aborted || controller.aborted || runSignal.aborted\n\t}\n\n\t// Whether the run-level signal has fired (a fresh read, so it reflects an abort — incl. a\n\t// `workflow.destroy()`, V7 — that landed during a phase).\n\t#cancelled(runSignal: AbortSignal): boolean {\n\t\treturn runSignal.aborted\n\t}\n\n\t// Whether the workflow is no longer runnable — its derived status has reached a terminal\n\t// state (a bail-true failure flipped it to `failed`, a GRACEFUL `workflow.stop()` the caller\n\t// invoked directly, or a force `skip`), so the remaining / not-yet-started work must not run.\n\t#halted(workflow: WorkflowInterface, phase?: PhaseInterface): boolean {\n\t\tconst status = workflow.status\n\t\treturn (\n\t\t\tstatus === 'failed' ||\n\t\t\tstatus === 'skipped' ||\n\t\t\tstatus === 'stopped' ||\n\t\t\tphase?.status === 'skipped' ||\n\t\t\tphase?.status === 'stopped'\n\t\t)\n\t}\n\n\t#stoppable(workflow: WorkflowInterface): boolean {\n\t\tconst status = workflow.status\n\t\treturn status !== 'failed' && status !== 'stopped'\n\t}\n\n\t// A NATURALLY-finished run that still derives `pending` executed but recorded NO work (zero phases,\n\t// or all phases empty / no-op) — vacuously done ⇒ force `completed`. Gated on EXACTLY `pending` so a\n\t// real `completed`, a bail-true `failed`, a `stopped`, or a derived `skipped` is never overridden.\n\t#completable(workflow: WorkflowInterface): boolean {\n\t\treturn workflow.status === 'pending'\n\t}\n\n\t// Discriminate the overloaded `execute` argument: a `WorkflowInterface` is the only one of the\n\t// two carrying `destroyed` (RUNTIME-ONLY — V2 — never a field on the pure-JSON\n\t// `WorkflowDefinition`) AND a `snapshot` method (the live entity's serialization method — a\n\t// `WorkflowDefinition` has no such method). Requiring BOTH is a sturdier structural\n\t// discriminator than `destroyed` alone (a definition could coincidentally carry a `destroyed`\n\t// field as arbitrary data; pairing it with a function-typed `snapshot` narrows to the actual\n\t// entity shape) without resorting to `as`.\n\t#isWorkflow(target: WorkflowDefinition | WorkflowInterface): target is WorkflowInterface {\n\t\treturn 'destroyed' in target && 'snapshot' in target && typeof target.snapshot === 'function'\n\t}\n}\n","import type { RunnerInterface, RunnerOptions, SchedulerInterface } from './types.js'\nimport { Scheduler } from './Scheduler.js'\nimport type { ContractInterface } from '@orkestrel/contract'\nimport type { DriverInterface, TableInterface } from '@orkestrel/database'\nimport type {\n\tWorkflowDefinition,\n\tWorkflowInterface,\n\tWorkflowManagerInterface,\n\tWorkflowManagerOptions,\n\tWorkflowOptions,\n\tWorkflowRunnerInterface,\n\tWorkflowRunnerOptions,\n\tWorkflowSnapshotRow,\n\tWorkflowStoreInterface,\n} from './types.js'\nimport { createContract, rawShape, stringShape } from '@orkestrel/contract'\nimport { createDatabase, createMemoryDriver } from '@orkestrel/database'\nimport { DEFAULT_BAIL } from './constants.js'\nimport { cloneWorkflowSnapshot } from './cloners.js'\nimport { WorkflowError } from './errors.js'\nimport {\n\tcaptureWorkflowOptions,\n\tdefinitionToSnapshot,\n\thasWorkflowHandlers,\n\trecoverWorkflowSnapshot,\n} from './helpers.js'\nimport { workflowShape } from './shapers.js'\nimport { DatabaseWorkflowStore } from './stores/DatabaseWorkflowStore.js'\nimport { MemoryWorkflowStore } from './stores/MemoryWorkflowStore.js'\nimport { Workflow } from './Workflow.js'\nimport { WorkflowManager } from './WorkflowManager.js'\nimport { WorkflowRunner } from './WorkflowRunner.js'\nimport { Runner } from './Runner.js'\n\n// Workflow contract factory — compiles the workflow shape (shapers.ts) into the\n// four lockstep outputs (JSON Schema + guard + parser + generator) and types the\n// result as the hand-written `WorkflowDefinition` (the source of truth, AGENTS §14).\n//\n// The compiled `ContractInterface<Infer<typeof workflowShape>>` is structurally\n// identical to `ContractInterface<WorkflowDefinition>` — verified bidirectionally,\n// with ZERO TS2589 (the three-level nesting that tripped the databases module's\n// `objectShape` generics does NOT strike here, because the shapes are kept\n// intersection-free per the shapers' design note). So the hand-written interface\n// stays the source of truth AND the contract's `is` / `generate` / `parse` narrow\n// to it natively — no `as`. The round-trip parity test (generate → is → parse)\n// guards against any future drift between the two.\n//\n// `parse` is the contract's own parser, used directly: the shared compiler now\n// re-applies each leaf's `min` / `max` / `pattern` refinement after coercion\n// (compilers.ts `compileParser`, via the shared `stringOf` / `boundsOf`\n// combinators), so a parsed\n// `WorkflowDefinition` already satisfies `is` — refinements included (AGENTS §14\n// parse↔guard soundness). An empty `id` or `concurrency: 0` parses to `undefined`\n// at the contract level, so no guard-gate wrapper is needed here.\n\n/**\n * Compile the workflow definition contract — the JSON Schema, guard, parser, and\n * seeded generator for a {@link WorkflowDefinition}, all derived from one shape and\n * kept in lockstep.\n *\n * @remarks\n * The returned {@link ContractInterface}:\n * - `schema` — the emitted JSON Schema for a workflow definition.\n * - `is` — a total guard that narrows `unknown` to a valid {@link WorkflowDefinition}\n * (malformed input returns `false`, never throws).\n * - `parse` — coerces `unknown` to a {@link WorkflowDefinition}, or `undefined` when\n * it does not match.\n * - `generate` — produces a deterministic valid {@link WorkflowDefinition} from an\n * optional seeded random source.\n *\n * @returns The compiled {@link WorkflowDefinition} contract\n *\n * @example\n * ```ts\n * import { createWorkflowContract } from '@orkestrel/workflow'\n *\n * const contract = createWorkflowContract()\n * const definition = contract.generate() // a valid WorkflowDefinition\n * contract.is(definition) // true\n * contract.parse({ id: '', phases: [] }) // undefined (malformed)\n * ```\n */\nexport function createWorkflowContract(): ContractInterface<WorkflowDefinition> {\n\treturn createContract(workflowShape)\n}\n\n/**\n * Build the live W-b entity tree from a {@link WorkflowDefinition} — the whole\n * {@link WorkflowInterface} → {@link import('./types.js').PhaseInterface} →\n * {@link import('./types.js').TaskInterface} tree, each level wired with its lineage\n * context, its emitter, and the cascade.\n *\n * @remarks\n * The definition is the DECLARATIVE blueprint; this seeds an initial all-`pending`\n * {@link WorkflowSnapshot} from it ({@link definitionToSnapshot}) and constructs the live\n * tree over that one path. The `bail` failure policy resolves to `options.bail`, else the\n * definition's `bail`, else the graceful {@link import('./constants.js').DEFAULT_BAIL}; it\n * feeds {@link import('./helpers.js').deriveWorkflowStatus}. Per-phase / per-task initial\n * listeners + metadata travel through `options.phases[id].on` /\n * `options.phases[id].tasks[id]` (the AGENTS §8 nested-by-id bag). The W-b tree is the\n * state machine ONLY — it does not execute tasks (W-c drives the transitions).\n *\n * `options.functions` is the {@link import('./types.js').WorkflowFunctions} registry each live\n * task's `run` name resolves against ONCE at construction into its runtime\n * {@link import('./types.js').TaskInterface.handler}. An omitted name is the deliberate no-op;\n * an unresolved present name remains inspectable but is rejected if execution is attempted.\n *\n * @param definition - The workflow definition to bring to life\n * @param options - Runtime options (initial listeners, `bail` override, per-node options)\n * @returns The live {@link WorkflowInterface} root\n *\n * @example\n * ```ts\n * import { createWorkflow } from '@orkestrel/workflow'\n *\n * const workflow = createWorkflow(definition, { on: { complete: () => done() } })\n * const phase = workflow.phase('phase-build')\n * phase?.task('task-compile')?.start() // pending → running (cascades up)\n * ```\n */\nexport function createWorkflow(\n\tdefinition: WorkflowDefinition,\n\toptions?: WorkflowOptions,\n): WorkflowInterface {\n\tconst captured = captureWorkflowOptions(options)\n\tconst bail = captured.bail ?? definition.bail ?? DEFAULT_BAIL\n\t// Seed BOTH tiers of the snapshot with the effective bail (`definitionToSnapshot`'s second arg),\n\t// so an `options.bail` override reaches each INHERITING phase's snapshot while a phase with its own\n\t// `bail` still wins (`phase.bail ?? bail`) — the per-phase-bail-aware derivation reads each\n\t// PhaseSnapshot's bail. `options.bail` itself is forwarded UNCHANGED (NOT overwritten with the\n\t// resolved `bail`): the snapshot already carries the resolved bail at both tiers, so `Workflow`\n\t// reads `#bail` from it; injecting a resolved `bail` here would make `Workflow` treat it as an\n\t// EXPLICIT uniform override and clobber per-phase overrides. A caller's genuine `options.bail`\n\t// stays as given and cascades (uniform re-run). Each task's `run` / `retries` / `timeout` carry\n\t// over onto the snapshot (definitionToSnapshot's per-task step), so `options.functions` (forwarded\n\t// unchanged) resolves every task's handler identically whether built fresh or restored.\n\treturn new Workflow(definitionToSnapshot(definition, bail), captured)\n}\n\n/**\n * Build an equivalent live W-b entity tree from a {@link WorkflowSnapshot} — the\n * inverse of {@link WorkflowInterface.snapshot}, restoring structure + each node's status\n * + recorded results + positional order + the persisted `#override`.\n *\n * @remarks\n * Round-trip fidelity is paramount: a `snapshot()` → `createRestoredWorkflow()` reproduces the\n * same status at every node (each `#override` restored DIRECTLY from the snapshot's own\n * `override` field, not guessed from a status divergence), the same recorded\n * {@link import('./types.js').TaskResult}s, and the same positional order (an interior\n * `skip` / `remove` survives). The snapshot is SELF-CONTAINED — it persists the `bail`\n * policy it ran under, so the restore re-derives status IDENTICALLY without a silent\n * default; the snapshot's `bail` is the source of truth, while an explicit `options.bail`\n * still wins when supplied (to deliberately re-run under a different policy). A structurally\n * invalid snapshot (a status — or override — outside the lifecycle vocabulary, or a\n * non-boolean `bail`) throws a `RESTORE` {@link WorkflowError}.\n * Runtime handlers are optional: without a matching `functions` entry, a persisted `run`\n * remains visible with an undefined `handler` so the exact state is inspectable. The runner\n * rejects that unresolved tree if execution is attempted.\n *\n * @param snapshot - The snapshot to restore (carries its own `bail` + `override`)\n * @param options - Runtime options (initial listeners, an optional `bail` override, per-node options)\n * @returns The restored live {@link WorkflowInterface} root\n *\n * @example\n * ```ts\n * import { createRestoredWorkflow } from '@orkestrel/workflow'\n *\n * const restored = createRestoredWorkflow(workflow.snapshot()) // bail comes from the snapshot\n * restored.status === workflow.status // true\n * ```\n */\nexport function createRestoredWorkflow(\n\tsnapshot: unknown,\n\toptions?: WorkflowOptions,\n): WorkflowInterface {\n\tconst captured = captureWorkflowOptions(options)\n\tconst owned = cloneWorkflowSnapshot(snapshot)\n\treturn new Workflow(owned, captured)\n}\n\n/**\n * Build an interrupted workflow back to life at its remaining retry budget.\n *\n * @remarks\n * Each phase captures every unique initial `run` binding once before constructing tasks. Recovery\n * validates those live tasks' captured callable handlers without rereading the registry, while the\n * retained registry identity remains available to resolve future live additions at their mint time.\n *\n * @param snapshot - The hostile persisted snapshot\n * @param options - Runtime handlers and entity options\n * @returns A recoverable live {@link WorkflowInterface} root\n *\n * @example\n * ```ts\n * import { createRecoveredWorkflow } from '@orkestrel/workflow'\n *\n * const recovered = createRecoveredWorkflow(snapshot, { functions })\n * recovered.status // 'pending' — interrupted running work returned to its remaining budget\n * ```\n */\nexport function createRecoveredWorkflow(\n\tsnapshot: unknown,\n\toptions?: WorkflowOptions,\n): WorkflowInterface {\n\tconst captured = captureWorkflowOptions(options)\n\tconst owned = cloneWorkflowSnapshot(snapshot)\n\tif (owned.override !== undefined || owned.phases.some((phase) => phase.override !== undefined)) {\n\t\tthrow new WorkflowError('RESTORE', `workflow '${owned.id}' has a terminal override`, {\n\t\t\tworkflow: owned.id,\n\t\t})\n\t}\n\tconst recovered = cloneWorkflowSnapshot(recoverWorkflowSnapshot(owned))\n\tconst workflow = new Workflow(recovered, captured)\n\tif (!hasWorkflowHandlers(workflow)) {\n\t\tthrow new WorkflowError('RESTORE', `workflow '${owned.id}' has an unresolved run`, {\n\t\t\tworkflow: owned.id,\n\t\t})\n\t}\n\treturn workflow\n}\n\n/**\n * Create the in-memory durable {@link WorkflowStoreInterface} — a process-lifetime\n * {@link MemoryWorkflowStore} persisting {@link WorkflowSnapshot}s by workflow id, the DEFAULT\n * backend behind the W-d persistence seam.\n *\n * @remarks\n * The snapshot analogue of the server package's `createMemorySessionStore`\n * (and the `createMemoryQueueStore` family), but LEANER — there is no idle-TTL, so no\n * options bag (AGENTS §21 minimal): a persisted run-state lives until an explicit `delete`. This is\n * the zero-plumbing DEFAULT (a plain `Map`); its driver-pluggable twin is\n * {@link createDatabaseWorkflowStore} (the snapshot as one opaque JSON column over a `databases`\n * table) — for a DURABLE store (run-state surviving a restart) pass it a JSON / SQLite / IndexedDB\n * driver, and it swaps in WITHOUT touching the runner or the entity tree. Restore stays a caller\n * concern: read a snapshot back and rebuild the live tree with {@link createRestoredWorkflow}.\n *\n * @returns A memory-backed {@link WorkflowStoreInterface}\n *\n * @example\n * ```ts\n * import { createMemoryWorkflowStore, createWorkflow, createRestoredWorkflow } from '@orkestrel/workflow'\n *\n * const store = createMemoryWorkflowStore()\n * const workflow = createWorkflow(definition)\n * await store.set(workflow.snapshot()) // persist the run state\n * const snapshot = await store.get(definition.id)\n * const restored = snapshot && createRestoredWorkflow(snapshot) // an identical live tree\n * ```\n */\nexport function createMemoryWorkflowStore(): WorkflowStoreInterface {\n\treturn new MemoryWorkflowStore()\n}\n\n/**\n * Create a {@link DatabaseWorkflowStore} over any {@link DriverInterface} — the durable,\n * driver-pluggable backing for the W-d persistence seam, the opt-in twin of\n * {@link createMemoryWorkflowStore}.\n *\n * @remarks\n * Builds a one-table database (`snapshots`, keyed by `id`) over the supplied driver, the snapshot\n * held as ONE OPAQUE JSON COLUMN — the column map is `{ id; snapshot }` where `snapshot` is a\n * `rawShape` (a JSON blob), exactly as `createDatabaseQueueStore` stores its `input`. The\n * snapshot is already a COMPLETE, self-contained, pure-JSON payload, so storing it whole is lossless\n * AND keeps the row type FLAT — a structured multi-column snapshot table would force the contract to\n * `Infer` the deeply-nested snapshot shape (workflow → phases → tasks → results) and trip TS2589;\n * the opaque column sidesteps it (the column reads back as `unknown`, narrowed on `get` by\n * {@link import('./helpers.js').isWorkflowSnapshot}). The `driver` DEFAULTS to\n * {@link createMemoryDriver}, so the store ALSO works in memory out of the box; pass a server\n * `createJSONDriver` / `createSQLiteDriver` (or a browser IndexedDB driver) for a persistent one —\n * the durability is the driver's job, the store engine is shared. It swaps in behind\n * {@link WorkflowStoreInterface} WITHOUT touching the runner or the entity tree.\n *\n * @param driver - The storage backend the snapshots persist to (defaults to {@link createMemoryDriver})\n * @returns A {@link WorkflowStoreInterface} over the driver\n *\n * @example\n * ```ts\n * import { createMemoryDriver } from '@orkestrel/database'\n * import { createDatabaseWorkflowStore, createWorkflow, createRestoredWorkflow } from '@orkestrel/workflow'\n *\n * const store = createDatabaseWorkflowStore(createMemoryDriver()) // a durable driver swaps in here\n * const workflow = createWorkflow(definition)\n * await store.set(workflow.snapshot()) // persist the run state (one JSON column)\n * const snapshot = await store.get(definition.id)\n * const restored = snapshot && createRestoredWorkflow(snapshot) // an identical live tree\n * ```\n */\nexport function createDatabaseWorkflowStore(\n\tdriver: DriverInterface = createMemoryDriver(),\n): WorkflowStoreInterface {\n\t// The snapshot is stored as ONE OPAQUE JSON column (`rawShape`), so the row infers FLAT —\n\t// `{ id: string; snapshot: unknown }` = `WorkflowSnapshotRow` — and the deeply-nested snapshot\n\t// shape never forces a contract `Infer` (the TS2589 trap a structured table would spring).\n\tconst columns = { id: stringShape(), snapshot: rawShape({}) }\n\tconst database = createDatabase({ driver, tables: { snapshots: columns } })\n\tconst table: TableInterface<WorkflowSnapshotRow> = database.table('snapshots')\n\treturn new DatabaseWorkflowStore(table)\n}\n\n/**\n * Create a workflow runner — a {@link WorkflowRunnerInterface} that EXECUTES a live W-b\n * workflow tree by COMPOSING the shipped substrate: phases sequential, tasks concurrent,\n * each task dispatched through its OWN resolved handler under the workflow's `bail` policy.\n *\n * @remarks\n * The runner is a PURE engine — it re-implements no concurrency / retry / abort logic, AND it\n * carries no behavior or provider registry of its own: each live task already\n * resolved its own {@link import('./types.js').WorkflowFunction} into\n * {@link import('./types.js').TaskInterface.handler} ONCE at construction, from the\n * {@link WorkflowOptions.functions} registry supplied to `execute` / {@link createWorkflow}.\n * Per-phase bounded concurrency is one {@link createRunner} per phase; `bail` maps onto that\n * Runner's fail-fast (`true` — the first failure aborts the in-flight siblings + skips the\n * rest) vs settle-all (`false` — failures are recorded, the run finishes); the run-level abort\n * / timeout / budget ({@link import('./types.js').WorkflowRunOptions}) fold through\n * `AbortSignal.any` (the agent runtime's pattern); pacing is the shipped scheduler.\n * `execute(definition, options?)` BUILDS the live tree from the definition itself (via\n * {@link createWorkflow} — one source of truth, returned in `WorkflowResult.workflow`), drives\n * the live entity (`start` → `complete` / `fail`), and resolves a\n * {@link import('./types.js').WorkflowResult}.\n *\n * External integrations remain application-owned: a caller wires an ordinary\n * {@link import('./types.js').WorkflowFunction} into its own {@link WorkflowOptions.functions}\n * registry. Only a task that omits `run` auto-completes; unresolved named work is rejected\n * before dispatch.\n *\n * @param options - An optional pacing `scheduler` (default the shipped cross-environment one).\n * See {@link WorkflowRunnerOptions}.\n * @returns A working {@link WorkflowRunnerInterface}\n *\n * @example\n * ```ts\n * import { createWorkflowRunner } from '@orkestrel/workflow'\n *\n * const runner = createWorkflowRunner()\n * const definition = { id: 'w', name: 'W', phases: [{ id: 'p', name: 'P', tasks: [\n * \t{ id: 't', name: 'T', run: 'compile' },\n * ] }] }\n * const result = await runner.execute(definition, {\n * \tfunctions: { compile: async (controller) => `built ${controller.task.id}` },\n * })\n * result.status // 'completed'\n * result.workflow.phase('p')?.task('t')?.status // 'completed'\n * ```\n */\nexport function createWorkflowRunner(options?: WorkflowRunnerOptions): WorkflowRunnerInterface {\n\treturn new WorkflowRunner(options?.scheduler ?? createScheduler())\n}\n\n/**\n * Create a {@link WorkflowManagerInterface} — the store-backed registry of\n * {@link WorkflowInterface}s, the additive manager tier mirroring the `@orkestrel/agent`\n * line's `createConversationManager` / `createWorkspaceManager`.\n *\n * @remarks\n * `options.functions` flows into every workflow the manager mints (`add`, via\n * {@link createWorkflow}) or hydrates (`open`'s registry-miss path, via\n * {@link createRestoredWorkflow}), so a hydrated workflow is RUNNABLE rather than a dead snapshot\n * mirror. `options.store` is the EXACT analogue of the twins' `store` seam — omitted ⇒ the\n * manager is registry-only (`open` resolves only what is registered, `save` is a no-op). This\n * is PURELY ADDITIVE: direct {@link WorkflowStoreInterface} use and\n * {@link createRestoredWorkflow} remain valid — the manager is one more caller-driven persistence\n * seam, not a replacement.\n *\n * @param options - The optional `store` seam and the `functions` registry threaded into every mint/hydrate\n * @returns A working {@link WorkflowManagerInterface}\n *\n * @example\n * ```ts\n * import { createMemoryWorkflowStore, createWorkflowManager } from '@orkestrel/workflow'\n *\n * const manager = createWorkflowManager({\n * \tstore: createMemoryWorkflowStore(),\n * \tfunctions: { compile: async (controller) => `built ${controller.task.id}` },\n * })\n * const workflow = manager.add(definition) // minted, registered, RUNNABLE\n * await manager.save(workflow.id) // persisted to the store\n * const reopened = await manager.open(workflow.id) // already registered — no store hit\n * ```\n */\nexport function createWorkflowManager(options?: WorkflowManagerOptions): WorkflowManagerInterface {\n\treturn new WorkflowManager(options)\n}\n\n/**\n * Create the safe cross-environment cooperative-yield default — a\n * {@link SchedulerInterface} built on `setTimeout` / `clearTimeout` alone, so it\n * runs unchanged in both the browser and Node.\n *\n * @remarks\n * `yield()` gives the host a turn via a zero-delay macrotask (so pending I/O,\n * timers, and rendering actually run — a microtask would not); `delay(ms)` resumes\n * after at least `ms`. Pass `options.signal` to make a pending yield/delay reject\n * with the signal's exact `reason`; the shared owned-signal lifecycle clears the timer\n * without invoking caller-owned listener methods.\n * `options.priority` is accepted for contract compliance but treated uniformly by\n * this default — environment backends honour it.\n *\n * @returns A working {@link SchedulerInterface}\n *\n * @example\n * ```ts\n * import { createAbort } from '@orkestrel/abort'\n * import { createScheduler } from '@orkestrel/workflow'\n *\n * const abort = createAbort()\n * const scheduler = createScheduler()\n *\n * // A cooperative loop: do a unit of work, then hand the host a turn.\n * while (!abort.signal.aborted) {\n * \tdoSomeWork()\n * \tawait scheduler.yield({ signal: abort.signal })\n * }\n * ```\n *\n * @example\n * ```ts\n * import { createScheduler } from '@orkestrel/workflow'\n *\n * // A backoff: wait a growing interval between retries.\n * const scheduler = createScheduler()\n * for (let attempt = 0; attempt < 5; attempt += 1) {\n * \tif (await tryOnce()) break\n * \tawait scheduler.delay(2 ** attempt * 100)\n * }\n * ```\n */\nexport function createScheduler(): SchedulerInterface {\n\treturn new Scheduler()\n}\n\n/**\n * Create a thin generic orchestrator that drives declared units — and any they\n * `spawn` — through a bounded-concurrency queue, collecting their results in order.\n *\n * @remarks\n * The Runner composes the workers `Queue` for backpressure, FIFO ordering, bounded\n * concurrency, retries, and the per-attempt timeout — it adds only orchestration, not\n * a second concurrency engine. `execute(inputs)` runs the unit set ONCE (a second call\n * throws) and resolves the units' results in order: the declared inputs first, then\n * any `spawn`ed siblings in spawn order. Each unit's handler gets a `Controller` — its\n * `id` / `input`, a `signal` that fires on the unit's `abort`, a runner-level `abort`,\n * or the attempt's timeout, a promise-parked `wait()`, and `spawn(input)` to fan out\n * sibling units. The run is **fail-fast**: the first unit failure (after retries)\n * aborts every other unit and rejects `execute` with that error. **Observable (§13):** a\n * typed `emitter` surfaces `start` / `unit` / `spawn` / `settle` / `fail` / `finish` / `abort`.\n *\n * Because `spawn` is fire-and-track (the runner awaits the whole spawn closure via an\n * outstanding-unit count, not a one-time snapshot), a handler need NOT await its spawns\n * for them to run — and on a bounded runner it should NOT `await` a spawn inline (a\n * slot-holding handler awaiting its own spawn can deadlock); fan out and return instead.\n *\n * @typeParam TInput - The work input each unit carries\n * @typeParam TResult - The value a unit's handler resolves\n * @param options - The `handler` plus optional `concurrency` (default `1`), `retries`\n * (default `0`), and a default per-attempt `timeout` in milliseconds\n * @returns A working {@link RunnerInterface}\n *\n * @example\n * ```ts\n * import { createRunner } from '@orkestrel/workflow'\n *\n * // A handler that fans out one sibling per declared unit, then returns its own value.\n * const runner = createRunner<number, number>({\n * \tconcurrency: 4,\n * \thandler: (controller) => {\n * \t\tif (controller.input < 10) controller.spawn(controller.input + 100) // fire-and-track\n * \t\treturn controller.input\n * \t},\n * })\n *\n * const results = await runner.execute([1, 2, 3])\n * // [1, 2, 3, 101, 102, 103] — declared inputs first (in order), then spawns (in order)\n * ```\n */\nexport function createRunner<TInput, TResult>(\n\toptions: RunnerOptions<TInput, TResult>,\n): RunnerInterface<TInput, TResult> {\n\treturn new Runner(options)\n}\n"],"mappings":";;;;;;;;AAUA,IAAa,eAAe;;;;;;;;AAS5B,IAAa,gBAAuC,OAAO,OAAO;CACjE;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,iBAAyC,OAAO,OAAO;CACnE;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,oBAA+C,OAAO,OAAO;CACzE;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;;;;AAUD,IAAa,yBAAgD,OAAO,OAAO;CAC1E;CACA;CACA;CACA;AACD,CAAC;;;;;;;;;;;;;;AAeD,IAAa,mBAAwE,OAAO,OAAO;CAClG,SAAS;EAAC;EAAW;EAAW;CAAS;CACzC,SAAS;EAAC;EAAa;EAAU;EAAW;CAAS;CACrD,WAAW,CAAC;CACZ,QAAQ,CAAC;CACT,SAAS,CAAC;CACV,SAAS,CAAC;AACX,CAAC;;;;;;;;;;;;;;;;;;;;AAqBD,IAAa,4BAA4B;;;;AAKzC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