UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,429 lines • 119 kB
/**
 * The TERMINAL record of one run: `TaskResult`, the plane word it still projects (`TaskStatus`), the
 * memory-scope summary it carries (`EffectiveMemoryScopes`) and the remote-workspace failure note
 * (`RemoteEnvFailureNote`). The cause itself lives one module over in `terminal-cause.ts`, which owns
 * the closed set and its replay table. Layer 0 vocabulary; `types.ts` re-exports every name below, so
 * no consumer's import changes.
 */
import type { DeniedBy, SettlementKind, SettlementParty } from "./gate-outcome.js";
import type { FileHistoryLeftAsIsFile, RewindFilesResult } from "./file-history-store.js";
import type { TerminalCause } from "./terminal-cause.js";
import type { NestedUsage } from "./tool-spec.js";
/**
 * `"suspended"` (design/45) is a **non-terminal** outcome: the task hit a durable tool-policy gate
 * (`ask` with a `CheckpointStore` wired) and persisted a checkpoint instead of finishing — resume it
 * with `runner.resume(checkpointToken, outcome)`. A nested orchestrator's boundary turns the pause into a
 * `failed` terminal that carries it (`mapNestedSuspend` in `src/agents/suspend-guard.ts` states which
 * orchestrators do, and the entry that continues the pause).
 *
 * `"needs_review"` (design/76 §2.5, dry-run / shadow; design/80 D-B, plan-gate) is also a **non-terminal,
 * resumable** outcome, but a DISTINCT one: it is the REVIEW-PAUSE terminal a human/judge must clear. Two
 * disjoint gate kinds share it (carrying a `reviewRef`, errorCode `"review.pending"`): a `{kind:"needs_review"}`
 * checkpoint — a profile's dry-run interception produced a predicted state-diff to REVIEW before it is applied,
 * resumed with a `dry_run_review` outcome — and a `{kind:"plan_review"}` checkpoint (design/80 D-B) — a
 * profile's plan-gate produced a proposed PLAN a human must approve/edit/reject BEFORE any step runs, resumed
 * with a `plan_review` outcome. Both are DISJOINT from `"suspended"`: that is a PRE-ACTION approval of a TOOL
 * CALL (resumed with `policy_ask`); these are human REVIEWS (the distinct gate.kind picks the resume outcome).
 * A `needs_review` pause meets the same nested boundary as a `suspended` one (`mapNestedSuspend`: code
 * `unexpected.needs_review`).
 */
/**
 * Terminal vs waiting. Three words are TERMINAL — the leg is over and nobody is expected to act: `completed`,
 * `failed`, and `blocked` (the AGENT's own report, through `report_blocked`, that it cannot finish and why —
 * a self-report, not a pause; it waits for nobody). Two words are WAITING — a person's decision resumes the
 * same leg through `runner.resume(token, …)`: `suspended` (a durable pre-action approval of a tool call) and
 * `needs_review` (a durable review pause). The task-registry face spells the two waiting words as `parked`.
 * A consumer that files `blocked` beside `suspended` is waiting on a decision that never comes.
 */
export type TaskStatus = "completed" | "blocked" | "failed" | "suspended" | "needs_review";
/**
 * One remote-workspace lifecycle failure, reported as data on {@link TaskResult.remoteEnvFailures}.
 * See that field for why the eleven-code taxonomy needed a structured channel to reach a caller at all.
 */
/**
 * ONE `humanReview` ledger row — what `stats.humanReview.gates[]` carries, what the runner's live
 * accumulator holds, and what a checkpoint persists. It lived as six structurally-identical inline
 * copies, the persisted one NARROWER than the rest, so "does a row carry the call it gated?" had six
 * answers and the persisted one said no while the bytes it stored said yes. One declaration now.
 */
export interface HumanReviewGateRow {
    /** `kind` / `decision` / `toolName` / `toolArg` are documented once, on `stats.humanReview.gates`. */
    kind: string;
    waitMs: number;
    decision?: string;
    toolName?: string;
    toolArg?: string;
    /**
     * The id of the tool call this row gated — the row's IDENTITY, not a display field. Minted with the
     * row at each of the four mint sites, never re-derived downstream: a run pushes rows from several
     * mints while only one passes through the host's `onAsk`, so the two ledgers' counts are legitimately
     * unequal and there was no key to reconcile on. Absent means one thing — the mint had no call id to
     * give (a probe row; a durable gate whose checkpoint carries a non-`tool_approval` pending action,
     * since a `resource_limit` / `needs_review` / `plan_review` pause gates no call; or an older engine).
     * Never a placeholder.
     */
    toolCallId?: string;
    /**
     * Who ended the wait this row books, as the engine's settlement record for the deciding answer names it: that record's
     * `who.party`, copied when the row is minted (`person` / `policy` / `host` / `engine`). It is the channel's report and the
     * engine does not authenticate it: `person` is what a channel that reported a person's answer produced, `policy` a machine's
     * answer, `host` the host's elapsed window or sweep. ABSENT says nothing about who answered: a blanket `onAsk: "allow"` and a
     * decide that carries no record (a `needs_review` resume) mint none, and a row stored before this member has none. After an
     * `env_failed` reopen the record is the retry's. `kind` is the gate's discriminant, never the answerer.
     */
    party?: Exclude<SettlementParty, "none">;
    /**
     * WHICH seat of that party answered, as the same record names it: its `who.approver` (the attribution the approval channel
     * reported — a `declareClassAnswers` table's declared word, a policy approver's or a person's `approver`, a durable decide's
     * `hostDecision.approver`), copied with {@link party} by the same mint. The channel's report, screened and not authenticated.
     * A row books one answered wait: for a call the leg's stream closes with a `tool_end` whose gate pass settled one ask, the row's
     * `party` and `approver` are that frame's `gate.settlement.who`. A call asked again after an approver's edit books a row per
     * answered wait, each naming its own answerer, while the frame names the call's last settlement only.
     * ABSENT when the record holds none (a person's bare `true`, the host's own elapsed window, whose record has no seat for one)
     * or the row has no {@link party}; a row stored before this member has none and reads back without it.
     */
    approver?: string;
}
export interface RemoteEnvFailureNote {
    /** Which lifecycle call failed. `"syncWorkspace"` is a workspace sync the run's result was still open for (a turn's end,
     *  a park); its `code` is the adapter's, or the engine's reading of a sync that did not answer: `unknown` (a throw, an
     *  answer outside the seam's shape), `timeout` (the engine's bound passed), `aborted` (the run was cut), `command_in_flight`
     *  (not made: an earlier sync of the workspace did not return after its abort; `attempts: 0`, as for any sync not made). */
    op: "suspendVM" | "resumeVM" | "postResumeInit" | "syncWorkspace";
    /** The adapter's verbatim code — the whole point of this note (`RemoteExecutionError.code`: a closed-set word, or a
     *  deployment's own `env.` code). */
    code: import("./remote-env.js").RemoteExecutionError["code"];
    /** `code` is in the retryable family (`RETRYABLE_REMOTE_ERROR_CODES`) — a re-attempt can plausibly work. */
    retryable: boolean;
    /** How many times the engine called `op` before giving up (1 = it did not retry). */
    attempts: number;
    /** The adapter's message. Human-facing; branch on `code`, not on this. */
    message: string;
}
/** Result returned when a task finishes or gets stuck. Designed to be machine-readable for an external AI. */
/**
 * design/178 v2 §2.3 (件①) — the value of {@link TaskResult.effectiveMemoryScopes}: the memory
 * visibility face a leg ACTUALLY ran under, as a DISCRIMINATED three-state union (deliberately no
 * `"partial"` state — the engine session is built only after every plane materialized, so a
 * half-mounted scene is a fail-open `memoryless` with residue, never a served half-face):
 *
 *  - `"mounted"` — the memory engine session mounted. `scopes` is the EFFECTIVE VISIBILITY set in
 *    the effective serving order, both exactly as the engine mounted them: per plane, the
 *    admission-projected read layering PLUS a distinct write-only scope where one exists (the
 *    engine registers the write scope's dir and its entries ride the injected index — a write-only
 *    scope IS visible; the common writeScope∈scopes form dedups to the plain layering), project
 *    plane first on a dual root. Each row carries its admission ORIGIN (`"deployment"` = the
 *    operator's own declared set; `"request"` = the caller's spec — the two trust planes of the
 *    org admission door). `writeScope` is the effective write face as granted (an org writeScope
 *    not explicitly granted reads `null` here, exactly as it ran). `contract` names the
 *    scope-identity contract in force (`"v2"` typed keys / `"legacy"` opaque strings).
 *    SCOPE OF THE CLAIM (stated precisely): the rows are the MEMORY-ENGINE scope set this leg
 *    mounted — the dirs the engine registered and indexed. They deliberately do NOT cover the
 *    separate memory-adjacent faces (the shared-memory store pair, the project-context memory
 *    layer — each its own surface with its own disclosure), and two REGISTERED engine-plane
 *    channels can carry another scope's bytes without a row here: a root-owning scope's non-empty
 *    on-disk index is served verbatim to a later mount of that root ("live file wins"),
 *    and control-plane announcements carry no producing scope and drain plane-wide. Both are
 *    engine mount semantics under their own tickets, disclosed here so this face is never read as
 *    a complete cross-face visibility proof.
 *  - `"memoryless"` — memory was configured but did not mount. `reason: "mount-failed"` = the
 *    fail-open mount arm caught a fault anywhere in the mount phase (directory resolution through
 *    materialize — named for the whole captured span, not one step); `reason: "no-backend"` = the
 *    spec enables memory but no `RunnerDeps.memoryBackend` is configured. `materializedResidue`
 *    (mount-failed only) lists plane scopes whose PHYSICAL materialize had already completed when
 *    the fault hit — a LOWER bound (a plane that threw mid-materialize is not listed; on-disk
 *    residue is ≥ this list), and explicitly NOT a visibility face: an auditor must never read
 *    residue as mounted scopes, which is why it is a separate seat from the always-empty `scopes`.
 *  - `"none"` — memory was not in play at all: `"no-spec"` = the task carries no usable memory
 *    spec; `"disabled"` = a spec is present with `enabled: false`.
 *
 * Deliberate-refusal configurations (`config.memory_*` codes) fail the whole prepare and produce
 * NO observation — this union never dresses a refusal as a state. Honesty note (design r7): the
 * `?: never` members forbid non-`undefined` values at the type level; the repo does not compile
 * with `exactOptionalPropertyTypes`, so explicit-`undefined` presence is a wire-validator concern,
 * not a type-level one.
 */
export type EffectiveMemoryScopes = {
    state: "mounted";
    reason?: never;
    contract: "v2" | "legacy";
    /** `shadowed` = how many of this scope's entries the session's write home retires from the
     *  DEFAULT read face by name (they stay reachable by id and through `includeShadowed`).
     *  PRESENT-IFF non-zero, and never on the write home's own row — absence is "none", which is
     *  why zero is not spelled. A mount-time snapshot: the tool faces re-derive it per call, so a
     *  later challenge or tombstone can make the live answer smaller than this number. */
    scopes: Array<{
        scope: string;
        origin: "deployment" | "request";
        shadowed?: number;
    }>;
    writeScope: string | null;
    /** The project identity the assembly point DECLARED for this task, echoed verbatim
     *  ({@link import("./memory.js").MemoryProjectKey}). PRESENT-IFF the spec carried one:
     *  absence means the deployment said nothing, which is not the same as `{ absent }`, which
     *  means it looked and found none. */
    projectKey?: import("./memory.js").MemoryProjectKey;
    materializedResidue?: never;
} | {
    state: "memoryless";
    reason: "mount-failed";
    contract?: "v2" | "legacy";
    scopes: [];
    writeScope: null;
    materializedResidue?: string[];
} | {
    state: "memoryless";
    reason: "no-backend";
    contract?: "v2" | "legacy";
    scopes: [];
    writeScope: null;
} | {
    state: "none";
    reason: "no-spec" | "disabled";
    contract?: never;
    scopes: [];
    writeScope: null;
    materializedResidue?: never;
};
/** One ask a run could not have answered and refused ({@link TaskResult.refusedAsks}): the call, why nobody answered it (the closed
 *  set the `delegation.ask_unresolvable` notice carries), and the way out the refusal named — the headless remedy's sentence, a
 *  binding's own, or the way out of a leg whose parks cannot be resumed; absent when the refusal named none. */
