{"version":3,"file":"execution.mjs","names":[],"sources":["../../../../../../../ai/src/supervisor/execution.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport { END } from \"../contracts/end.type\";\nimport type { EventIdentity, WithoutIdentity } from \"../contracts/events/event-identity.type\";\nimport type { SupervisorEventMap } from \"../contracts/events/event-map.type\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type {\n  SupervisorReport,\n  SupervisorResult,\n  SupervisorTerminatedBy,\n} from \"../contracts/result/supervisor-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { WorkflowResult } from \"../contracts/result/workflow-result.type\";\nimport type { StreamContract } from \"../contracts/stream/stream.contract\";\nimport type {\n  ClassifierConfig,\n  ClassifierContext,\n  ClassifierOutput,\n  ClassifierRefineContext,\n  ClassifierRefineResult,\n  ClassifierSnapshot,\n} from \"../contracts/supervisor/classifier-context.type\";\nimport type {\n  DispatchContext,\n  StreamableExecutable,\n  SupervisableExecutable,\n  SupervisableExecuteOptions,\n  SupervisableResult,\n} from \"../contracts/supervisor/dispatch-context.type\";\nimport type {\n  EvaluateBranchResult,\n  EvaluateContext,\n  EvaluateResult,\n} from \"../contracts/supervisor/evaluate-context.type\";\nimport type {\n  AckSnapshot,\n  AgentBranchSnapshot,\n  IterationSnapshot,\n} from \"../contracts/supervisor/iteration-snapshot.type\";\nimport type { RouteContext } from \"../contracts/supervisor/route-context.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorExecuteOptions } from \"../contracts/supervisor/supervisor-execute-options.type\";\nimport type { SupervisorInput } from \"../contracts/supervisor/supervisor-input.type\";\nimport type {\n  SupervisorSnapshot,\n  SupervisorSnapshotStatus,\n} from \"../contracts/supervisor/supervisor-snapshot.type\";\nimport type { WorkflowInstance } from \"../contracts/workflow/workflow.contract\";\nimport {\n  AIError,\n  MaxIterationsError,\n  SchemaValidationError,\n  SupervisorCancelledError,\n  SupervisorFailedError,\n} from \"../errors\";\nimport { assignSafeKey, isUnsafeMergeKey, mergeSafely } from \"../security/safe-merge\";\nimport { mergeUsage, stampReportLineage, withoutRunFrame, withRunFrame } from \"../utils\";\nimport type { AgentMiddleware } from \"../contracts/middleware/middleware.contract\";\nimport type { MiddlewareSupervisorContext } from \"../contracts/middleware/middleware-context.type\";\nimport type { MiddlewareState } from \"../contracts/middleware/middleware-state.type\";\nimport { runPipeline } from \"../middleware/pipeline\";\nimport { createCancelledError } from \"./cancellation\";\nimport { capFanOut, decide, resolveMaxFanOut, type DispatchDecision } from \"./decide\";\nimport type { SupervisorEmitter } from \"./emitter\";\nimport type { ResolvedCallbackEntry, ResolvedIntentEntry } from \"./entries\";\nimport { isAgentResult, isWorkflowResult } from \"./entries\";\nimport { persistSupervisorSnapshot } from \"./snapshot\";\nimport type { SupervisorStreamController, SupervisorStreamEvent } from \"./supervisor-stream\";\n\nconst DEFAULT_MAX_ITERATIONS = 10;\nconst LOG_MODULE_BASE = \"ai.supervisor\";\n\nexport type SupervisorExecutionParams<TOutput> = {\n  config: SupervisorConfig<TOutput>;\n  entries: Map<string, ResolvedIntentEntry>;\n  signature: string;\n  emitter: SupervisorEmitter;\n  input: SupervisorInput;\n  runId: string;\n  options?: SupervisorExecuteOptions;\n  streamController?: SupervisorStreamController<SupervisorResult<TOutput>>;\n  resumeFrom?: SupervisorSnapshot;\n};\n\n/**\n * Per-call driver that owns the full lifecycle of one supervisor run.\n *\n * **Role.** Short-lived state container and phase orchestrator —\n * mirrors `agent/Execution` and `workflow/runWorkflow`, one level up.\n *\n * **Responsibility.**\n * - Owns: the iteration loop, per-iteration dispatch (single or\n *   fan-out), evaluate scheduling, usage aggregation across router +\n *   every branch + evaluate, snapshot collection, event emission\n *   through all three tiers, KV-store checkpointing, final result\n *   assembly (state validation against the output schema → typed data).\n * - Does NOT own: how child agents produce responses (delegated via\n *   `agent.execute` / `workflow.execute`), the routing decision\n *   itself (delegated to `decide.ts`), snapshot persistence mechanics\n *   (delegated to `snapshot.ts`), the stream queue plumbing\n *   (delegated to `supervisor-stream.ts`).\n *\n * `execute()` never throws — every unexpected failure funnels into\n * `this.error` and is returned on `result.error` with an appropriate\n * `SupervisorFailedError` / `MaxIterationsError` / `SupervisorRoutingError`\n * / `SupervisorCancelledError`.\n *\n * @example\n * // Inside supervisor.execute() — never constructed by user code directly:\n * return new SupervisorExecution(params).run();\n */\nexport class SupervisorExecution<TOutput> {\n  private readonly config: SupervisorConfig<TOutput>;\n  private readonly entries: Map<string, ResolvedIntentEntry>;\n  private readonly signature: string;\n  private readonly emitter: SupervisorEmitter;\n  private readonly input: SupervisorInput;\n  private readonly runId: string;\n  private readonly options?: SupervisorExecuteOptions;\n  private readonly streamController?: SupervisorStreamController<SupervisorResult<TOutput>>;\n  private readonly resumeFrom?: SupervisorSnapshot;\n\n  private readonly maxIterations: number;\n  private readonly logger: Logger = log;\n  private readonly logModule: string;\n\n  /**\n   * Supervisor-level middleware stack — `config.middleware` (default\n   * empty). Each entry's optional `supervisor` hook map fires once\n   * around the whole run via `runPipeline(..., \"supervisor\", ...)` in\n   * {@link run}; entries without that hook map are skipped by the\n   * pipeline.\n   */\n  private readonly middleware: ReadonlyArray<AgentMiddleware>;\n  /**\n   * Per-run shared-state bag threaded through every `supervisor`-level\n   * hook (`before` / `after` / `onError`) of this one run. Fresh `Map`\n   * per `SupervisorExecution` so two concurrent runs of the same\n   * supervisor get isolated bags — mirrors the agent pipeline.\n   */\n  private readonly middlewareState: MiddlewareState = new Map();\n\n  private readonly snapshots: IterationSnapshot[] = [];\n  private readonly childReports: BaseReport[] = [];\n  private readonly usage: Usage = { input: 0, output: 0, total: 0 };\n\n  private readonly startedAtIso: string;\n  private readonly startPerf = performance.now();\n\n  private iteration = 0;\n  private carriedFeedback?: EvaluateResult;\n  /**\n   * Per-intent `next` directive (Q24 / Stage 4d) collected at the\n   * end of an iteration after evaluate hasn't already steered. When\n   * set, `decideDispatch` consumes it on the next iteration's start —\n   * skipping the router entirely. Cleared after consumption.\n   *\n   * Only the dispatch variant is stored; an `END` collection\n   * terminates the iteration loop directly inside `runIteration`.\n   */\n  private carriedNextDispatch?: { intents: string[] };\n  private terminatedBy: SupervisorTerminatedBy = \"error\";\n  private status: SupervisorReport[\"status\"] = \"failed\";\n  private cancelledAtIso?: string;\n  private error?: AIError;\n  private data?: TOutput;\n  private lastDispatchIntents: string[] = [];\n  /**\n   * Per-execute typed accumulator. Initialized from `config.state`\n   * (default `{}`) at construction; rehydrated from the last\n   * snapshot's `state` on resume; mutated in-place as each iteration's\n   * intents strip-merge their outputs into it.\n   */\n  private state: Record<string, unknown> = {};\n  /**\n   * Per-iteration artifacts bag (Phase 5 / decisions §35). Tools\n   * dispatched within an iteration mutate `ctx.artifacts` — which\n   * points at this object. After the iteration's branches settle and\n   * their slices merge into state, this bag validates against\n   * `config.artifactsSchema` (if set) and merges via\n   * `config.finalizeArtifacts` or auto-spread, then resets to `{}`\n   * for the next iteration. The reset is crucial — long runs and\n   * orchestrator sessions never accumulate raw artifacts here.\n   */\n  private currentArtifacts: Record<string, unknown> = {};\n  /**\n   * Frozen copy of the iteration's `currentArtifacts` bag captured at\n   * merge time — BEFORE `finalizeArtifacts` (or auto-spread) reshaped\n   * it into state (Phase 8 / decisions §38). Surfaced on the iteration\n   * snapshot's `artifacts` field for forensic / telemetry consumers\n   * that want the raw tool contributions.\n   *\n   * Reset to `{}` at the start of every iteration so a snapshot built\n   * for an iteration whose tools wrote nothing carries an empty bag,\n   * not a stale carry-over.\n   */\n  private capturedIterationArtifacts: Readonly<Record<string, unknown>> = Object.freeze({});\n  /**\n   * Classifier (Phase 7 / decisions §37) forensic record. Set on iter\n   * 0 when `SupervisorConfig.classifier` is configured AND the run\n   * started fresh (resumes don't re-fire classifier — same as ack).\n   * Surfaced on `SupervisorReport.classifier` and threaded into\n   * `ctx.classifier` on RouteContext / DispatchContext /\n   * EvaluateContext from iter 0 onward.\n   */\n  private classifierSnapshot?: ClassifierSnapshot;\n  /**\n   * Iter-0 dispatch decision pre-computed by the classifier (Phase 7).\n   * When set, `decideDispatch` short-circuits and uses this directly\n   * with `source: \"classifier\"`. Cleared after consumption.\n   */\n  private carriedClassifierDispatch?: { intent: string };\n  /** Set true by classifier refine returning END to halt before any dispatch. */\n  private classifierHalted = false;\n  /**\n   * Receptionist forensic record. Set when an `ackAgent` was\n   * configured AND the run started fresh (resumes don't re-fire ack).\n   * Surfaced on `SupervisorReport.ack`.\n   */\n  private ackSnapshot?: AckSnapshot;\n  /**\n   * Read-only request-scoped context surfaced on every `ctx.context`.\n   * Shallow-copied + frozen at construction so callbacks see a stable\n   * snapshot of the caller's bag and can't mutate the original.\n   * Always present — defaults to a frozen `{}` when no context was\n   * passed. NOT persisted in snapshots.\n   */\n  private readonly context: Readonly<Record<string, unknown>>;\n  /**\n   * Prior conversation messages threaded through every callback context\n   * (`ctx.history`) and forwarded verbatim to dispatched agents (and the\n   * receptionist `ack` agent) as `agent.execute(input, { history })`.\n   * Frozen reference so callbacks see a stable view; not deep-cloned —\n   * conversation messages are treated as immutable by convention. NOT\n   * persisted in snapshots (re-supply on `resume()`).\n   */\n  private readonly history: ReadonlyArray<Message>;\n  /**\n   * Resolved natural-language objective from `SupervisorConfig.goal`.\n   * Materialized to plain text at construction (string passes through;\n   * `SystemPromptContract` is `.resolve()`-d). `undefined` when the\n   * supervisor was configured without a goal.\n   */\n  private readonly goal: string | undefined;\n\n  public constructor(params: SupervisorExecutionParams<TOutput>) {\n    this.config = params.config;\n    this.entries = params.entries;\n    this.signature = params.signature;\n    this.emitter = params.emitter;\n    this.input = params.input;\n    this.runId = params.runId;\n    this.options = params.options;\n    this.streamController = params.streamController;\n    this.resumeFrom = params.resumeFrom;\n\n    this.maxIterations = params.config.maxIterations ?? DEFAULT_MAX_ITERATIONS;\n    this.logModule = `${LOG_MODULE_BASE}.${params.config.name}`;\n    this.middleware = params.config.middleware ?? [];\n\n    // Shallow-copy + freeze the caller's context. Shallow only —\n    // freezing deeply would break valid use cases (mutable DB\n    // clients, abort controllers) without delivering meaningful\n    // safety beyond what TS `Readonly` already enforces.\n    this.context = Object.freeze({ ...(params.options?.context ?? {}) });\n    // Freeze the array reference so callbacks can't mutate the slot\n    // (`history.push(...)`); messages themselves are passed by reference\n    // — supervisors trust the agent layer's read-only convention.\n    // Precedence: per-call `options.history` (most explicit) overrides\n    // factory-level `config.history` (default for callers who don't\n    // supply per-call history). Final fallback is an empty array.\n    this.history = Object.freeze([...(params.options?.history ?? params.config.history ?? [])]);\n\n    // Resolve `goal` to plain text once, at construction. `string`\n    // passes through; `SystemPromptContract` is `.resolve()`-d (it owns\n    // its own placeholder substitution). `undefined` when no goal was\n    // configured — every `ctx.goal` consumer must guard for absence.\n    if (typeof params.config.goal === \"string\") {\n      this.goal = params.config.goal;\n    } else if (params.config.goal) {\n      this.goal = params.config.goal.resolve();\n    } else {\n      this.goal = undefined;\n    }\n\n    if (params.resumeFrom) {\n      this.snapshots.push(...params.resumeFrom.snapshots);\n      this.iteration = params.resumeFrom.iteration + 1;\n      this.startedAtIso = params.resumeFrom.startedAt;\n      // Resume rehydrates state from the last persisted iteration —\n      // every iteration's snapshot carries the post-merge state, so\n      // the resume point's state is the last snapshot's state.\n      const lastSnapshot = params.resumeFrom.snapshots[params.resumeFrom.snapshots.length - 1];\n      this.state = {\n        ...(lastSnapshot?.state ??\n          (params.config.state as Record<string, unknown> | undefined) ??\n          {}),\n      };\n    } else {\n      this.startedAtIso = new Date().toISOString();\n      this.state = {\n        ...((params.config.state as Record<string, unknown> | undefined) ?? {}),\n      };\n    }\n  }\n\n  /**\n   * Resolve the history slice forwarded to a child execution (router /\n   * dispatched agent / ack). Precedence:\n   *\n   *   1. Per-entry `history` callback — full override; whatever it\n   *      returns goes through (after defensive copy).\n   *   2. `SupervisorConfig.historyWindow.<role>` — last-N slice of the\n   *      caller-supplied history.\n   *   3. Default — full history for `router`/`agents`, empty for `ack`\n   *      (receptionists rarely benefit from scroll-back).\n   *\n   * Always returns a fresh `Message[]` (the agent layer\n   * mutates by reference internally, e.g. via `messages.push(...)`).\n   */\n  private resolveHistoryFor(\n    role: \"router\" | \"agents\" | \"ack\",\n    routeContext: RouteContext,\n    entrySlicer?: (ctx: RouteContext) => Message[] | ReadonlyArray<Message>,\n  ): Message[] {\n    if (entrySlicer) {\n      const sliced = entrySlicer(routeContext);\n      return sliced ? [...sliced] : [];\n    }\n\n    const window = this.config.historyWindow?.[role];\n\n    if (role === \"ack\") {\n      // Default for ack is empty — receptionists rarely need history.\n      // Override is opt-in via `historyWindow.ack: N`.\n      if (window === undefined || window <= 0) {\n        return [];\n      }\n\n      return this.history.slice(-window);\n    }\n\n    if (window === undefined || window < 0) {\n      return [...this.history];\n    }\n\n    if (window === 0) {\n      return [];\n    }\n\n    return this.history.slice(-window);\n  }\n\n  /**\n   * Apply only the global `historyWindow.agents` slice — used by the\n   * recursive `ctx.intents.X.execute()` re-entry path where no\n   * `RouteContext` is available to feed the per-entry slicer.\n   */\n  private applyAgentsWindow(): Message[] {\n    const window = this.config.historyWindow?.agents;\n\n    if (window === undefined || window < 0) {\n      return [...this.history];\n    }\n\n    if (window === 0) {\n      return [];\n    }\n\n    return this.history.slice(-window);\n  }\n\n  /**\n   * Entry point. Wraps the core run (`runCore`) in the\n   * `supervisor`-level middleware pipeline, then emits the terminal\n   * `supervisor.cancelled` / `supervisor.error` / `supervisor.completed`\n   * events and closes the stream (if any) with the post-pipeline result\n   * — so a middleware that short-circuits or transforms the final\n   * result still produces a well-formed public outcome. Returns the\n   * uniform `{ data, report, usage, error }` shape. Never throws.\n   */\n  public async run(): Promise<SupervisorResult<TOutput>> {\n    const context = this.buildSupervisorContext();\n\n    let result: SupervisorResult<TOutput>;\n\n    try {\n      result = (await runPipeline(\n        this.middleware,\n        \"supervisor\",\n        context,\n        () => this.runCore(),\n        this.logger,\n      )) as SupervisorResult<TOutput>;\n    } catch (thrown) {\n      // A `supervisor`-level hook threw without recovery (or\n      // `onError` returned void). The iteration loop's own failures\n      // are already absorbed into `this.error` inside `runCore` and\n      // never reach here — this catch covers middleware aborts and\n      // any unexpected throw, funneling them into a well-formed\n      // result so `supervisor.execute()` keeps its never-throws\n      // contract.\n      this.error = toAIError(thrown);\n      this.status = this.error instanceof SupervisorCancelledError ? \"cancelled\" : \"failed\";\n      this.terminatedBy = this.error instanceof SupervisorCancelledError ? \"cancelled\" : \"error\";\n\n      if (this.error instanceof SupervisorCancelledError) {\n        this.cancelledAtIso = this.error.cancelledAt;\n      }\n\n      if (this.error instanceof MaxIterationsError) {\n        this.status = \"max-iterations\";\n        this.terminatedBy = \"max-iterations\";\n      }\n\n      result = await this.finalize();\n    }\n\n    if (result.error) {\n      if (this.status === \"cancelled\") {\n        this.emit(\"supervisor.cancelled\", {\n          cancelledAt: this.cancelledAtIso ?? new Date().toISOString(),\n          reason: (result.error as SupervisorCancelledError).reason,\n        });\n      } else {\n        this.emit(\"supervisor.error\", { error: result.error });\n      }\n    }\n\n    this.emit(\"supervisor.completed\", { result });\n\n    this.streamController?.end(result);\n\n    this.logger.info(this.logModule, \"completed\", \"supervisor completed\", {\n      runId: this.runId,\n      status: this.status,\n      iterations: this.snapshots.length,\n      duration: performance.now() - this.startPerf,\n    });\n\n    return result;\n  }\n\n  /**\n   * Build the `supervisor`-level middleware context — the stable\n   * identity of this run plus the per-run shared-state bag every hook\n   * sees. Constructed once per run, before the pipeline `before` hooks\n   * fire. Mirrors the agent's `buildExecuteContext`, one level up.\n   */\n  private buildSupervisorContext(): MiddlewareSupervisorContext {\n    return {\n      supervisor: {\n        name: this.config.name,\n        signature: this.signature,\n      },\n      input: this.input,\n      options: this.options,\n      state: this.middlewareState,\n      signal: this.options?.signal,\n    };\n  }\n\n  /**\n   * Inner body wrapped by the `supervisor`-level pipeline. Emits the\n   * `supervisor.starting` event, drives the iteration loop, absorbs\n   * every iteration-loop failure into `this.error` (so the run never\n   * throws from here), and returns the assembled `SupervisorResult`.\n   * `supervisor`-level `after` hooks receive this result, with `error`\n   * populated when the loop failed; `before` hooks can short-circuit\n   * before this ever runs.\n   */\n  private async runCore(): Promise<SupervisorResult<TOutput>> {\n    this.emit(\"supervisor.starting\", {\n      supervisorName: this.config.name,\n      input: this.input,\n    });\n\n    this.logger.info(this.logModule, \"starting\", \"supervisor starting\", {\n      runId: this.runId,\n      maxIterations: this.maxIterations,\n    });\n\n    try {\n      await this.runIterationLoop();\n    } catch (thrown) {\n      this.error = toAIError(thrown);\n      this.status = this.error instanceof SupervisorCancelledError ? \"cancelled\" : \"failed\";\n      this.terminatedBy = this.error instanceof SupervisorCancelledError ? \"cancelled\" : \"error\";\n\n      if (this.error instanceof SupervisorCancelledError) {\n        this.cancelledAtIso = this.error.cancelledAt;\n      }\n\n      if (this.error instanceof MaxIterationsError) {\n        this.status = \"max-iterations\";\n        this.terminatedBy = \"max-iterations\";\n      }\n    }\n\n    return this.finalize();\n  }\n\n  /**\n   * Drive the iteration loop until a terminal condition fires:\n   * `END` / `satisfied:true` / `maxIterations` / signal abort /\n   * routing error. Between-iteration cancellation is guaranteed —\n   * the signal is checked before every iteration starts.\n   */\n  private async runIterationLoop(): Promise<void> {\n    while (this.iteration < this.maxIterations) {\n      this.throwIfCancelled();\n\n      const continued = await this.runIteration();\n\n      if (!continued) {\n        return;\n      }\n\n      this.iteration += 1;\n    }\n\n    throw new MaxIterationsError(\n      `supervisor \"${this.config.name}\" exceeded maxIterations=${this.maxIterations}`,\n      { maxIterations: this.maxIterations },\n    );\n  }\n\n  /**\n   * Run one iteration end-to-end: decide → dispatch → evaluate →\n   * snapshot. Returns `true` when the loop should continue to the\n   * next iteration, `false` when this iteration terminated the run\n   * (success or satisfied-verdict). Failures throw — the loop's\n   * outer catch converts them into typed errors on the result.\n   */\n  private async runIteration(): Promise<boolean> {\n    const iterationStartedAt = new Date();\n    const iterationStart = performance.now();\n    const iterationUsage: Usage = { input: 0, output: 0, total: 0 };\n\n    // Phase 8 / decisions §38 — reset the captured-artifacts forensic\n    // surface at iteration start so a snapshot built for an iteration\n    // whose tools wrote nothing carries an empty bag, not a stale\n    // carry-over from the prior iteration. `mergeArtifactsIntoState`\n    // refreshes this with the live bag (frozen) before merge.\n    this.capturedIterationArtifacts = Object.freeze({});\n\n    this.emit(\"supervisor.iteration.starting\", { iteration: this.iteration });\n\n    // Kick off the receptionist (`ack`) in parallel with phase A's\n    // dispatch decision — fires on iter 0 only when the run is fresh\n    // (resumes don't re-emit; user already saw the original ack). The\n    // promise is NOT awaited inline — `settleAck` probes it\n    // non-blockingly later so a slow ack never extends total wall-\n    // clock time. If ack hasn't settled by the probe point, its slice\n    // is abandoned with a warning + error on the report.\n    const ackPromise =\n      this.iteration === 0 && !this.resumeFrom && this.config.ack ? this.runAck() : undefined;\n\n    // Phase 7 / decisions §37 — classifier prelude. Runs once on iter 0\n    // for fresh runs only (resumes inherit the prior classifier output\n    // via state + report.classifier). Awaited inline because its\n    // output drives the iter-0 dispatch decision; ack remains\n    // non-blocking parallel by design.\n    if (this.iteration === 0 && !this.resumeFrom && this.config.classifier) {\n      await this.runClassifier();\n\n      if (this.classifierHalted) {\n        // Refine returned END (or classifier-alone mode interpreted\n        // an END signal). Settle ack, mark terminated, capture a\n        // synthetic decision snapshot, and exit the loop. State may\n        // already carry refine's slice — do not clobber.\n        await this.settleAck(ackPromise, iterationUsage);\n        this.terminatedBy = \"classifier\";\n        this.status = \"completed\";\n\n        await this.recordTerminalDecisionSnapshot(\n          {\n            kind: \"end\",\n            source: \"classifier\",\n            raw: END,\n            durationMs: 0,\n          },\n          iterationStartedAt,\n          iterationStart,\n          iterationUsage,\n        );\n\n        return false;\n      }\n    }\n\n    const decision = await this.decideDispatch();\n\n    this.aggregateUsage(iterationUsage, decision.usage);\n\n    if (decision.kind === \"end\") {\n      await this.settleAck(ackPromise, iterationUsage);\n      this.terminatedBy = decision.source === \"route\" ? \"route\" : \"router\";\n      this.status = \"completed\";\n\n      await this.recordTerminalDecisionSnapshot(\n        decision,\n        iterationStartedAt,\n        iterationStart,\n        iterationUsage,\n      );\n\n      return false;\n    }\n\n    const branchSnapshots = await this.dispatchBranches(decision);\n\n    for (const snapshot of branchSnapshots) {\n      this.aggregateUsage(iterationUsage, snapshot.usage);\n    }\n\n    // Settle ack (if kicked off) before phase C merge. Probe is\n    // non-blocking — `setImmediate` yields one macrotask cycle so an\n    // already-resolved ack wins via microtask priority; otherwise the\n    // probe returns NOT_READY and ack is abandoned (slice dropped,\n    // warning logged, error captured on `report.ack`). Specialist\n    // branches override the receptionist on key collision either way.\n    await this.settleAck(ackPromise, iterationUsage);\n\n    // Merge branch outputs into supervisor state in decision.intents\n    // order so fan-out conflict resolution is deterministic — last\n    // intent in the array wins on key collisions (Q15). Errored\n    // branches don't contribute. Entries without an `output` schema\n    // (agent/workflow) are NOT auto-merged — declaring the slice is\n    // opt-in. Callbacks always merge (their full return value when\n    // no schema; strip-merged when schema is declared) — they had\n    // their schema applied inside runCallback already.\n    this.mergeBranchesIntoState(decision.intents, branchSnapshots);\n\n    // Phase 5 / decisions §35 — merge tool-side artifacts into state\n    // AFTER branch slices land but BEFORE evaluate runs, so the\n    // evaluate verdict sees the post-merge state including blocks /\n    // citations / soft signals contributed by tools. Resets the bag\n    // for the next iteration; long runs and orchestrator sessions\n    // never accumulate raw artifacts.\n    await this.mergeArtifactsIntoState();\n\n    this.lastDispatchIntents = decision.intents;\n\n    const evaluateVerdict = await this.runEvaluate(branchSnapshots);\n\n    if (evaluateVerdict !== undefined && evaluateVerdict !== null) {\n      this.emit(\"supervisor.evaluate.verdict\", {\n        iteration: this.iteration,\n        verdict: evaluateVerdict,\n      });\n    }\n\n    const iterationEndedAt = new Date();\n    const duration = performance.now() - iterationStart;\n\n    const snapshot: IterationSnapshot = Object.freeze({\n      iteration: this.iteration,\n      result: indexByIntent(branchSnapshots),\n      decision: {\n        source: decision.source,\n        next: decision.raw,\n        reasoning: decision.reasoning,\n        durationMs: decision.durationMs,\n      },\n      evaluateVerdict,\n      state: { ...this.state },\n      artifacts: this.capturedIterationArtifacts,\n      startedAt: iterationStartedAt.toISOString(),\n      endedAt: iterationEndedAt.toISOString(),\n      duration,\n      usage: iterationUsage,\n    });\n\n    this.snapshots.push(snapshot);\n\n    this.emit(\"supervisor.iteration.completed\", {\n      iteration: this.iteration,\n      snapshot,\n    });\n\n    await this.checkpoint(\"running\");\n\n    if (evaluateVerdict?.satisfied) {\n      this.terminatedBy = \"evaluate\";\n      this.status = \"completed\";\n\n      return false;\n    }\n\n    this.carriedFeedback = evaluateVerdict;\n\n    // Stage 4d (Q24): when evaluate hasn't taken a stance via\n    // `reassignTo`, collect each branch's `intent.next(ctx)` to drive\n    // the next iteration without a router call. Evaluate's\n    // `reassignTo` outranks `next` — if evaluate forced a target,\n    // `next` doesn't get to vote.\n    const evaluateForcedReassign =\n      evaluateVerdict?.reassignTo !== undefined &&\n      normalizeReassign(evaluateVerdict.reassignTo).length > 0;\n\n    if (!evaluateForcedReassign) {\n      const collected = this.collectIntentNext(decision.intents, branchSnapshots);\n\n      if (collected?.kind === \"end\") {\n        this.terminatedBy = \"route\";\n        this.status = \"completed\";\n        this.carriedNextDispatch = undefined;\n        return false;\n      }\n\n      if (collected?.kind === \"dispatch\") {\n        this.carriedNextDispatch = { intents: collected.intents };\n      }\n    }\n\n    // Phase 7 / decisions §37 — classifier-alone supervisor auto-\n    // terminates after iter 0's branch settles. Without router/route,\n    // there's no decision source for iter 1; preempt the throw with\n    // a clean termination. `intent.next` from iter 0's dispatched\n    // intent still wins if it set a continuation (rare, but allowed).\n    if (\n      this.iteration === 0 &&\n      this.config.classifier &&\n      !this.config.router &&\n      !this.config.route &&\n      !this.carriedNextDispatch\n    ) {\n      this.terminatedBy = \"classifier\";\n      this.status = \"completed\";\n\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Resolve the dispatch decision for this iteration — defers to\n   * `decide.ts`. When `carriedFeedback.reassignTo` is set the\n   * supervisor overrides the router/route decision with an\n   * evaluator-forced dispatch (design §2 — \"Evaluate can override\n   * router\").\n   */\n  private async decideDispatch(): Promise<DispatchDecision> {\n    if (this.config.router) {\n      this.emit(\"supervisor.router.deciding\", { iteration: this.iteration });\n    }\n\n    const reassignTo = normalizeReassign(this.carriedFeedback?.reassignTo);\n\n    if (reassignTo.length > 0) {\n      this.carriedNextDispatch = undefined;\n      for (const intent of reassignTo) {\n        if (!this.entries.has(intent)) {\n          throw new SupervisorFailedError(\n            `evaluate.reassignTo targeted unknown agent \"${intent}\"`,\n            { context: { available: [...this.entries.keys()] } },\n          );\n        }\n      }\n\n      const decision: DispatchDecision = {\n        kind: \"dispatch\",\n        intents: reassignTo,\n        source: \"route\",\n        raw: reassignTo.length === 1 ? reassignTo[0] : reassignTo,\n        durationMs: 0,\n      };\n\n      this.emit(\"supervisor.router.decided\", {\n        iteration: this.iteration,\n        next: decision.raw,\n        reasoning: this.carriedFeedback?.feedback,\n        durationMs: 0,\n      });\n\n      return decision;\n    }\n\n    // Phase 7 / decisions §37 — classifier prelude (iter 0 only)\n    // produced an intent dispatch decision. Skip router/route /\n    // initialAgent entirely; classifier's pick wins. Cleared after\n    // consumption — iter 1+ falls through to router/route as usual.\n    if (this.carriedClassifierDispatch) {\n      const carried = this.carriedClassifierDispatch;\n      this.carriedClassifierDispatch = undefined;\n\n      const decision: DispatchDecision = {\n        kind: \"dispatch\",\n        intents: [carried.intent],\n        source: \"classifier\",\n        raw: carried.intent,\n        durationMs: 0,\n      };\n\n      this.emit(\"supervisor.router.decided\", {\n        iteration: this.iteration,\n        next: decision.raw,\n        reasoning: this.classifierSnapshot?.reasoning,\n        durationMs: 0,\n      });\n\n      return decision;\n    }\n\n    // Stage 4d: per-intent `next` collected from the previous\n    // iteration drives this dispatch — skip router/route entirely.\n    if (this.carriedNextDispatch) {\n      const carried = this.carriedNextDispatch;\n      this.carriedNextDispatch = undefined;\n\n      const decision: DispatchDecision = {\n        kind: \"dispatch\",\n        intents: carried.intents,\n        source: \"route\",\n        raw: carried.intents.length === 1 ? carried.intents[0] : carried.intents,\n        durationMs: 0,\n      };\n\n      this.emit(\"supervisor.router.decided\", {\n        iteration: this.iteration,\n        next: decision.raw,\n        reasoning: undefined,\n        durationMs: 0,\n      });\n\n      return decision;\n    }\n\n    const decision = await decide({\n      config: this.config as SupervisorConfig<unknown>,\n      entries: this.entries,\n      iteration: this.iteration,\n      maxIterations: this.maxIterations,\n      iterations: this.snapshots,\n      input: this.input,\n      state: this.state,\n      context: this.context,\n      history: this.history,\n      goal: this.goal,\n      evaluateFeedback: this.carriedFeedback,\n      classifier: this.classifierSnapshot,\n      signal: this.options?.signal,\n      useInitialAgent: this.iteration === 0 && !this.resumeFrom,\n    });\n\n    // Capture the router agent's report into the supervisor's tree so\n    // router cost + internals are observable alongside dispatched\n    // branches. Only present when decide() went through a router agent.\n    if (decision.routerReport) {\n      this.childReports.push(decision.routerReport);\n    }\n\n    this.emit(\"supervisor.router.decided\", {\n      iteration: this.iteration,\n      next: decision.raw,\n      reasoning: decision.reasoning,\n      durationMs: decision.durationMs,\n    });\n\n    return decision;\n  }\n\n  /**\n   * Dispatch every intent named by the decision in parallel. Per-\n   * branch errors don't abort siblings — they're recorded on the\n   * branch snapshot and let evaluate (or default termination logic)\n   * decide the response.\n   *\n   * `capFanOut` runs here as well as in `decide.ts` — this is the one\n   * chokepoint every dispatch source funnels through (router/route\n   * decisions, `evaluate.reassignTo`, classifier picks, per-intent\n   * `next` unions), so the width bound holds even for the paths that\n   * build a `DispatchDecision` without going through `normalize()`.\n   * Idempotent for already-normalized decisions.\n   */\n  private async dispatchBranches(\n    decision: DispatchDecision & { kind: \"dispatch\" },\n  ): Promise<AgentBranchSnapshot[]> {\n    const intents = capFanOut(decision.intents, this.entries, resolveMaxFanOut(this.config));\n\n    const branches = await Promise.all(intents.map((intent) => this.dispatchOne(intent)));\n\n    return branches;\n  }\n\n  /**\n   * Execute a single branch — resolve the input, invoke the\n   * agent / workflow / callback, apply the per-intent `output`\n   * transformer, and produce an immutable `AgentBranchSnapshot`.\n   */\n  private async dispatchOne(intent: string): Promise<AgentBranchSnapshot> {\n    const entry = this.entries.get(intent)!;\n\n    if (entry.type === \"callback\") {\n      return this.dispatchCallback(entry);\n    }\n\n    const routeContext: RouteContext = {\n      iteration: this.iteration,\n      input: this.input,\n      state: this.state,\n      iterations: this.snapshots,\n      feedback:\n        typeof this.carriedFeedback?.feedback === \"string\"\n          ? this.carriedFeedback.feedback\n          : undefined,\n      evaluateFeedback: this.carriedFeedback,\n      context: this.context,\n      history: this.history,\n      goal: this.goal,\n      classifier: this.classifierSnapshot,\n    };\n\n    const resolvedInput = this.resolveBranchInput(entry, routeContext);\n    const dispatchCtxForPlaceholders = this.seedDispatchContext(\n      intent,\n      resolvedInput,\n      new Set<string>([intent]),\n      [],\n    );\n    const placeholders = entry.placeholders\n      ? entry.placeholders(dispatchCtxForPlaceholders)\n      : undefined;\n\n    this.emit(\"supervisor.agent.starting\", {\n      iteration: this.iteration,\n      intent,\n      input: resolvedInput,\n    });\n\n    const startedAt = new Date();\n    const startPerf = performance.now();\n\n    let rawResult: AgentResult<unknown> | WorkflowResult<unknown> | undefined;\n    let branchError: AIError | undefined;\n    let branchUsage: Usage = { input: 0, output: 0, total: 0 };\n\n    try {\n      // Run the unit nested so observe-all doesn't ALSO self-route it as a\n      // standalone trace — its report is captured into `childReports` below.\n      rawResult = await withoutRunFrame(() =>\n        this.invokeUnit(entry, resolvedInput, placeholders, routeContext),\n      );\n\n      if (rawResult.error) {\n        branchError = rawResult.error;\n      }\n\n      branchUsage = rawResult.usage;\n\n      // Capture the child's execution report into the supervisor's\n      // recursive tree. Each dispatched agent/workflow contributes\n      // one BaseReport node; fan-out produces sibling children.\n      if (rawResult.report) {\n        this.childReports.push(rawResult.report);\n      }\n    } catch (thrown) {\n      branchError = toAIError(thrown);\n    }\n\n    const sliceOutcome = await this.applyOutputSchema(entry, rawResult);\n    const transformedOutput = sliceOutcome.value;\n    if (sliceOutcome.error && !branchError) {\n      branchError = sliceOutcome.error;\n    }\n    const endedAt = new Date();\n    const duration = performance.now() - startPerf;\n\n    const snapshot: AgentBranchSnapshot = Object.freeze({\n      intent,\n      input: resolvedInput,\n      output: transformedOutput,\n      usage: branchUsage,\n      startedAt: startedAt.toISOString(),\n      endedAt: endedAt.toISOString(),\n      duration,\n      error: branchError,\n    });\n\n    if (branchError) {\n      this.emit(\"supervisor.agent.failed\", {\n        iteration: this.iteration,\n        intent,\n        error: branchError,\n      });\n    } else {\n      this.emit(\"supervisor.agent.completed\", {\n        iteration: this.iteration,\n        intent,\n        output: transformedOutput,\n        usage: branchUsage,\n        duration,\n      });\n    }\n\n    return snapshot;\n  }\n\n  /**\n   * Dispatch a callback intent as a top-level branch — produces an\n   * `AgentBranchSnapshot` and pushes the synthesized callback report\n   * onto the supervisor's recursive children. Delegates the actual\n   * callback invocation to {@link runCallback} so nested\n   * `ctx.intents.X.execute()` calls can reuse the same machinery.\n   *\n   * Each branch dispatch starts with a fresh per-branch call stack —\n   * sibling fan-out branches don't share cycle-detection state, so\n   * branch A and branch B both invoking the same intent isn't a\n   * cycle. The branch's own intent name is seeded onto the stack so\n   * a callback that re-enters itself via `ctx.intents.X.execute()` trips\n   * cycle detection on the first recursion.\n   */\n  private async dispatchCallback(entry: ResolvedCallbackEntry): Promise<AgentBranchSnapshot> {\n    const intent = entry.intent;\n    const callStack = new Set<string>([intent]);\n    const callbackInput = entry.input\n      ? entry.input(this.seedDispatchContext(intent, this.input, callStack, []))\n      : this.input;\n    const inputForSnapshot =\n      typeof callbackInput === \"string\" ? callbackInput : safeStringify(callbackInput);\n\n    this.emit(\"supervisor.agent.starting\", {\n      iteration: this.iteration,\n      intent,\n      input: inputForSnapshot,\n    });\n\n    const outcome = await this.runCallback(entry, callbackInput, callStack, this.childReports);\n\n    const snapshot: AgentBranchSnapshot = Object.freeze({\n      intent,\n      input: inputForSnapshot,\n      output: outcome.output,\n      usage: outcome.report.usage,\n      startedAt: outcome.report.startedAt,\n      endedAt: outcome.report.endedAt,\n      duration: outcome.report.duration,\n      error: outcome.error,\n    });\n\n    if (outcome.error) {\n      this.emit(\"supervisor.agent.failed\", {\n        iteration: this.iteration,\n        intent,\n        error: outcome.error,\n      });\n    } else {\n      this.emit(\"supervisor.agent.completed\", {\n        iteration: this.iteration,\n        intent,\n        output: outcome.output,\n        usage: outcome.report.usage,\n        duration: outcome.report.duration,\n      });\n    }\n\n    return snapshot;\n  }\n\n  /**\n   * Run a callback intent and produce its leaf report + final\n   * output. Used both for top-level branch dispatch (via\n   * {@link dispatchCallback}) and for nested `dispatch.byName`\n   * recursion. The synthesized report is appended to `reportSink`,\n   * which is either `this.childReports` (top-level) or the calling\n   * callback's own `children[]` (nested) — that's what gives the\n   * unified report tree its compositional shape.\n   *\n   * Usage on the report rolls up children's usage; the callback\n   * itself contributes zero (it's dev code, no token spend).\n   */\n  private async runCallback(\n    entry: ResolvedCallbackEntry,\n    input: unknown,\n    callStack: Set<string>,\n    reportSink: BaseReport[],\n  ): Promise<{ output: unknown; error?: AIError; report: BaseReport }> {\n    const childReports: BaseReport[] = [];\n    const dispatchCtx: DispatchContext = this.seedDispatchContext(\n      entry.intent,\n      input,\n      callStack,\n      childReports,\n    );\n\n    // The runId this callback node will own — pre-computed so the\n    // ambient `RunFrame` installed around the callback body can stamp\n    // it as the `parentRunId` of any agent run nested inside.\n    const callbackRunId = `${this.runId}.${entry.intent}`;\n\n    const startedAt = new Date();\n    const startPerf = performance.now();\n\n    let rawOutput: unknown;\n    let error: AIError | undefined;\n\n    // Install an ambient run frame for the full async subtree of the\n    // callback. Any `agent.execute(...)` / `workflow.execute(...)` /\n    // `supervisor.execute(...)` the callback invokes DIRECTLY — without\n    // going through `ctx.run(...)` or `ctx.intents.X.execute()` — reads\n    // this frame at report-build time and auto-attaches its report onto\n    // `childReports`, nesting under this callback node with usage/cost\n    // rolled up. Mirrors how `workflow step.agent` captures child agent\n    // reports, but driven ambiently so the dev threads no ids.\n    try {\n      rawOutput = await withRunFrame(\n        {\n          sink: childReports,\n          rootRunId: this.runId,\n          parentRunId: callbackRunId,\n          sessionId: this.options?.sessionId,\n        },\n        () => Promise.resolve(entry.callback(dispatchCtx)),\n      );\n    } catch (thrown) {\n      error =\n        thrown instanceof AIError\n          ? thrown\n          : new SupervisorFailedError(\n              `callback intent \"${entry.intent}\" threw: ${\n                thrown instanceof Error ? thrown.message : String(thrown)\n              }`,\n              { cause: thrown },\n            );\n    }\n\n    let transformedOutput: unknown = rawOutput;\n\n    if (!error && entry.output) {\n      const validation = await entry.output[\"~standard\"].validate(rawOutput);\n      if (validation.issues) {\n        error = new SchemaValidationError(\n          `intent \"${entry.intent}\" output failed validation: ${validation.issues\n            .map((issue) => issue.message)\n            .join(\"; \")}`,\n          { issues: validation.issues },\n        );\n        transformedOutput = undefined;\n      } else {\n        transformedOutput = validation.value;\n      }\n    }\n\n    const endedAt = new Date();\n    const duration = performance.now() - startPerf;\n    const rolledUsage = aggregateChildUsage(childReports);\n\n    const report: BaseReport = {\n      runId: callbackRunId,\n      rootRunId: this.runId,\n      name: entry.intent,\n      type: \"callback\",\n      status: error ? \"failed\" : \"completed\",\n      startedAt: startedAt.toISOString(),\n      endedAt: endedAt.toISOString(),\n      duration,\n      usage: rolledUsage,\n      children: childReports,\n    };\n\n    reportSink.push(report);\n\n    return { output: transformedOutput, error, report };\n  }\n\n  /**\n   * Build a {@link DispatchContext} with a typed `intents` map of\n   * `IntentRunner` closures, each closing over the supplied call\n   * stack and report sink. Cycle detection uses the call stack —\n   * re-entering an intent already on it throws\n   * `SupervisorFailedError` with code `SUPERVISOR_DISPATCH_CYCLE`\n   * and the offending chain in the message.\n   *\n   * Replaces the Phase-3.3 `ctx.dispatch.byName` plumbing with\n   * property-access on a typed map (Q5/Q6) — autocomplete, no typo\n   * crashes, `.execute()` matches every other primitive's verb.\n   */\n  private seedDispatchContext(\n    intent: string,\n    input: unknown,\n    callStack: Set<string>,\n    reportSink: BaseReport[],\n  ): DispatchContext {\n    type RunnerSlot = {\n      execute: (input?: unknown) => Promise<unknown>;\n      stream: (input?: unknown) => unknown;\n    };\n    const intentsMap: Record<string, RunnerSlot> = {};\n\n    for (const target of this.entries.keys()) {\n      intentsMap[target] = {\n        execute: (override?: unknown) =>\n          this.runIntent(target, override === undefined ? input : override, callStack, reportSink),\n        stream: (override?: unknown) =>\n          this.streamIntent(\n            target,\n            override === undefined ? input : override,\n            callStack,\n            reportSink,\n            intent,\n          ),\n      };\n    }\n\n    return {\n      iteration: this.iteration,\n      intent,\n      input,\n      state: this.state,\n      result: {},\n      iterations: this.snapshots,\n      signal: this.options?.signal ?? new AbortController().signal,\n      intents: intentsMap as DispatchContext[\"intents\"],\n      context: this.context,\n      history: this.history,\n      goal: this.goal,\n      run: (executable, runInput, runOptions) =>\n        this.runInline(executable, runInput, runOptions, callStack, reportSink),\n      stream: (executable, runInput, runOptions) =>\n        this.streamInline(executable, runInput, runOptions, callStack, reportSink, intent),\n      classifier: this.classifierSnapshot,\n    } as DispatchContext;\n  }\n\n  /**\n   * Backing implementation for `ctx.intents.X.execute(input?)`.\n   * Looks up the named intent in the supervisor's registry, asserts\n   * the call wouldn't close a cycle, and runs the dispatchable\n   * through the same machinery a top-level branch would — except\n   * the resulting report nests under the calling callback's\n   * `children[]` rather than the supervisor's top-level child list,\n   * and only the final output is returned (no snapshot).\n   */\n  private async runIntent(\n    target: string,\n    callerInput: unknown,\n    callStack: Set<string>,\n    reportSink: BaseReport[],\n  ): Promise<unknown> {\n    if (callStack.has(target)) {\n      const chain = [...callStack, target].join(\" → \");\n      throw new SupervisorFailedError(\n        `ctx.intents.${target}.execute: cycle detected (${chain})`,\n        { context: { intent: target } },\n        \"SUPERVISOR_DISPATCH_CYCLE\",\n      );\n    }\n\n    const entry = this.entries.get(target);\n\n    if (!entry) {\n      throw new SupervisorFailedError(\n        `ctx.intents.${target}.execute: unknown intent \"${target}\" — must be a key in the supervisor's \\`intents\\` map`,\n        { context: { intent: target } },\n      );\n    }\n\n    callStack.add(target);\n\n    try {\n      if (entry.type === \"callback\") {\n        const { output, error } = await this.runCallback(entry, callerInput, callStack, reportSink);\n\n        if (error) {\n          throw error;\n        }\n\n        return output;\n      }\n\n      // Agent / workflow path. The unified-report tree gets the\n      // child's report under the calling callback's children — we\n      // intentionally do NOT also push to `this.childReports` (that\n      // would double-count). The agent/workflow's own usage flows\n      // up through the callback's roll-up.\n      const inputString =\n        typeof callerInput === \"string\" ? callerInput : safeStringify(callerInput);\n\n      if (entry.type === \"agent\") {\n        // Recursive `ctx.intents.X.execute()` re-entry path — no\n        // `RouteContext` constructed here, so the per-entry slicer is\n        // skipped; only the global `historyWindow.agents` window\n        // applies. The original outer dispatch already passed a sliced\n        // view; this sub-call mirrors that behavior.\n        const reentryHistory = this.applyAgentsWindow();\n        // Suppress the enclosing callback's ambient run frame for this\n        // call — we capture the report onto `reportSink` explicitly\n        // below, so the agent must NOT also self-capture (double-count).\n        const result = await withoutRunFrame(() =>\n          entry.unit.execute(inputString, {\n            signal: this.options?.signal,\n            ...(reentryHistory.length > 0 ? { history: reentryHistory } : {}),\n          }),\n        );\n\n        if (result.report) {\n          reportSink.push(result.report);\n        }\n\n        if (result.error) {\n          throw result.error;\n        }\n\n        return result.data ?? result.text ?? undefined;\n      }\n\n      // workflow — suppress the ambient frame (explicit capture below).\n      const result = await withoutRunFrame(() =>\n        entry.unit.execute(inputString as never, {\n          signal: this.options?.signal,\n        }),\n      );\n\n      if (result.report) {\n        reportSink.push(result.report);\n      }\n\n      if (result.error) {\n        throw result.error;\n      }\n\n      return result.data;\n    } finally {\n      callStack.delete(target);\n    }\n  }\n\n  /**\n   * Backing implementation for `ctx.intents.X.stream(input?)` (Phase 6\n   * / decisions §36). Streaming sibling of {@link runIntent} — same\n   * cycle protection, same auto-merge of supervisor-level concerns,\n   * but routes through the unit's `.stream()` method when available\n   * and bubbles deltas as `supervisor.agent.streaming` under the\n   * **calling callback's** intent name (not the dispatched intent's).\n   */\n  private streamIntent(\n    target: string,\n    callerInput: unknown,\n    callStack: Set<string>,\n    reportSink: BaseReport[],\n    callerIntent: string,\n  ): StreamContract<SupervisableResult> {\n    if (callStack.has(target)) {\n      const chain = [...callStack, target].join(\" → \");\n      throw new SupervisorFailedError(\n        `ctx.intents.${target}.stream: cycle detected (${chain})`,\n        { context: { intent: target } },\n        \"SUPERVISOR_DISPATCH_CYCLE\",\n      );\n    }\n\n    const entry = this.entries.get(target);\n\n    if (!entry) {\n      throw new SupervisorFailedError(\n        `ctx.intents.${target}.stream: unknown intent \"${target}\" — must be a key in the supervisor's \\`intents\\` map`,\n        { context: { intent: target } },\n      );\n    }\n\n    if (entry.type === \"callback\") {\n      throw new SupervisorFailedError(\n        `ctx.intents.${target}.stream: callback intents are not streamable — use \\`.execute(input?)\\` instead`,\n        { context: { intent: target } },\n      );\n    }\n\n    callStack.add(target);\n\n    const inputString = typeof callerInput === \"string\" ? callerInput : safeStringify(callerInput);\n\n    return this.streamSupervisedExecutable(\n      entry.unit as StreamableExecutable,\n      inputString,\n      undefined,\n      callerIntent,\n      reportSink,\n      () => callStack.delete(target),\n    );\n  }\n\n  /**\n   * Backing implementation for `ctx.run(executable, input, options?)`\n   * (Phase 6 / decisions §36). Runs an inline / un-registered\n   * executable under supervision: auto-merges `signal`, `toolCtx`,\n   * `history` defaults; nests the resulting report under the\n   * calling callback's `children[]`. Per-call options REPLACE auto-\n   * defaults — standard Warlock convention.\n   *\n   * Cycle protection by executable `name` matches the registered-\n   * intent path so a callback that recurses on the same agent trips\n   * the same error, regardless of whether the agent was looked up\n   * via `ctx.intents.X.execute()` or passed inline.\n   */\n  private async runInline(\n    executable: SupervisableExecutable,\n    input: unknown,\n    options: SupervisableExecuteOptions | undefined,\n    callStack: Set<string>,\n    reportSink: BaseReport[],\n  ): Promise<SupervisableResult> {\n    const name = executable.name;\n\n    if (callStack.has(name)) {\n      const chain = [...callStack, name].join(\" → \");\n      throw new SupervisorFailedError(\n        `ctx.run(\"${name}\"): cycle detected (${chain})`,\n        { context: { intent: name } },\n        \"SUPERVISOR_DISPATCH_CYCLE\",\n      );\n    }\n\n    callStack.add(name);\n\n    try {\n      const merged = this.mergeInlineOptions(options);\n      const inputForExecutable = this.coerceInlineInput(executable, input);\n      // Suppress the enclosing callback's ambient frame — `ctx.run(...)`\n      // captures the report onto `reportSink` explicitly below, so the\n      // executable must not also self-capture (double-count).\n      const result = (await withoutRunFrame(() =>\n        (\n          executable as {\n            execute: (input: unknown, options?: unknown) => Promise<SupervisableResult>;\n          }\n        ).execute(inputForExecutable, merged),\n      )) as SupervisableResult;\n\n      if (result.report) {\n        reportSink.push(result.report);\n      }\n\n      return result;\n    } finally {\n      callStack.delete(name);\n    }\n  }\n\n  /**\n   * Backing implementation for `ctx.stream(executable, input, options?)`\n   * (Phase 6 / decisions §36). Streaming sibling of {@link runInline}.\n   * Routes through the executable's native `.stream()` method,\n   * subscribes to delta events, and bubbles them as\n   * `supervisor.agent.streaming` under the calling callback's intent\n   * name. The returned `StreamContract` is the executable's own —\n   * iteration and `.result` work identically.\n   *\n   * Cycle protection on entry mirrors {@link runInline}; release runs\n   * after `.result` settles so a same-callback recursion is caught\n   * regardless of which path closed the cycle.\n   */\n  private streamInline(\n    executable: StreamableExecutable,\n    input: unknown,\n    options: SupervisableExecuteOptions | undefined,\n    callStack: Set<string>,\n    reportSink: BaseReport[],\n    callerIntent: string,\n  ): StreamContract<SupervisableResult> {\n    const name = executable.name;\n\n    if (callStack.has(name)) {\n      const chain = [...callStack, name].join(\" → \");\n      throw new SupervisorFailedError(\n        `ctx.stream(\"${name}\"): cycle detected (${chain})`,\n        { context: { intent: name } },\n        \"SUPERVISOR_DISPATCH_CYCLE\",\n      );\n    }\n\n    callStack.add(name);\n\n    return this.streamSupervisedExecutable(\n      executable,\n      this.coerceInlineInput(executable, input),\n      options,\n      callerIntent,\n      reportSink,\n      () => callStack.delete(name),\n    );\n  }\n\n  /**\n   * Shared wiring for both `ctx.intents.X.stream()` and\n   * `ctx.stream(...)`. Subscribes to the executable's stream, re-\n   * emits deltas as `supervisor.agent.streaming` under the calling\n   * callback's intent name, and pushes the inner report onto the\n   * reportSink once `.result` settles. The returned StreamContract\n   * is the executable's own — the framework attaches handlers\n   * transparently via `.on(...)`.\n   */\n  private streamSupervisedExecutable(\n    executable: StreamableExecutable,\n    input: unknown,\n    options: SupervisableExecuteOptions | undefined,\n    callerIntent: string,\n    reportSink: BaseReport[],\n    release: () => void,\n  ): StreamContract<SupervisableResult> {\n    const merged = this.mergeInlineOptions(options);\n    // Suppress the enclosing callback's ambient frame — the inner report\n    // is captured onto `reportSink` explicitly when `.result` settles\n    // below, so the executable must not also self-capture (double-count).\n    const stream = withoutRunFrame(() =>\n      (\n        executable as {\n          stream: (input: unknown, options?: unknown) => StreamContract<SupervisableResult>;\n        }\n      ).stream(input, merged),\n    );\n\n    // Bubble inner deltas under the CALLING callback's intent name.\n    // Agents fire `agent.trip.streaming`; supervisors fire\n    // `supervisor.agent.streaming` already — the inner intent name\n    // there is the inner supervisor's specialist, which we replace\n    // with the outer callback's name so attribution is consistent.\n    const handlers: Record<string, (event: { delta: string }) => void> = {\n      \"agent.trip.streaming\": ({ delta }) => {\n        this.emit(\"supervisor.agent.streaming\", {\n          iteration: this.iteration,\n          intent: callerIntent,\n          delta,\n        });\n      },\n      \"supervisor.agent.streaming\": ({ delta }) => {\n        this.emit(\"supervisor.agent.streaming\", {\n          iteration: this.iteration,\n          intent: callerIntent,\n          delta,\n        });\n      },\n    };\n\n    stream.on(handlers);\n\n    // Always release the cycle-protection slot after `.result` settles\n    // (success OR failure) so subsequent calls in the same callback\n    // see a clean stack. Push report on success.\n    void stream.result.then(\n      (result) => {\n        if (result?.report) {\n          reportSink.push(result.report);\n        }\n\n        release();\n      },\n      () => release(),\n    );\n\n    return stream;\n  }\n\n  /**\n   * Build the options object passed into an inline `.execute()` /\n   * `.stream()` call. Auto-merges supervisor-level defaults\n   * (`signal`, `toolCtx`, `history` window) under the caller's\n   * options. Per-call values REPLACE the auto-defaults — when the\n   * dev passes `signal: undefined` they explicitly opt out.\n   */\n  private mergeInlineOptions(\n    options: SupervisableExecuteOptions | undefined,\n  ): SupervisableExecuteOptions {\n    const supplied = (options ?? {}) as Record<string, unknown>;\n    const merged: Record<string, unknown> = { ...supplied };\n\n    if (!(\"signal\" in supplied)) {\n      merged.signal = this.options?.signal;\n    }\n\n    if (!(\"toolCtx\" in supplied)) {\n      merged.toolCtx = {\n        artifacts: this.currentArtifacts,\n        signal: this.options?.signal,\n      };\n    }\n\n    if (!(\"history\" in supplied)) {\n      const window = this.applyAgentsWindow();\n\n      if (window.length > 0) {\n        merged.history = window;\n      }\n    }\n\n    return merged as SupervisableExecuteOptions;\n  }\n\n  /**\n   * Coerce an arbitrary inline input into the shape the underlying\n   * executable expects. Agents take `string`; workflows + supervisors\n   * take whatever they declared. We safe-stringify objects only when\n   * passing to an agent — workflow / supervisor calls hand the value\n   * through unchanged so structured inputs work.\n   */\n  private coerceInlineInput(executable: SupervisableExecutable, input: unknown): unknown {\n    // `isAnonymous` is the only member unique to `AgentContract`. All\n    // three primitives expose `signature`, `execute`, `stream` and\n    // `resume`, so none of those tells them apart — an earlier\n    // `!(\"signature\" in executable)` check narrowed to `never` and made\n    // this branch permanently dead.\n    const isAgent = \"isAnonymous\" in executable;\n\n    if (isAgent && typeof input !== \"string\") {\n      return safeStringify(input);\n    }\n\n    return input;\n  }\n\n  /**\n   * Invoke the underlying dispatchable unit. Agents and workflows\n   * both satisfy `ExecutableContract<string, …>` so the call shape\n   * is uniform; the `type` discriminator picks which options get\n   * threaded through (e.g. per-call stream event bubbling for\n   * agents, which we wire inline so child agent tokens surface as\n   * `supervisor.agent.streaming`).\n   */\n  private async invokeUnit(\n    entry: Exclude<ResolvedIntentEntry, ResolvedCallbackEntry>,\n    input: string,\n    placeholders: Record<string, unknown> | undefined,\n    routeContext: RouteContext,\n  ): Promise<AgentResult<unknown> | WorkflowResult<unknown>> {\n    // When the supervisor itself is being streamed by the caller, run\n    // the child agent in streaming mode too — that's the only way\n    // token deltas surface up the tree as `supervisor.agent.streaming`\n    // events. `agent.execute()` always uses `model.complete()` which\n    // never fires `agent.trip.streaming`, so wiring a callback there\n    // is a silent no-op for tokens. Lifecycle events (trip.started /\n    // tool.called / completed) still fire through `.on()` regardless\n    // — they're driven by orchestration boundaries, not the wire mode.\n    const isStreaming = this.streamController !== undefined;\n\n    if (entry.type === \"agent\") {\n      // `type` and `unit` aren't a discriminated union on the entry\n      // type — narrow manually. `resolveIntentEntries` guarantees\n      // `unit` matches `type` at runtime.\n      const agent = entry.unit as AgentContract<unknown>;\n      const handlers = {\n        \"agent.trip.streaming\": ({ delta }: { delta: string }) => {\n          this.emit(\"supervisor.agent.streaming\", {\n            iteration: this.iteration,\n            intent: entry.intent,\n            delta,\n          });\n        },\n      };\n\n      // Phase 5 / decisions §34 — stream-mode intents drop the\n      // structured-output schema (factory already rejects coexistence)\n      // and always run via `agent.stream()` so token deltas surface as\n      // `supervisor.agent.streaming` events regardless of whether the\n      // top-level caller streamed the supervisor.\n      const isStreamMode = entry.mode === \"stream\";\n\n      // Stage 4b/4d: forward `intent.output` as the agent's per-call\n      // output schema when declared. The agent then parses model\n      // output as structured data; `applyOutputSchema` re-validates\n      // (cheap) and strip-merges into supervisor state.\n      const resolvedHistory = this.resolveHistoryFor(\"agents\", routeContext, entry.history);\n      const agentOptions = {\n        signal: this.options?.signal,\n        on: handlers,\n        ...(placeholders ? { placeholders } : {}),\n        ...(entry.output && !isStreamMode ? { output: entry.output } : {}),\n        ...(resolvedHistory.length > 0 ? { history: resolvedHistory } : {}),\n        toolCtx: {\n          artifacts: this.currentArtifacts,\n          signal: this.options?.signal,\n        },\n      };\n\n      if (isStreamMode || isStreaming) {\n        const childStream = agent.stream(input, agentOptions);\n        return childStream.result;\n      }\n\n      return agent.execute(input, agentOptions);\n    }\n\n    const workflow = entry.unit as WorkflowInstance<unknown, unknown>;\n\n    return workflow.execute(input, {\n      signal: this.options?.signal,\n      on: {\n        \"workflow.step.streaming\": ({ delta }) => {\n          this.emit(\"supervisor.agent.streaming\", {\n            iteration: this.iteration,\n            intent: entry.intent,\n            delta,\n          });\n        },\n      },\n    });\n  }\n\n  /**\n   * Build the input string passed to a branch's child execution.\n   * Default: pass the supervisor's original `ctx.input` through\n   * unchanged. The per-intent `entry.input` override is the escape\n   * hatch for the rare case where the agent's user message itself\n   * must vary per intent.\n   *\n   * Q17 lock: dropped `composeAgentInput` + `defaultComposeAgentInput`.\n   * Their three jobs (carry original / prior outputs / feedback) all\n   * have cleaner homes in the new model — original is the input\n   * itself, prior outputs are state (Stage 4b), feedback is a\n   * router-only signal (Q18).\n   */\n  private resolveBranchInput(\n    entry: Exclude<ResolvedIntentEntry, ResolvedCallbackEntry>,\n    ctx: RouteContext,\n  ): string {\n    const override = entry.input?.(ctx);\n\n    if (typeof override === \"string\") {\n      return override;\n    }\n\n    // Q1: supervisor-level input may be an object payload. Agents\n    // need a string — JSON-stringify when no per-intent override\n    // converted it. Devs wanting a different shape supply\n    // `entry.input(ctx)`.\n    return typeof ctx.input === \"string\" ? ctx.input : safeStringify(ctx.input);\n  }\n\n  /**\n   * Strip-merge the agent/workflow's raw output against the per-intent\n   * `output` schema (Q11/Q13). Returns the validated slice that:\n   *\n   *   1. Lands on `IterationSnapshot.result[intent].output` (so\n   *      consumers see the same shape that hit state).\n   *   2. Shallow-merges into `this.state` (handled by the caller).\n   *\n   * When `entry.output` is omitted the agent's full `data` (or `text`\n   * fallback for unstructured agents) flows through unvalidated — but\n   * is NOT auto-merged into state. State contribution is opt-in via\n   * declaring the slice schema.\n   *\n   * Validation failure surfaces as a per-branch error on the\n   * snapshot; sibling branches still run.\n   */\n  private async applyOutputSchema(\n    entry: Exclude<ResolvedIntentEntry, ResolvedCallbackEntry>,\n    raw: AgentResult<unknown> | WorkflowResult<unknown> | undefined,\n  ): Promise<{ value: unknown; error?: AIError }> {\n    if (!raw) {\n      return { value: undefined };\n    }\n\n    const sourceValue = isAgentResult(raw)\n      ? (raw.data ?? raw.text ?? undefined)\n      : isWorkflowResult(raw)\n        ? raw.data\n        : undefined;\n\n    // Phase 5 / decisions §34 — stream-mode agents have no `output`\n    // schema. The assembled prose comes back as `raw.text` (the agent\n    // never produced structured `data` because we dropped the schema\n    // in `invokeUnit`). Wrap it as `{ [streamTo]: text }` so the\n    // existing strip-merge path lands the prose under the named state\n    // key without further special-casing downstream.\n    if (entry.type === \"agent\" && entry.mode === \"stream\") {\n      const text = typeof sourceValue === \"string\" ? sourceValue : \"\";\n\n      return { value: { [entry.streamTo as string]: text } };\n    }\n\n    if (!entry.output) {\n      return { value: sourceValue };\n    }\n\n    const validation = await entry.output[\"~standard\"].validate(sourceValue);\n\n    if (validation.issues) {\n      return {\n        value: undefined,\n        error: new SchemaValidationError(\n          `intent \"${entry.intent}\" output failed validation: ${validation.issues\n            .map((issue) => issue.message)\n            .join(\"; \")}`,\n          { issues: validation.issues },\n        ),\n      };\n    }\n\n    return { value: validation.value };\n  }\n\n  /**\n   * Fire the receptionist (`ack`) — runs in parallel with phase A on\n   * iteration 0 only. Accepts three shapes:\n   *\n   * - `AckEntry` — `{ agent, placeholders?, input?, output? }`. LLM\n   *   form. Streams tokens via `supervisor.ack.streaming`; report\n   *   node pushes onto `childReports[]`.\n   * - `AckRunEntry` — `{ run, output? }`. Pure-code callback. Settles\n   *   without an LLM call. No streaming events; just `.completed`.\n   * - `AckCallback` — bare `(ctx) => slice` shorthand for the\n   *   pure-code form when no schema is declared.\n   *\n   * Failures are recorded but never abort the run — the receptionist\n   * tripping doesn't stop the specialist from doing the actual job.\n   * The returned outcome is what `mergeAckIntoState` consumes.\n   */\n  private async runAck(): Promise<\n    | {\n        output: unknown;\n        usage: Usage;\n        duration: number;\n        error?: AIError;\n      }\n    | undefined\n  > {\n    const ack = this.config.ack;\n    if (!ack) return undefined;\n\n    const routeContext: RouteContext = {\n      iteration: this.iteration,\n      input: this.input,\n      state: this.state,\n      iterations: this.snapshots,\n      feedback:\n        typeof this.carriedFeedback?.feedback === \"string\"\n          ? this.carriedFeedback.feedback\n          : undefined,\n      evaluateFeedback: this.carriedFeedback,\n      context: this.context,\n      history: this.history,\n      goal: this.goal,\n      classifier: this.classifierSnapshot,\n    };\n\n    const startedAt = new Date();\n    const startPerf = performance.now();\n\n    // Bare-callback shorthand: `ack: (ctx) => slice`.\n    if (typeof ack === \"function\") {\n      return this.runAckCallback(\n        ack as (ctx: RouteContext) => unknown | Promise<unknown>,\n        undefined,\n        routeContext,\n        startedAt,\n        startPerf,\n      );\n    }\n\n    // Run-entry form: `ack: { run, output? }`.\n    if (\"run\" in ack && typeof (ack as { run?: unknown }).run === \"function\") {\n      const runEntry = ack as {\n        run: (ctx: RouteContext) => unknown | Promise<unknown>;\n        output?: StandardSchemaV1<unknown>;\n      };\n      return this.runAckCallback(runEntry.run, runEntry.output, routeContext, startedAt, startPerf);\n    }\n\n    // Agent-entry form: `ack: { agent, placeholders?, input?, output? }`.\n    return this.runAckAgent(\n      ack as {\n        agent: import(\"../contracts/agent/agent.contract\").AgentContract<unknown>;\n        placeholders?: (ctx: RouteContext) => Record<string, unknown>;\n        input?: (ctx: RouteContext) => string;\n        output?: StandardSchemaV1<unknown>;\n        history?: (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n      },\n      routeContext,\n      startedAt,\n      startPerf,\n    );\n  }\n\n  /**\n   * Pure-code receptionist path — invokes the callback, strip-validates\n   * the return value (when an `output` schema is declared), records the\n   * snapshot, emits `supervisor.ack.completed`, returns the outcome.\n   * No streaming events fire (callbacks settle synchronously from the\n   * supervisor's POV).\n   */\n  private async runAckCallback(\n    run: (ctx: RouteContext) => unknown | Promise<unknown>,\n    output: StandardSchemaV1<unknown> | undefined,\n    routeContext: RouteContext,\n    startedAt: Date,\n    startPerf: number,\n  ): Promise<{\n    output: unknown;\n    usage: Usage;\n    duration: number;\n    error?: AIError;\n  }> {\n    const usage: Usage = { input: 0, output: 0, total: 0 };\n    let validatedOutput: unknown;\n    let ackError: AIError | undefined;\n\n    try {\n      const raw = await run(routeContext);\n\n      if (output) {\n        const validation = await output[\"~standard\"].validate(raw);\n        if (validation.issues) {\n          ackError = new SchemaValidationError(\n            `ack output failed validation: ${validation.issues\n              .map((issue) => issue.message)\n              .join(\"; \")}`,\n            { issues: validation.issues },\n          );\n        } else {\n          validatedOutput = validation.value;\n        }\n      } else {\n        validatedOutput = raw;\n      }\n    } catch (thrown) {\n      ackError = toAIError(thrown);\n    }\n\n    const endedAt = new Date();\n    const duration = performance.now() - startPerf;\n\n    this.ackSnapshot = Object.freeze({\n      input: typeof this.input === \"string\" ? this.input : safeStringify(this.input),\n      output: validatedOutput,\n      usage,\n      startedAt: startedAt.toISOString(),\n      endedAt: endedAt.toISOString(),\n      duration,\n      error: ackError,\n    });\n\n    this.emit(\"supervisor.ack.completed\", {\n      output: validatedOutput,\n      usage,\n      duration,\n      error: ackError,\n    });\n\n    return { output: validatedOutput, usage, duration, error: ackError };\n  }\n\n  /**\n   * Agent-driven receptionist path — invokes the agent, streams tokens\n   * via `supervisor.ack.streaming`, captures the report node, strip-\n   * validates against `output` (when declared), records the snapshot,\n   * emits `supervisor.ack.completed`.\n   */\n  private async runAckAgent(\n    ack: {\n      agent: import(\"../contracts/agent/agent.contract\").AgentContract<unknown>;\n      placeholders?: (ctx: RouteContext) => Record<string, unknown>;\n      input?: (ctx: RouteContext) => string;\n      output?: StandardSchemaV1<unknown>;\n      history?: (ctx: RouteContext) => Message[] | ReadonlyArray<Message>;\n    },\n    routeContext: RouteContext,\n    startedAt: Date,\n    startPerf: number,\n  ): Promise<{\n    output: unknown;\n    usage: Usage;\n    duration: number;\n    error?: AIError;\n  }> {\n    const placeholders = ack.placeholders?.(routeContext);\n    const inputForAck =\n      ack.input?.(routeContext) ??\n      (typeof this.input === \"string\" ? this.input : safeStringify(this.input));\n\n    const isStreaming = this.streamController !== undefined;\n\n    const handlers = {\n      \"agent.trip.streaming\": ({ delta }: { delta: string }) => {\n        this.emit(\"supervisor.ack.streaming\", { delta });\n      },\n    };\n\n    const resolvedHistory = this.resolveHistoryFor(\"ack\", routeContext, ack.history);\n    const agentOptions = {\n      signal: this.options?.signal,\n      on: handlers,\n      ...(placeholders ? { placeholders } : {}),\n      ...(ack.output ? { output: ack.output } : {}),\n      ...(resolvedHistory.length > 0 ? { history: resolvedHistory } : {}),\n    };\n\n    let rawResult: AgentResult<unknown> | undefined;\n    let ackError: AIError | undefined;\n    let usage: Usage = { input: 0, output: 0, total: 0 };\n\n    try {\n      if (isStreaming) {\n        const childStream = ack.agent.stream(inputForAck, agentOptions);\n        rawResult = await childStream.result;\n      } else {\n        rawResult = await ack.agent.execute(inputForAck, agentOptions);\n      }\n\n      if (rawResult.error) {\n        ackError = rawResult.error;\n      }\n\n      usage = rawResult.usage ?? usage;\n\n      // Ack agent's report node in the supervisor's recursive tree.\n      if (rawResult.report) {\n        this.childReports.push(rawResult.report);\n      }\n    } catch (thrown) {\n      ackError = toAIError(thrown);\n    }\n\n    const endedAt = new Date();\n    const duration = performance.now() - startPerf;\n\n    // Strip-validate against `ack.output` (when declared) — same\n    // contract as per-intent output schemas.\n    let validatedOutput: unknown;\n    if (rawResult && !ackError && ack.output) {\n      const sourceValue = rawResult.data ?? rawResult.text ?? undefined;\n      const validation = await ack.output[\"~standard\"].validate(sourceValue);\n      if (validation.issues) {\n        ackError = new SchemaValidationError(\n          `ack output failed validation: ${validation.issues\n            .map((issue) => issue.message)\n            .join(\"; \")}`,\n          { issues: validation.issues },\n        );\n      } else {\n        validatedOutput = validation.value;\n      }\n    } else if (rawResult && !ackError) {\n      validatedOutput = rawResult.data ?? rawResult.text ?? undefined;\n    }\n\n    this.ackSnapshot = Object.freeze({\n      input: inputForAck,\n      output: validatedOutput,\n      usage,\n      startedAt: startedAt.toISOString(),\n      endedAt: endedAt.toISOString(),\n      duration,\n      error: ackError,\n    });\n\n    this.emit(\"supervisor.ack.completed\", {\n      output: validatedOutput,\n      usage,\n      duration,\n      error: ackError,\n    });\n\n    return { output: validatedOutput, usage, duration, error: ackError };\n  }\n\n  /**\n   * Probe the ack promise non-blockingly. Yields one macrotask cycle\n   * (`setImmediate`) so an already-resolved ack wins via microtask\n   * priority; if the probe returns first, the slice is abandoned —\n   * warning logged, error captured on `report.ack`, run completes\n   * regardless. Specialists own the actual answer; the receptionist\n   * was just a reassuring preview.\n   */\n  private async settleAck(\n    ackPromise:\n      | Promise<{ output: unknown; usage: Usage; duration: number; error?: AIError } | undefined>\n      | undefined,\n    iterationUsage: Usage,\n  ): Promise<void> {\n    if (!ackPromise) return;\n\n    const NOT_READY = Symbol(\"ack-not-ready\");\n    const probe = await Promise.race([\n      ackPromise,\n      new Promise<typeof NOT_READY>((resolve) => setTimeout(() => resolve(NOT_READY), 0)),\n    ]);\n\n    if (probe === NOT_READY) {\n      this.logger.warn(\n        this.logModule,\n        \"ack.abandoned\",\n        \"ack receptionist did not settle before iteration completed; slice dropped\",\n      );\n      const abandonedAt = new Date();\n      this.ackSnapshot = Object.freeze({\n        input: typeof this.input === \"string\" ? this.input : safeStringify(this.input),\n        output: undefined,\n        usage: { input: 0, output: 0, total: 0 },\n        startedAt: abandonedAt.toISOString(),\n        endedAt: abandonedAt.toISOString(),\n        duration: 0,\n        error: new SupervisorFailedError(\n          \"ack receptionist did not settle before iteration completed\",\n          { context: { ackAbandoned: true } },\n        ),\n      });\n      return;\n    }\n\n    const ackOutcome = probe;\n    if (ackOutcome) {\n      this.aggregateUsage(iterationUsage, ackOutcome.usage);\n      this.mergeAckIntoState(ackOutcome);\n    }\n  }\n\n  /**\n   * Merge the receptionist's strip-validated slice into state. Called\n   * from `settleAck` BEFORE branch merges so specialists override the\n   * receptionist on key collision — the receptionist hedges, the\n   * specialist commits.\n   */\n  private mergeAckIntoState(ackOutcome: { output: unknown; error?: AIError }): void {\n    if (ackOutcome.error || !ackOutcome.output) return;\n\n    if (typeof ackOutcome.output !== \"object\" || ackOutcome.output === null) return;\n\n    const slice = ackOutcome.output as Record<string, unknown>;\n\n    this.mergeIntoState(slice, \"ack\");\n  }\n\n  /**\n   * Single funnel for \"shallow-merge a model-influenced slice into\n   * `this.state`\". Wraps the shared {@link mergeSafely} guard so no\n   * merge site can assign `__proto__` / `constructor` / `prototype`\n   * onto the run's state object, and logs when something tried.\n   *\n   * Every slice reaching state is model- or tool-influenced (agent\n   * outputs validated against a DEVELOPER-supplied schema, which may\n   * legitimately be permissive: `z.record()`, `.passthrough()`,\n   * `z.any()`), so the key names are untrusted input even when the\n   * values are shaped.\n   */\n  private mergeIntoState(slice: Record<string, unknown>, origin: string): void {\n    const skipped = mergeSafely(this.state, slice);\n\n    this.warnOnUnsafeKeys(skipped, origin);\n  }\n\n  /** Shared logging for refused prototype-tampering keys. */\n  private warnOnUnsafeKeys(skipped: string[], origin: string): void {\n    if (skipped.length === 0) return;\n\n    this.logger.warn(\n      this.logModule,\n      \"state.merge.unsafe-key\",\n      `dropped prototype-tampering key(s) from \"${origin}\" merge: ${skipped.join(\", \")}`,\n      { origin, keys: skipped },\n    );\n  }\n\n  /**\n   * Run the iter-0 classifier prelude (Phase 7 / decisions §37).\n   * Resolves the configured classifier (agent / callback / entry\n   * form), invokes it, runs the optional `refine` post-process hook,\n   * and either:\n   *\n   *   - sets `carriedClassifierDispatch` so the upcoming\n   *     `decideDispatch` short-circuits to the chosen intent, OR\n   *   - sets `classifierHalted = true` so `runIteration` terminates\n   *     before any dispatch (refine returned `END`).\n   *\n   * Captures the full forensic record on `classifierSnapshot` —\n   * surfaced on `SupervisorReport.classifier` and threaded into\n   * `ctx.classifier` on every downstream context.\n   *\n   * Errors in the classifier OR the refine hook abort the run with\n   * a `SupervisorFailedError` so issues surface loudly instead of\n   * silently falling through to router/route.\n   */\n  private async runClassifier(): Promise<void> {\n    const startedAt = new Date();\n    const startPerf = performance.now();\n    const startedAtIso = startedAt.toISOString();\n\n    this.emit(\"supervisor.classifier.starting\", { iteration: 0 });\n\n    const ctx = this.buildClassifierContext();\n    const config = this.config.classifier as ClassifierConfig;\n\n    let raw: ClassifierOutput | undefined;\n    let usage: Usage = { input: 0, output: 0, total: 0 };\n    let executionError: AIError | undefined;\n\n    try {\n      const outcome = await this.invokeClassifier(config, ctx);\n      raw = outcome.output;\n      usage = outcome.usage;\n    } catch (thrown) {\n      executionError = toAIError(thrown);\n    }\n\n    if (executionError || !raw) {\n      const error =\n        executionError ??\n        new SupervisorFailedError(\n          `ai.supervisor(\"${this.config.name}\"): classifier produced no output`,\n          { context: { iteration: 0 } },\n        );\n\n      this.classifierSnapshot = {\n        intent: undefined,\n        refined: false,\n        halted: true,\n        raw: raw ?? { intent: \"\" },\n        startedAt: startedAtIso,\n        endedAt: new Date().toISOString(),\n        duration: performance.now() - startPerf,\n        usage,\n        error,\n      };\n\n      mergeUsage(this.usage, usage);\n\n      this.emit(\"supervisor.classifier.failed\", { error });\n\n      // Classifier failure aborts the run — no fallback to router/route.\n      // Phase 7 / decisions §37.\n      throw error;\n    }\n\n    // Validate the classifier's chosen intent against the registry\n    // before running refine — refine may override, but we still want\n    // to fail fast on raw classifier output that targets nothing.\n    if (!this.entries.has(raw.intent)) {\n      const error = new SupervisorFailedError(\n        `ai.supervisor(\"${this.config.name}\"): classifier picked unknown intent \"${raw.intent}\" — must be a key in \\`intents\\``,\n        { context: { iteration: 0, available: [...this.entries.keys()] } },\n        \"SUPERVISOR_INVALID_ROUTE\",\n      );\n\n      this.classifierSnapshot = {\n        intent: undefined,\n        refined: false,\n        halted: true,\n        raw,\n        startedAt: startedAtIso,\n        endedAt: new Date().toISOString(),\n        duration: performance.now() - startPerf,\n        usage,\n        error,\n      };\n\n      mergeUsage(this.usage, usage);\n\n      this.emit(\"supervisor.classifier.failed\", { error });\n\n      throw error;\n    }\n\n    // Refine pass — optional. Refine receives the classifier output\n    // on `ctx.result.data` plus `run` / `stream` for inline secondary\n    // classifiers. Returns: undefined (use as-is) | END (halt) |\n    // { intent?, ...slice } (override + merge).\n    const refineHook = this.resolveRefineHook(config);\n    let final: ClassifierOutput = raw;\n    let refined = false;\n    let halted = false;\n\n    if (refineHook) {\n      let refineResult: ClassifierRefineResult;\n\n      try {\n        refineResult = await refineHook(this.buildClassifierRefineContext(ctx, raw));\n      } catch (thrown) {\n        const error = toAIError(thrown);\n\n        this.classifierSnapshot = {\n          intent: undefined,\n          refined: false,\n          halted: true,\n          raw,\n          startedAt: startedAtIso,\n          endedAt: new Date().toISOString(),\n          duration: performance.now() - startPerf,\n          usage,\n          error,\n        };\n\n        mergeUsage(this.usage, usage);\n\n        this.emit(\"supervisor.classifier.failed\", { error });\n\n        throw error;\n      }\n\n      const interpretation = this.interpretRefineResult(refineResult, raw);\n\n      if (interpretation.error) {\n        this.classifierSnapshot = {\n          intent: undefined,\n          refined: true,\n          halted: true,\n          raw,\n          startedAt: startedAtIso,\n          endedAt: new Date().toISOString(),\n          duration: performance.now() - startPerf,\n          usage,\n          error: interpretation.error,\n        };\n\n        mergeUsage(this.usage, usage);\n\n        this.emit(\"supervisor.classifier.failed\", { error: interpretation.error });\n\n        throw interpretation.error;\n      }\n\n      refined = interpretation.refined;\n      halted = interpretation.halted;\n      final = interpretation.final ?? raw;\n\n      // Merge refine's slice into state BEFORE dispatching — refine\n      // can augment state (e.g. detected language) regardless of\n      // override-vs-keep decision.\n      if (interpretation.sliceToMerge) {\n        this.mergeIntoState(interpretation.sliceToMerge, \"classifier.refine\");\n      }\n    }\n\n    // Always merge the (possibly refined) classifier output's\n    // remaining fields into state — universal locked fields (intent,\n    // reasoning, confidence) plus any dev-extended fields. Subject\n    // to the supervisor's `output` schema validation at finalize.\n    this.mergeIntoState(final as unknown as Record<string, unknown>, \"classifier\");\n\n    this.classifierSnapshot = {\n      intent: halted ? undefined : final.intent,\n      reasoning: final.reasoning,\n      confidence: final.confidence,\n      refined,\n      halted,\n      raw,\n      startedAt: startedAtIso,\n      endedAt: new Date().toISOString(),\n      duration: performance.now() - startPerf,\n      usage,\n    };\n\n    mergeUsage(this.usage, usage);\n\n    this.emit(\"supervisor.classifier.completed\", {\n      output: {\n        intent: this.classifierSnapshot.intent,\n        reasoning: this.classifierSnapshot.reasoning,\n        confidence: this.classifierSnapshot.confidence,\n      },\n      intent: this.classifierSnapshot.intent,\n      refined,\n      halted,\n      duration: this.classifierSnapshot.duration,\n      usage,\n    });\n\n    if (halted) {\n      this.classifierHalted = true;\n\n      return;\n    }\n\n    // Validate the FINAL intent against the registry — refine may\n    // have overridden to an unknown name. Throw loudly.\n    if (!this.entries.has(final.intent)) {\n      const error = new SupervisorFailedError(\n        `ai.supervisor(\"${this.config.name}\"): classifier.refine returned unknown intent \"${final.intent}\" — must be a key in \\`intents\\``,\n        { context: { iteration: 0, available: [...this.entries.keys()] } },\n        \"SUPERVISOR_INVALID_ROUTE\",\n      );\n\n      this.classifierSnapshot = { ...this.classifierSnapshot, halted: true, error };\n      this.classifierHalted = true;\n\n      this.emit(\"supervisor.classifier.failed\", { error });\n\n      throw error;\n    }\n\n    this.carriedClassifierDispatch = { intent: final.intent };\n  }\n\n  /**\n   * Resolve the configured classifier into a callable that returns\n   * `{ output, usage }`. Handles the four accepted shapes — bare\n   * agent / bare callback / agent-entry / run-entry. Pure shape\n   * normalization; no side effects.\n   */\n  private async invokeClassifier(\n    config: ClassifierConfig,\n    ctx: ClassifierContext,\n  ): Promise<{ output: ClassifierOutput; usage: Usage }> {\n    // (a) Bare callback shorthand.\n    if (typeof config === \"function\") {\n      const output = await (\n        config as (ctx: ClassifierContext) => Promise<ClassifierOutput> | ClassifierOutput\n      )(ctx);\n\n      return { output, usage: { input: 0, output: 0, total: 0 } };\n    }\n\n    // (b) Run-entry — `{ run, refine? }`.\n    if (typeof (config as { run?: unknown }).run === \"function\") {\n      const runFn = (\n        config as { run: (ctx: ClassifierContext) => Promise<ClassifierOutput> | ClassifierOutput }\n      ).run;\n      const output = await runFn(ctx);\n\n      return { output, usage: { input: 0, output: 0, total: 0 } };\n    }\n\n    // (c) Agent-entry — `{ agent, placeholders?, input?, history?, refine? }`.\n    if (typeof (config as { agent?: { execute?: unknown } }).agent?.execute === \"function\") {\n      const entry = config as {\n        agent: AgentContract<unknown>;\n        placeholders?: (ctx: ClassifierContext) => Record<string, unknown>;\n        input?: (ctx: ClassifierContext) => string;\n        history?: (ctx: ClassifierContext) => Message[] | ReadonlyArray<Message>;\n      };\n\n      return this.invokeClassifierAgent(\n        entry.agent,\n        ctx,\n        entry.placeholders,\n        entry.input,\n        entry.history,\n      );\n    }\n\n    // (d) Bare agent shorthand.\n    if (typeof (config as { execute?: unknown }).execute === \"function\") {\n      return this.invokeClassifierAgent(config as AgentContract<unknown>, ctx);\n    }\n\n    throw new SupervisorFailedError(\n      `ai.supervisor(\"${this.config.name}\"): \\`classifier\\` is not an agent, callback, or entry object`,\n      { context: { authoring: true } },\n    );\n  }\n\n  /**\n   * Invoke a classifier agent with the supervisor's standard wiring\n   * — placeholders, input override, history slicing, signal,\n   * streaming bubble. Output schema validation belongs to the agent\n   * itself; we just pull the typed `data` (or fall back to parsing\n   * `text`) and assert the locked `intent` field.\n   */\n  private async invokeClassifierAgent(\n    agent: AgentContract<unknown>,\n    ctx: ClassifierContext,\n    placeholders?: (ctx: ClassifierContext) => Record<string, unknown>,\n    inputResolver?: (ctx: ClassifierContext) => string,\n    historySlicer?: (ctx: ClassifierContext) => Message[] | ReadonlyArray<Message>,\n  ): Promise<{ output: ClassifierOutput; usage: Usage }> {\n    const inputForAgent =\n      inputResolver?.(ctx) ??\n      (typeof ctx.input === \"string\" ? ctx.input : safeStringify(ctx.input));\n\n    const history = historySlicer ? [...historySlicer(ctx)] : this.applyAgentsWindow();\n\n    const isStreaming = this.streamController !== undefined;\n\n    const handlers = {\n      \"agent.trip.streaming\": ({ delta }: { delta: string }) => {\n        this.emit(\"supervisor.classifier.streaming\", { delta });\n      },\n    };\n\n    const agentOptions = {\n      signal: this.options?.signal,\n      on: handlers,\n      ...(placeholders ? { placeholders: placeholders(ctx) } : {}),\n      ...(history.length > 0 ? { history } : {}),\n    };\n\n    let result: AgentResult<unknown>;\n\n    if (isStreaming) {\n      result = await agent.stream(inputForAgent, agentOptions).result;\n    } else {\n      result = await agent.execute(inputForAgent, agentOptions);\n    }\n\n    if (result.error) {\n      throw result.error;\n    }\n\n    if (result.report) {\n      this.childReports.push(result.report);\n    }\n\n    const data = result.data ?? result.text ?? undefined;\n    const output = this.coerceClassifierOutput(data);\n\n    return { output, usage: result.usage };\n  }\n\n  /**\n   * Coerce an agent's output into the locked classifier shape.\n   * Accepts a typed object with `intent` (the canonical case) or a\n   * plain string (interpreted as the intent name with no reasoning).\n   * Throws `SupervisorFailedError` if neither shape matches.\n   */\n  private coerceClassifierOutput(data: unknown): ClassifierOutput {\n    if (typeof data === \"string\") {\n      return { intent: data };\n    }\n\n    if (\n      data &&\n      typeof data === \"object\" &&\n      typeof (data as { intent?: unknown }).intent === \"string\"\n    ) {\n      const record = data as Record<string, unknown>;\n\n      return {\n        intent: record.intent as string,\n        reasoning: typeof record.reasoning === \"string\" ? (record.reasoning as string) : undefined,\n        confidence:\n          typeof record.confidence === \"number\" ? (record.confidence as number) : undefined,\n      };\n    }\n\n    throw new SupervisorFailedError(\n      `ai.supervisor(\"${this.config.name}\"): classifier output missing required \\`intent\\` field — got ${JSON.stringify(data)?.slice(0, 200)}`,\n      { context: { iteration: 0 } },\n    );\n  }\n\n  /**\n   * Build the read-only context passed to a classifier callback / agent\n   * resolvers. No dispatch helpers — registered intents haven't fired\n   * yet; pre-running them from the classifier would be confusing.\n   */\n  private buildClassifierContext(): ClassifierContext {\n    return {\n      iteration: 0,\n      input: this.input,\n      state: this.state,\n      context: this.context,\n      history: this.history,\n      signal: this.options?.signal ?? new AbortController().signal,\n      goal: this.goal,\n    };\n  }\n\n  /**\n   * Build the refine context — extends ClassifierContext with the\n   * classifier's just-resolved output plus `run` / `stream` so the\n   * refine hook can spin up secondary classifiers / validators\n   * inline (Phase 6 features).\n   */\n  private buildClassifierRefineContext(\n    base: ClassifierContext,\n    raw: ClassifierOutput,\n  ): ClassifierRefineContext {\n    const callStack = new Set<string>();\n    const reportSink = this.childReports;\n\n    return {\n      ...base,\n      result: { data: raw },\n      run: (executable, runInput, runOptions) =>\n        this.runInline(executable, runInput, runOptions, callStack, reportSink),\n      stream: (executable, runInput, runOptions) =>\n        this.streamInline(executable, runInput, runOptions, callStack, reportSink, \"classifier\"),\n    };\n  }\n\n  /**\n   * Pull the optional `refine` hook off whichever classifier-config\n   * shape was supplied. Bare-callback and bare-agent forms have no\n   * refine; only entry forms do.\n   */\n  private resolveRefineHook(\n    config: ClassifierConfig,\n  ):\n    | ((ctx: ClassifierRefineContext) => Promise<ClassifierRefineResult> | ClassifierRefineResult)\n    | undefined {\n    if (typeof config === \"function\") {\n      return undefined;\n    }\n\n    const refine = (config as { refine?: unknown }).refine;\n\n    return typeof refine === \"function\"\n      ? (refine as (\n          ctx: ClassifierRefineContext,\n        ) => Promise<ClassifierRefineResult> | ClassifierRefineResult)\n      : undefined;\n  }\n\n  /**\n   * Interpret a refine return value into actionable bits — final\n   * classifier output to dispatch, slice-to-merge, halted/refined\n   * flags, or an error. See {@link ClassifierRefineResult} for the\n   * accepted shapes.\n   */\n  private interpretRefineResult(\n    refineResult: ClassifierRefineResult,\n    raw: ClassifierOutput,\n  ): {\n    final?: ClassifierOutput;\n    sliceToMerge?: Record<string, unknown>;\n    refined: boolean;\n    halted: boolean;\n    error?: AIError;\n  } {\n    if (refineResult === undefined) {\n      return { final: raw, refined: false, halted: false };\n    }\n\n    if (refineResult === END) {\n      return { refined: true, halted: true };\n    }\n\n    if (typeof refineResult !== \"object\" || refineResult === null) {\n      return {\n        refined: false,\n        halted: true,\n        error: new SupervisorFailedError(\n          `ai.supervisor(\"${this.config.name}\"): classifier.refine returned an unsupported value — expected undefined, END, or an object`,\n          { context: { iteration: 0 } },\n        ),\n      };\n    }\n\n    const record = refineResult as Record<string, unknown>;\n    const intentField = record.intent;\n    const halted = intentField === END;\n    const intentOverride = typeof intentField === \"string\" ? intentField : undefined;\n\n    // Slice-to-merge is the refine return MINUS the `intent` field\n    // (which is dispatch metadata, not state contribution).\n    const slice: Record<string, unknown> = {};\n\n    for (const [key, value] of Object.entries(record)) {\n      if (key === \"intent\") continue;\n\n      // `refine` is a dev callback, but its return is routinely built\n      // from the classifier model's output — guard the key names here\n      // too so a tampered slice never even exists.\n      assignSafeKey(slice, key, value);\n    }\n\n    const final: ClassifierOutput = {\n      ...raw,\n      ...(intentOverride ? { intent: intentOverride } : {}),\n    };\n\n    return {\n      final: halted ? undefined : final,\n      sliceToMerge: Object.keys(slice).length > 0 ? slice : undefined,\n      refined: true,\n      halted,\n    };\n  }\n\n  /**\n   * Run the `evaluate` callback (when configured) after the\n   * iteration's branches settle and outputs have merged into state.\n   * Errors in the callback surface as `SupervisorFailedError` so a\n   * buggy evaluate doesn't silently swallow the whole run.\n   *\n   * Phase 3.4 (Stage 4b) — `EvaluateContext.state` carries the\n   * post-merge accumulator so verdicts can be state-aware. Q9\n   * lifted the router-only restriction; evaluate now runs in both\n   * router and route modes.\n   */\n  private async runEvaluate(branches: AgentBranchSnapshot[]): Promise<EvaluateResult> {\n    if (!this.config.evaluate) {\n      return undefined;\n    }\n\n    const evaluateContext: EvaluateContext = {\n      iteration: this.iteration,\n      input: this.input,\n      state: this.state,\n      result: indexBranchesForEvaluate(branches),\n      iterations: this.snapshots,\n      context: this.context,\n      history: this.history,\n      goal: this.goal,\n      classifier: this.classifierSnapshot,\n    };\n\n    try {\n      return await (\n        this.config.evaluate as (ctx: EvaluateContext) => EvaluateResult | Promise<EvaluateResult>\n      )(evaluateContext);\n    } catch (thrown) {\n      const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n      throw new SupervisorFailedError(`evaluate callback threw: ${message}`, {\n        cause: thrown,\n      });\n    }\n  }\n\n  /**\n   * Merge each branch's output into supervisor `state` in\n   * `decision.intents` order — Q15 conflict rule: last intent in\n   * the array wins on key collisions. Errored branches don't\n   * contribute. Non-object outputs (primitives, null) are skipped\n   * with a warning log; they can't shallow-merge into an object.\n   *\n   * For agent/workflow intents: merging is opt-in via declaring an\n   * `output` schema (the strip-merge gate). Without a schema, the\n   * raw output stays on the branch snapshot but doesn't pollute\n   * state. For callback intents: their return is already strip-merged\n   * (or pass-through) inside `runCallback` — we just merge what's on\n   * the branch snapshot.\n   */\n  private mergeBranchesIntoState(intentsOrder: string[], branches: AgentBranchSnapshot[]): void {\n    const indexed = new Map<string, AgentBranchSnapshot>();\n    for (const branch of branches) {\n      indexed.set(branch.intent, branch);\n    }\n\n    const mergedKeys = new Map<string, string>();\n\n    for (const intent of intentsOrder) {\n      const branch = indexed.get(intent);\n      if (!branch || branch.error) continue;\n\n      const entry = this.entries.get(intent);\n\n      // For agent/workflow intents, only merge when the slice schema\n      // was declared (output present on the entry). For callbacks,\n      // their output is always merged (the schema, if any, was\n      // applied inside runCallback). Stream-mode agents (Phase 5 /\n      // decisions §34) merge unconditionally — `applyOutputSchema`\n      // already shaped their slice as `{ [streamTo]: text }`, and\n      // they have no `output` schema by construction.\n      const isStreamModeAgent = entry?.type === \"agent\" && entry.mode === \"stream\";\n      const shouldMerge =\n        entry?.type === \"callback\" || (entry && entry.output !== undefined) || isStreamModeAgent;\n\n      if (!shouldMerge) continue;\n\n      const slice = branch.output;\n\n      if (!slice || typeof slice !== \"object\" || Array.isArray(slice)) {\n        if (slice !== undefined) {\n          this.logger.warn(\n            this.logModule,\n            \"state.merge.skip\",\n            `intent \"${intent}\" output is not a mergeable object — skipping state merge`,\n            { intent, type: typeof slice },\n          );\n        }\n        continue;\n      }\n\n      for (const [key, value] of Object.entries(slice as Record<string, unknown>)) {\n        // Branch outputs are validated against a DEVELOPER-supplied\n        // schema, which may be permissive enough to pass a key named\n        // `__proto__` straight through — refuse before assigning.\n        if (isUnsafeMergeKey(key)) {\n          this.warnOnUnsafeKeys([key], `intent \"${intent}\"`);\n          continue;\n        }\n\n        const previousOwner = mergedKeys.get(key);\n        if (previousOwner !== undefined && previousOwner !== intent) {\n          this.logger.warn(\n            this.logModule,\n            \"state.merge.conflict\",\n            `state key \"${key}\" written by both \"${previousOwner}\" and \"${intent}\" — last-in-decision-array wins (Q15)`,\n            { key, previousOwner, currentIntent: intent },\n          );\n        }\n        this.state[key] = value;\n        mergedKeys.set(key, intent);\n      }\n    }\n  }\n\n  /**\n   * Merge the iteration's accumulated `currentArtifacts` bag into\n   * supervisor state (Phase 5 / decisions §35). Runs once per\n   * iteration after branch slices land and before evaluate.\n   *\n   * Order of operations:\n   *\n   * 1. **Empty-bag fast path** — if no tool wrote anything, skip\n   *    validation and merge entirely; reset the bag for the next\n   *    iteration is also a no-op (already empty).\n   * 2. **Schema validation** — when `config.artifactsSchema` is set,\n   *    validate the bag against it. Failure aborts the iteration via\n   *    a thrown `SchemaValidationError`; the iteration loop's outer\n   *    catch surfaces it on `result.error`. Validation is opt-in\n   *    (no schema → no validation cost).\n   * 3. **Merge** — `config.finalizeArtifacts` when supplied, else\n   *    auto-spread `state = { ...state, ...artifacts }`. Replace\n   *    semantics under auto-spread; `finalizeArtifacts` carries\n   *    full responsibility for concat / dedupe / cross-iteration\n   *    accumulation when configured.\n   * 4. **Reset** — `currentArtifacts = {}`. The next iteration's\n   *    tool calls start with a fresh empty bag; long runs never\n   *    accumulate raw artifacts here.\n   */\n  private async mergeArtifactsIntoState(): Promise<void> {\n    const artifacts = this.currentArtifacts;\n    const keys = Object.keys(artifacts);\n\n    // Phase 8 / decisions §38 — capture the raw bag BEFORE validation\n    // or merge so the iteration snapshot surfaces what the tools\n    // actually wrote, regardless of what `finalizeArtifacts` did with\n    // it. Frozen — consumers should never mutate forensic data.\n    // Always run, even on empty bags — snapshot builder reads\n    // `capturedIterationArtifacts` regardless.\n    this.capturedIterationArtifacts = Object.freeze({ ...artifacts });\n\n    if (keys.length === 0) {\n      return;\n    }\n\n    const schema = this.config.artifactsSchema;\n\n    if (schema) {\n      const validation = await schema[\"~standard\"].validate(artifacts);\n\n      if (validation.issues) {\n        throw new SchemaValidationError(\n          `supervisor \"${this.config.name}\": iteration ${this.iteration} artifacts failed validation: ${validation.issues\n            .map((issue) => issue.message)\n            .join(\"; \")}`,\n          { issues: validation.issues, context: { iteration: this.iteration } },\n        );\n      }\n    }\n\n    const finalize = this.config.finalizeArtifacts as\n      | ((\n          state: Record<string, unknown>,\n          artifacts: Record<string, unknown>,\n        ) => Record<string, unknown>)\n      | undefined;\n\n    if (finalize) {\n      const merged = finalize(this.state, artifacts);\n\n      // Mutate in place so external references to `this.state`\n      // (snapshot copies, evaluate ctx) stay coherent. Drop keys\n      // the finalize callback removed; overwrite the rest.\n      //\n      // `Object.hasOwn` rather than `key in merged`: `in` walks the\n      // prototype chain, so a `merged` whose prototype was tampered\n      // upstream (tool-written artifact key named `__proto__`) would\n      // make removed keys look present and silently keep stale state.\n      for (const key of Object.keys(this.state)) {\n        if (!Object.hasOwn(merged, key)) {\n          delete this.state[key];\n        }\n      }\n\n      this.mergeIntoState(merged, \"finalizeArtifacts\");\n    } else {\n      this.mergeIntoState(artifacts, \"artifacts\");\n    }\n\n    this.currentArtifacts = {};\n  }\n\n  /**\n   * Collect each branch's `intent.next(ctx)` directive after state\n   * merge (Stage 4d / Q24). Iterates `decision.intents` order so\n   * union resolution is deterministic.\n   *\n   * Rules:\n   * - Errored branch → silent (treated as if no `next` defined).\n   * - Branch with no `next` → silent; abstains (does NOT drag the\n   *   iteration to the router).\n   * - Branch returns `END` → supreme; terminates immediately and\n   *   discards other branches' opinions.\n   * - Branch returns `string` or `string[]` → contributes to the\n   *   union of unique intent names. Validated against the\n   *   supervisor's registry; unknown keys throw `SupervisorFailedError`.\n   * - All branches silent → returns `undefined`; caller falls back\n   *   to router/route.\n   */\n  private collectIntentNext(\n    intentsOrder: string[],\n    branches: AgentBranchSnapshot[],\n  ): { kind: \"dispatch\"; intents: string[] } | { kind: \"end\" } | undefined {\n    const indexed = new Map<string, AgentBranchSnapshot>();\n    for (const branch of branches) {\n      indexed.set(branch.intent, branch);\n    }\n\n    const collected: string[] = [];\n    const seen = new Set<string>();\n    let anySilent = false;\n\n    for (const intent of intentsOrder) {\n      const branch = indexed.get(intent);\n      if (!branch || branch.error) {\n        anySilent = true;\n        continue;\n      }\n\n      const entry = this.entries.get(intent);\n      if (!entry?.next) {\n        anySilent = true;\n        continue;\n      }\n\n      // Build a per-branch DispatchContext for the resolver. Cycle\n      // stack is fresh-and-self-seeded so a `next` that calls\n      // `ctx.intents.X.execute()` reuses the per-iteration cycle\n      // detection mechanic.\n      const dispatchCtx = this.seedDispatchContext(\n        intent,\n        branch.input,\n        new Set<string>([intent]),\n        [],\n      );\n\n      let raw: string | string[] | typeof END | undefined;\n      try {\n        raw = entry.next(dispatchCtx) as string | string[] | typeof END | undefined;\n      } catch (thrown) {\n        const message = thrown instanceof Error ? thrown.message : String(thrown);\n        throw new SupervisorFailedError(`intent \"${intent}\" \\`next\\` resolver threw: ${message}`, {\n          cause: thrown,\n          context: { intent },\n        });\n      }\n\n      if (raw === undefined) {\n        anySilent = true;\n        continue;\n      }\n\n      if (raw === END) {\n        return { kind: \"end\" };\n      }\n\n      const proposed = Array.isArray(raw) ? raw : [raw];\n\n      for (const target of proposed) {\n        if (typeof target !== \"string\") {\n          throw new SupervisorFailedError(\n            `intent \"${intent}\" \\`next\\` returned a non-string value`,\n            { context: { intent } },\n          );\n        }\n\n        if (!this.entries.has(target)) {\n          throw new SupervisorFailedError(\n            `intent \"${intent}\" \\`next\\` returned unknown intent \"${target}\"`,\n            {\n              context: { intent, target, available: [...this.entries.keys()] },\n            },\n          );\n        }\n\n        if (!seen.has(target)) {\n          seen.add(target);\n          collected.push(target);\n        }\n      }\n    }\n\n    void anySilent;\n\n    if (collected.length === 0) {\n      // No branch directed the next iteration — fall back to router.\n      return undefined;\n    }\n\n    return { kind: \"dispatch\", intents: collected };\n  }\n\n  /**\n   * Finalize the supervisor result: validate accumulated state\n   * against the output schema and build the public `SupervisorResult`.\n   * Assemble-only — event emission and stream close happen in\n   * `run()` around this call.\n   */\n  private async finalize(): Promise<SupervisorResult<TOutput>> {\n    if (this.status === \"completed\" && !this.error) {\n      try {\n        this.data = await this.buildTypedData();\n      } catch (thrown) {\n        this.error = toAIError(thrown);\n        this.status = \"failed\";\n        this.terminatedBy = \"error\";\n      }\n    }\n\n    const endedAt = new Date();\n\n    // `max-iterations`, the orchestrator-only `awaiting-input`, and the\n    // planner-only `awaiting-approval` are members of the shared\n    // `ReportStatus` union but not of the narrower\n    // `SupervisorSnapshotStatus`. A supervisor never reaches\n    // `awaiting-input` / `awaiting-approval` at runtime; all collapse to\n    // the existing `failed` fallback here so the snapshot status stays\n    // representable.\n    const finalStatus: SupervisorSnapshotStatus =\n      this.status === \"max-iterations\" ||\n      this.status === \"awaiting-input\" ||\n      this.status === \"awaiting-approval\"\n        ? \"failed\"\n        : this.status;\n\n    await this.checkpoint(finalStatus);\n\n    const report: SupervisorReport = {\n      runId: this.runId,\n      rootRunId: this.runId,\n      name: this.config.name,\n      version: this.config.version,\n      // \"team\" when this engine was driven by ai.team (config.reportType),\n      // else \"supervisor\" — so team runs are distinguishable on the wire.\n      type: this.config.reportType ?? \"supervisor\",\n      supervisorName: this.config.name,\n      signature: this.signature,\n      status: this.status,\n      // Stamp the terminal error so the observe path surfaces it on the\n      // supervisor span (an observer never sees the result envelope).\n      // Absent on a completed run.\n      ...(this.error ? { error: this.error } : {}),\n      terminatedBy: this.terminatedBy,\n      iterations: this.snapshots.length,\n      startedAt: this.startedAtIso,\n      endedAt: endedAt.toISOString(),\n      duration: performance.now() - this.startPerf,\n      cancelledAt: this.cancelledAtIso,\n      usage: this.usage,\n      children: this.childReports,\n      snapshots: this.snapshots,\n      ack: this.ackSnapshot,\n      classifier: this.classifierSnapshot,\n    };\n\n    // Stamp lineage on the assembled tree exactly once per run.\n    // Walker rewrites inner self-roots from every nested agent /\n    // workflow / callback report the supervisor absorbed, propagates\n    // sessionId, and writes `reportSchemaVersion` on the root.\n    stampReportLineage(report, {\n      rootRunId: this.runId,\n      sessionId: this.options?.sessionId,\n    });\n\n    return {\n      type: this.config.reportType ?? \"supervisor\",\n      data: this.data,\n      report,\n      usage: this.usage,\n      error: this.error,\n    };\n  }\n\n  /**\n   * Build the typed `data` at finalize. Stage 4c — single mode:\n   *\n   * - When `config.output` is declared, validate the accumulated\n   *   `state` against it and return the validated value (Q8).\n   *   `result.data` always matches the schema, or `result.error`\n   *   carries the validation issues.\n   * - When `config.output` is omitted, return the raw state object.\n   *\n   * Validation failure surfaces as `SchemaValidationError` on\n   * `result.error`; the run is still considered semantically\n   * \"completed\" (intents ran, evaluate said done) but the typed\n   * data slot is empty.\n   */\n  private async buildTypedData(): Promise<TOutput | undefined> {\n    if (this.config.output) {\n      return validateOutput<TOutput>(this.config.output, this.state as unknown);\n    }\n\n    return this.state as TOutput;\n  }\n\n  /**\n   * Record a snapshot for an iteration whose first decision was\n   * `END` — no dispatch, no evaluate, just the decision record. Keeps\n   * the snapshot log uniform so a late-route-to-END still appears in\n   * the forensic history rather than vanishing.\n   */\n  private async recordTerminalDecisionSnapshot(\n    decision: DispatchDecision & { kind: \"end\" },\n    iterationStartedAt: Date,\n    iterationStart: number,\n    iterationUsage: Usage,\n  ): Promise<void> {\n    const snapshot: IterationSnapshot = Object.freeze({\n      iteration: this.iteration,\n      result: {},\n      decision: {\n        source: decision.source,\n        next: decision.raw,\n        reasoning: decision.reasoning,\n        durationMs: decision.durationMs,\n      },\n      state: { ...this.state },\n      artifacts: this.capturedIterationArtifacts,\n      startedAt: iterationStartedAt.toISOString(),\n      endedAt: new Date().toISOString(),\n      duration: performance.now() - iterationStart,\n      usage: iterationUsage,\n    });\n\n    this.snapshots.push(snapshot);\n\n    this.emit(\"supervisor.iteration.completed\", {\n      iteration: this.iteration,\n      snapshot,\n    });\n\n    await this.checkpoint(\"running\");\n  }\n\n  /**\n   * Write the current run state to the configured KV store (if any).\n   * Persistence failures surface as `supervisor.error` events and\n   * logged warnings but never abort the run — checkpoint best-effort\n   * by design, matching `workflow` semantics.\n   */\n  private async checkpoint(status: SupervisorSnapshotStatus): Promise<void> {\n    const outcome = await persistSupervisorSnapshot({\n      config: this.config as SupervisorConfig<unknown>,\n      signature: this.signature,\n      runId: this.runId,\n      input: this.input,\n      startedAt: this.startedAtIso,\n      iteration: this.snapshots.length - 1,\n      snapshots: this.snapshots,\n      status,\n    });\n\n    if (!outcome.ok) {\n      this.logger.warn(this.logModule, \"persist.failed\", \"snapshot persist failed\", {\n        runId: this.runId,\n      });\n    }\n  }\n\n  /**\n   * Between-iteration cancellation check. Called at the top of\n   * every iteration; signal abort here means the loop exits before\n   * any routing happens.\n   */\n  private throwIfCancelled(): void {\n    if (this.options?.signal?.aborted) {\n      throw createCancelledError(this.options.signal);\n    }\n  }\n\n  /**\n   * Aggregate one usage record (typically a branch or a router call)\n   * into both the run-wide total and the iteration-local total.\n   */\n  private aggregateUsage(iterationUsage: Usage, partial?: Usage): void {\n    if (!partial) {\n      return;\n    }\n\n    // Route both the run-wide and iteration-local totals through the shared\n    // all-channel merge so cost + cache/reasoning propagate (a bare\n    // input/output/total sum silently dropped them).\n    mergeUsage(this.usage, partial);\n    mergeUsage(iterationUsage, partial);\n  }\n\n  /**\n   * Fan an event out through the three-tier emitter AND mirror it\n   * into the stream controller when streaming. Event names map 1:1\n   * to stream event types so consumers iterating the stream see the\n   * exact same surface as `.on()` / `options.on` handlers.\n   */\n  private emit<K extends keyof SupervisorEventMap>(\n    event: K,\n    payload: WithoutIdentity<SupervisorEventMap[K]>,\n  ): void {\n    // Inject run identity once, here, so the three-tier emitter, the\n    // structured log line, and the stream all see it. `rootRunId ===\n    // runId` for a standalone run; nested propagation is a follow-up.\n    const identity: EventIdentity = {\n      runId: this.runId,\n      rootRunId: this.runId,\n    };\n\n    const fullPayload = { ...payload, ...identity } as SupervisorEventMap[K];\n\n    this.emitter.emit(event, fullPayload, this.options?.on);\n    this.logEvent(event, fullPayload);\n\n    if (this.streamController) {\n      this.streamController.push({\n        type: event,\n        ...(fullPayload as object),\n      } as SupervisorStreamEvent);\n    }\n  }\n\n  private logEvent<K extends keyof import(\"../contracts/events/event-map.type\").SupervisorEventMap>(\n    event: K,\n    payload: import(\"../contracts/events/event-map.type\").SupervisorEventMap[K],\n  ): void {\n    const action = event.replace(/^supervisor\\./, \"\");\n\n    switch (event) {\n      case \"supervisor.starting\":\n        this.logger.info(this.logModule, action, \"supervisor starting\", {\n          runId: this.runId,\n        });\n        return;\n\n      case \"supervisor.iteration.starting\":\n        this.logger.debug(this.logModule, action, \"iteration starting\", {\n          iteration: (payload as { iteration: number }).iteration,\n        });\n        return;\n\n      case \"supervisor.router.decided\":\n        this.logger.debug(this.logModule, action, \"router decided\", {\n          iteration: (payload as { iteration: number }).iteration,\n          next: (payload as { next: unknown }).next,\n        });\n        return;\n\n      case \"supervisor.agent.completed\": {\n        const typed = payload as {\n          intent: string;\n          duration: number;\n          usage: Usage;\n        };\n        this.logger.success(this.logModule, action, `branch \"${typed.intent}\" done`, {\n          duration: typed.duration,\n          usage: typed.usage,\n        });\n        return;\n      }\n\n      case \"supervisor.agent.failed\": {\n        const typed = payload as { intent: string; error: AIError };\n        this.logger.warn(this.logModule, action, `branch \"${typed.intent}\" failed`, {\n          code: typed.error.code,\n          message: typed.error.message,\n        });\n        return;\n      }\n\n      case \"supervisor.error\": {\n        const { error } = payload as { error: AIError };\n        this.logger.error(this.logModule, action, error.message, {\n          code: error.code,\n        });\n        return;\n      }\n\n      case \"supervisor.cancelled\": {\n        const typed = payload as { cancelledAt: string; reason?: string };\n        this.logger.warn(this.logModule, action, \"supervisor cancelled\", {\n          cancelledAt: typed.cancelledAt,\n          reason: typed.reason,\n        });\n        return;\n      }\n\n      case \"supervisor.iteration.completed\":\n        this.logger.debug(this.logModule, action, \"iteration completed\", {\n          iteration: (payload as { iteration: number }).iteration,\n        });\n        return;\n\n      default:\n        // Streaming / per-branch starting events are high-volume — no\n        // dedicated log line.\n        return;\n    }\n  }\n}\n\nfunction indexByIntent(branches: AgentBranchSnapshot[]): Record<string, AgentBranchSnapshot> {\n  const indexed: Record<string, AgentBranchSnapshot> = {};\n\n  for (const branch of branches) {\n    indexed[branch.intent] = branch;\n  }\n\n  return indexed;\n}\n\nfunction indexBranchesForEvaluate(\n  branches: AgentBranchSnapshot[],\n): Record<string, EvaluateBranchResult> {\n  const indexed: Record<string, EvaluateBranchResult> = {};\n\n  for (const branch of branches) {\n    indexed[branch.intent] = {\n      output: branch.output,\n      input: branch.input,\n      usage: branch.usage,\n      durationMs: branch.duration,\n      error: branch.error,\n    };\n  }\n\n  return indexed;\n}\n\nfunction normalizeReassign(reassignTo: string | string[] | undefined): string[] {\n  if (!reassignTo) {\n    return [];\n  }\n\n  if (Array.isArray(reassignTo)) {\n    return reassignTo;\n  }\n\n  return [reassignTo];\n}\n\nfunction toAIError(thrown: unknown): AIError {\n  if (thrown instanceof AIError) {\n    return thrown;\n  }\n\n  const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n  return new SupervisorFailedError(message, { cause: thrown });\n}\n\n/**\n * Sum a list of child `BaseReport.usage` values. Callbacks\n * themselves contribute zero own-cost (they're dev code, not LLM\n * calls); their report's `usage` equals the sum of whatever\n * agents / workflows / nested callbacks they dispatched via\n * `ctx.intents.X.execute()`. Mirrors `compositeAsTool` semantics.\n */\nfunction aggregateChildUsage(children: BaseReport[]): Usage {\n  const total: Usage = { input: 0, output: 0, total: 0 };\n  for (const child of children) {\n    mergeUsage(total, child.usage);\n  }\n  return total;\n}\n\n/**\n * Best-effort stringification for the snapshot's `input` field when\n * a callback intent's resolved input is a non-string value. Falls\n * back to a typed placeholder if `JSON.stringify` throws (circular\n * refs, BigInt, etc.) so a snapshot write never fails on its own.\n */\nfunction safeStringify(value: unknown): string {\n  if (value === undefined) {\n    return \"undefined\";\n  }\n\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return `[unserializable: ${typeof value}]`;\n  }\n}\n\nasync function validateOutput<TOutput>(\n  schema: StandardSchemaV1<TOutput>,\n  value: unknown,\n): Promise<TOutput> {\n  const validation = await schema[\"~standard\"].validate(value);\n\n  if (validation.issues) {\n    throw new SchemaValidationError(validation.issues.map((issue) => issue.message).join(\"; \"), {\n      issues: validation.issues,\n    });\n  }\n\n  return validation.value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwEA,MAAM,yBAAyB;AAC/B,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCxB,IAAa,sBAAb,MAA0C;CAsIxC,AAAO,YAAY,QAA4C;gBA1H7B;yCAiBkB,IAAI,IAAI;mBAEV,CAAC;sBACL,CAAC;eACf;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;mBAGnC,YAAY,IAAI;mBAEzB;sBAY2B;gBACF;6BAIL,CAAC;eAOA,CAAC;0BAWU,CAAC;oCAYmB,OAAO,OAAO,CAAC,CAAC;0BAiB7D;EAiCzB,KAAK,SAAS,OAAO;EACrB,KAAK,UAAU,OAAO;EACtB,KAAK,YAAY,OAAO;EACxB,KAAK,UAAU,OAAO;EACtB,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO;EACpB,KAAK,UAAU,OAAO;EACtB,KAAK,mBAAmB,OAAO;EAC/B,KAAK,aAAa,OAAO;EAEzB,KAAK,gBAAgB,OAAO,OAAO,iBAAiB;EACpD,KAAK,YAAY,GAAG,gBAAgB,GAAG,OAAO,OAAO;EACrD,KAAK,aAAa,OAAO,OAAO,cAAc,CAAC;EAM/C,KAAK,UAAU,OAAO,OAAO,EAAE,GAAI,OAAO,SAAS,WAAW,CAAC,EAAG,CAAC;EAOnE,KAAK,UAAU,OAAO,OAAO,CAAC,GAAI,OAAO,SAAS,WAAW,OAAO,OAAO,WAAW,CAAC,CAAE,CAAC;EAM1F,IAAI,OAAO,OAAO,OAAO,SAAS,UAChC,KAAK,OAAO,OAAO,OAAO;OACrB,IAAI,OAAO,OAAO,MACvB,KAAK,OAAO,OAAO,OAAO,KAAK,QAAQ;OAEvC,KAAK,OAAO;EAGd,IAAI,OAAO,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