export interface RefusedAsk {
    readonly toolName: string;
    readonly toolCallId: string;
    readonly cause: import("./ask-unresolvable-notice.js").AskUnresolvableCause;
    /** The caller-side change (the host's words: the `delegation.ask_unresolvable` notice says the same). */
    readonly remedy?: string;
    /** Present where the engine can say what issuing the call again after this refusal does, and says it: the way out the leg's
     *  model read in place of {@link remedy}, and the one a parent's model reads in its report of the leg. Two sentences: nobody on the
     *  leg can approve it (its seat is no person's callback and no policy, and no park can take it — the arm naming no person, ending on
     *  the one no-person sentence; a policy's seat on a leg with no park route reads that sentence too, as before, though the policy may
     *  allow the call issued again: not a case the engine can say), or it is asked again (a leg that cannot hold a park whose own seat re-asks — a host driving the gate, a
     *  person's callback, a declared policy). Absent ⇒ the model read {@link remedy}. An ask an ancestor floated back carries it only
     *  where this leg has no park route at all (the no-person sentence) — which of the ancestor's seats a re-issue reaches is otherwise
     *  not known where the refusal is minted, so the leg's park state never makes it say more. Absent too on a binding refusal (its sentence
     *  stands alone), and where nobody could answer but the refusal names no way out (an inherited or forced mandate on a leg with no
     *  park lane whose host did not declare it not resumable — {@link remedy} is absent there as well). */
    readonly modelRemedy?: string;
    /** #5244 — a durable approval park was attempted for the call and could not be minted: its sentence, the one the
     *  `delegation.ask_unresolvable` notice carries as `detail.parkFailed` (one reading, {@link import("./ask-unresolvable-notice.js").refusedAskOf}),
     *  and {@link remedy} then names the park first. Absent where no park was attempted, or the refusal names no way out. */
    readonly parkFailed?: string;
    /** Beside {@link parkFailed}: the missing piece of durable-suspend infrastructure the failure is, when it is one (the notice's
     *  `detail.parkFailedReason`, a word of `SUSPEND_LANE_REASONS`). */
    readonly parkFailedReason?: import("./suspend-lane-reasons.js").SuspendLaneReason;
}
/**
 * A leg's verdict that the gate refused ({@link TaskResult.verdictRefused}): at least one call of the leg's verdict tool (its
 * submission `StructuredOutput`, a goal iteration's `DeclareDone`, a delegated leg's `ReportBlocked`, an observer's `ObserverReport` — the catalog's `verdict` rows for
 * the leg's kinds) was refused at the gate on this run, and no call of it was delivered on this run (let go by the gate and its body
 * ran: every verdict body records its outcome when it runs — a delivery before the refusal counts the same as one after it, and so
 * does one that lands in a turn being cut). A deny on an end minted while its turn was being cut (the run's own stop — a host cancel,
 * the walltime, a stop the run made — or a cut of the turn alone — a person's halt, an immediate steer, an extension's
 * `$.turn.abort`) is no refusal: the terminal or the turn's notice says why. A paused result carries none (the run is not over). Read off the refused call's own gate record — the object its `tool_end.gate` carries — never
 * composed again: `deniedBy` is that record's `disposition.deniedBy`, `settlement` its settlement's `kind` (present exactly when that
 * record carries one: an ask settled, or a person's yes a later layer vetoed).
 */
export interface VerdictRefusal {
    /** The verdict tool's wire name (the roster's). */
    readonly toolName: string;
    /** The LAST refused call of it. */
    readonly toolCallId: string;
    readonly deniedBy: DeniedBy;
    readonly settlement?: SettlementKind;
    /** How many calls of the leg's verdict tool the gate refused on this run (≥ 1). */
    readonly attempts: number;
}
/**
 * One call the gate refused on a run ({@link TaskResult.refusedToolCalls}): the call, and the refusal's own words read off its gate
 * record (`tool_end.gate`) — `deniedBy` is the record's `disposition.deniedBy`, `settlement` its settlement's `kind` (present exactly
 * when the record carries one) — never composed again. `countedBy`: the leg's own record that already counts this call — an ask
 * nobody could answer (`refusedAsks`, the call is one of its entries) or a call of the leg's verdict tools when the verdict never
 * landed (`verdictRefused`, its `attempts` count it); absent for every other refused call.
 */
export interface RefusedToolCall {
    readonly toolName: string;
    readonly toolCallId: string;
    readonly deniedBy: DeniedBy;
    readonly settlement?: SettlementKind;
    readonly countedBy?: "refusedAsks" | "verdictRefused";
}
/**
 * Every call the gate refused on a run, bounded ({@link TaskResult.refusedToolCalls}): the first refused calls in order, and how many
 * more there were, split the way the listed ones are — counted by the leg's own records (`countedBy` on a listed call), a person's
 * refusal (`human_refused`), or anything else. `listed.length + byPerson + other + counted` is every refused call.
 */
export interface RefusedToolCalls {
    /** The first {@link import("./member-outcome.js").REFUSALS_LISTED} refused calls, in refusal order. */
    readonly listed: readonly RefusedToolCall[];
    /** The refused calls past the listed ones — absent when every one is listed. */
    readonly unlisted?: {
        readonly byPerson: number;
        readonly other: number;
        readonly counted: number;
    };
}
export interface TaskResult {
    taskId: string;
    /**
     * The ENGINE-minted identity of THIS run (uuidv7), minted once at the top of prepare and
     * never rewritten. The third id of the trio, and the only one the engine owns:
     *  - {@link taskId} — the leg's task identity: a background sub-agent's registry task id, else the
     *    HOST's task identity, else (when the host named none) the session id — so it answers the SAME
     *    value for every run of one session (or of one background row);
     *  - {@link sessionId} — the conversation, shared by every run that continues it;
     *  - `runId` — this call. Two runs of one session ALWAYS differ here; a host-supplied `taskId` does
     *    not change it (the host's handle and the engine's run are different questions).
     *
     * Use it to join a run's per-run disclosures (`task.user_steer_undrained` /
     * `task.user_followup_undrained` / `route.fallback_to_primary` / `steering.parked_input_blocked` /
     * `task.turn_interrupted` all carry `detail.runId`) and its `task.start`/`task.end` trace pair to
     * the result they belong to. Do NOT use it as an aggregation key across runs — that is what
     * `taskId`/`taskSignature` are for.
     *
     * **In-presence condition**: present on every terminal of a run that ENTERED prepare — a prepare-time
     * refusal included. The id is minted and published at prepare's FIRST statement precisely so this
     * holds: prepare itself emits run-scoped disclosures (`route.fallback_to_primary`), and a disclosure
     * naming a run that no terminal ever names would be unjoinable on exactly the failure path it is
     * about. It is absent only where no run was entered — a throw above the prepare call — and on
     * stub/synthesized results a host assembles itself. Optional for that reason, never fabricated, and
     * never the `"unknown"` sentinel `taskId`/`sessionId` fall back to on that path.
     */
    runId?: string;
    /**
     * Use this to continue the same conversation on the next call. On a parked result — a `paused` terminal, or a `failed` one
     * carrying `nestedPause` — it is the session of the leg that parked, which is the parked row's own `Checkpoint.sessionId`.
     * A composition entry's legs (a cascade's rungs, a verification gate's verifier) do not run in the caller's session, so a
     * host links such a row to its run by the row's `CheckpointState.compositionLeg.hostSessionId`, never by assuming the row
     * sits in the session it submitted.
     *
     * A delegated leg whose session row's owner was never verified names none: `""` — one refused over the row (`terminal.code`
     * `delegation.owner_unbound` / `delegation.owner_mismatch`), and one that ended (stopped, cancelled, past a host's deadline) before its
     * owner read answered. The row it was handed, or its store created, is not offered for continuing (it may be another principal's);
     * a refusal's `message` names it for the operator.
     */
    sessionId: string;
    /**
     * The leg's placement fixed point: the one value its prepare resolved for the tree's placement root (the caller's explicit
     * `RunInternals.placementRoot`, else the delegation root, else the leg's own session — on a resume, the parked row's recorded
     * root), the same value its env factory was minted with and its parks record. A composition entry places every later leg at
     * its first leg's `placementRoot`. **In-presence condition**: present on every terminal of a run whose prepare resolved it;
     * absent on a result a run did not assemble (a host's own stub, a composition's synthetic terminal).
     */
    placementRoot?: string;
    /**
     * WHY the run ended — the ONE tagged cause ({@link TerminalCause}), and the ONLY terminal record on this
     * result: there is no `status` word and no `errorCode`/`errorMessage`/`blockedReason`/`checkpointToken`/
     * `checkpointId`/`checkpointGate`/`workspaceRestoreMode` beside it (a second spelling of the same fact
     * would be the one a reader reaches for, and the two would have to be kept equal forever). Branch on
     * `terminal.kind`: `"paused"` carries the token and the gate together (a suspended run with no token
     * cannot be constructed), `"failed"` carries the code and the message together, `"blocked"` its reason.
     * A face that still speaks the five-word {@link TaskStatus} derives it with
     * {@link import("./runner/terminal-projection.js").terminalProjection} — the one cause→word derivation.
     */
    terminal: TerminalCause;
    /** design/99 MF-25: the EFFECTIVE model id this task ran on — the ENGINE-SELECTED, RESOLVED `Model.id`, not
     *  the requested `TaskSpec.model` ref (a role / name / `@mention`). A mid-run degradation is observed
     *  separately (the degraded-model fields); what the PROVIDER called it rides {@link responseModel}. */
    model?: string;
    /** The PROVIDER'S OWN name for the model that answered this run's FINAL turn, when it DIFFERS from the
     *  id the request was sent with — the result-face twin of `turn_end.responseModel`. {@link model} above
     *  stays the ENGINE-SELECTED id a resume re-seeds and a catalog resolves; a UI echoing "served by X"
     *  prints this one when it is here, and when it is not says no name was reported — absence is not agreement.
     *  **In-presence condition**: the final assistant message carried one. ABSENT ⇒ the provider named the
     *  requested id or named nothing (one reading, not two), it named one the engine dropped (outside the echo
     *  shape, or holding a value the request was declared with; counted as the trace frame `brain.echo_dropped`,
     *  field `responseModel`), there was no final assistant message, or the final turn AGREED while an earlier one
     *  did not — the per-turn frames are the complete record, this is the terminal one. Never present on the
     *  engine's synthetic messages, which carry no provider report; a mismatch is announced either way as
     *  `route.response_model_mismatch`. */
    responseModel?: string;
    /**
     * The leg's effective REASONING resolution: the result-face twin of {@link model} for the thinking
     * knob. How the requested tier resolved on the leg's request (`requested`/`effective`/`graded`/`clamped`/`format`/
     * `endpoint`, plus `dropped:true` exactly when `effective` is `"provider_default"`) — `effective` is what the request's
     * thinking keys say: a tier, `"on"` (thinking on, no tier named), or `"provider_default"` (no thinking key at all); field
     * semantics on {@link import("../brain/reasoning.js").ResolvedReasoning}. It is the SAME value the `reasoning.resolved`
     * trace frame carries — the two faces cannot tell different stories; this seat serves consumers without a tracer (the
     * trace frame is the deployment-observability face, this is the caller face).
     *
     * **In-presence condition** — mirrors the trace frame exactly: present on every terminal of a leg that ran
     * with a REQUESTED thinking tier, `off` included (the `spec > role > model.defaultThinking` chain); absent when the leg had
     * no tier, and on prepare failures (the resolution is minted after prepare). On a resumed task each leg re-resolves against
     * the leg's own serving model.
     *
     * **First-request correction** — the leg-entry value is the wire applier's answer before any request exists, so it cannot
     * see what only the brain holds (a budget knob from the brain's construction config, the request's own output cap). The
     * leg's first request whose terminal message reaches the leg — its own model object's request, a success or a failure
     * the stream engine ended — carries its own answer on that message, and the seat takes it once (the trace twin is
     * re-emitted when it differs). Requests a mod, a tool or an internal lane makes never reach the leg's messages, so they
     * cannot restate the leg's posture. A terminal minted outside the engine (a guardrail timeout, a first-token deadline, a
     * cut turn, a deployment Brain's own message) carries no answer: the seat keeps the entry value and waits for the next.
     *
     * **Degradation law** — same as {@link model}, whose resolution this is: the seat describes the leg's
     * PRIMARY serving model at leg entry. A mid-run degradation (reactive fallback / near-budget switch)
     * changes the serving model WITHOUT re-minting this seat or its trace twin — read {@link degraded} to see
     * the switch; the fallback's own reasoning capability is deliberately NOT re-reported here (re-resolving
     * one face would desync it from the task-start `reasoning.resolved` frame). A consumer needing the
     * fallback's reasoning posture resolves `degraded.to` itself (`resolveReasoning` is exported).
     */
    effectiveReasoning?: import("../brain/reasoning.js").ResolvedReasoning;
    /**
     * The leg's fast mode at its end (`fastModeReadingOf`, `brain/fast-mode.ts`) — the reference result's `fast_mode_state` /
     * `fast_mode_disabled_reason`, plus when a cooldown ends: `{ state: "off" | "cooldown" | "on", reason?, cooldown?: { until,
     * reason } }`, read for the leg's model then (a degrade's model after one). Present when the leg asked for fast mode (its
     * spec or `TaskStream.setFastMode`) or its session has sent fast speed before; absent otherwise — a host reads a model's
     * reading without a session through `fastModeReadingOf`. Which responses were actually served fast is `Usage.speed` per
     * message.
     */
    fastMode?: import("../brain/fast-mode.js").FastModeReading;
    /** Final assistant text — on a top-level leg whose `classic.MessageDisplay` handlers changed what the stream showed of
     *  the answer's messages, the text the stream showed of them ({@link resultDisplayedBy} names who changed it), so a consumer
     *  replacing the streamed rows with `result` does not show what the display took out. A window no handler's answer stood for
     *  (a handler failed, its deadline passed before any handler answered) shows the model's text, so `result` holds it too.
     *  When the caller's stop (`interrupt()`, `halt()`, the caller's signal) ended the display of one of the answer's messages
     *  before its end, `result` is what had been shown of them by then — the same reading: what the stream showed — and
     *  {@link resultDisplayedInPart} says that part of what the model said was never shown (read the rest from the session). */
    result: string;
    /**
     * Where {@link result} was read from: the session-tree entry ids of the committed assistant messages the engine selected
     * as the answer's source, in conversation order — the ids `message_committed.entryId` carries on the stream. One id for
     * an ordinary answer; every member of the continuation chain when a cut answer was continued (`result` is their texts,
     * joined). `result` is the answer's one authority: a committed message can differ from what streamed (engine notes
     * placed at finalize, a degenerate cut trimmed), so a consumer that rendered the stream replaces the named messages'
     * text rows with `result` instead of comparing; one that cannot bind an id (it lost that `message_committed`) reads the
     * named entries from the session rather than guessing which rows they were.
     *
     * EMPTY when `result` was read from no committed message (the run produced no assistant message, or only one that was
     * never appended — an empty failure). A named message may contribute no text (a tool-calling message a park or a stop
     * ended on; a thinking-only head of a continuation chain), so `result` may be empty beside a non-empty list. ABSENT when
     * the provenance is unknown: a record an older engine wrote, a result rebuilt from a checkpoint row alone, or an answer
     * a leg read from a message committed before it began (whose append that leg never saw).
     *
     * Not yet byte-equal: `result` alone drops inline `<think>…</think>` blocks and is trimmed; the named messages keep both.
     */
    resultEntryIds?: readonly string[];
    /**
     * Whether this call's own input was taken into the conversation: the leg's prompt message — the objective on a fresh
     * leg, the continuation on a resumed one — committed to its session. Read off that commit, the same append that
     * publishes the row's `message_committed { role: "user" }` frame, whose `entryId` this one is.
     *
     *  - `{ committed: true, sessionId, entryId }` — the message is in session `sessionId` under entry `entryId`. On a
     *    single leg `sessionId` is this result's {@link sessionId}; on a composition it names the leg that took the input in
     *    (a cascade's rungs each run in a session of their own).
     *  - `{ committed: false }` — this call took nothing in: it ended before its prompt message was committed (refused at
     *    the entrance, screened out, cancelled, a prepare failure). Why is the {@link terminal}'s to say.
     *  - ABSENT — not known: a record an older engine wrote, a result rebuilt from a row alone, a result a host assembled,
     *    or a commit whose entry id the session store did not hand back as a non-empty string.
     *
     * A composition (verification gate, cascade, repair loop) folds its own dispatched legs in dispatch order: the first
     * leg that took the input in answers; when none did, it is `{ committed: false }` if every leg said so and absent if
     * any leg's account was unknown. `stats.turns` is not this fact: a first model call that fails still counts a turn,
     * and the input was committed before it.
     */
    intake?: {
        committed: true;
        sessionId: string;
        entryId: string;
    } | {
        committed: false;
    };
    /**
     * Where the session continues from after this call: the entry the next run on the session continues from when nothing
     * moves it — the leaf after the last write of this call's leg that landed before the leg handed the session back. The leg
     * writes everything it owes the session (the date anchor, the cross-boundary record and the workspace state included)
     * before it reads this, and closes its write view in the same step: a write of the leg that reaches the store after
     * that point is refused, so it cannot land past the value. The date anchor, the cross-boundary record and the read of the
     * branch at the value share one teardown bound (15 s in production) by equal shares of what is left, in that order: the anchor
     * waits at most a third of it, the record half of what is left, the read all that remains — time an earlier one does not use
     * goes to the ones after it, so however many of the three stall they delay the result by one bound at most (the workspace
     * state write waits on a bound of its own before them).
     *
     *  - `{ sessionId, entryId }` — the leaf after this call's own last landed write, on a branch made of this call's own writes
     *    (the first landed on the leaf the leg took the session at, each later one on the leaf its previous write left). With no
     *    other writer it is the session's leaf, and the session's leaf set back to `entryId` holds the conversation the next run
     *    continues with, its system-prompt inputs included.
     *    Another writer may append after it (the session's leaf then moves on and is not this value), or make a write of this
     *    call's settle fail (the value is then the leaf before that write — this call's own answer, say); either way the value
     *    is this call's own conversation, never someone else's. A prompt blocked before it was taken in can still hand one: the
     *    leg may have written what a session's first leg owes (the date anchor). A redo hands `entryId` to `resumeAt` with the `at`
     *    mode on the next message: every value is taken there, whatever entry it is (an answer, a tool result, a date anchor, a
     *    compaction), and the next run continues from where this call ended — unless a store that loads a bounded window does not
     *    hold its branch whole (`resume_at.outside_window`, nothing written). The conversation only: `restoreFiles` with it is refused
     *    (`rewind_snapshot.unresolvable`, the files stay). A host gates that on the engine capability `task.continues_from`.
     *  - `{ none: "run_open" }` — the run has not ended: this leg parked it durably (any gate), or its resume put the approval
     *    back to pending. The leg that ends the run hands its own value.
     *  - `{ none: "nothing_taken_in" }` — this call's leg landed no write on the session (usually: its input never got in), or
     *    the call ran no leg at all (a composition's own refusal, a workflow call that did not run).
     *  - `{ none: "unsettled" }` — where the leg left the session is not settled: a write it issued had not settled when its
     *    view closed (a date anchor whose write outlasts its share of the bound included), one of its writes landed on a leaf
     *    another writer had moved the session to (the branch at its last write is not this call's conversation), the
     *    conversation up to its last write still holds a tool call a reconcile would close by appending, the branch could not be
     *    read to tell, or the leg ended in a throw before it reached this reading. The first write is held to that too: an entry
     *    another writer added after the leg took the session reads `unsettled` even when it landed before the leg read its
     *    context (and the model saw it) — rare; that call then hands no redo point and says why once, never a wrong one.
     *    Final: the value is never minted later.
     *
     * A composition (verification gate, cascade, repair loop) hands its own fold, never its last leg's by spread: the landing of
     * the last of its legs that ran in the session of the leg whose result it returns (`sessionId`) and landed a write there —
     * the implementation's session for a gate, the returned attempt's for a repair loop (after a clean restart, the restart's),
     * the passing rung's for a cascade (the last rung's when none passed). A cascade releases each rung's session when the rung
     * ends: on a store that evicts what is released, the session this value names is gone (a redo is refused,
     * `resume_at.not_found`).
     *
     * ABSENT only when the engine that produced the result does not have this member (an older engine's record).
     */
    continuesFrom?: {
        sessionId: string;
        entryId: string;
    } | {
        none: "run_open" | "nothing_taken_in" | "unsettled";
    };
    /**
     * Present when {@link result} is what the stream showed and an extension changed it: the extensions whose
     * `classic.MessageDisplay` answers changed what was shown of the answer's messages (a window rewritten or cut), in the order
     * they first did — whether the display reached the end of those messages or the caller's stop ended it short (`result` is
     * then what had been shown by the stop). A handler that failed a window changed nothing and is not named
     * (`mods.display_withheld` says it). Absent when no handler changed what was shown of the answer, or on a leg that raises
     * no display.
     */
    resultDisplayedBy?: readonly string[];
    /**
     * `true` when {@link result} is only what the display had shown of the answer when it ended, and part of the model's text was
     * never shown: the caller's stop (`interrupt()`, `halt()`, the caller's signal) ended the
     * display of one of the answer's messages while a non-blank piece of its text was still unshown (a window being answered, text
     * the windows had not reached, text that came after the stop). It says that text was left unshown, not how `result` compares in
     * length: a display that rewrites can show text of any length. Read what the engine stored of the message from the session, in the
     * committed messages {@link resultEntryIds} names (a reply cut off while it streams keeps the text that was streamed, not text
     * that only a block's close carried). `result` itself is unchanged by this — it stays what the stream showed, and a display may
     * have taken words out of it on purpose, so showing the stored text is the host's call. Present on any terminal kind (a
     * `completed` one with an empty `result` included). Absent when nothing was left unshown: a leg that raises no display (no `classic.MessageDisplay` handler, a
     * delegated child), a display that reached the end of the answer, a stop that came after everything the model had said was
     * shown, a stop before it said anything, a tail of blank text. Not the same fact as {@link resultDisplayedBy} (who CHANGED what
     * was shown): a pass-through handler stopped mid-window changed nothing, so that field is absent while this one is present.
     */
    resultDisplayedInPart?: true;
    /**
     * Best-effort salvaged assistant text from a terminal FAILURE. Three facts a reader may lean on:
     * - PRESENCE means "this failure is one of the terminals below and handed back the work it had produced": a
     *   consumer that only wants to know whether work was salvaged tests the key, with no code check;
     * - when present it is byte-equal to {@link result} (the assembler fills it from the one local that `result` is
     *   trimmed from — the answer's displayed projection: `<think>` tags stripped, a display handler's rewrite applied,
     *   a degenerate tail trimmed — not the raw stream bytes), and it is never a blank string;
     * - on every other terminal it is `undefined` (the key is absent once the result is serialized; on the in-process
     *   object it is an own key whose value is `undefined`).
     *
     * So the fallback `r.result || r.salvagedOutput` never reads the second operand: wherever `salvagedOutput` holds
     * text, `result` holds the same text. Read `result` for the text on ANY terminal — a consumer that reads only
     * `salvagedOutput` on failure discards the final assistant text of every failure outside the list (and text cut
     * mid-stream by a caller's stop, which has no salvage code), and an error shell's own `result` is empty. A
     * composition's or a workflow member's synthesized result (the cascade's spent budget, the repair loop's failed
     * isolation check, a workflow journal's oversize tombstone) carries the engine's own sentence in `result` instead
     * of model text.
     *
     * The populating terminals, and what the text means on each:
     * - `errorCode === "output.degenerate"` (degenerate-repetition cutoff): the model's text up to the
     *   loop, with the degenerate tail TRIMMED at the brain stream layer (byte-identical repeats dropped,
     *   one instance of the repeating unit kept — see `trimDegenerateTail`). Declared LOSSY normalization:
     *   the trim never drops unique bytes, but the repetition COUNT is not preserved — a payload whose
     *   meaning lives in how many times a unit repeats (fixed-length padding, "output N copies") comes
     *   back as one instance; this is not the raw failure snapshot.
     * - the `limits.max_*_exceeded` family (a per-slice window was exhausted on a task that did not opt
     *   into resource-suspend): whatever text the run had produced before the loud terminal — when the bound cut a reply
     *   while it streamed, the text that reply had streamed, as {@link result} reads it (the session keeps the model's text as
     *   an `"aborted"` assistant message).
     * - the `"env."` namespace (`"env.lifetime_expired"`, and from 7.75.0 a deployment's own `env.` code the environment refused itself
     *   with) / `"usage.window_exhausted"` (ruled 2026-08-04): the same, for the EXTERNAL stop causes — an expiring or refusing
     *   environment or a closed deployment window that could not be suspended into a checkpoint. Nothing about the run itself failed, so its work is handed back on the
     *   same seat the ceilings use. (An entry-time `usage.window_exhausted` refusal ran nothing, so there
     *   is nothing to salvage and the field is absent.)
     *
     * Undefined on every other terminal and when there was nothing to salvage.
     */
    salvagedOutput?: string;
    /**
     * Present iff this run compacted its context at least once at a turn boundary or a prompt-too-long
     * recovery, or opened its compaction breaker: `passes` = landed compactions, `kind` = the last landed
     * pass's trigger (`reactive` is the wire's `forced`), `breakerOpen` = compaction was disabled for the
     * rest of the run (later context was trimmed away, not summarized). The end-of-task settle pass is
     * NOT counted (ruled): it summarizes AFTER the work, for the next run, and says nothing about what this
     * run's model saw. Projected onto a delegated child's terminal frame so
     * the parent can tell that a child forgot.
     */
    compaction?: {
        passes: number;
        breakerOpen: boolean;
        kind?: import("./task-notification.js").CompactionKind;
    };
    /**
     * The remote-workspace lifecycle failures this run hit, as DATA. The seam declares eleven
     * distinct `RemoteExecutionErrorCode`s, but every one of them used to reach the caller as the same
     * thing: a `suspendVM` refusal was swallowed into the `onError` side channel and the result read
     * `limits.max_turns_exceeded` (identical for a transient auth blip and a permanently-unsupported adapter), while
     * a failed restore reported the single code `resume.env_failed` with the real code buried in prose. A
     * deployment that wants to distinguish "refresh the credential and re-resume" from "this adapter can
     * never do it" had nothing but a string to parse.
     *
     * - `op` — which lifecycle call failed.
     * - `code` — the adapter's verbatim code (`RemoteExecutionError.code`).
     * - `retryable` — whether `code` is in the retryable family (`RETRYABLE_REMOTE_ERROR_CODES`). For the
     *   IDEMPOTENT restore ops the engine has already spent its own bounded retries (see `attempts`); this
     *   flag is what a caller acts on for the ops the engine deliberately does not retry — a `suspendVM`
     *   takes a snapshot, so re-driving it is the caller's decision, not the engine's.
     * - `attempts` — how many times the engine called it (1 = no retry was made or none was warranted).
     * - `message` — the adapter's message, for humans.
     *
     * Present only when at least one lifecycle call failed (absent = nothing to report), so a consumer that
     * ignores the field is unchanged. It is DIAGNOSTIC: {@link terminal} keeps its existing meaning —
     * a failed suspend still ends the task the way it always did, it is just no longer anonymous. A `resumeVM` the
     * environment refused standing (a code outside the retryable family, other than `unknown` and `aborted`) is no note
     * here: the leg's restore seat fails it with that code as {@link terminal}'s own. A failed workspace sync
     * (`op: "syncWorkspace"`) never moves {@link terminal}; the sync at the leg's end runs after this result is handed out,
     * so its failure is told (`workspace.sync_failed`) and is no note here.
     */
    remoteEnvFailures?: RemoteEnvFailureNote[];
    /**
     * The asks of this run that nobody could answer and that were refused — one entry per refused call, in refusal order, minted at
     * the gate's one deny exit beside the `delegation.ask_unresolvable` notice (the same facts). The run's terminal is unchanged (a
     * refused ask is a tool result the run went on from); this is what the leg did NOT get done. Present only when at least one ask
     * was refused — never an empty array.
     */
    refusedAsks?: readonly RefusedAsk[];
    /**
     * Every call the gate refused on this run ({@link RefusedToolCalls}, bounded) — whatever refused it: the deployment's policy, a
     * rule, a hook, the mode, an ask's answer (a person's no, a policy's, a window that ran out, nobody to answer). Read off each call's
     * END, the end that carried its gate record; a deny on an end minted while the turn it ran in was being cut (a cancel, the walltime,
     * a person's halt) is no refusal. The run's terminal is unchanged (a refused call is a tool result the run went on from). Where the
     * three records above and below say WHY a refusal mattered (an ask nobody could answer, the leg's verdict never landing, a person's
     * halt), this says WHICH calls were refused and by whose word — a member's holder reads all of them through one projection
     * (`memberRefusalsOf`). Per run; present only when at least one call was refused.
     */
    refusedToolCalls?: RefusedToolCalls;
    /**
     * Present when this run's terminal failure came from the PROVIDER BOUNDARY — the transport or the
     * provider failed the model call, as opposed to this deployment refusing to send one, a limit being
     * reached, or the model's own output being unusable. Its PRESENCE is the assertion; the members are
     * whatever the failing attempt actually stated about itself:
     *   - `status`    — the failing HTTP status, when the provider answered with one. Absent for a
     *     connect failure, a stall, a mid-stream tear, and an in-band error frame delivered inside a
     *     200 — never zeroed, since 0 reads as a number a consumer may format.
     *   - `requestId` — the provider's own request identifier for that attempt, when it stated one in a
     *     shape worth carrying. This is the handle a provider's support channel asks for.
     * Both may be absent together: that is a provider failure nobody could label further, which is a
     * different statement from "not a provider failure" (the field itself absent).
     *
     * Nested rather than three loose keys so the assertion and its evidence cannot drift apart — there
     * is no state in which a consumer sees the claim beside a status belonging to some other attempt.
     * The same family rides the assistant message itself as `isApiErrorMessage` / `apiErrorStatus` /
     * `requestId`; this seat is its RUN-LEVEL projection, lifted from that message at the one assembly
     * point rather than re-derived, and the two spellings are named here so the mapping is written down
     * instead of inferred.
     *
     * PRESENCE, deliberately narrow: filled only when the provider failure is the terminal that NAMED
     * this result. A run that hit a provider failure and then a higher-ranked terminal (a budget
     * ceiling, a walltime cut) reports that other cause and leaves this absent — the same rule
     * {@link usageWindowRetryAfterMs} states for itself, and for the same reason: a diagnostic seat
     * beside a cause it does not belong to is worse than a missing one.
     */
    apiFailure?: {
        status?: number;
        requestId?: string;
    };
    /**
     * How long (milliseconds) until the deployment usage window that stopped this task frees up — the wait
     * hint a scheduler needs to decide WHEN to re-submit, rather than polling.
     *
     * **In-presence condition:** set on exactly two terminals — `errorCode === "usage.window_exhausted"`
     * (either moment: the entry refusal that ran nothing, or the running terminal that could not suspend)
     * and `errorCode === "memory.admission_required"` (the prepare-throw path sets it there too — see
     * assemble-result's accepted-code pair). Absent everywhere else, INCLUDING when a usage window did
     * stop the run but a higher-ranked terminal
     * named the result (a budget ceiling crossed on the same turn): the reported cause is then that other
     * code, and a wait filed under it would describe something the code does not name.
     *
     * **Do not branch on its presence** to work out WHY a task stopped — read `errorCode` for that (the
     * standing rule for every optional field on this type). A consumer treating "has `retryAfterMs`" as
     * "was rate-limited" misreads both directions: the same code can arrive without one, and the field
     * says nothing about which of the two governance moments produced it (`stats.turns`/`result` do).
     *
     * A DURABLE pause carries its own wait elsewhere: a `suspended` result's hint rides the checkpoint gate
     * (`resumeAfterMs`), which the resume path consumes — the two are deliberately separate seats for the
     * two different resumption stories (re-submit the task vs resume the checkpoint), never aliases.
     *
     * The same number is also delivered to `RunnerDeps.onError` on the typed error (unchanged) — this seat
     * is for the caller that holds the result and never wired that sink.
     */
    retryAfterMs?: number;
    /**
     * The audit record of the run's **first** switch away from the requested model: a main-loop answer the
     * model lane walked down the requested catalog entry's `fallbacks` chain (on a gate word of
     * `RunnerDeps.modelFallback`), or the near-budget switch (`reason: "budget"`). Lets a caller know the
     * result was produced by another model and alert/track it. Audit only — pricing does not read it (every
     * answer is priced at the model that made it) and the near-budget switch has its own bit, so a walk does
     * not spend it. Set even when no hop served — `status:"failed"` + `degraded` means "the requested model
     * failed, and so did its chain".
     */
    degraded?: {
        from: string;
        /** The last hop tried (the hop that served, when one did); the switch target on the budget path. */
        to: string;
        /** The gate word the request left the requested model on (`DegradeReason`); `budget` on the near-budget
         *  switch; `route_refused` when the requested model's own route was refused by the deployment Brain's judgment
         *  before it was sent (nothing was sent — its entry leads `skipped`). `network` / `auth` / `stream_torn` are the
         *  three words added with the model lane, `route_refused` the one after them — consumers switching exhaustively
         *  add the arms. */
        reason: import("./model-fallbacks.js").DegradeReason;
        /** The fallback-chain model ids tried after the requested model, in order (absent on the budget path). */
        chain?: string[];
        /** The hops the deployment Brain's route judgment refused before they were sent, in chain order — the requested model first
         *  when its own route was refused (`reason: "route_refused"`) — each model id, the refusal code and the fix sentence the
         *  judgment stated (`route.judgment_failed` for a judgment that threw or answered no verdict; each absent when it stated
         *  none; a credential refusal's fix names the root the credential belongs to); absent when none was refused and on the
         *  budget path. */
        skipped?: {
            model: string;
            code?: string;
            fixHint?: string;
        }[];
        /** How the walk ended, the marker's word: `served` (a fallback hop answered — `to`) or `exhausted` (no hop could; the turn's
         *  answer is the requested model's own failure — `to` is the last hop tried, not the model that answered). Absent on the budget path. */
        outcome?: "served" | "exhausted";
        /** Whose message the walked turn's answer is: `to` when a hop served, `from` when the chain was exhausted. Absent on the budget path. */
        answeredBy?: string;
        /** 1-based turn during which the switch happened. A walk: the turn whose answer was walked. Budget: the
         *  turn whose cumulative cost crossed the threshold (the switch takes effect from the next turn). */
        atTurn: number;
    };
    /** The validated object the model submitted via `submit_output` when `TaskSpec.outputSchema` was set
     *  (1.41). Undefined if the model answered in prose instead, or the task didn't finish via the output
     *  tool. Cast it with `Static<typeof yourSchema>`. (Exhausting the output-retry cap → `failed` +
     *  `errorCode="output.invalid"`, and this stays undefined.) */
    structuredOutput?: unknown;
    /**
     * The leg's VERDICT WAS REFUSED ({@link VerdictRefusal}): at least one call of its verdict tool was refused at the gate (any layer —
     * the deployment's policy, a hook, the org, a person's rule, the mode, an ask nobody could answer, a person's no) on this run, and no
     * call of it was delivered on this run; a call whose turn was cut (a cancel, the walltime, a person's halt) is not counted, and a
     * paused result never carries it. What tells "the model did not submit" (no {@link structuredOutput}, no `verdictRefused`) from "it submitted and the
     * gate refused it" (`verdictRefused` present) — the terminal is the same either way (`completed` unless something else ended the run,
     * e.g. the output retry cap's `output.invalid`). Present ⇔ the run announced `task.verdict_refused` (one notice per run). The other two
     * refusal members answer other questions over the same gate records: {@link refusedAsks} lists every ask nobody could answer (any
     * tool), {@link haltedOnUserRejection} says the run ended because a person said no (any tool, a plan too). Per run, like them: a
     * resumed leg carries the refusals of its own run.
     */
    verdictRefused?: VerdictRefusal;
    /**
     * design/101 §E19 + design/381 — NON-FATAL rewind disclosures for this run: the legs where the rewind
     * machinery did something other than what the request's plain reading implies, reported as data instead
     * of silence. Present only when at least one applies (absent = nothing to disclose), so a consumer that
     * ignores the field is unchanged. A rewind that could NOT be delivered as asked is NOT a note — it is a
     * terminal failure (`rewind_snapshot.unresolvable` / `rewind.store_unconfigured` /
     * `rewind.restore_failed` / `rewind.invalid_spec` /
     * `rewind.conflicting_targets` / `rewind.child_scope_unsupported` / `rewind.capture_disabled`; `config.invalid_argument`
     * when the session's id ends like a file-history address on a row outside the address epoch — `fileHistoryScopeOf`).
     *
     * - `conversation_only` — {@link TaskSpec.resumeAt} branched the transcript WITHOUT
     *   {@link TaskSpec.restoreFiles}, so the working tree was deliberately left where it was (CC's
     *   "Restore conversation" mode). Legal and useful; the note is what makes the two axes' divergence
     *   visible.
     * - `files_env_unsupported` — a file restore was requested but this deployment mounts no
     *   filesystem-capable `ExecutionEnv` (stub env), so the file axis was inert. Not an error: such a
     *   deployment has no working tree to rewind.
     * - `restore_partial` — {@link TaskSpec.acceptPartialRestore} tolerated a partial restore: ≥1 tracked
     *   file was refused or failed while the others converged; the message carries the per-file ledger
     *   summary (applied / identical / refused / failed). Present ONLY under that explicit opt-in — the
     *   default posture is the loud terminal `rewind.restore_failed` (DV-15).
     * - `restore_left_as_is` — the restore left one or more tracked files as they are (`FileHistoryRestoreResult.leftAsIs`, each
     *   row with its class from `FILE_HISTORY_LEFT_AS_IS_CLASSES`): the message names each by its key, says why each class of them
     *   did not move and how a host learns of such files beforehand; each file is named with the directory it lies in, and a
     *   `complete` restore says how many other files it restored (none is said as none). Not a refusal or a failure: the run's
     *   whole-or-nothing judgment does not count these rows. Present whenever the restore left a file; the note carries the same
     *   files as rows ({@link leftAsIs}), which a host reads instead of the sentence.
     * - `restore_outside_root` — the run's restore changed (its bytes or its mode) or deleted one or more files OUTSIDE the root the
     *   run works in (a file the session edited outside it, under its absolute key; a key spelled through a link inside the root that
     *   leads out of it — judged where the file really lies): the message names each by its absolute path as addressed and
     *   what was done to it. Present only on a run that restored files (`rewindFilesTo`, `resumeAt` + `restoreFiles`) and only when
     *   such a file was actually changed or deleted — a file refused or left as it is is not one. A result member, not a notice: nothing is told on
     *   `onNotice` for it. (`Runner.rewindFiles` answers no sentence; its `files[].outsideRoot` is the same fact, row by row.)
     *
     * (design/381 closed-set surgery: `snapshot_store_unconfigured` is RETIRED — its only producer was
     * the per-task capture request, and capture is now always-on when a store is wired; a restore request
     * with no store keeps the fail-loud terminal instead.)
     */
    rewindNotes?: Array<{
        code: "conversation_only" | "files_env_unsupported" | "restore_partial" | "restore_left_as_is" | "restore_outside_root";
        /** Human-readable statement of what did NOT happen and why — safe to show a user verbatim. */
        message: string;
        /** On a `restore_left_as_is` note only (and always on it): the files the sentence names, one row each — the restore's own rows,
         *  the type a failed restore's `detail.leftAsIs` and `Runner.rewindFiles`' `restore.leftAsIs` carry (`path` the key, `place` the
         *  directory its history records — the one the sentence names beside the key —, `class`, `reason`, `outsideRoot`), in the
         *  restore's own order. Absent on every other code. A machine reading: branch on `class`, locate by `place`. */
        leftAsIs?: FileHistoryLeftAsIsFile[];
    }>;
    /**
     * The file restore this run carried out (`rewindFilesTo`, `resumeAt` + `restoreFiles`), as the restore answered it — the SAME value
     * `Runner.rewindFiles` answers as `restore`, minted by the same restore reading: `outcome` (`complete`, or `partial` where
     * `acceptPartialRestore` accepted it), the counts' lists, every file it wrote, deleted or refused (`files`, each with its
     * `targetPath` and `outsideRoot`) and every file it left as it is (`leftAsIs`). The sentences about the same restore are
     * {@link rewindNotes}; this is the rows a host reads instead. PRESENCE: exactly when the run's restore was accepted, whatever
     * terminal the run then reached (a refusal after the restore landed included); absent on a run that asked no restore, and on one
     * whose restore was refused or failed (`rewind.restore_failed` carries that ledger on its `detail`; `terminal.rewind` says whether
     * the tree moved).
     */
    fileRestore?: Extract<RewindFilesResult, {
        dryRun: false;
    }>["restore"];
    /**
     * The files THIS RUN's hands actually mutated, with how many times each — the same
     * `{path, edits}` shape the delegated-child projection publishes as
     * {@link import("../agents/subagent-steps.js").SubagentEditedFile}, so a host can read the two
     * seats side by side. A run is one host-side user message, which is the granularity a
     * "restore the code this message changed" affordance needs; the per-model-turn beat
     * (`turn_end`) deliberately has no such seat.
     *
     * **Source**: the hands band's own mutation lane. One entry is bumped when a `Write`/`Edit`/
     * `NotebookEdit`/`SaveToolResult` call's FINAL env write did not PROVABLY write nothing — it landed, failed
     * ambiguously, or threw — not when a tool call starts, not from a tool-name table over the event stream.
     * The consequences are the contract:
     *  - a refused or gated write is not counted, nor a write that failed with a code whose contract says
     *    nothing was written (the same lane point that retracts its first-touch history record); a write that
     *    failed ambiguously or threw IS counted, since its bytes may have landed — the list is an upper bound on
     *    that edge, never a lower one;
     *  - a `Bash` command that changed a file is not counted: it does not go through those lanes.
     *    This matches the reference implementation's own trigger set;
     *  - one tool CALL counts once, so a batch `Edit` (multiple `edits[]` against one file in one
     *    call) is one edit here, exactly as the child projection counts it.
     *
     * **`path` form**: the model-supplied path argument, verbatim — the same coordinate
     * `SubagentEditedFile.path` uses, deliberately not the canonical containment key, so both seats
     * spell a file the way the transcript does. IDENTITY, however, is the canonical FILE, not the
     * spelling: a relative argument resolves against the run's LIVE cwd, so one spelling can name two
     * different files across a `cd` (two entries, each showing that spelling) and two spellings can
     * name one file (ONE entry, showing the first spelling that reached it). Insertion order = order
     * of first edit.
     *
     * **Three-valued on the failure edge, upper bound never lower**: a write failure is three-valued.
     * A failure whose error code's contract states nothing was written is a proven no-op and is NOT
     * counted. An AMBIGUOUS failure or a thrown write IS counted: an `ExecutionEnv` whose write is not
     * atomic can truncate a file and then report an error, that file may really have changed, and the
     * first-touch history record for it is kept for exactly that reason — so this list names it too,
     * and a `rewindFilesTo` will restore it. (The reference env replaces whole files by stage+rename —
     * fully old or fully new — so this edge belongs to its in-place fallback arms and to third-party
     * envs.) A host therefore reads this list as "files that may differ from before this run", never
     * as "writes the model saw succeed"; the tool answers carry that.
     *
     * **In-presence condition**: present iff this run's hands landed ≥1 such write — zero edits means
     * the key is ABSENT, never an empty array. It does NOT depend on whether a
     * `RunnerDeps.fileHistoryStore` is wired: this is an observation of what this run did, not a
     * durable history, and a deployment with no history store still gets it (what a store adds is the
     * ability to REWIND, not the ability to say what changed). It covers this run's OWN band only — a
     * delegated child's writes ride the child's own result and the delegation projection, not this
     * key.
     *
     * **Bound**: at most 1000 distinct files. Past that, already-listed files keep counting and new
     * ones are not added — a result seat cannot be unbounded, and a single user message reaching a
     * thousand distinct files is already outside what this observation is for. A consumer that must
     * know whether it is reading a saturated list can compare the length against that ceiling.
     */
    editedFiles?: import("../agents/subagent-steps.js").SubagentEditedFile[];
    /**
     * The run's MEMBER LEDGER (`RunLedger`) — present exactly when the task keeps one (its first leg declared `TaskSpec.runLedger`;
     * a resumed leg keeps its row's), on every terminal:
     * one row per member it dispatched with the engine's reading of how each ended, what each said and did, and which completed
     * rows no accepted check points at; the run's coverage; a headline computed from those counts (never the model's words); and
     * the same in fixed sentences (`text`) for an outlet with no interface of its own. `result` is unchanged by it — the ledger
     * stands BESIDE the model's answer. A host's wire carries it under {@link import("./run-ledger.js").RUN_LEDGER_WIRE_KEY}.
     */
    runLedger?: import("./run-ledger.js").RunLedger;
    /** Present exactly on a resumed leg whose spec declares `TaskSpec.runLedger` while the row it resumed was parked by a leg that
     *  kept no ledger: the sentence saying the task keeps none ({@link import("./run-ledger.js").RUN_LEDGER_NOT_KEPT_SENTENCE}) —
     *  whether a task keeps one is fixed by its first leg. No notice code. */
    runLedgerNotKept?: string;
    /**
     * Present (`true`) exactly when the run's FINAL turn was halted by a person's BARE rejection of a
     * tool call, or of the plan a plan pause held — the parent-thread control-flow boundary: the rejected
     * call's same-message siblings that had not started were settled un-executed (each an error result
     * coded `gate.batch_halted`), and the engine deliberately did NOT re-invoke the model, so the run ends
     * awaiting the user's direction. A resumed leg that redeems such a rejection records the decision and
     * makes no model request at all (its `result` is the transcript's last assistant message — the plan
     * request, or the parked call's message; empty when the transcript has no answer yet). On this path `status` is still `"completed"` (nothing failed, nothing is suspended,
     * the session is continuable as ever) — this field is what tells such an end apart from a natural
     * finish: `result` text is whatever the model had produced BEFORE the rejection (often empty), and
     * a consumer surface should read the state as "stopped by the user, awaiting their direction",
     * never as "the task finished its work". Absent everywhere else — including when queued user input
     * (a steer/follow-up) continued the run past the rejection and it later ended naturally.
     */
    haltedOnUserRejection?: true;
    /**
     * Present (`true`) exactly when a {@link TaskStream.halt}
     * (the bare user interrupt, the CC Esc form — cut the in-flight turn, stop at that boundary, wait
     * for the person's next input) was CONSUMED by this run: the engine's own record says the run
     * ended FOR it. The attribution law, one sentence: signed ⇔ the halt's cut settled a turn (the loop
     * reported the interrupt settlement it took for the seat the halt aborted — stream shape, batch
     * shape, or the recovery lane's arms) OR the halt's stop request was among the sources a boundary
     * consult stopped the loop for (the pre-turn guard that refuses the next turn — the birth-window
     * halt included — or the post-turn consult). The MINTER states the fact; the result assembly reads
     * it and never infers causation from the final's shape (a brain minting its own `aborted` final
     * beside a late halt reads as the failure it is) nor from the verb's acceptance.
     *
     * The ruled terminal form is completed-with-marker, this seat being the marker: `status` is
     * `"completed"` on the ordinary path (a clean, resumable ending — the session continues via the
     * ordinary next-run front door), and this field is what tells a person-stopped ending apart from a
     * natural finish — same reading discipline as {@link haltedOnUserRejection}, its sibling seat
     * ("stopped by the user, awaiting their direction", never "the task finished its work"). `result` is
     * whatever the cut turn had produced before the halt — a reply cut while it streamed counts the text it had streamed, as
     * the stream showed it ({@link result}; the session keeps the model's text as an `"aborted"` assistant message) (possibly empty — a turn cut before it said anything answers
     * `""`, never with an earlier turn's answer — a turn that was continuing a split answer answers with that answer so
     * far); a halt consumed by a boundary stop leaves the last turn's answer. Rides EVERY terminal a
     * consumed halt reaches — a halt whose cut settled a turn and then raced a real failure/limit, or
     * whose boundary stop coincided with a review/resource park (`needs_review` / `suspended`),
     * truthfully says a person also stopped it (the slice-2 status-keyed suppression is retired).
     *
     * ABSENT (never `false`) whenever the halt was not consumed, however it was answered: a halt
     * landing after the run's abort already fired (first-writer-wins, the `interrupt()` attribution
     * law — that ending belongs to the abort); a halt accepted while the run was already ending for its
     * own reason (a natural completion past the loop's final commit point, a brain's own terminal, a
     * durable approval park whose commit won the race and whose abort then owned the ending); a
     * steer-now cut (its stamp is `steer`). In every such case the halt's trace is its verb receipt plus
     * one `task.halt_unconsumed` notice — the seat is never signed on a guess.
     */
    haltedByUser?: true;
    /**
     * The registration (its `ctx.origin.plugin`) whose `$.turn.abort` ended the run's LAST model turn — present iff
     * that cut was consumed by the loop as the final turn's settlement, the same law as `haltedByUser` (signed ⇔ consumed).
     * An extension's cut does not stop the run: a queued follow-up opens the next turn, a `classic.Stop` block asks for one,
     * and either clears the fact — so this seat is present only when the cut turn was the last one, with nothing after it.
     * The run then reads `status: "completed"`, `result` = whatever the cut turn had produced, a reply cut while it streamed
     * counting the text it had streamed (possibly empty: a turn cut
     * before it said anything answers `""`, never with an earlier turn's answer; a turn continuing a split answer answers
     * with that answer so far). One `task.turn_interrupted` notice
     * (`detail.cause: "extension_abort"`) rides every ACCEPTED cut, ending or not; an accepted cut that no settlement took as
     * its turn's cause (the turn had already ended as its answer, or the run's own ending won) leaves this seat absent and is
     * disclosed by one `task.halt_unconsumed` (`detail.source: "extension"`).
     */
    turnAbortedBy?: string;
    /**
     * Present exactly when the run COMPLETED strictly past a ceiling the caller declared (`TaskSpec.limits`): its last turn answered and owed no
     * further request, so nothing was cut and nothing is owed — the verdict is `completed`, and this says the ceiling was crossed on the way (the
     * figures were never on the result: `stats` holds the spend, not the ceiling). The same fact rides one `operator` notice,
     * `task.completed_past_limit`, from one evaluation — branch on this member, never on the notice's sentence.
     *  - `axis` — which ceiling, in the words of a parked run's `resource_limit` reason: `budget_tokens`, `budget_cost`, `walltime`. There is no
     *    `turns` word: a run that answers on the turn its cap allows used its allowance, and one that reached the cap with a turn owed fails or
     *    parks — a completed run is never past its turn cap. When several ceilings are crossed it names the first of tokens, cost, walltime.
     *  - `limit` — the ceiling the engine compared, in the axis's unit: tokens (`budget_tokens`; for a resource-slice run the smaller of the
     *    slice window and what the cross-slice allocation had left), MICRO-USD (`budget_cost`, the unit of `stats.costMicroUsd`), MILLISECONDS
     *    (`walltime`).
     *  - `observed` — the figure against it, same unit: for the budget axes what the holding run's SUBTREE settled (its own requests and those
     *    of every run it started or woke), for the walltime axis the ms elapsed when the turn boundary found the window passed (work after the
     *    answer does not move it).
     *  - `heldBy` (budget axes) — `own`: the ceiling is this run's; `ancestor`: it belongs to a run this one hangs under (the run that started
     *    or woke it), so raising this run's own ceiling does not help.
     * Also present on a `failed` run that ended because its next model request did not fit what was left (`limits.max_tokens_exceeded` /
     * `limits.max_cost_exceeded`): there `observed` is what the holding run's subtree had settled when the request was refused (not past the
     * limit — the request was not sent). Absent on every other terminal, when a ceiling was only met, and when no ceiling was crossed.
     */
    limitCrossed?: {
        axis: Exclude<import("./checkpoint-store.js").ResourceLimitReason, import("./checkpoint-store.js").PlatformLimitReason | "turns">;
        limit: number;
        observed: number;
        heldBy?: "own" | "ancestor";
    };
    /**
     * The deliveries of AskUserQuestion calls a person ANSWERED but that no call collected (the leg ended first — abort, batch
     * teardown, or a loop failure — before the call executed, or the call's signal ended its wait before the answer came,
     * #4316). Rides EVERY terminal
     * when non-empty, because the alternative is an answer a human produced vanishing with nothing to
     * show for it: the answers were NOT delivered to the model and are gone with this leg — re-ask if
     * the decision is still needed. `RunnerDeps.onError` (classification `"unconsumed-human-answer"`)
     * carries the same fact as an additional alert; this field is the mandatory face for an answer that arrived before the
     * result was assembled — one that arrives after it reaches only that alert.
     */
    strandedHumanAnswers?: ReadonlyArray<{
        /** The engine-minted per-delivery identity (AskQuestionRequest.deliveryId) — the KEY: call ids can
         *  repeat across deliveries, so two lost answers on one call id are still two records here. */
        deliveryId: string;
        toolCallId: string;
    }>;
    /**
     * HOST-SUPPLIED: the approval plane's report that this leg ended with human approvals still
     * OUTSTANDING (the ask identities it is holding, and when the OLDEST of them was created).
     *
     * **Who writes it, and why not the engine.** Core mints no ask identity — an ask id belongs to the
     * deployment's approval store, and `resolveAsk` only awaits the host's `onAsk` — and core starts no
     * approval clock. So this seat is filled by the `Runner` a deployment hands to
     * `runWorkflow`/`startWorkflow`: that call both RAN the leg and owns the pending-approval map, which
     * is the only place the two facts meet without inventing an attribution. Core's own Runner never
     * writes it. ABSENT is therefore the ordinary world — an older deployment, or one whose approvals are
     * always answered inline — and every such leg behaves exactly as it did before this seat existed.
     *
     * **Three-state, deliberately.** Absent = "this deployment is not reporting outstanding approvals, or
     * there are none"; present = "these asks are outstanding". An EMPTY `askIds` is neither and is
     * refused: it would let a half-written record read as "waiting on nothing", which is precisely the
     * misdiagnosis the seat exists to prevent. A present-but-malformed value is announced and then
     * treated as no report — never silently folded into absence, and never granted the exemption below.
     *
     * **What core does with it** (`src/orchestration/workflow.ts`): a workflow agent leg whose progress
     * watchdog fired while an approval was outstanding was NOT stalled — it was waiting on a person, by
     * design — so that attempt is not charged against the stall-retry budget. The run's own
     * `totalTimeoutMs` remains the backstop for a wait nobody ever answers.
     */
    pendingApproval?: {
        askIds: readonly string[];
        oldestCreatedAtMs: number;
    };
    /**
     * HOST-SUPPLIED: how long this leg spent BLOCKED on human approvals, in ms, as the deployment's
     * approval plane measured it. Same writer and same absence contract as {@link pendingApproval}: the
     * approval clock belongs to whoever holds the ask, so the figure is SINGLE-SOURCED there and core neither
     * estimates it nor accumulates it (two sides publishing two numbers for one wait is the drift this seat
     * exists to avoid). ABSENT is the ordinary world.
     *
     * Already CUMULATIVE for the leg — a receipt states the leg's total wait so far, not that attempt's
     * increment — so a later receipt SUPERSEDES an earlier one. Adding successive receipts double-counts.
     *
     * **Absence is not zero.** `0` is "nobody was waited on"; absent is "this deployment does not supply the
     * fact". A consumer that defaults absence to `0` reports a deployment's silence as a measurement.
     *
     * What it is FOR: a workflow that hit its total timeout cannot otherwise say whether it was SLOW or
     * WAITING. `WorkflowRun.timeoutInterruption.approvalWaitedMs` carries the largest leg's figure onto the
     * terminal disclosure for exactly that reading — near `timeoutMs` ⇒ the window went on a person, not on
     * work.
     */
    approvalWaitedMs?: number;
    /**
     * The READ-face this leg's read surfaces actually judged under, as an
     * engine-filled OBSERVATION (never a knob: writing it on a spec does nothing). It is the run's ONE
     * resolved face — the same value the hands toolkit enforced and the delegation carriers rode — with
     * the hands-less resume pin folded in (a row resumed on a hands-less worker still reports the
     * checkpoint-frozen `"roots"`).
     *
     * **In-presence condition (#242 widened):** present on every leg that completes prepare — hands
     * mounted (any run with the built-in fs band) AND every hands-less leg (resume legs fold the
     * checkpoint seed stricter-wins; non-resume legs report the live resolution). Absent only on
     * prepare-failure terminals (nothing ran). Consumers that keyed on absence = "no posture" must
     * re-key: absence now means only "prepare never completed". Rides every OTHER terminal, not just
     * `completed` — the posture is a fact about the leg that ran, whatever ended it.
     *
     * Purpose: a POST-COMPLETION follow-on leg spawned OUTSIDE the delegation tree (the verify gate's
     * verifier and fix legs are the canonical case) cannot see the checkpoint fold the completed leg ran
     * under — its spawner holds only the resume-side config, which never contained the frozen posture.
     * Folding this seat into the follow-on spec (stricter-wins: only `"roots"` ever tightens; an
     * `"open"` observation is never forwarded) closes that escape for ANY follow-on, not just the
     * verifier. See {@link effectiveReadDenyPatterns} for the deny-set half.
     */
    effectiveReadFace?: import("../tools/fs/containment-face.js").ContainmentFace;
    /**
     * The WRITE-face containment state in force on this leg, the read seat's twin as an engine-filled
     * OBSERVATION. Same in-presence condition as {@link effectiveReadFace} (every leg that completes
     * prepare; absent only on prepare-failure terminals) and the same purpose: a POST-COMPLETION follow-on
     * leg folds it stricter-wins into its own spec. Only `"roots"` is ever worth forwarding; an `"open"`
     * observation never widens anything by itself.
     */
    effectiveWriteFace?: import("../tools/fs/containment-face.js").ContainmentFace;
    /**
     * The sensitive-path deny ADDITIONS in force on this leg beyond the
     * built-in table, normalized (deployment ∪ task ∪ checkpoint-frozen seed), as an engine-filled
     * OBSERVATION. "In force" = judged by this leg's own read surfaces where they mounted, and carried
     * to its delegation subtree either way (a hands-less resume leg reports the entries its children
     * judge under).
     * This seat is the only place a checkpoint-FROZEN deny entry becomes visible after the resumed leg
     * completes: the resume-side caller's own config never contained it. A follow-on leg's spawner
     * unions these into the child's `readDenyPatterns` (add-only; the child's compile folds exact
     * duplicates, so re-supplying deployment-shared entries is idempotent) — that is how the frozen
     * posture rides every leg that continues this work, not just the delegation subtree.
     *
     * **In-presence condition:** present iff non-empty. Built-in entries are never listed — they are the
     * DEPLOYMENT's own selection (the default tiers unless it says otherwise), re-compiled per leg and reported on its wiring
     * manifest ({@link import("./wiring-manifest.js").WiringManifest.readDeny}). Same terminal coverage as
     * {@link effectiveReadFace}: rides any terminal of a leg that ran; absent on prepare failures.
     *
     * On a DURABLE-PAUSE hand-back these seats are additionally the RE-SUPPLY hint: a checkpoint
     * minted by a leg with no face resolution (a hands-less non-resume continuation) carries no
     * frozen face section of its own, so a caller resuming that token must fold these entries back
     * into the resume-side config (`readDenyPatterns` / `readFace: "roots"`). The resumed leg unions
     * them into its own judgment and delegation carriers; the union is NOT serialized into any
     * further checkpoint that leg may mint (a hands-less RESUME mint re-freezes only its original seed; a non-resume hands-less pause mints its live-resolved posture, #242), so
     * fold them on EVERY resume — the standing resume contract. The seats describe the posture
     * governing the WORK, never the contents of any checkpoint row.
     */
    effectiveReadDenyPatterns?: readonly import("../tools/fs/read-deny.js").NormalizedReadDenyEntry[];
    /**
     * The leg's RECORD, over its whole life, that its byte floor was not kept: PRESENT IFF a read-deny table this leg compiled —
     * the one at prepare, or any one compiled after it because the person's persisted rules changed while the leg ran — held rows,
     * and the leg's execution environment does not declare it keeps the floor (`capabilities.keepsReadFloor`), on a deployment
     * that does not require the floor (one that does refuses the leg at prepare, or the calls that judge with the later table).
     * There, a recursive read under a root reads the files below it, deny rows included, and their bytes reach the conversation.
     * Always `kept: false` when present; ABSENT = no table the leg compiled held a row its environment did not keep, or the
     * leg never compiled one (no hands), or its prepare did not return (a run refused during its prepare after its table was judged carries no record), or an engine older than this member assembled the result.
     * Beside it, the rows of that table by whose they are: `deploymentRowCount` the rows the deployment's own seats name (its active
     * built-in tiers and `RunnerDeps.readDenyPatterns`), `callerRowCount` every other row (the request's patterns, the deny
     * permission rules, the person's rules), `rowCount` their sum. Of a leg that compiled more than one unkept table, the one with
     * the most caller rows. Present whenever this engine assembled the record — a leg whose rows are all the deployment's carries it
     * too (`callerRowCount: 0`), though its person is not told (`config.read_deny_floor_unkept` is told only for caller rows); absent
     * only on a record an engine older than these members assembled.
     *
     * One latch, judged where each table is compiled and read twice, never re-derived: the wiring manifest's
     * {@link import("./wiring-manifest.js").WiringManifest.readDenyFloor} read it as the manifest was derived (the leg's wiring as
     * it started), and this member reads it as the result is assembled — so this member holds wherever the manifest's cell does,
     * and also for a table that gained rows after the manifest went out. To ask "did this leg run with a floor that was not
     * kept", read this member. The person's notice (`config.read_deny_floor_unkept`) is told once per session while the fact holds
     * (a leg that kept the floor ends it) and is not this record. A table is judged before it can be used, so every table anything in the leg judged with is on it; a table whose
     * compile is still running when the result is assembled (a request's read landed new rows and the model then answered
     * without another call) is one nothing in the leg judged with, and is not. On every terminal of a leg whose prepare
     * completed, the stream layer's failure backstop included. A composition entry's result (the verify gate's, a cascade's, a
     * repair loop's) carries the fold over the legs it closes over, not only its returned leg's record: present iff any of them
     * carries it — the implementation leg and every fix round, every verifier leg of the verify gate, every rung, every attempt
     * (the record with the most caller rows; on a tie a counted record first, then the first read — the verify gate reads the
     * implementation side's before its verifiers'); a later leg
     * never takes an earlier leg's record back. Not among them, so with no record that reaches the host: a child a leg delegated
     * work to (the child's own result carries its record; the parent's result does not).
     */
    readDenyFloor?: {
        kept: false;
        rowCount?: number;
        callerRowCount?: number;
        deploymentRowCount?: number;
    };
    /**
     * The configuration roots a TASK layer declared for this leg — {@link import("./task-spec.js").TaskSpec.agentConfigDirs}, its own
     * and the ones a resumed row recorded (the leg mint's carried part, `src/core/runner/leg-caller-places.ts`; the deployment's
     * own `RunnerDeps.agentConfigDir` is not listed: every leg of the deployment declares it again) — as an engine-filled
     * OBSERVATION. Same purpose as {@link effectiveReadDenyPatterns}: a root only the parked row knew never appears in the
     * resume-side config, so a POST-COMPLETION follow-on leg (the verify gate's verifier and fix legs) unions these into its
     * own `agentConfigDirs`, and the rows stay placed below the root on every leg that continues the work. Present iff
     * non-empty; rides any terminal of a leg that ran.
     */
    effectiveAgentConfigDirs?: readonly string[];
    /** The caller homes a TASK layer declared for this leg ({@link import("./task-spec.js").TaskSpec.agentHomeDirs}, its own and a
     *  resumed row's) — {@link effectiveAgentConfigDirs}'s twin for the home-anchored rows, same purpose, same presence. */
    effectiveAgentHomeDirs?: readonly string[];
    /**
     * The leg refused reads outside its declared directories — its one resolution of
     * {@link import("./task-spec.js").TaskSpec.blockReadsOutsideRoots}: the declaration, or the resumed row's record
     * (`CheckpointState.readBlock`) — as an engine-filled OBSERVATION (never a knob: writing it on a spec does nothing). Same
     * purpose as {@link effectiveReadFace}: a row parked with the seat on resumes with it whatever the resume-side config sends, so a
     * POST-COMPLETION follow-on leg (the verify gate's verifier and fix legs) reads the seat HERE (beside the caller's own `true`: whichever restricts).
     * **In-presence condition:** present (always `true`) iff the leg resolved the seat on; rides any terminal of a leg that ran;
     * absent when the leg did not refuse such reads, and on prepare failures. The stream layer's failure backstop (a leg that throws
     * past its result assembly) carries it too, as it does every posture seat, by the one assembly (`resultPostureSeats`) — once the
     * leg's identity wiring published them; a leg that throws between the end of its prepare and that wiring carries none.
     */
    effectiveBlockReadsOutsideRoots?: true;
    /**
     * The command sandbox requirement this leg ran its commands under — {@link import("./task-spec.js").TaskSpec.sandbox} as judged,
     * with a resumed row's recorded requirement as its floor (`CheckpointState.commandSandbox`, the value this leg's own rows record) —
     * as an engine-filled OBSERVATION (never a knob: writing it on a spec does nothing). Same purpose as
     * {@link effectiveBlockReadsOutsideRoots}: the verify gate's verifier and fix legs run in the boundary read HERE (the caller's stated keys
     * laid over it), so a resume whose config does not send `sandbox` again still runs them inside the parked boundary. A copy: the holder's edits reach nothing.
     * **In-presence condition:** present iff a requirement was stated for the leg (its own or a resumed row's) — `enabled: false`
     * included, so presence alone does not say the commands were sandboxed; rides any terminal of a leg that ran; absent on prepare
     * failures.
     */
    effectiveSandbox?: import("./command-sandbox.js").TaskSandboxSettings;
    /**
     * The leg treated what its execution environment produced as content from outside the deployment's trust boundary — its
     * external-content-target fold: the environment's declaration (`ExecutionEnvCapabilities.externalContentTarget`, undeclared read
     * as outside), a resumed row's record (`CheckpointState.externalContentTarget`), or the later-leg seat a composition hands
     * ({@link import("./runner/contracts.js").RunInternals.externalContentTarget}) — as an engine-filled OBSERVATION. Same purpose as
     * {@link effectiveBlockReadsOutsideRoots}: the verify gate hands it to its verifier and fix legs from HERE, so a resume onto an
     * environment that declares no external target keeps the fold on those legs (the memory face, the environment disclosure).
     * **In-presence condition:** present (always `true`) iff the fold is on; rides any terminal of a leg that ran; absent when it is
     * off, and on prepare failures.
     */
    effectiveExternalContentTarget?: true;
    /**
     * design/178 v2 §2.3 (件①) — the memory VISIBILITY face this leg actually ran under, as an
     * engine-filled OBSERVATION (never a knob: writing it on a spec does nothing). This is the
     * EFFECTIVE face, not the requested one: a refused request never reaches a terminal at all (the
     * whole prepare fails with its governance code), so what this seat answers is "what was actually
     * given" — the delta against the request is directly readable (an org writeScope not explicitly
     * granted collapses to `null` here as it did in the run; a fail-open mount failure reads
     * `memoryless`, never a dressed-up mount).
     *
     * **In-presence condition** (same law as {@link effectiveReadFace}): present on every terminal of
     * a leg that COMPLETED prepare — the memory-less states are answered as their own values
     * (`none` / `memoryless`), so consumers must never read ABSENCE as "no memory"; absence means
     * only "prepare never completed". Delegated children mint their own on their own legs (their
     * request plane can only narrow the parent's frozen org verdict); a resume leg's value is the
     * re-adjudication at resume time (admission runs in every prepare — the current-policy reading,
     * same axis as the read-face seats).
     *
     * Minted AFTER the materialize outcome, not after the admission verdict — the fail-open mount
     * arm sits between the two, and stamping earlier would report a mount that never happened.
     * See {@link EffectiveMemoryScopes} for the per-state field law.
     */
    effectiveMemoryScopes?: EffectiveMemoryScopes;
    /**
     * `turns`/`tokens`/`costMicroUsd` are this task's OWN model usage. `nested` is the summed usage of any
     * delegated sub-runs (sub-agents) it spawned — present only when it delegated. The true total
     * cost is `tokens + (nested?.tokens ?? 0)`; a large `nested` is the multi-agent "~15×" made visible.
     */
    stats: {
        turns: number;
        tokens: number;
        /** design/97 CORE-8 (②): total TOOL CALLS executed (one per `tool_start`) — distinct from `turns` (model
         * rounds; a turn may issue several parallel tool calls). For a CC-style "N tool calls" per-agent row.
         * **v1 fidelity (audit MINOR)**: counted in THIS run leg via the harness dispatch path, so on a DURABLE
         * RESUME it under-reports — the resumed gated call (executed by the resume engine, not the harness) and any
         * cross-slice resource-suspend legs are not folded (turns/tokens/cost ARE folded; toolCalls is per-leg, like
         * the compaction subtotal). OBSERVE-ONLY (never gates budget). The workflow display is unaffected (its agents
         * fail-on-suspend, never durably resume). A `spentToolCalls` ledger fold is a follow-on. */
        toolCalls?: number;
        /** #692 C-b (additive): present (`true`) when the usage figures on this face are a LOWER BOUND rather than a
         *  measurement — at least one model round of the leg reported no usage frame (the brain's `usageMissing`
         *  mark; the same word the per-turn `turn_end` frame carries), or the result was minted by a host / an
         *  orchestration lane that never ran a model round it could measure (a refused spawn's journal entry, a
         *  prepare-time refusal, a synthetic abort). The numeric members stay required and stay what was counted:
         *  `tokens: 0` beside this key reads "unknown", never "free". Absent ⇔ every round reported usage. */
        usageMissing?: true;
        /** Prompt (input) tokens that MISSED the prefix cache, summed across the task's turns and normalized
         * across providers (Anthropic already reports `input_tokens` this way; OpenAI/vLLM include the cache
         * in theirs, so the subsets are removed). Mutually exclusive with `cachedTokens`/`cacheWriteTokens`;
         * the three of them sum to `totalInputTokens`.
         *
         * **RB-457-a (BREAKING at 3.0.0)**: this used to carry the cache-INCLUSIVE total, which collides with
         * the Anthropic protocol's identically-named quantity — a consumer computing
         * `cachedTokens / (promptTokens + cachedTokens)` double-counted the cache subset and reported
         * `h/(1+h)` (a 98% hit rate surfaced as 49.5%). Use `totalInputTokens` for the old value; use
         * `cacheHitRate` rather than recomputing a ratio. */
        promptTokens?: number;
        /** Prompt tokens served from the model's prefix cache (a cache HIT), summed over the task's
         * turns — when the gateway reports it (vLLM/OpenAI `prompt_tokens_details.cached_tokens`,
         * DeepSeek `prompt_cache_hit_tokens`, Anthropic `cache_read_input_tokens`); a call that did not report it adds nothing
         * and marks {@link cacheReadUnreported}. */
        cachedTokens?: number;
        /** Prompt tokens written to the cache at either lifetime (Anthropic `cache_creation_input_tokens`), summed over the calls that
         *  reported it; the OpenAI-shaped wires do not report it ({@link cacheWriteUnreported}). {@link cacheWriteTokensLong} is the
         *  one-hour part of it. */
        cacheWriteTokens?: number;
        /** The prefix-cache hit rate for this task, ∈ [0,1], over the model-call LANES whose every call reported what the ratio
         * needs (the main loop, and each side-call lane — compaction, classifier, mod, advisor — judged separately):
         * `(cachedTokens − Σ excluded.cachedTokens) / (totalInputTokens − Σ excluded.totalInputTokens)` over
         * {@link cacheHitRateExcludes}. Cost-critical; a low value on a multi-turn task means the cacheable prefix is unstable
         * (see `design/09`). Track it per task and trend it per session. Undefined when no complete lane presented input —
         * a cache count the provider did not report is UNKNOWN and is never read as a 0% hit.
         * **Prefer this over recomputing a ratio** — it is the one place the denominator is defined. */
        cacheHitRate?: number;
        /** The lanes left out of {@link cacheHitRate} — a lane some call on which did not report its cache reads (or, where the
         *  provider's input excludes the cached parts, its cache writes), or reported no usage — each with what it contributed to
         *  {@link cachedTokens} / {@link totalInputTokens}, so the rate's operands are those totals minus these. Absent ⇔ no lane was
         *  left out. On a multi-leg composition's stats a lane is listed when it was left out in any leg (the amounts are those legs'). */
        cacheHitRateExcludes?: readonly {
            readonly lane: import("./runner/side-call-account.js").UsageLane;
            readonly cachedTokens: number;
            readonly totalInputTokens: number;
        }[];
        /** Present (`true`) when some model call of the task did not report its cache reads: {@link cachedTokens} is then the counted
         *  sum, not a measurement (a call's unreported count adds nothing to it). Absent ⇔ every call reported them. */
        cacheReadUnreported?: true;
        /** Present (`true`) when some model call of the task did not report its cache writes (the OpenAI-shaped wires never do):
         *  {@link cacheWriteTokens} is then the counted sum, not a measurement. Absent ⇔ every call reported them. */
        cacheWriteUnreported?: true;
        /** The cache-INCLUSIVE prompt total across the task's turns — `promptTokens + cachedTokens +
         *  cacheWriteTokens`, matching OTel `gen_ai.usage.input_tokens`. This is the
         *  quantity cost is computed from, the denominator of `cacheHitRate`, and the figure to use for
         *  "how much context did this task present" (window/budget views). `promptTokens` carried
         *  this value up to 2.13.x; it now carries the cache MISS count and this field is its own
         *  accumulator rather than an alias. Optional BY DESIGN, like every usage field on this stats
         *  face: undefined means the gateway reported no usage (and pre-3.0.0 persisted rows never had
         *  it) — the event-face `turn_end.usage.totalInputTokens` is required because there the whole
         *  `usage` object is already conditional (intentional asymmetry, not a gap). */
        totalInputTokens?: number;
        /** Completion (output) tokens summed over the task's turns. */
        outputTokens?: number;
        /** The part of {@link cacheWriteTokens} written at the 1-hour lifetime (Anthropic `cache_creation.ephemeral_1h_input_tokens`),
         *  summed over the calls that stated the split — a SUBSET of `cacheWriteTokens`, never added to it. The writes of a call that
         *  stated no split (a wire that reports only the total) are in `cacheWriteTokens` alone, their lifetime unknown, priced at the
         *  five-minute price; the one-hour part is priced at the model's one-hour write price (`Model.cost.cacheWriteLong`; absent ⇒ the
         *  five-minute one). 0 when no call stated a one-hour part. */
        cacheWriteTokensLong?: number;
        /** Authoritative (and only) cost figure: **integer micro-USD** (1e-6 USD), computed in core from
         *  injected pricing — integer to avoid float-accumulation error in billing. (design/157 B19: the
         *  float-USD twin was removed; divide by 1e6 at the display edge if you need USD.)
         *  **ABSENT when any spend was unpriced** (RB-368): the serving model had neither a
         *  `RunnerDeps.pricing` entry nor a `Model.cost` declaration — an unpriced run reports NO cost
         *  rather than a fabricated 0, so "no price table" stays distinguishable from "declared free"
         *  (an explicit all-zero `Model.cost` still reports 0). `costBreakdown` is omitted with it. Each call is priced at the tier
         *  that served it: a call whose usage said `speed: "fast"` at its table's fast tier (`Model.cost.fast` /
         *  `ModelPricing.fast`); such a call on a table without a fast tier is unpriced spend, as above. */
        costMicroUsd?: number;
        /** Wall time, in milliseconds, of this run's own main-loop model calls (the reference result's `duration_api_ms`), summed over its turns — the sum of the per-turn
         *  `turn_end.usage.apiDurationMs` and of the `brain.call` trace rows' `ts − callStartedAt` (one measurement, three faces). Each call
         *  is timed from the moment the engine hands the request to the brain to its final message; a call with no stamp adds 0 (a hop a
         *  fallback walk left behind), and the compaction / classifier / mod / advisor calls are not timed at all. A
         *  delegated sub-run's time is its own leg's `apiDurationMs`: {@link nested} carries tokens, turns, tasks and cost, not time. A
         *  resumed leg reports its own calls (unlike `tokens`, no prior slice is folded in). On a composition's stats (cascade, repair
         *  loop, verify) it is the sum over its legs. Present on every result of a leg that ran; absent where no leg ran. */
        apiDurationMs?: number;
        /** How many of this run's main-loop model calls the provider served at fast speed (their usage said `speed: "fast"`,
         *  `Usage.speed`) — the same judgment that prices those calls at the fast tier of the model's price table (`cost.fast`;
         *  {@link costMicroUsd}). Absent when none was. On a composition's stats it is the sum over its legs. */
        fastSpeedCalls?: number;
        nested?: NestedUsage;
        /**
         * Post-task memory-consolidation usage (design/41), when consolidation ran. Its own line item —
         * **kept out of `tokens`/`costMicroUsd` and excluded from the budget gate** — so a completed task is
         * never retroactively flipped to a budget terminal by reconcile cost. `tokens` is 0 when every note
         * took a cheap (no-LLM) path; `applied` counts store mutations the pass made (cheap-path
         * UPDATE/DELETE + applied LLM decisions) so callers can observe reconcile efficacy without re-reading
         * the store. Absent when consolidation was disabled / no-op / produced no notes. Populated
         * asynchronously by whatever engine-plane pass produced it (consolidation is fire-and-forget).
         */
        memory?: {
            tokens: number;
            costMicroUsd: number;
            applied: number;
        };
        /**
         * design/100 §E12 — the prompt-suggestion pass's usage, when it ran. Same budget-excluded side-observable
         * treatment as {@link memory}: **kept out of `tokens`/`costMicroUsd` and excluded from the budget gate**, so
         * the (fire-and-forget, post-completion) suggestion pass can never retroactively flip a done task to
         * a budget terminal. Absent when `suggestNextPrompts` was off / produced nothing. Populated asynchronously —
         * see {@link TaskStream.suggestions}.
         */
        suggestions?: {
            tokens: number;
            costMicroUsd: number;
        };
        /**
         * TB telemetry B2: counters for the engine's wall-clock/deadline mechanisms, so a
         * bench/monitoring consumer can judge from the RESULT whether they actually engaged (refute-130
         * lesson: "did P1/P2 fire" was unanswerable from artifacts). Present only when at least one
         * mechanism engaged this leg; absent = none did (byte-compatible).
         */
        mechanisms?: {
            /** design/132: HOW MANY natural-end final-verification injections fired this run — 1 = the R9 one-shot
             *  only, 2 = R9 + the oracle-grounding re-entry (hard cap). Present iff at least one fired. */
            finalVerifyInjections?: number;
            /** design/133: number of attachment blocks injected this run — turn-boundary bundles
             *  (todo/task reminders, changed-files notes, plan-mode re-reminders, listing drift frames;
             *  each bundled block counts once) PLUS the [c209-C] first-frame listing deliveries riding the
             *  first user message (agent_listing / skills_listing — counted only when the first prompt was
             *  actually sent, R2 C5: a hook-blocked / budget-rejected run counts zero). */
            attachmentsInjected?: number;
            /** design/164: how many distinct LIMIT-APPROACH sentences a model request carried this run (0..2 — the
             *  "start converging" one and the "deliver now" one, each counted once however many requests carried it;
             *  a crossing straight past the second threshold counts 1). Absent when none was carried, which is also the
             *  answer for a task that armed no limit axis at all. */
            approachNoticesSent?: number;
            /** Repetition telemetry (2026-07-10 observability): brain-side degenerate-repetition
             *  stream CUTS this run (each pairs with an `output.degenerate`-classified turn). */
            repetitionCuts?: number;
            /** Repetitions that landed in a detection window but were SPARED by a 2e1c161 structural
             *  allowance (code-line shape / divider run) — the raw material for judging the allowance. */
            repetitionSpared?: number;
            /** Per-event details (turn + rule + period/reps + a ≤120-char segment sample), capped at 20
             *  entries — `repetitionCuts`/`repetitionSpared` keep the true totals past the cap. */
            repetitionEvents?: Array<{
                turn: number;
                action: "cut" | "spared";
                rule: "char-run" | "unit-loop";
                period: number;
                reps: number;
                segment: string;
            }>;
            /** design/319 (B ticket, G9② observation seat) — reminder-disclosure trigger counts for the
             *  leg, keyed `<outlet>.<form>`: outlets `read` / `notebook` / `pdf` / `mcp` / `webFetch` /
             *  `webSearch`; forms
             *  · `bare` (bare-form trailer appended — reminder-shaped text without this session's mark),
             *  · `marked` (marked-form trailer — never throttled),
             *  · `bare_throttled` (a bare trailer suppressed by the 60s per-key window),
             *  · `defused` (an MCP/web segment's exact-mark bytes were rewritten — the lane's one sanctioned
             *    byte change, always paired with a `marked` disclosure),
             *  · `envelope` (text shaped like one of the engine's OTHER authority envelopes — the DISCLOSED
             *    subset is `task-notification` / `new-diagnostics` / `user_memory` / `skills` /
             *    `total_tokens` / `instruction-files`; `scope` is
             *    fenced but not disclosed, since `<scope>…</scope>` is also an ordinary build-file element.
             *    That family carries no mark, so its sentence is positional rather than byte-testable. It
             *    rides ON the reminder copy when both families hit, so `envelope` can be bumped alongside
             *    `marked`/`bare` on one result),
             *  · `envelope_throttled` (an envelope sentence suppressed by its OWN 60s window — the two
             *    families throttle independently, so one may emit while the other reports suppression),
             *  · `mark_echo` (observation ONLY, never a disclosure: the session's mark VALUE appeared in
             *    external bytes with no reminder-shaped tag around it, so the tag-grammar detector cannot
             *    reach it. Nothing is rewritten and no trailer is appended; it is an upper bound on model
             *    exposure for the lanes that do not defuse).
             *  Present only when ≥1 key is non-zero. The map is OPEN by type — fold by key rather than
             *  switching on a closed set. This is the D-4/D-6 re-ruling data (defuse/trailer widening to
             *  Read/Bash/Grep): a reading, never a gate. */
            reminderDisclosures?: Record<string, number>;
        };
        /**
         * design/91 — **human-review burden** (design/89 §2.4 C2 axis). The wall-clock time a task spent waiting
         * on a human at an approval gate, plus the count, bucketed by `gate.kind`. Both human-review paths are
         * captured: the **synchronous** `onAsk`/`resolveAsk` await (`t_return − t_call`) and the **durable**
         * suspend→resume wait (`resumedAt − checkpoint.suspendedAt`, including the human's offline time); a
         * multi-leg suspend/resume chain **accumulates across legs**. All timestamps come from {@link RunnerDeps.now}.
         *
         * **NOT an LLM cost (load-bearing, design/91 §1):** human-review time is wall-clock latency, not token
         * spend — it is **NEVER folded into `costMicroUsd`, `costBreakdown`, or the budget gate** (the same
         * budget-excluded side-observable treatment as {@link memory}). Adding human seconds to token µUSD is the
         * design/89 §2.1 "apples + oranges" trap; the supervisor Pareto frontier keeps `(token cost, human seconds,
         * correctness)` as three SEPARATE axes.
         *
         * @contract stats.human_review.kept — present exactly when a ledger was kept for this result: every leg the
         * engine prepared keeps one, so every result such a leg settled carries the member, and a leg no gate waited on a
         * person in answers `{ count: 0, totalWaitMs: 0, gates: [] }` — the zero is a measurement, not a default. Absent
         * means one thing: no ledger was kept — a result the engine assembled when the leg's prepare or settle threw, a
         * composition's own terminal that dispatched no leg, or a result an engine older than this rule settled. A
         * composition's result (cascade, repair loop, verify) carries the sum of its legs' ledgers, present when any leg's
         * result carried one. Every checkpoint row the engine mints carries the chain's ledger in the same shape
         * ({@link import("./checkpoint-store.js").Checkpoint.humanReview}).
         */
        humanReview?: {
            /** Number of asks a party answered (each synchronous `resolveAsk` return + each durable resume of an
             *  approval suspend): a person, or the deployment's policy, host or engine, named per row by `gates[].party`. Equals `gates.length`. */
            count: number;
            /** Cumulative wall-clock the approval gates were alive (ms), summed across all legs. Equals `Σ gates[].waitMs`. */
            totalWaitMs: number;
            /** One entry per ask a party answered, in order. `kind` = the gate's discriminant (`human` /
             *  `irreversible_ask` for durable; `human` for a synchronous ask). `decision` = the adjudication when
             *  known (`allow`/`deny`). design/99 MF-24: `toolName` = the gated tool; `toolArg` = a
             *  SHORT, SECRET-SCRUBBED one-line summary of its input (the same `primaryActivityArg` boundary as the MF-W
             *  activity arg) — the permission-denial ledger's "denied: Bash(rm …)" display. `toolArg` rides every mint
             *  that has the input in scope: the synchronous ask from the request, the durable-resume gate from the
             *  checkpoint's `pendingAction`; `toolCallId` names the call the row gated (absent = not joinable); `party` names who ended the
             *  wait as the engine's record states it — see {@link HumanReviewGateRow.party}, and `approver` which seat of it ({@link HumanReviewGateRow.approver}): a row says WHAT was gated, and by whom only through them. */
            gates: HumanReviewGateRow[];
        };
        /**
         * design/80 D-E-core: a thin FINANCE TAXONOMY of the LLM-derived costs the engine actually prices,
         * decomposing the task's spend into report categories (derived from existing cost sources — no new
         * persisted structure). **CORE = LLM-token-derived ONLY** — the deployment SERVICE adds the infra axes it
         * owns (tool-call / sandbox-walltime / egress; it has the k8s cost data) and composes them with this for
         * the supervisor surface. Each category is ≥ 0 and the LLM parts reconcile to the independently-summed
         * LLM total: `llmRootMicroUsd + compactionMicroUsd === costMicroUsd` and the fully-reconciled
         * spend is `costMicroUsd + nested.costMicroUsd` — `costMicroUsd` deliberately EXCLUDES nested
         * subagent cost (it lands in `nested`, see assemble-result.ts), so `nestedSubagentMicroUsd` sits
         * OUTSIDE the costMicroUsd identity, not inside it (measured correction: the previous wording
         * `llmRoot + nested + compaction === costMicroUsd` only held when nested was 0).
         * Present whenever stats are assembled, EXCEPT when `costMicroUsd` is absent for unpriced spend
         * (RB-368) — the taxonomy would partition a fabricated total, so it is omitted together with it.
         */
        costBreakdown?: {
            /** Root-agent LLM cost (micro-USD) = `costMicroUsd − compactionMicroUsd` (the sub-category folded into
             *  it): the advisor consultations the root agent made are in it. NOT minus nested — nested cost is never folded into `costMicroUsd` (it lands in `nested`).
             *  ⚠️ APPROXIMATE on a multi-slice `resource_limit` RESUME (design/80 D-E-core): the
             *  durable resource ledger persists only the AGGREGATE prior spend, not its compaction subtotal, so
             *  prior slices' compaction folds in HERE rather than into `compactionMicroUsd`. The TOTAL (`costMicroUsd`)
             *  stays exact; only this llmRoot-vs-compaction split is per-leg-approximate across resource slices. */
            llmRootMicroUsd: number;
            /** Delegated sub-agent (nested) LLM cost (micro-USD) = `nested?.costMicroUsd ?? 0`. */
            nestedSubagentMicroUsd: number;
            /** design/100 §E12 — prompt-suggestion pass LLM cost (micro-USD) = `suggestions?.costMicroUsd ?? 0`; filled
             *  asynchronously after the (post-completion) pass (0 until then). A separate, budget-excluded line. */
            suggestionsMicroUsd?: number;
            /** Within-task compaction LLM cost (micro-USD) — part of `costMicroUsd`, so subtracted from root.
             *  ⚠️ See {@link llmRootMicroUsd}: under-reports prior slices' compaction on a multi-slice resource resume. */
            compactionMicroUsd: number;
            /** The model calls made beside the main loop — the permission classifier's, mods' `$.model.complete` and the advisor
             *  tool's consultations — in micro-USD. An **"of which" line**, not a partition member: this cost is part of `costMicroUsd` and stays INSIDE
             *  {@link llmRootMicroUsd}, so `llmRootMicroUsd + compactionMicroUsd === costMicroUsd` keeps holding. Present once
             *  at least one such call was booked this leg (absent ⇒ none; a result with no such call is unchanged). A call
             *  whose reply carried no usage marks `stats.usageMissing` instead of adding here.
             *  ⚠️ Like {@link compactionMicroUsd}, per-leg on a multi-slice `resource_limit` RESUME: the prior slices' side-call
             *  spend is inside the exact `costMicroUsd` and `llmRootMicroUsd` but not in this line. */
            sideCallMicroUsd?: number;
        };
    };
}