UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

3,633 lines • 282 kB
/**
 * The prepare CONTRACTS — the types that cross between `prepareTask` and the phase modules it drives.
 *
 * WHY THEY LIVE HERE. Every one of these was declared inside `prepare-task.ts`, the file that PRODUCES
 * them, so any module needing to name one had to import its own driver. Thirteen such edges had
 * accumulated by the time the dependency-direction gate was written: six phases reaching up for a
 * contract type, the vocabulary file reaching up for two more through inline `import()` type
 * positions, a phase reaching sideways for a pure path helper, and the orchestrator and its own
 * consumer naming each other. A contract belongs BELOW both the producer and the consumer; that is
 * all this file is.
 *
 * It declares TYPES ONLY — nothing is emitted, so it sits on the vocabulary floor beside `types.ts`
 * without adding a runtime edge anywhere. The blocks below are verbatim moves, in their original
 * order, JSDoc included, so the move stays auditable as a move.
 */
import type { HumanReviewGateRow } from "../task-result.js";
import type { RepairBundle } from "../../agents/repair-loop.js";
import type { SubagentRetainLedger } from "../../agents/retain-ledger.js";
import type { BrainCallGuardrailRef } from "../../brain/timeout.js";
import type { ActiveWorktreeSession, AgentHarness, AgentMessage, AgentTool, AnnouncedListingSnapshotInput, ExecutionEnv, LoopTerminalReason, RowAdmission, ThinkingLevel } from "../../internal/harness.js";
import type { Model } from "../../internal/llm.js";
import type { WorkflowSizeGuideline } from "../../orchestration/workflow-size-guideline.js";
import type { ToolManifestRow } from "../../prompt-assembly/tool-catalog.js";
import type { EngineText } from "../../prompt-assembly/engine-text.js";
import type { CwdRef, ContainmentFace } from "../../tools/fs/index.js";
/** A leg's WRITE face: the face in force (read per call, following the mode's face) and whether a seat or a clamp DECLARED the fence (a checkpoint row records it; a resume keeps it). */
export interface WriteFaceSeat {
    readonly inForce: () => ContainmentFace;
    readonly fenced: boolean;
}
/** The two faces the children of a leg that narrowed only its own hands (`TaskSpec.ownHandsReadOnly`) are handed — resolved
 *  without that narrowing (`prepare-hands-readface.ts` `carriedFacesOf`). */
export interface CarriedFaces {
    readonly read: ContainmentFace;
    readonly write: WriteFaceSeat; /** a live seat opens the write face, the mode aside */
    readonly writeSeatOpen: boolean;
}
import type { MaterializedA2a } from "../a2a.js";
import type { CompactionForkContext, RapidRefillState } from "../auto-compaction.js";
import type { AutoModeArmingRecipe } from "../auto-mode-arming.js";
import type { AutoModeDecider, AutoModeDenialTracker, DenialLimitFallbackFace } from "../auto-mode.js";
import type { SettlementKind } from "../gate-outcome.js";
import type { AskClass } from "../ask-origin.js";
import type { Checkpoint, CheckpointState, CheckpointStore, CheckpointToken, PendingSteerEntry, PlatformLimitReason, ReopenReason, ResourceLedger, ResourceLimitReason, ResumeOutcome, SerializedCheckpointState } from "../checkpoint-store.js";
import type { ExecutionOutcomeRecordWord } from "../checkpoint-execution-record.js";
import type { ClearedProjectionLedger, MicroCompactMachine, OccurrenceIndex } from "../context-edit.js";
import type { ModBus } from "../mods/kernel/index.js";
import type { LegModBus, LegMods } from "../mods/stations.js";
import type { HookInvocationIdentity, OrgGateVerdict, PermissionDeniedPayload, PostToolBatchCall, ToolGateInput } from "../hooks.js";
import type { LegNotice } from "../leg-identity.js";
import type { MaterializedMcp } from "../mcp.js";
import type { MemoryEngine } from "../memory-engine/engine.js";
import type { ResolvedSkillListingBudget } from "../skill-listing-budget.js";
import type { HarvestReport, MemorySessionHandle } from "../memory-engine/types.js";
import type { SessionPermissionRules } from "../session-policy-store.js";
import type { SafeNotifier } from "../safe-notify.js";
import type { RecoveredOrphan } from "../session-reconcile.js";
import type { SessionStore, StoredSession } from "../session.js";
import type { TaskOutcome } from "../task-outcome.js";
import type { SessionBoundSpecMember } from "../task-spec-members.js";
import type { ModelPricing } from "../pricing.js";
import type { PushQueue } from "../push-queue.js";
import type { SessionAddress, SessionCompletionLane, SystemInjectionPriority, TaskNotificationPayload, TaskNotificationSink } from "../task-notification.js";
import type { OnAsk, PermissionResult, ToolCallRequest, ToolPolicy } from "../tool-policy.js";
import type { PlacementTarget, RemoteExecutionEnv, SnapshotId, WorkspaceHandle } from "../remote-env.js";
import type { ToolDisclosureManifest } from "../trace.js";
import type { AgentDefinition, Brain, CompactOutcome, ModelRef, ModelRoles, NestedUsageAccum, PermissionMode, RunnerDeps, ShellGateDoctrine, TaskEvent, TaskEventIdentity, TaskResult, TaskSpec, TaskStream, ToolActivity, ToolEffect } from "../types.js";
import type { InheritedAutoModeFace, PermissionModeController } from "../mode-policy.js";
import type { WiringManifest } from "../wiring-manifest.js";
import type { SkillGateSeats, SkillGrantLane, SkillGrantRecord, SkillGrantSource } from "../skill-grant.js";
import type { BudgetAxis } from "./assemble-result.js";
import type { GitStatusLaneRef } from "./git-status-frame.js";
import type { SessionReadFileStates } from "./session-read-file-states.js";
import type { LegModeCeiling, SessionModeSeats } from "./session-mode-seats.js";
import type { BlockedRef, OutputRef, SkillListingEntry } from "./synthetic-tools.js";
import type { AttachmentSource } from "../attachment-source.js";
import type { createAttachmentState, WriteFamily } from "./turn-attachments.js";
import type { SideCallBook } from "./side-call-account.js";
import type { ModelFallbackSeat } from "./model-fallback-seat.js";
import type { DrainedLegFrame, LegAt } from "./leg-frame.js";
import type { cacheFamilyOf } from "./usage-accounting.js";
import type { RewindOutcome } from "./rewind-outcome.js";
/** The frozen task-start copies of the caller's tool-face control arrays (the config-doors phase reads them through
 *  `readToolFaceLists`, synchronously, before the first await); the driver compiles the selector from them ({@link ToolFaceSnapshot}). */
export type { ToolFaceLists } from "../tool-face-lists.js";
/**
 * The leg's tool face: its compiled tool selector (the ONE answer to "may this run use this tool" — the roster valve, every
 * "is X available" mount decision, the MCP refresh and re-dial, the deferred-search lane, and the ceiling every child inherits)
 * and the frozen disclosure lists. Named here rather than reached for through a phase's Result — an indexed access into a
 * sibling phase's Result is a sideways dependency wearing a type's clothes.
 */
export interface ToolFaceSnapshot {
    selector: import("../tool-face.js").ToolSelector;
    defer: readonly string[] | undefined;
    alwaysLoad: readonly string[] | undefined;
    /** The model-gate restore selector ({@link TaskSpec.restoreGatedTools}), fourth
     *  seat of the same frozen task-start snapshot: the gate decision and the delegation carrier
     *  read THIS, never the live spec. */
    restoreGated: readonly string[] | true | undefined;
}
/**
 * The once-per-session announcement ledger's OPERATOR SINK as the phases see it: the
 * `RunnerDeps.onError` signature, deduplicated per (code, text) across the session. The ledger itself
 * (load, digests, settle) lives in announce-once-ledger.ts; a phase that announces once invokes only
 * this member, so the member's shape is declared here — below every phase — rather than reached for
 * sideways as the ledger module's type.
 */
export interface AnnounceOnceSink {
    onError: NonNullable<RunnerDeps["onError"]>;
    /**
     * The same operator sink for a fact about the DEPLOYMENT rather than the conversation (a built-in tool pair that
     * declines to mount because of the deployment's own selector or roster): deduplicated per RUNNER by
     * `(code, text)` instead of per session, because a serving layer that opens a fresh session per request would
     * otherwise repeat a standing configuration fact on every request. Independent of the session record — it
     * writes nothing to the transcript. Same signature as `RunnerDeps.onError`.
     */
    onErrorOncePerRunner: NonNullable<RunnerDeps["onError"]>;
}
/** Static per-tool irreversibility tier, resolved at prepare time by the safety scan. */
export type IrreversibilityTier = Map<string, "never" | "maybe" | "always">;
/** Declared reversibility probes by tool name, collected by the safety scan on the same pass. */
export type ReversibilityProbes = Map<string, NonNullable<TaskSpec["tools"]>[number]["reversibilityProbe"]>;
/**
 * The prepare-FAILURE cleanup stack. A phase that acquires a resource (an execution env, an MCP
 * client, an A2A client) pushes its release the moment the handle exists, so a throw further down
 * cannot leak it — before this the driver could only see a half-acquired handle by hoisting a `let`
 * to the top of the function and hoping every acquisition site remembered to assign it.
 *
 * IT IS ARMED ONLY ON THE FAILURE PATH. The driver calls {@link RollbackStack.commit} before it
 * builds `Prepared`: past that point the stack is empty and every resource's cleanup belongs to the
 * Runner's finish/teardown, which is where a SUCCESSFUL run's resources have always been released.
 * The catch path calls {@link RollbackStack.unwindAll}, which runs the cleanups in reverse order,
 * each exactly once, none of them able to stop another — a bounded settle, the same posture the
 * teardown leg already uses. NEVER call unwind on the success path.
 *
 * The detach guard for an owned execution env and the worktree-isolation check stay with the DRIVER: a phase pushes, it does not destroy, because the driver's reference is
 * the authoritative one and a phase-local rebind could never reach it.
 */
export interface RollbackStack {
    /** Register one cleanup for the failure path. Called immediately after the handle is acquired. */
    push(cleanup: () => void | Promise<void>): void;
    /** Disarm: prepare succeeded, so ownership passes to `Prepared` and the stack is emptied. */
    commit(): void;
    /** Failure path only — run every registered cleanup in reverse order, each once, none blocking another. */
    unwindAll(): Promise<void>;
}
/**
 * The run's view of deployment usage governance, built once at prepare when
 * `RunnerDeps.usageWindows` + `usageWindowStore` are both wired (absent otherwise, so every consumer is
 * an explicit `!== undefined` test and an ungoverned deployment executes not one extra line).
 *
 * Both methods are called SEQUENTIALLY by the run loop (entry check, then one commit per turn boundary,
 * then one final commit) — the delta bookkeeping in `commit` assumes that and is not a concurrency
 * primitive.
 */
export interface UsageGovernance {
    /** The ledger key this run is governed under — the principal, or the shared global key. */
    readonly key: string;
    /** Does any governed window carry a MONEY ceiling? Read by the run loop's pricing seats: only a
     *  cost-governing deployment has to treat an unevaluable price table as unpriced spend. */
    readonly governsCost: boolean;
    /** Ms the caller must wait before ANY window would admit work again, or `undefined` when none is
     *  exhausted as of `now`. Reads the ledger; propagates a store failure (an unreadable ceiling must not
     *  read as an open one). */
    check(now: number): Promise<number | undefined>;
    /**
     * Charge whatever of the run's cumulative spend has not been charged yet. Takes the run's CUMULATIVE
     * totals rather than deltas so no caller can double-charge by calling twice, and so a caller that skips
     * a boundary loses nothing.
     *
     * `cumulativeCost` is the MONEY half (integer micro-USD, `stats.costMicroUsd`). Pass `{ unpricedBecause }` (the first
     * unpriced call's cause, `RunState.telemetry.unpricedCause`) when the run's spend has no cost figure at all — a deployment
     * governing a `maxCostUsd` window then REFUSES here, naming that cause, rather than charging the fabricated 0 that would let
     * the ceiling silently stop applying. A token-only deployment ignores the argument entirely.
     */
    commit(cumulativeTokens: number, cumulativeCost: number | {
        readonly unpricedBecause: string;
    }, now: number): Promise<void>;
}
/**
 * The run's turn-start file-history BOUNDARY seat. `begin(entryId)` starts the capture for the turn's own entry — the run's
 * first committed row of a person's input (origin `human_input`; first-wins: at most one boundary per turn incarnation, DV-4);
 * `settle()` awaits the in-flight capture's settle and is the caller's LEASE CLOSE (awaited before the next tool executes) as
 * well as the finish-tail durability await. The capture is bounded by a 30s timeout whose abort FENCES the attempt (the
 * store's `boundaryPublishVerdict` guarantees a timed-out capture never publishes); failure is disclosed via
 * onError(phase:"rewind") and, to the person, `rewind.boundary_unrecorded`, and NEVER blocks the turn — a turn whose capture
 * failed simply has no boundary (the reference behaves the same), and there is no mid-turn re-capture (the store's spent
 * lease refuses it with zero reads).
 */
export interface FileHistoryBoundarySeat {
    begin(entryId: string): void;
    settle(): Promise<void>;
}
/**
 * The commit-side facts of the run's ONE durable pause: the terminal cause the result assembles
 * ({@link import("../types.js").PausedCause} — gate, token, checkpoint id, restore mode), the COMMITTED scope
 * (read verbatim by the reap/cancel path — never re-derived from the spec, which the cross-scope re-scope
 * may no longer match), and the id of the tool call the park is holding (only a `tool_approval` pending
 * action parks ON a call; absent, never guessed, for the kinds that hold none).
 */
/** See {@link Prepared.undeliveredContinuationRef} — `parkedSteers` is in ISSUE order, and the wake message rides it with no `seq` (no store minted one). */
export interface UndeliveredContinuation {
    parkedSteers: Array<Omit<PendingSteerEntry, "seq"> & {
        seq?: number;
    }>;
    orphanTasks: Array<{
        id: string;
        description?: string;
    }>;
}
export interface CommittedPause {
    cause: import("../types.js").PausedCause;
    scope: string;
    gatedCallId?: string;
    /** The store the park's row was put into and the grant holder that put carried: every later write the run makes on this park (the
     *  parked-input migration, the stream's reap) reads them here, never a store or a holder of its own. */
    writes: ParkWrites;
}
/** The pair a park's own writes carry: the store its row lives in, and the leg's write holder (`writeHolderOf`; absent ⇒ none). */
export interface ParkWrites {
    readonly store: import("../checkpoint-store.js").CheckpointStore;
    readonly holder?: string;
}
/** The session's date anchor as prepare read it off the branch. The system-prefix date is frozen per
 *  SEGMENT — from session start, or from the latest landed compaction, to the next one. */
export interface DateAnchorRead {
    /** The anchor written for the current segment; undefined ⇒ the leg renders today and anchors it. */
    current: {
        prefixDate: string;
        announcedDate: string;
    } | undefined;
    /** The current segment: the nearest compaction entry's id, null before the first compaction. */
    segment: string | null;
    /** The request head the anchor for the current segment recorded (the head of the epoch the session last
     *  opened); undefined ⇒ none recorded — the leg compares nothing and anchors its own. */
    head?: PrefixHeadDigests;
    /** Which store content the current segment's memory band was composed from; undefined ⇒ none recorded — the leg reads
     *  the store live and anchors what it read. */
    memory?: MemoryTailSnapshot;
    /** The head the session's legs last anchored, whatever segment it was written for (across a compaction too): what a
     *  leg's own head is compared with to declare a leg-start change; undefined ⇒ the branch holds none. */
    lastHead?: PrefixHeadDigests;
}
/** Which store content the memory band of one segment was composed from, as the epoch anchor names it — never the content
 *  itself: the bytes (`IndexCopy`, each plane's raw index text and the marked bit) are kept in this process's memory only
 *  and found by both members together. A leg of the segment that finds them composes the band from them (its
 *  configuration-driven parts — the write instruction or a notice, the disciplines — are each leg's own), so a memory write
 *  moves the system prompt at the next segment; a leg that does not (another process, a moved key) reads the store live. */
export interface MemoryTailSnapshot {
    /** Short digest of what the band may show (each plane's memory directory, scopes and write scope, whether the engine trusts
     *  its index, whether the mount reads the committed view only, the store state — the entries withheld as challenged, the
     *  erasure count): a leg whose key differs — memory mounted differently, a withholding or an erasure since — reads live. */
    mount: string;
    /** The sha256 of the content's bytes (`indexCopyDigest`). */
    digest: string;
}
/** A leg's request head as the session's epoch anchor keeps it: one short unsalted digest per prompt block (by block
 *  id) and the tool table's wire digest — what a later leg compares its own head with to name the segments that moved. */
export interface PrefixHeadDigests {
    blocks: Readonly<Record<string, string>>;
    tools: string;
}
/**
 * One engine frame whose commit waits for the receipt of the message carrying it.
 *
 * @contract frames.commit_on_receipt — an engine-minted frame that rides a user message (the git-status
 * frame, a leg's first-request frames, every turn-boundary attachment) is recorded —
 * an announced set or value, a drained pending entry, a once digest, a window's stamp, a latch, its echo and count
 * — ONLY when the run loop's `message_end` walk sees a persisted user entry whose text equals the carrying text it
 * was registered with; every receipt with that text settles on that one entry. Collection records nothing: a
 * message that never reaches the transcript (a pre-append failure, a suppressed or undrained steer, a leg that
 * ends first) leaves the frame unannounced, and the next boundary or leg renders it again. A lost receipt costs a
 * duplicate frame, never a fact the model was recorded as told and was not.
 */
export interface FrameReceipt {
    /** The carrying message's exact text (its first text block) — the receipt's match key. */
    text: string;
    /** Which frame this receipt settles. No collector renders a frame whose receipt is still pending (the frame is on
     *  its way, not yet in the transcript) — the one reading is `frameCarried` (compaction-restate.ts). */
    source: "git_status" | "posture" | "advisor_tool" | "language" | "sandbox_instructions" | AttachmentSource;
    /** Runs inside the `message_end` walk: advances the run-local record and parks any session write for the next
     *  serialization point. Synchronous, except a step that must read the session first (a changed-files notice's
     *  announcement, {@link announceWhenCarried}): it returns a promise the walk's handler hands back, so the
     *  announcement lands before the next listener reads the event. */
    commit: (entryId: string) => void | Promise<void>;
}
/**
 * The limit-approach notice's leg seat. The turn boundary measures the axes and records the HIGHEST threshold the tightest
 * one has crossed, with the sentence that crossing froze; the request-build handler appends that one sentence to the end of
 * every request built after it — never steered, never written to the transcript, one sentence per request (a higher crossing
 * replaces the lower one, it is not added to it). `announce` is the crossing's echo and count, run by the first request that
 * carries it and then cleared, so each threshold is counted once however many requests carry it.
 */
export interface LimitApproachSeat {
    crossed?: {
        index: 0 | 1;
        text: string;
        announce?: () => void;
    };
    /** Where the last request built in this leg carried the sentence (its index in the handler's view) and which one it carried.
     *  The next request carries it at its own end, so the sentence leaves the previous request's last message: the handler
     *  declares the move from there (`history_rewrite` from the ledger's `"tail"`), and the leg's end declares it for the
     *  session's next leg, whose first request no longer carries it. */
    carried?: {
        at: number;
        text: string;
    };
}
/** The leg's frame-receipt ledger — see {@link FrameReceipt}. `listingSnapshotOwed` is the parked
 *  announced-listing snapshot write (a session append from inside the walk would race the loop's own
 *  next transcript append); the boundary's end and the prompt's settle flush it. */
export interface FrameReceiptLedger {
    pending: FrameReceipt[];
    listingSnapshotOwed: boolean;
}
/**
 * The one closure that stops a run leg for a classifier denial-limit fallback NOBODY JUDGED — the
 * synchronous gate's headless arms and the durable resume station both call it, and both reach it
 * through {@link Prepared.stopForDenialLimit}. Declared here, beside the seat it fills
 * ({@link Prepared.gateStopRef}), so the two stations name one type rather than two.
 *
 * `settlement` is the kind that ENDED a parked fallback's wait, and is present only on the DURABLE station: the synchronous one
 * has no settlement to report (no approver was reached at all), and that absence is what selects its clause of the shared sentence.
 * `decidedVia` is the seat of the policy's refusal that ended the fallback (either station); `host_window_closed` selects its own clause, as does `windowExpired` (the approver answered the fallback `window_expired`).
 */
export type StopForDenialLimit = (info: {
    toolName: string;
    toolCallId: string;
    fallback: DenialLimitFallbackFace;
    settlement?: SettlementKind;
    decidedVia?: import("../gate-outcome.js").DecidedVia;
    windowExpired?: true;
}) => void;
/** The gate's seat inputs for one call (the static seat or the `Skill` tool's per-call reader, the run's skill and allow-list rows). */
export type GateSeatInputsFor = (calledName: string, wireName: string) => import("../mode-policy.js").PermissionSeatInputs & SkillGateSeats & import("../allow-entry.js").AllowEntryGateSeats;
/**
 * The leg's ONE write-boundary latch: the word the store refused one of the leg's session writes with, read where the result is
 * assembled — `conflict` (another writer moved the leaf: the caller may evict and retry) or `holder.superseded` (the run's grant is no
 * longer current: stop, never retry). `holder.superseded` outranks `conflict` and is never replaced (`latchWriteRefusal`,
 * branch-writeback.ts). `stop` is the leg's stop, bound once the leg can be stopped: the latch calls it the moment it reads
 * `holder.superseded`, so a lane that swallows a write failure (a turn-boundary compaction) does not send the model another request.
 */
export interface WriteRefusal {
    word: "conflict" | "holder.superseded" | undefined;
    stop?: () => void;
}
export interface Prepared {
    harness: AgentHarness;
    /** The CONCRETE built-in session (engine-internal: prepare constructs/acquires `StoredSession` itself,
     *  and the epoch pin path needs its `appendPromptEpoch`/`getPromptEpoch`). Public consumer faces take
     *  the `Session` contract instead. */
    session: StoredSession;
    sessionId: string;
    /** The occupant of the session row this leg acquired (`SessionMetadata.incarnation`, read once from {@link session} at
     *  prepare); absent = no token (a row written before occupants were minted, or that read failed). With {@link sessionId} it
     *  is the leg's session ADDRESS (`task-notification.ts` `SessionAddress`): what its notification lane parks under, drains
     *  and registers as. */
    sessionIncarnation?: string;
    /** `true` = that read threw: the leg names no occupant it knows, so the notification store takes it as no admission and drains
     *  it nothing (`SessionAddress.unread`); what is kept for the session waits for a leg that reads its occupant. */
    sessionIncarnationUnread?: true;
    /** This leg's task id, minted ONCE at prepare ({@link import("../leg-identity.js").legTaskIdOf}): its identity, frames, events'
     *  `sourceTaskId`, trace frames and `TaskResult.taskId` read it here; none re-spells it. */
    taskId: string;
    /**
     * THIS INVOCATION's own identity, minted once at the top of {@link prepareTask} and never
     * rewritten. The third id of the trio, and the only one the engine owns outright:
     *  - `spec.taskId` — the HOST's task identity (absent whenever the host names nothing);
     *  - `sessionId`   — the CONVERSATION's identity (shared by every run that continues it);
     *  - `runId`       — THIS call of the engine.
     *
     * The gap it closes: the leg's task id ({@link taskId}) answers the same value for
     * two runs of one session whenever the host supplies no task id, so every per-run account keyed on
     * it FOLDED two runs into one row (two runs each losing one steer read as one run losing one).
     * A per-run account must key on this; a per-TASK fact (trace `taskId`, the host's own correlation
     * handle) must keep the task spelling — the two are different questions and the station sweep
     * judged each one.
     *
     * Minted here (never at the Runner's stream entry) so that a standalone `prepareTask` exercise gets
     * a real id too, and so the mint has exactly one site. A leg whose prepare THROWS never returns a
     * `Prepared` at all — but the id still reaches its caller through the `runIdSink` carrier, because
     * prepare emits run-scoped disclosures of its own and each must have a terminal that names it.
     */
    runId: string;
    /** Wall-clock epoch ms minted once beside {@link runId} at prepare entry; every leg-start reader (`manifest.leg.instance.startedAt`, `task_started.startedAt`, `task.start.ts`) reads this value. */
    legStartedAt: number;
    /** The deployment's host floor as the config doors compiled it (absent ⇒ none declared) — the task images' guard reads it. */
    hostFloor?: import("../host-floor.js").HostFloor;
    /** The (owner, scope) key this run's registry-facing tools register rows under — ({@link taskId}, mount domain), minted once at prepare; the teardown sweeps read it and never re-derive it. */
    registryAccess: {
        readonly owner: string;
        readonly scope: string;
    };
    /** The run's member ledger book (`TaskSpec.runLedger`), present only on a run that declares one: the report tool delivers
     *  through it, and the settle reads the final ledger off it onto the result. */
    runLedgerBook?: import("../run-ledger.js").RunLedgerBook;
    /** The session's reminder provenance mark this run mints under (adopted
     *  through the prepare adoption ladder: checkpoint seed → trusted fork channel → session entry →
     *  fresh mint). Every engine-authored `<system-reminder>` open tag in the run carries it, and the
     *  system prompt's Harness declaration names it. Always present on a completed prepare. */
    reminderMark: string;
    /** borrowed-readonly — the leg's startup seed table the request's copy projection reads (the window check renders with it). */
    seededCopies?: ReadonlyMap<string, string>;
    /** The leg's reminder-disclosure trigger counters (mutated by the
     *  disclosure outlets at tool-execute time; read once at result assembly into
     *  `stats.mechanisms.reminderDisclosures` when any key is non-zero). Always present. */
    reminderDisclosureCounts: import("../reminder-disclosure.js").ReminderDisclosureCounts;
    /** Whether the full shell is on this leg's roster (the inherited-gate phase's bit, asserted against the mount). */
    fullShellReachable: boolean;
    /** The run's approval-posture facts as prepared — the effective permission mode and the ask seam's effective
     *  answer. The posture composition renders them into the engine's own marked reminders; no gate decision keys on them. */
    approvalPosture: import("../auto-mode-directive.js").ApprovalPostureFacts;
    /** The output-style frame body, rendered once at prepare from the screened `TaskSpec.outputStyle` (absent = no seat). */
    outputStyleFrame?: string;
    /** The run-time reminders (boundary-reminders.ts): their lane as prepare resolved it (the run's traits, the task's switches, a
     *  top-level leg), the leg's handle on its session tree's elapsed-time clock (session-prompt-seats.ts), and how it opened (`LegOpening`). */
    runTimeReminders: {
        readonly lane: import("./boundary-reminders.js").RunTimeReminderLane;
        readonly elapsedClock: import("./session-prompt-seats.js").ElapsedTimeClock;
        readonly opening: {
            current?: import("./boundary-reminders.js").LegOpening;
        };
    };
    /** The leg's live permission-mode seat: the effective mode every mode consumer reads, the steer verb writes. */
    permissionMode: PermissionModeController;
    /** The ISOLATION-AWARE working-tree root for this task (a worktree's cwd when `isolation: "worktree"`, else
     *  `deps.rootPath ?? executionEnv.cwd`) — the same value the hands/LSP/policy/restore use. The Runner's
     *  rewind/snapshot path MUST key off THIS, not `deps.rootPath`, or a worktree-isolated turn snapshots the base
     *  repo (CORE-1~9 audit MAJOR). */
    taskRootPath: string;
    model: Model;
    /** Effective thinking level (explicit `spec.thinking` or the resolved role's default). */
    thinking?: ThinkingLevel;
    /** The leg's fast mode (`TaskSpec.fastMode`, `TaskStream.setFastMode`) over its session tree's facts — the per-call handle
     *  (the main loop's, a compaction pass's, the suggestions') and every reading (`./fast-mode-seat.ts`). */
    fastMode: import("./fast-mode-seat.js").FastModeLeg;
    mcp: MaterializedMcp;
    /** The run handle's `reconnectMcpServer` implementation — {@link MaterializedMcp.reconnect} plus the
     *  live-roster application and the operator disclosure, which are runner concerns and not the MCP
     *  handle's. Present only when this leg DECLARED MCP servers; the stream verb's seat stays unbound
     *  otherwise and it refuses typed. */
    mcpRedial?: (server: string) => Promise<import("../mcp.js").McpReconnectResult>;
    /** Present only when `spec.a2a` declared peers — the run loop owes it the same end-of-task dispose
     *  it owes {@link mcp} (no sockets are held, but a disposed mount is what makes a post-task tool
     *  call refuse loudly instead of dialing a peer on a dead task's behalf). */
    a2a?: MaterializedA2a;
    blockedRef: BlockedRef;
    /** Holds the structured output once `submit_output` is called (when `spec.outputSchema` is set). */
    outputRef: OutputRef;
    /** Fires when the task aborts (timeout / max turns / end). Passed to `ToolPolicy.check` so a
     * pending human-approval gate is released instead of hanging past the deadline (F4). */
    abortController: AbortController;
    /** The leg's write-boundary latch: the word a refused session write said during the run (`conflict` → `errorCode = "conflict"`;
     *  `holder.superseded` → the leg stopped on that tick, `errorCode = "holder.superseded"`). */
    writeRefusal: WriteRefusal;
    /** Tool-call ids the gate blocked (policy/hook/plan-mode deny) or suspended —
     *  populated only while a consumer is wired (per-tool post hooks or postToolBatch). The runner's
     *  batch collector DELETES on match (its tool_execution_end is the only end-event a blocked call
     *  emits; the tool_result-side delete in prepare-task never fires for immediate results). */
    blockedToolCalls: Set<string>;
    /**
     * The leg's tool-call OCCURRENCES (`tool-occurrence.ts`): one record per call attempt, the only holder of what
     * the engine knows about a call in flight — its start frame, its gate rounds (the gate's exit record and any
     * refusal after it), its wait on the person, its heartbeat clocks. Every frame of the call, the heartbeat, the
     * trace row and the resumed leg's execution record read it; a call leaves it when its end frame is minted.
     *
     * An engine-owned seat and not a field on the tool RESULT because a result is not a trustworthy carrier: its
     * `details` is tool-authored and replaceable by post-tool hooks, so provenance read from it would let a failing
     * tool claim a person approved it. Writers: the announcing stations, the gate station, the shell read
     * admission, the resumed leg's belts; the end projection closes the record.
     */
    toolOccurrences: import("./tool-occurrence.js").ToolOccurrenceTable;
    /** The leg's ONE seat for its two decision screens (`hook-progress-lane.ts`): a `classic.PreToolUse` screening holds its call on
     *  {@link toolOccurrences} (`tool_progress.gate: "hook"`), and every screen — that one, a prompt's — is framed (`hook_progress`)
     *  by {@link hookProgress}. Built with the occurrence table; the gate stations, the approved-call re-screen, the
     *  objective, the live steer and the parked redelivery all run their screens inside it. */
    hookScreens: import("./hook-progress-lane.js").HookScreenSeat;
    /** The leg's HOOK-PROGRESS lane, minted with {@link hookScreens} so a screen that starts before the run body exists (a steer
     *  taken as soon as the handle is published) is already in it; the driver binds it to `pushContent` and `ident` beside
     *  {@link toolProgressRef} — a screen that came due before then is announced at the bind — and closes it at the leg's end. */
    hookProgress: import("./hook-progress-lane.js").HookProgressLane;
    /**
     * The parent-thread human-rejection halt fact (see `isBareHumanRefusal`): present from the
     * moment a bare human rejection halts the turn's batch — or a resumed leg records one (a parked call's, a plan
     * pause's; `rejectedToolCallId` then names the gated call, or the call that asked for the plan pause when the row
     * recorded one) — until the run ends or the NEXT provider
     * request begins (user input continuing the run clears it). Consumers: the runner's stop gate
     * (suppress natural-end pushback / final-verify injection — engine continuations must not restart
     * a run a person just stopped), the turn-boundary engine steers (same reason), and the result
     * stamp (`TaskResult.haltedOnUserRejection` — a human-halted run must not read as an ordinary
     * completion). Engine-owned sideband, same trust reasoning as `approvalSettlement` above.
     */
    batchHaltRef: {
        current?: {
            rejectedToolCallId?: string;
        };
    };
    /** Summed usage of nested sub-runs (sub-agents) spawned by this task's tools: a live read of the run's spend account
     *  (everything under its node) plus what a resumed leg carried from the chain before it. */
    nestedStats: NestedUsageAccum;
    /** This leg's node of the spend account: every real model request of the leg is admitted against it (and its ceilings'
     *  ancestors) before it is sent; it closes when the leg ends. */
    spend: import("../spend-account.js").SpendAccount;
    /** The deps bag this leg reads its model lane from (the deployment's, with the leg's meter riding it). */
    laneDeps: RunnerDeps;
    /** Prepare-time rewind disclosures (conversation-only branch / no snapshot backend / no file
     *  env), echoed verbatim onto `TaskResult.rewindNotes`. Present only when there is something to say. */
    rewindNotes?: NonNullable<TaskResult["rewindNotes"]>;
    /** The leg's record of what its rewind did (`./rewind-outcome.ts`: whether the tree moved, where the conversation's leaf stands,
     *  the restore it accepted) — `terminal.rewind` and `TaskResult.fileRestore` on every terminal assembly reads. Absent on a leg that
     *  asks for no rewind. The same object the backstop carrier names ({@link TaskIdRef.rewind}). */
    rewindOutcome?: RewindOutcome;
    /** The run's edited-file ledger read face — what its OWN hands landed, as `TaskResult.editedFiles`
     *  (undefined when nothing landed: the key is absent, never an empty array). A LIVE reader rather
     *  than a snapshot, so the throw-path backstop terminal reports the same ledger the ordinary
     *  assembly would. Always present on Prepared; independent of whether a fileHistoryStore is wired. */
    editedFilesSnapshot: () => TaskResult["editedFiles"];
    /** The run's turn-start boundary seat (present iff the run records file history into a wired store and
     *  the run mounts a real fs env). runtask calls begin() at the first committed row of a person's input and
     *  awaits settle() at the lease close + the finish tail. */
    fileHistoryBoundary?: FileHistoryBoundarySeat;
    /** The run's RESOLVED read face for the result observation seat
     *  (`TaskResult.effectiveReadFace`): `carrierReadFace()`'s value at prepare completion — the hands
     *  block's single resolution, or the hands-less legs' resolver run (live spec-time facts, with the
     *  checkpoint seed folded stricter-wins where one exists). Every leg that completes prepare has a
     *  read posture now — this is what its delegation subtree is clamped by even where no faces mount. */
    effectiveReadFace?: ContainmentFace;
    /** owned — the same observation on the WRITE seat (`TaskResult.effectiveWriteFace`). */
    effectiveWriteFace?: ContainmentFace;
    /** The normalized deny ADDITIONS in force (deployment ∪ task ∪ checkpoint seed; built-ins excluded), echoed on
     *  `TaskResult.effectiveReadDenyPatterns`. Present iff non-empty; a defensive copy (the working array stays the engine's). */
    effectiveReadDenyPatterns?: readonly import("../../tools/fs/read-deny.js").NormalizedReadDenyEntry[];
    /** owned (value) — the leg's one resolution of `TaskSpec.blockReadsOutsideRoots` (the hands phase's answer, a resumed row's
     *  record included), echoed on `TaskResult.effectiveBlockReadsOutsideRoots`. Present (`true`) iff it is on. */
    effectiveBlockReadsOutsideRoots?: true;
    /** owned (value) — the command sandbox requirement the leg runs under (`TaskSpec.sandbox` as judged, a resumed row's recorded
     *  requirement as its floor — the value the leg's rows record), echoed on `TaskResult.effectiveSandbox`. Present iff one stands. */
    effectiveSandbox?: import("../command-sandbox.js").TaskSandboxSettings;
    /** owned (value) — the leg's external-content-target fold (the environment's declaration ∨ a resumed row's record ∨ the later-leg
     *  seat a composition hands), echoed on `TaskResult.effectiveExternalContentTarget`. Present (`true`) iff on. */
    effectiveExternalContentTarget?: true;
    /** The leg's declared places; their carried parts are echoed on `TaskResult.effectiveAgent{Config,Home}Dirs`. */ callerPlaces?: import("./leg-caller-places.js").LegCallerPlaces;
    /** The memory-visibility observation prepareMemory minted (echoed on
     *  `TaskResult.effectiveMemoryScopes`). Always present on a completed prepare (the memory-less
     *  states are their own values); the seat is optional only so a Prepared shape without the phase
     *  cannot fabricate one. */
    effectiveMemoryScopes?: import("../types.js").EffectiveMemoryScopes;
    /** The byte floor's latch over every read-deny table this leg compiles, at prepare and after (the read-face phase's own,
     *  read, never re-derived): echoed on `TaskResult.readDenyFloor` at assembly; the wiring manifest read it when it was derived. `current`: `false`, or the rows of the unkept judgment the latch holds. `judged`: a table was judged (none on a hands-less leg). */
    readFloorUnkept: {
        readonly current: import("../../tools/fs/read-floor.js").ReadFloorRows | false;
        readonly judged: boolean;
    };
    /** The leg's placement fixed point as prepare resolved it ONCE — the value the env-factory ctx was minted with and the suspend
     *  stamp records — echoed on `TaskResult.placementRoot`. Absent when the resolution came out empty (`""` is absence). */
    placementRoot?: string;
    /** The per-task logical cwd ref when a real shell is mounted (else undefined); the workspace frame reads it. */
    cwdRef?: CwdRef;
    /** The leg's `workspace_changed` seat (its one snapshot projection): the run binds the sink after `wiring_manifest` (the leg-start frame) and observes after each tool. */
    workspaceFrame: import("../workspace-snapshot.js").WorkspaceFrameSeat;
    /** The root the hand tools resolve root-relative spellings against (present with hands; read-only hands included). */
    handsRoot?: string;
    /** The leg's target-reading stamp (present with hands): the resume belts stamp the executed bytes' request with it. */
    stampCallTarget?: import("../effective-path-target.js").CallTargetStamp;
    /** The run's TOOL-PROGRESS lane seat, late-bound for the same reason `harnessRef` is (the tool band is
     *  built during prepare; the lane needs `pushContent` and `ident`, which exist only after it returns).
     *  The driver binds `current` right after `pushContent` exists. Always present on a completed prepare —
     *  the CELL, not the lane: unbound means "no run body has claimed this band", and emissions no-op. */
    toolProgressRef: {
        current?: ToolProgressLane;
    };
    /** The leg's `$.turn.abort` seat, late-bound like `toolProgressRef`: the mods facade is bound during prepare,
     *  the turn counter and the notice sink exist only in the run body, which fills `seat`. Unfilled means no run
     *  body owns the leg yet, and the method answers "no model request is running". */
    turnAbortRef: import("../mods/dollar.js").TurnAbortRef;
    /** The run's advertised-writable-directory seat (present with hands): `roots` is what the prompt advertised as writable and the fence admitted. Read live wherever a policy is adjudicated off a resumed leg, so the write gate's exemption domain is that same list. `planFile` is the session plan file it admitted (`TaskSpec.planFile`) — the posture frames name it. */
    advertisedWritableDirs?: Pick<import("./advertised-writable-dirs.js").AdvertisedWritableDirs, "roots" | "planFile" | "readPlanFile">;
    /** The leg's ONE exempt root (its single resolution of `RunnerDeps.memoryEngineDir`), stamped wherever a policy is adjudicated off a resumed leg (`ToolCallRequest.exemptRoots`) — the same list the live gate stamps. */
    exemptRoots: readonly string[];
    /** The ACTIVE EnterWorktree session ref (mounted with the worktree tools; undefined without
     *  real write hands). runtask's settle write reads `current` for the workspace-state entry. */
    worktreeSessionRef?: {
        current?: ActiveWorktreeSession;
    };
    /** The settle-write base — the canonical root + what the cwd/worktree were RESTORED to at
     *  prepare. runtask diffs the live refs against this at settle and appends a `workspace_state` entry
     *  when the state changed (skipped on a durable suspend — the checkpoint lane owns that state). */
    workspaceStateSettle?: {
        rootCanonical: string;
        restoredHandsCwd?: string;
        restoredWorktreeDir?: string;
        baselineUnknown?: boolean;
    };
    /** The settle-time session-seat SEAL (see prepare-hands-readface): re-anchors
     *  the per-session read-state seat to the entry id THIS run last committed (its own
     *  message_committed tail — provenance, never a shared-leaf re-read). The driver calls it once at
     *  the run's settle, every terminal (suspend included), under the session lock; undefined argument
     *  (no commits) is a no-op. Synchronous, never throws. Absent ⇔ hands-less / no seat channel. */
    sealReadStateSeat?: (ownCommittedTailEntryId: string | undefined) => void;
    /** The DENY-NARROWING layers (session rules, inherited ancestor rules, the frozen constraint projections; deny-only).
     *  Re-checked on RESUME before an approved pending tool executes, so a rule tightened during the suspend still applies. */
    denyNarrowingPolicy?: ToolPolicy;
    /** The run's skill grant lane: its deny rows (a skill's `disallowed-tools`) are re-read on RESUME at the same station as the
     *  person's deny rows, on the bytes that will run. */
    skillGrants: SkillGrantLane;
    /** The skills this leg loads (normalized, past the load gate; empty when none) — the one list its `Skill` tool activates from, its park binds and the resumed execution boundary judges a parked Skill approval against. */
    skillSpecs: readonly SkillGrantSource[];
    /** The person's own persisted-rule lane (deny/ask rows), re-adjudicated on RESUME at the same
     *  station as the deny-narrowing layers: a deny row added while the call was parked vetoes the execution
     *  (`deniedBy: "persisted_rule"`), and so does a call the lane could not read against the rows (re-issue and
     *  re-approve); an ask row does not (the approval is its answer), and a store that could not be read
     *  contributes no row. Absent when no rule store is wired. */
    persistedRuleLane?: {
        adjudicate: (req: ToolCallRequest) => Promise<import("../hooks.js").PersistedRuleAnswer>;
    };
    /** The deployment's caller policy, re-checked on a durable resume when the bytes to execute are not the bytes the gate saw. */
    basePolicyForResumeEdit?: ToolPolicy;
    /** The leg's consolidation write judge (`createConsolidationWriteJudge`, the settle tail's background consolidation asks it). */
    consolidationWriteJudge: import("../memory-engine/consolidation-driver.js").ConsolidationWriteJudge;
    approvedCallScreen?: (call: {
        toolCallId: string;
        toolName: string;
        args: unknown;
        answered: readonly AskClass[] | undefined;
    }) => Promise<{
        readonly refused: string;
        readonly extension?: string;
    } | {
        readonly admit: () => void;
    }>;
    /** The leg's `tool.call` station (`mods/tool-call.ts`) — every execution of a call passes it; absent when no handler hangs on the event. */
    toolCallStation?: import("../mods/tool-call.js").ToolCallStation;
    /** The leg's ONE adoption step, run at the run-body opening (`prepare-leg-adoption.ts`); never throws, its report rides the first request. */
    legAdoption: import("../../agents/yield-adoption.js").LegAdoption;
    /** One call's command sandbox plan by its wire name (`command-sandbox.ts`) — the gate's mint, for an approved call a durable
     *  RESUME executes outside the loop: that execution runs under it as a live call runs under the gate's. */
    commandSandboxPlanOf: (call: {
        readonly toolName: string;
        readonly toolCallId: string;
        readonly args: unknown;
        readonly parkedClasses?: readonly import("../ask-origin.js").AskClass[];
    }) => import("../command-sandbox.js").CommandSandboxPlan;
    /** The leg's shell READ STATION, re-run on a durable RESUME before an approved shell call executes: the parked leg's
     *  admission died with that leg, so the resumed bytes are judged (and admitted for their pre-spawn re-establishment)
     *  on THIS leg — a deny row found now vetoes, an operator's edit is judged on the `rejudge` seat. */
    shellReadCheck?: import("../../tools/fs/shell-read-check.js").ShellReadCheck;
    shellReadLandings?: import("../../tools/fs/shell-read-check.js").ShellReadLandings;
    declaredReadKeys?: (toolCallId: string, call: Pick<import("../tool-registry.js").ToolCallLike, "face">) => readonly string[] | "unjudged" | undefined;
    crossBoundary?: {
        readonly check: import("../cross-boundary-taint.js").CrossBoundaryCheck | undefined;
        settle(owed: import("../cross-boundary-taint.js").OwedDeliveries, boundMs?: number): Promise<void>;
        storeWaits(): number;
    };
    /** The ORG adjudication face, re-resolved on a durable RESUME before an approved
     *  pending call executes. The resume path bypasses the harness gate by design (a human already
     *  adjudicated the checkpointed call), which is exactly where org policy skew is most likely: the
     *  suspend may have outlived the snapshot revision that was current when it was minted. Present only
     *  on a governed deployment. */
    permissionRuleOrg?: {
        adjudicate: (req: ToolCallRequest) => Promise<OrgGateVerdict>;
    };
    /** Takes the `spec.signal` abort listener off once the leg's loop ended (its job is over); the run's end takes it off on every exit. */
    releaseSignal: () => void;
    /** The leg has stopped: its children's mode ceiling moves to the session's current leg (called once its loop settled). */
    endModeCeiling: () => void;
    /**
     * End-of-leg sweep for questions this leg's gate routed to a person. Called once by the
     * run loop at task end, on every exit path. A binding that is still present means a person ANSWERED and
     * the call never executed to collect it (aborted, batch torn down, loop threw): that answer is disclosed
     * through the deployment's error sink rather than dropped, because "a human answered and it vanished" is
     * precisely the failure this whole path exists to remove — it must not reappear inside the mechanism
     * that removes it. Idempotent, never throws.
     */
    settleContentAskBindings: () => ReadonlyArray<{
        deliveryId: string;
        toolCallId: string;
    }>;
    /** The leg's main requests that do not extend the session's previous main request (`./prefix-ledger.ts`), in the order
     *  they were about to go out; the run's stream subscribes and mints one `prefix_changed` frame per change (released with
     *  the leg). Nothing is published while `RunnerDeps.cacheBreakDetection` is `false`. */
    prefixChanges: import("./prefix-ledger.js").PrefixChangeSeat;
    /** The leg's end on the session's prefix ledger, called once when the leg's lanes close: what the leg's last request carried
     *  and the next leg's will not (the limit-approach sentence, {@link LimitApproachSeat.carried}) is declared, and the leaf the leg
     *  ended on is recorded for the next leg's start to compare its branch with (`SessionPrefixLedger.closeLeg`; read
     *  asynchronously, never awaited). */
    endPrefixLeg: () => void;
    /** Reads a side request (a summary, a classification, an advisor or mod call, the suggestion pass) against the session's
     *  main line before it goes out; its reply's `brain.call` row carries the reading (`readingOfUsage`). */
    observeSideRequest: import("./prefix-ledger.js").RequestObserver;
    /**
     * 提示词主权批 — the labelled composition of the assembled system prompt, emitted as the
     * `prompt.assembled` trace event at task start. `constitution` says who owned the safety layer:
     * `"core"` (structural, the default), `"replaced"` (provider set `replaceAll` — deliberate opt-out),
     * `"provider-assembled"` (migration guard: a historic provider returned a full prompt, passed through
     * un-doubled + onError hint). Deployments/tests assert on this to make "which blocks were in the
     * prompt" a runtime fact instead of archaeology.
     */
    /**
     * This leg's EFFECTIVE wiring manifest (built once in prepare from resolved
     * facts through the same derivation as the static half). runtask emits it as the
     * `wiring_manifest` TaskEvent after the prepare consume point and before the leg's first
     * model/tool interaction. Host/operator plane — never enters model context.
     */
    wiringManifest: WiringManifest;
    /**
     * This leg's frozen identity envelope, minted ONCE in prepare beside the wiring
     * manifest (same leg derivation, one mint — {@link mintHookInvocationIdentity}). Every hook
     * station runtask drives (stop/stopFailure/userPromptSubmit/postToolBatch, the compaction
     * wrapper) and the 件B delegation-lifecycle observer read THIS object; prepare's own stations
     * (the tool gate, the post-tool contexts) close over the same const. Always present — a prepared
     * leg always knows its identity.
     */
    hookIdentity: HookInvocationIdentity;
    /** Where this leg's user-face notices go and the admission every one is delivered under, minted ONCE in prepare beside the ask
     *  source ({@link mintLegNotice}): the leg's own session on a top-level leg, the delegation tree's root naming this leg on a
     *  delegated one. The gate's stations and the shell's withheld-variables line read it; no seat derives an address of its own. */
    legNotice: LegNotice;
    /** The leg's mods bus: one per leg, admitted at this leg's prepare (both seats, `plugin.register` run once for this leg). Every classic station raises its event on it; its `records` are the manifest's `mods[]`. */
    modBus: ModBus;
    /** End that bus's lifetime (`LegMods.end`): the leg's terminal does, before `session.end` (`raiseSessionEnd`); the lane
     *  that ran the leg does again on its way out, so no exit keeps a timer running. A second call does nothing. */
    endModLife: () => void;
    /** The leg's one admission seat (`session-append.ts`): a direct writer passes each row through it first (`appendAdmittedRow`). */
    admitRows: RowAdmission;
    /** The leg's one receiving station (`session-receive.ts`): the live lane, the turn-open redelivery and the box drain's pull
     *  hand every frame to it before the model reads it. */
    receiveSeat: import("../task-notification.js").FrameReceiver;
    /** The turn-open redelivery's hand-over while the receiving station judges it (set only when a handler listens and frames
     *  were parked): the leg's prompt waits on it, so what the station hands over is in the first model call. */
    turnOpenRedelivery: {
        current?: Promise<void>;
    };
    /** The leg's `session.compact` station and its `$.session.compact` window (`session-compact.ts`): every compaction lane runs
     *  its pass through it. */
    compactStation: import("../mods/session-compact.js").CompactStation;
    /** The leg's latest context measurement (`lifecycle-stations.ts`): each turn boundary writes it, `$.session.usage` reads it. */
    sessionMeasure: import("../mods/lifecycle-stations.js").SessionMeasureSeat;
    /**
     * This session's DURABLE box, present iff this leg mounted the session-box drain (a top-level leg
     * over a cross-process-safe mailbox with a grammatical session id). The notification lane binds it
     * to the park seat ({@link import("../task-notification.js").PendingSessionNotifications.admit})
     * so a child's uplink frame parked for this session while it is idle lands in the box the next run
     * drains — one mount judgment, the drain and the park read it alike. Absent ⇒ in-process parking.
     */
    sessionBox?: import("../task-notification.js").SessionBoxBinding;
    /**
     * #1036 — the leg's TWO SETTLEMENT LEDGERS, one cell shared by the three beats that fill and
     * read them: the harness's transcript-append sink writes receipts, the compaction commit beat
     * writes effects, and the session-box drain's settlement half-pass reads both and clears what it
     * consumed. Always present (the cell is minted with the leg); empty on a run with no session box,
     * because nothing registers an interest and the receipt sink only records awaited keys.
     */
    frameSettlement: import("../frame-settlement.js").FrameSettlement;
    /** The attachments the objective declared, as the door screened them (absent: none, or a resume leg — whose door
     *  refuses any). */
    userAttachments?: readonly import("../user-attachment.js").ScreenedUserAttachment[];
    /** The pending commits of this leg's attachment frames, settled by the transcript-append receipt sink — the one place
     *  an attachment's read effects are applied. Always present. */
    attachmentDelivery: import("../user-attachment.js").AttachmentDelivery;
    /** The run's once-per-run account of an image sent unprocessed over the soft target — the tool-result seat's and the leg's (task images, attachments). */
    imageUnprocessed: (bytes: number) => void;
    /** The leg's one file reader — the Read tool's own (one read state, one set of disclosure windows and counters),
     *  handed to the leg's other carriers of a file. Present iff hands are mounted. */
    modelFileReader?: import("../../tools/fs/fs-read.js").ModelFileReader;
    /** The run's synthetic-Read judge over every layer that can refuse a model's own `Read` (the changed-file notice reads
     *  it; so does the attachment read, as a face that puts contents in front of the model). */
    syntheticReadVerdict: import("../synthetic-read-verdict.js").SyntheticReadJudge;
    /**
     * #1036 — the session-box drain's BOUNDARY PASS, called by the turn-boundary lane as its tail
     * (in a `finally`, so every early exit of the boundary still settles). Present iff this leg bound
     * the drain. `continues` = this leg will issue another request after this boundary, which is what
     * decides whether the pass's NEW-delivery half runs; the settlement half runs either way.
     *
     * It is a tail call and not a `turn_boundary` hook of the drain's own because the ORDER matters and
     * a hook's position is registration-order luck: settlement must run AFTER this boundary's
     * compaction, or a record whose frame the compaction just summarized away is already acked (deleted
     * from the box) by the time anyone could notice.
     */
    peerBoundaryRound?: (o: {
        continues: boolean;
    }) => Promise<void>;
    /** The composition manifest (v3) the `prompt.assembled` frame reports (`trace.ts`, the same member types). */
    promptManifest: {
        identity: import("../trace.js").PromptManifestIdentity;
        selectors: import("../trace.js").PromptManifestSelectors;
        blocks: Array<{
            id: string;
            chars: number;
            hash: string;
        }>;
        /** How far the salted digests compare (`session` / `leg`) — `./session-hash-salt.ts`. */
        hashScope: import("../trace.js").PromptHashScope;
        sections: import("../trace.js").PromptManifestSection[];
        /** Each overlay the composition superseded; absent when none was. */
        superseded?: import("../../prompt-assembly/overlay.js").SupersededOverlay[];
        /** S2 (additive): the mounted tools plane — contract identity, durable-replay aliases,
         *  presentation-invariant shape digest and full wire digest per tool (initial mount face). */
        tools?: ToolManifestRow[];
        /** The nine-element cache identity — digests only, no prompt
         *  text; backfilled once the final wire tool list exists. Live post-refresh truth rides
         *  `prepared.turnSnapshot`. */
        snapshot?: {
            cacheIdentity: string;
            elements: import("../../prompt-assembly/turn-snapshot.js").CacheIdentityElements;
        };
        /** The run's lowering record (version/wire form/known
         *  intentional divergences — run-static v1, one brain serves every call). */
        lowering?: import("../../prompt-assembly/turn-snapshot.js").LoweringRecord;
        /** The RESOLVED deferred-tool disclosure strategy for this leg and which
         *  seat chose it. Absent when nothing is deferred (there is no disclosure to describe). */
        toolDisclosure?: ToolDisclosureManifest;
    };
    /** This run's prompt identity inputs and its pinned center layer's provenance, threaded to every compaction-boundary
     *  epoch selection so a boundary restates the same identity the prepare-time record names. Replaced by a committed
     *  compaction-boundary center change. */
    promptIdentity: import("../../prompt-assembly/epoch.js").RunPromptIdentity;
    /** The LIVE nine-element identity face (refreshed by deferred materialization and
     *  the deferred-materialization adoption swap); the manifest holds the prepare-time initial copy. */
    turnSnapshot?: import("../../prompt-assembly/turn-snapshot.js").TurnPromptSnapshot;
    /** The compaction-boundary center-layer seam (undefined = no source wired, or a child run — a child composes its
     *  parent's layer). Returns the maybeCompact `centerAdoption` fragment or undefined; `apply` runs post-CAS only
     *  (auto-compaction owns the ordering). Both `promptIdentity` and `promptOverheadTokens` on THIS object are mutated by
     *  a successful change (read them at call time, never capture early). */
    centerCompactionCandidate?: () => NonNullable<import("../auto-compaction.js").MaybeCompactOptions["centerAdoption"]> | undefined;
    /** Deferred-tool disclosure: the monotonic set of activated deferred-tool names. Empty
     *  (and no `tool_search` injected) when nothing is deferred. Mutated by BOTH disclosure lanes across
     *  the run — the injected `tool_search` and the direct-call placeholder lane (default ON) —
     *  under ONE shared activation critical section, plus resume seeding at prepare. A leg on which the
     *  model never calls `tool_search` is therefore NOT quiescent. */
    activeTools: Set<string>;
    /** The DECLARED deferred set (populated by `classifyDeferred`, ghost names already pruned).
     *  Present iff the task has deferred tools at all; `deferredToolNames − activeTools` is the
     *  "undiscovered" census the tool_search_usage_reminder lane enumerates. Frozen at prepare time: a
     *  name never leaves the deferred set, it only moves into `activeTools`. */
    deferredToolNames?: ReadonlySet<string>;
    /** The deferral census seat, present iff {@link deferredToolNames} is. */ toolDisclosure?: import("./deferral-census.js").ToolDisclosureSeat;
    /** The RESOLVED materialization strategy this run runs under (`true` = "static":
     *  activation never swaps the placeholder; the real schema's only in-context carrier is the
     *  ToolSearch result text). Consumed by the tools_delta boundary renderer, whose "full schemas are
     *  loaded" wording is a statement about the tools block and is only true under swap. `false` when
     *  nothing is deferred (the knob is inert then). */
    toolMaterializeStatic: boolean;
    /** Is the direct-call lane mounted on this run's placeholders (`TaskSpec.deferSelfResolve`
     *  not disabled; default ON)? The SAME fact `createToolSearchTool` receives as `directCallEnabled`,
     *  surfaced here so every model-facing face that describes what happens to a call on a
     *  still-deferred tool reads ONE value — under the direct lane a schema-valid call executes rather
     *  than failing, so an absolute failure claim is only true for the opt-out posture. `false` when
     *  nothing is deferred (no placeholders, so the fact is inert). */
    deferDirectCall: boolean;
    /** Is THIS deferred name on the static face? False under `"swap"`, and false under
     *  `"static"` for a tool whose declaration the result-text carrier cannot hold (the per-tool
     *  exemption: it materializes into the tools block instead). Read at call time — the roster is
     *  mutated in place by MCP refresh, so renderability is a live fact. Absent when nothing is
     *  deferred; a caller with no accessor has no deferred family to describe. */
    staticFaceFor?: (name: string) => boolean;
    /**
     * The MemoryEngine session. Present when `deps.memoryBackend` + `spec.memory.enabled`
     * hold AND the engine mount succeeded: a materialize failure without a `config.memory_*` code is
     * fail-open (reported via `deps.onError`, the task runs memory-less), leaving this absent even though
     * both flags hold.
     * `harvest` is the swallow-guarded boundary hook (task terminal in runtask + the checkpoint mint
     * point in commitSuspendSaga): it runs the FULL gate set (containment/secret/caps/deletion fuse),
     * commits entry patches to the backend, self-heals the derived index, and re-baselines (a second
     * harvest of an unchanged session yields zero patches). It NEVER throws.
     * S2-B (O-F7/C-F3): the report is NOT discarded — `harvest` hands it to the Runner-owned
     * `deps.onMemoryHarvestReport` callback (with the boundary phase), and the engine itself enqueues
     * the announcement-queue entry at its harvest tail (drained into the NEXT session's first inject —
     * 时机①; the r1 in-run attachments lane was cut, O-F2/C-F4). `phase` defaults to "terminal" (the
     * runtask call site passes nothing); the checkpoint-mint call site passes "checkpoint".
     */
    memoryEngineSession?: {
        /** The WRITE-plane pair (dual roots collapse to one session face; these are the
         *  plane that owns the write gate — the read-only plane is internal to `inject`/`harvest`). */
        engine: MemoryEngine;
        handle: MemorySessionHandle;
        /** The session's scope contract (`TaskSpec.memory.scopeContract`): the owner of `handle.writeScope` is read under it. */
        scopeContract: "v2" | undefined;
        /** Merged injection across all planes (single-root sessions: identical to engine.inject(handle)). `frozen` = the
         *  segment's anchored index text by plane (each plane serves its own instead of reading); `served` = the text each
         *  plane's injection was composed from (what the anchor freezes when nothing was frozen yet). */
        inject: (frozen: import("../memory-engine/index-copies.js").IndexCopy["planes"] | undefined) => Promise<{
            injection: import("../memory-engine/engine.js").MemoryInjection;
            served: import("../memory-engine/index-copies.js").IndexCopy["planes"];
        }>;
        harvest: (phase?: "checkpoint" | "terminal") => Promise<HarvestReport | undefined>; /** One NEW entry in the write home through the session's memory write gate (`memory-engine/entry-create.ts`); the caller tools' write port reads it. */
        createEntry: (draft: import("../memory-engine/entry-create.js").MemoryEntryDraft) => Promise<import("../memory-engine/entry-create.js").MemoryEntryCreateOutcome>;
        /** End this mount's session leg WITHOUT a harvest: the run that mounted it will never reach its
         *  terminal harvest (a prepare that failed after the mount). Never throws. */
        release: () => Promise<void>;
        /**
         * The session's capture opt-out face (the `TaskStream.optOutMemoryCapture`
         * verb's target; host-API only — no tool face reads it, §2.6). `flip` re-adjudicates the
         * entitlement at call time (fresh caps resolve), mints the one-way record, runs the §2.3
         * boundary sweep, and delivers the effectiveness notice; its typed refusals are the
         * `memory.capture_optout_*` family. `optedOut` is the live state read (declared / standing /
         * flipped) — a GENUINE-record read: a store fault answers false here and TRUE on
         * `indeterminate` instead: the fault must reach the delegation floor
         * as its own third state, never as either boolean; an irreversible record is never minted off
         * an unreadable state, and an outage must not spawn un-floored children. Present whenever
         * the memory session mounted.
         */
        captureOptOut?: {
            /** Dual form: a sync capture store answers synchronously; a Promise-form store answers a Promise. `await` is correct on either arm. */
            optedOut: () => boolean | Promise<boolean>;
            indeterminate: () => boolean | Promise<boolean>;
            flip: (reason?: string) => Promise<{
                outcome: "created" | "existed";
            }>;
        };
        /**
         * The session's ONE-WAY pollution face. `markPolluted` fires when an
         * external-content-class tool is invoked (the prepare-time tool wrap below is the caller);
         * durable + in-process, no unmark exists at any layer. `polluted` is what the harvest legs read
         * (they consult it at harvest time themselves — this accessor serves observers/tests).
         */
        pollution: {
            polluted: () => Promise<{
                at: number;
                reason: string;
                cause?: import("../memory-engine/types.js").MemoryOriginCause;
            } | undefined>;
            /** `cause` is the structured mechanical fact the mark records (and the
             *  origin marker minted off it carries): `"observed"` for a witnessed external event,
             *  `"static"` for the capability over-approximation, `"derived"` for recall-taint. Absent
             *  folds to `"observed"` at mint time (the honest floor). The in-process half lands before it
             *  returns; the promise answers the DURABLE marker's outcome and never rejects — every caller
             *  delivers the external content only after it answered, and withholds it on `"unpersisted"`
             *  (the marker is what another engine reads when it attributes writes made beside this session). */
            markPolluted: (reason: string, cause?: import("../memory-engine/types.js").MemoryOriginCause) => Promise<import("../memory-engine/layout.js").SessionPollutionMarkOutcome>;
        };
        /** The task's content-safety config (normalized memory spec): the allowlist for
         *  UNDECLARED tools and the strict execution-class upgrade. Consumed by the tool wrap only. */
        contentSafety: {
            trustedTools: ReadonlySet<string>;
            execIsExternalContent: boolean;
        };
        /**
         * The delegation-settlement handle: what a settlement writer needs. Consumers (the subagent
         * background leg's write-ahead + terminal observation, the tool wrap's sync unattestable row)
         * can outlive this prepared leg, so they write through these fields alone — never through the
         * live engine/session objects above. Present only under `memoryProvenance: "carry"` (the
         * default): an `"off"` deployment keeps the pre-336 accepted-cost posture byte-level.
         */
        settlement?: {
            /** The WRITE plane's governance store (the settlement / lineage / challenge documents and the pollution
             *  marker a settled delegation's effects reach). */
            governance: import("../memory-engine/types.js").MemoryGovernanceStore;
            sessionId: string;
            provenance: "carry";
        };
        /**
         * The Read-tool recall-taint judgment, present only under
         * `memoryProvenance: "carry"`. True ⇔ the delivered ABSOLUTE path sits inside a mounted memory
         * plane and its head bytes carry a committed external-origin marker; the tool wrap then marks
         * the session derived (same seat and cause as the memory_get propagation). Never throws;
         * relative paths and unreadable files answer false (named residuals beside the Bash channel).
         */
        recallTaint?: {
            /** The exposure verdict of the committed entry whose seat the delivered path is (`"clean"` when it
             *  is none): `"marked"` ⇒ the Read marks the session derived; `"challenged"` ⇒ derived too, and the
             *  delivery carries a note that the memory tools withhold the entry until the host resolves its challenge. */
            judgeDeliveredPath: (absPath: string) => Promise<"clean" | "marked" | "challenged">;
        };
    };
    /** A per-task env minted by `RunnerDeps.executionEnvFactory` (the remote seam) that THIS task owns
     *  and the Runner must tear down on task end. Undefined when the env came from a (caller-owned) static
     *  `deps.executionEnv` or the stub — those outlive the task and must NOT be destroyed here. */
    ownedEnv?: ExecutionEnv;
    /** The leg's workspace sync seat (`./workspace-sync.ts`): present exactly when the env the leg works in (`ownedEnv`, else
     *  the static `deps.executionEnv`) carries `syncWorkspace`. The harness's turn watch, the parks and the teardown reach it. */
    workspaceSync?: import("./workspace-sync.js").LegWorkspaceSync;
    /** The run's ONE committed durable pause ({@link CommittedPause}): a mutable holder the commit-side
     *  publisher (`publishCommittedSuspend`) writes exactly once per run when a park commits — an approval
     *  or content ask, a resource slice, a platform pause, a plan or dry-run review — and the run loop reads
     *  to assemble the result's `terminal: { kind: "paused", … }`. WHICH pause it is is the cause's own
     *  `gate.kind` (a registry row), not the holder it landed in: the two same-shaped holders that used to
     *  split the approval family from the review family, and the commit-side routing between them, are
     *  gone. `current` is absent until a park commits. */
    pausedRef: {
        current?: CommittedPause;
    };
    /** A resumed leg's continuation content that has NOT reached the transcript yet: EVERY input frame the
     *  prompt carries (parked steers, the wake message, the approver's words) and the orphans whose obituary rides it. Set
     *  before the prompt, emptied at the prompt's own receipt (never its hand-off); a re-park carries it forward (the saga folds the
     *  orphans in, the adoption re-parks the frames), and what no re-park carries the undrained account announces. */
    undeliveredContinuationRef: {
        current: UndeliveredContinuation;
    };
    /** Ruled 2026-08-05 (matrix ruling arm A): set true by the resume engine when this leg EXECUTES the
     *  approved pending call — the restart-loop cap then counts from a fresh base (consecutive
     *  no-progress suspends only). See `suspendChainBase`. */
    suspendProgressRef: {
        executedApproved: boolean;
    };
    /** The remote-workspace lifecycle failures this run hit, appended in call order and echoed
     *  verbatim on `TaskResult.remoteEnvFailures`. A shared array (not a per-call return) because a suspend
     *  refusal is reported through the deployment's `onError` side channel and the run then continues or
     *  stops by its own rules — without this collector the caller's result kept no trace that a durable
     *  suspend was even attempted, let alone which of the eleven codes refused it. Empty unless something
     *  failed. Resume-leg failures do NOT land here (that leg throws out of prepare before a `Prepared`
     *  exists) — they ride the thrown error's `remoteEnvFailure` carrier instead. */
    remoteEnvFailures: NonNullable<TaskResult["remoteEnvFailures"]>;
    /** The asks this run refused because nobody could answer them, appended by the gate's deny exit (beside its notice) and echoed on
     *  `TaskResult.refusedAsks` when non-empty. */
    refusedAsks: import("../task-result.js").RefusedAsk[];
    /** The run's record of a refused verdict (`TaskResult.verdictRefused`), fed by every call end — see verdict-refusal.ts. */
    verdictLedger: import("./verdict-refusal.js").VerdictLedger;
    /** Set when a suspend was REFUSED because the task already suspended `maxSuspends`
     *  times (a resume/restart loop) — the run is aborted and assembles as `failed`/`suspend.loop` instead
     *  of minting yet another checkpoint. */
    suspendLoopRef: {
        hit: boolean;
    };
    /** Opt-in resource-slice suspend. Present (≠ undefined) ONLY when the task opted in
     *  (`spec.resourceSuspend`) AND it is eligible to suspend durably (a checkpoint store, durable tool
     *  results, and a remote — or static caller-owned, never per-task-stub — env). The run loop calls it at a
     *  CLEAN turn boundary when a resource limit (turns/budget/walltime) was hit: it mints a `resource_limit`
     *  checkpoint + pauses the workspace + stops the loop cleanly (NOT abort). Answers what the request came to
     *  ({@link BoundarySuspendOutcome}); anything but `committed` ⇒ the caller falls through to the normal limit stop.
     *  `sliceSpend` (Slice 4) is THIS slice's cost/tokens/turns, debited onto the cross-slice ledger. Only a TASK-axis
     *  reason reaches it — the external causes have their own lane below. */
    suspendForResource?: (reason: Exclude<ResourceLimitReason, PlatformLimitReason>, sliceSpend: {
        costMicroUsd: number;
        tokens: number;
        turns: number;
        walltimeMs: number;
    }) => Promise<BoundarySuspendOutcome>;
    /** The PLATFORM-cause suspend — the same commit saga as {@link suspendForResource},
     *  exposed on the INFRASTRUCTURE alone (checkpoint store + durable tool results + remote/no owned env),
     *  WITHOUT the `spec.resourceSuspend` opt-in. The run loop calls it at a clean turn boundary for the
     *  external causes — a scheduler's yield (`preempt`), an exhausted deployment usage window
     *  (`usage_window`), an execution environment about to be reclaimed (`env_lifetime`) — causes the task did
     *  not choose and cannot ask differently for, so a deployment that CAN keep the work has no reason to be
     *  asked whether it wants to. `hint.resumeAfterMs` (usage windows only) rides the gate and extends the
     *  checkpoint deadline. Answers what the request came to ({@link BoundarySuspendOutcome}); the caller reads
     *  the cause's fallback off the boundary's one table (a preempt continues, the other two stop loudly). */
    suspendForPlatformLimit?: (reason: PlatformLimitReason, sliceSpend: {
        costMicroUsd: number;
        tokens: number;
        turns: number;
        walltimeMs: number;
    }, hint?: {
        resumeAfterMs: number;
    }) => Promise<BoundarySuspendOutcome>;
    /** Why this leg cannot suspend durably — the clauses of every missing infrastructure piece, the one sentence the
     *  `resourceSuspend` INACTIVE line and an unhonourable yield both name (the manifest's `suspendLane.reasons` are its
     *  codes). Absent ⇔ the infrastructure is ready. */
    suspendLaneGap?: string;
    /** Epoch ms at which this run must stop and checkpoint because the EXECUTION
     *  ENVIRONMENT's declared lifetime is about to expire (`ExecutionEnv.lifetimeMs` minus
     *  {@link ENV_LIFETIME_SUSPEND_MARGIN_MS}). Undefined ⇒ the env declared no lifetime (every local env,
     *  and any adapter on an unbounded host) or declared one the engine could not anchor — in both cases the
     *  boundary check is dead code. Epoch, not monotonic: the anchor
     *  comes from the PLATFORM (an env can be older than this process), which is a wall-clock fact and the
     *  one domain both sides can name. */
    envLifetimeSuspendAt?: number;
    /** Deployment usage governance for this run, or undefined when the deployment wired
     *  none (or wired windows without a ledger, which is reported and not enforced). */
    usageGovernance?: UsageGovernance;
    /** 1.296 件2b — epoch ms at which the loop ISSUED the current provider call (stamped by the
     *  per-call stall-watchdog closure, consumed+cleared by runtask's brain.call trace row as
     *  `callStartedAt`). Always present. */
    callIssuedAtRef: {
        current?: number;
    };
    /** Was the run's WORK cut by a stop? Two observation points, one record, read by the answer-settled
     *  verdict (`answerSettled`) beside the harness's own undrained-input account:
     *  - `continuation` — the loop decided to CONTINUE past its last assistant turn and that continuation was never sent.
     *    TWO writers: the loop-trace sink, from the loop's own steps — a `continue` step (a drained steer / follow-up, a
     *    nudge, a next tool turn) sets it, the terminal step clears it unless the loop exited at its pre-dispatch abort guard
     *    (`aborted_before_stream`); and the leg's exit (`runLeg`), which sets it when the leg's last message is the spend
     *    account's unsent refusal — the same fact: in both, `final` is still the PREVIOUS turn's message. A clean "stop"
     *    the loop itself had decided was not the end is not a settled answer.
     *  - `abortedBeforeTurnEnd` — the run's abort was already in force when a turn ENDED (written by the
     *    `turn_end` handler before the turns cap fires its own abort). The ruling's line is the last
     *    `turn_end`: a stop that landed before it landed on work — even when the brain ignored the signal
     *    and delivered a full "stop" answer through it (the loop then ends at its own decision, so the
     *    continuation bit never sets); a stop that landed after it landed on the tail.
     *  Always present; both false on a run nothing stopped. */
    workCutRef: {
        continuation: boolean;
        abortedBeforeTurnEnd: boolean;
    };
    /** The word the loop's exit named (its terminal trace step; absent until it exits), read by the terminal arbitration
     *  (`ResultFlags.loopTerminal`) for the exits the final message cannot state. Always present. */
    loopTerminalRef: {
        reason?: LoopTerminalReason;
    };
    /** The loop's malformed-tool-use retry's re-asks so far this run (`LoopMalformedToolUseRecovery.onReask`, wired with the
     *  recovery lanes; a message ends before its own turn's re-ask) — read as `task.tool_turn_incomplete` `detail.reasksSoFar`. */
    loopReasksRef: {
        count: number;
    };
    /** Records the FIRST brain call this run's outer guardrail gave up on (see
     *  {@link import("../../brain/timeout.js").withBrainCallGuardrail}). Always present; `timedOut`
     *  stays absent unless the guardrail fired. The run loop reads it AFTER the loop settles and gives
     *  the task the typed terminal — the harness turns a loop throw into an error assistant message, so
     *  without this the cause would reach the caller only as the generic `provider.error`. */
    brainCallGuardrailRef: BrainCallGuardrailRef;
    /**
     * The tool gate's own TYPED STOP: set (once) when the classifier denial limit fell back to a person
     * and nobody judged it — no approver to fall back to (headless), or a DURABLE park whose decide
     * settled with a word the nobody-judged table reads as such — together with the run abort. The run
     * loop adopts it as the terminal `threw` (`TaskResult.errorCode` = the error's `code`,
     * `errorMessage` = its sentence) the same way it adopts the brain-call guardrail's — a loop that
     * ended because THIS lane aborted it must report the cause, not the consequence. The abort-result
     * details seam reads it too, so the aborted call's own `tool_end` carries the code. `undefined` ⇒ no
     * gate stop happened.
     */
    gateStopRef: {
        terminal?: Error & {
            code: string;
        };
    };
    /** The ONE closure that fills {@link Prepared.gateStopRef} (minted by `createDenialLimitStop`),
     *  carried on `Prepared` so the DURABLE resume station reaches the same seat, the same sentence
     *  composer and the same notice as the synchronous gate's arms — the second station of one rule, not
     *  a second rule. */
    stopForDenialLimit: StopForDenialLimit;
    /** Set by a tool calling `ctx.requestReview()` (the first-party `present_plan` tool, CC
     *  ExitPlanMode parity): the run loop honors it at the next CLEAN turn boundary by minting a `plan_review`
     *  checkpoint. `{ pending }` is set (with an optional reason) the moment a tool requests review, the batch's other
     *  requests queue in `later`; the boundary reads `pending` and clears both. The first request in a batch that may still
     *  show a plan wins, and so does its `requestedByCallId` — the engine-bound id of the call that asked, which the mint
     *  writes onto the parked row — and what that call's final result showed, recorded where the call's end is projected:
     *  the plan its card carried (`presented`, whose digest the mint writes), or why it showed a reviewer nothing
     *  (`withdrawn`: it yields to the next request; the first, if all are withdrawn, the mint refuses). */
    reviewRequestRef: import("../present-plan-tool.js").ReviewRequestCell;
    /** Present (≠ undefined) ONLY when a `checkpointStore` is wired (the deployment can pause). The
     *  run loop calls it at a CLEAN turn boundary with the pending request, whole, when `reviewRequestRef.pending` is set: it
     *  mints a `plan_review` checkpoint (`status:"needs_review"` by its registry row) + pauses the workspace + aborts the loop,
     *  reusing the SAME commit saga as the human/resource suspends. Returns true iff it committed a resumable checkpoint;
     *  false ⇒ the request could not be honored (caller drops it and continues) — a `withdrawn` request among them, said on
     *  the error face in the one `plan_review park skipped: …` sentence. */
    suspendForReview?: (request: import("../present-plan-tool.js").PendingReview) => Promise<boolean>;
    /** The prior cross-slice {@link ResourceLedger} (from the resumed checkpoint), so the run
     *  loop can size this slice's effective budget = `min(maxCostUsd, remaining)`. Undefined on the first slice
     *  (or a non-resource task). */
    resourceLedger?: ResourceLedger;
    /** A mutable holder the run loop populates (right after `stats` exists) so the
     *  human/irreversible_ask suspend can debit THIS leg's live cumulative spend onto the durable approval
     *  ledger it attaches (the resource-slice path passes `sliceSpend` explicitly; this event-driven gate has
     *  no such arg, so it reads the live spend here). Read at suspend time; absent ⇒ this leg's spend is not
     *  debited (the prior ledger still rides for the cross-leg READ). */
    liveSpendRef: {
        get?: () => {
            costMicroUsd: number;
            tokens: number;
            turns: number;
            walltimeMs: number;
        };
    };
    /** The cell the run body binds with the leg's side-call door once `stats` exists; a lane built at prepare (the
     *  permission classifier) books its replies through it. A lane that books before the run body bound it is an
     *  engine defect and throws. */
    sideCallBookRef: {
        book?: SideCallBook;
    };
    /** The per-task human-review accumulator (synchronous `resolveAsk` waits this leg + the carried
     *  prior-leg burden seeded from the resumed checkpoint). The run loop ADDS the durable-resume latency
     *  (`now() − cp.suspendedAt`) on a resume, then surfaces it as `stats.humanReview` at settle (always, `count: 0`
   *  included). **Budget-EXCLUDED** — never folded into cost/the budget gate. */
    /** borrowed-mutable — the hands' read-state map (the SAME `Map` object the toolkit and the context
     *  lane hold; absent without hands). Read by the provider-rejection recovery arm so its stale-result
     *  clears retire the entries those transmissions fed, through the same landing the frontier pass uses. */
    readFileState?: import("../../tools/fs/safety.js").ReadFileState;
    humanReviewRef: {
        count: number;
        totalWaitMs: number;
        gates: HumanReviewGateRow[];
    };
    /** The injectable wall-clock the run loop uses for the durable-resume human-review latency
     *  (`humanLatencyMs = now() − cp.suspendedAt`), so it reads the SAME clock as the suspend-side `suspendedAt`. */
    now: () => number;
    /** The FULL resolved tool list (real tools, never deferred placeholders) so the
     *  resume engine can execute a previously-suspended pending tool call directly (it bypasses the gate —
     *  the human already adjudicated it). Same wrapping (offload + ctx) the harness runs with.
     *
     *  ONE array, mutated in place; identity is the contract (every closure that resolves a name at run time
     *  reads this exact array). The array is PRIVATE to the `RosterBuilder` (tool-roster.ts) —
     *  every station below writes through its verbs (`mount` / `mountAll` / `unmountWhere` / `replaceAt` /
     *  `replaceDomain`) and this field is the builder's read face. WRITER TABLE — the only
     *  stations that write it, in prepare order:
     *   · caps-and-workflow — MINTS it (`spec.tools` through the ctx wrap + the large-result wrapper), then pushes
     *     ReportBlocked (enableBlockedReport ≠ false), ReportFindings (no caller tool of that name/alias),
     *     ExitPlanMode + EnterPlanMode (enablePlanMode ∧ the plan-review face), Workflow (self-orchestration active
     *     ∧ runner self ∧ hard sandbox ∧ governance baseline);
     *   · the driver — pushes StructuredOutput (outputSchema);
     *   · protocol-tools — pushes the MCP tools (through the remote wrapper), RefreshMcpTools (servers declared),
     *     the A2A tools; at RUN time its refresh closure splices a server's name-prefix domain out and back in;
     *   · hands mount — pushes the hands band (env wired);
     *   · delegation-surface — pushes TaskStop (background ∨ workflow door), SendMessage (door ∨
     *     parentNotify ∨ peer lane, ∧ runner self ∧ no shadow), AgentTranscript (door ∧ runner self ∧ no shadow),
     *     ListAgents (peer lane ∧ built-in SendMessage ∧ mountable), Monitor (background), EnterWorktree +
     *     ExitWorktree (tracked cwd), ReadToolResult (offload store);
     *   · question-face — pushes AskUserQuestion (the mount decision);
     *   · the driver — pushes CronCreate/CronDelete/CronList (write hands; inert without a daemon);
     *   · lsp — pushes the LSP tool (manager wired);
     *   · project-context — pushes Skill (manifest), the shared-memory pair and the memory-engine tools;
     *   · defer-classify — SPLICES OUT the excluded names and the retracted pair (the only removals at prepare);
     *   · memory-engine-session — REPLACES entries in place with the content-origin wrappers when it arms (a mounted
     *     memory session or a recorder channel); the refresh seam re-runs the same pass through `contentOriginWrapRef`
     *     after a re-splice (identity-tracked, so a wrapper is never wrapped again).
     *  tool-disclosure and listings only READ it (`harnessTools` is a derived list; placeholders never enter here). */
    tools: readonly AgentTool[];
    /**
     * This leg's minted TOOL ROSTER (the same object `wiringManifest.tools` carries):
     * one row per mounted instance in wire order. Minted ONCE at the prompt-assembly station (the same
     * pass that projects the prompt manifest's tool rows, so the two agree by construction); the park
     * station reads the gated call's identity off it, the exemption probe hands it to the host.
     */
    toolRoster: import("../tool-roster.js").ToolRoster;
    /**
     * The run-time delta seat: every roster change after prepare (the RefreshMcpTools
     * seam) re-mints the roster here and publishes a `ToolRosterDelta`. The run loop subscribes at the
     * point it emits `wiring_manifest` and forwards each delta as a `tool_roster_delta` event; until it
     * does, deltas are buffered in order.
     */
    toolRosterDeltas: import("../tool-roster.js").ToolRosterDeltaSeat;
    /**
     * The leg's card projector (`tool_end.structured` / `structuredSkeleton`): the engine card set ∪ the caller rows' declared
     * `renderHints.resultCards`; an undeclared `details.type` is dropped and announced ONCE per leg
     * (`config.tool_card_undeclared`). The ONE card port: every tool_end body projection (the live loop, the resumed
     * batch, the reconcile-recovered orphan) takes it as a parameter; no module-level card set exists to fall back to.
     */
    structuredProjector: import("./tool-output-projection.js").CardProjector;
    /** Name→effect map for every tool this task can call. Used by the abort-path orphan
   *  reconcile to make interrupted tool_results effect-aware (read/idempotent = safe to
     *  repeat; write/unknown = outcome unknown). Unknown names default to `write` (conservative). */
    toolEffects: Map<string, ToolEffect>;
    /** scan-1/A5 — the orphans the WAKE/CRASH reconcile closed while preparing this run (empty on a fresh or
     *  clean session). The run loop replays them onto the stream at run open as synthetic `tool_end` +
     *  `message_committed` frames, the same pair the live-abort leg mints at run close: a previous PROCESS
     *  died holding those calls, so this run's stream is the only place a consumer can ever learn they ended.
     *  Not the live-abort set — that one is reconciled inside the run and never passes through here. */
    wakeRecovered: RecoveredOrphan[];
    /** Fixed per-request prompt overhead (system prompt + tool schemas, ≈chars/4 tokens). Fed to
     *  `maybeCompact.overheadTokens` so the compaction trigger stays accurate in the anchor-less
     *  regime (custom Brains that don't report usage). */
    promptOverheadTokens: number;
    /** Accessor for the MAIN lane's latest real brain request (systemPrompt/messages/
     *  tools snapshot, recorded at the harness's provider seam just before each main-loop call). Fed
     *  to `maybeCompact.forkContext` on all three compaction lanes so the summary request can FORK the
     *  already-paid main prefix (CC form). `undefined` until the run's first main-loop call. Summary
     *  calls themselves never pass through the recorded seam (they ride the separate compaction-brain
     *  wrapper), so the snapshot is never polluted by a summary request. */
    lastBrainContext: () => CompactionForkContext | undefined;
    /** The same recorded request, unconditionally — the one write {@link lastBrainContext} also reads, minus its lossy-projection
     *  exclusion: what the main lane last sent (the advisor and `$.session.messages()` read it). `undefined` until the first call. */
    lastSentRequest: () => CompactionForkContext | undefined;
    /** The leg's advisor-instructions seat (advisor-instructions.ts); absent when the leg neither mounts the advisor nor has told the model of it. */
    advisorInstruction?: import("./advisor-instructions.js").AdvisorInstructionSeat;
    /** The leg's language seat (language-frame.ts); absent when the leg states no language, or has nothing to tell and nothing told. */
    languageSeat?: import("./language-frame.js").LanguageSeat;
    /** The sandbox instructions frame seat (`command-sandbox-frame.ts`): the text an armed run's first request owes, told once per
     *  segment and again when it changes; absent when the run keeps no sandbox and none was told. */
    sandboxFrameSeat?: import("./command-sandbox-frame.js").SandboxFrameSeat;
    /** #1123 — the memory notices this prepare drained (whole engine reminders, model lane only, no echo): the leg's first
     *  request carries them once, ahead of the user's message — a fresh leg's first user message, a resumed leg's
     *  continuation. Never the system prompt (an event there breaks the cached prefix twice). Absent when nothing drained. */
    memoryNoticesFrame?: string;
    /** The post-compaction restore (`MaybeCompactOptions.workingFileAttachments.restore`): re-reads the candidates through
     *  the leg's one file reader under the run's synthetic-Read judge — the user attachment's own path read — deduplicated
     *  against the read state the summary leaves, and mints their attachment frames (`readCompactionRestore`); what became of
     *  each is its record on the `compacted` frame (`restoreOutcomes`). A fault that kept a file from the transcript — the
     *  restore threw, the transcript would not take a frame — is reported (`onError` phase `degraded`, classification
     *  `attachment-read`). Present only with hands. */
    compactionRestore?: Required<Pick<NonNullable<import("../auto-compaction.js").MaybeCompactOptions["workingFileAttachments"]>, "restore" | "undelivered">>;
    /** CC post-compact restore parity (2026-07-03): the task's READ files, most recent
     *  first (from the hands' readFileState `lastReadAt` stamps). The restore prefers this over the modified set — CC
     *  restores what the model RECENTLY READ, including untouched reference files. Present only with hands.
     *  Seeded entries are excluded — their content lives in the system-prompt lane, which compaction never touches. */
    recentlyReadFiles?: () => string[];
    /** Canonicalizes a raw (often relative, model-typed) path the
     *  SAME way the hands toolkit does (`resolveKey` against the hands' containment root), so `maybeCompact`'s
     *  kept-tail/instruction-source exclusions compare paths in the SAME
     *  coordinate `recentlyReadFiles()` already uses — without this a plain string match silently never
     *  fires for the common relative-vs-canonical case. Present only with hands; absent there is no
     *  containment root to resolve against, and every path source is already in the same raw coordinate anyway. */
    normalizeAttachmentPath?: (raw: string) => Promise<string>;
    /** Wired to `MaybeCompactOptions.onApplied` by every compaction lane (the reference clears readFileState at its
     *  compaction landing site, @388663). Drops every read-state entry the summary took out of view
     *  (`readFileStateAfterSummary`); the restored files then re-register through their frames' own commits. Present
     *  only with hands. `preserveReadState` carries the files the context the summary leaves still shows — their
     *  existing entry survives the clear (the model's view of the file did not change).
     *
     *  SCOPE — read "every compaction lane" as exactly that and no wider. The request-layer
     *  stale-result pass takes a Read body off the wire with no compaction at all, and retires its own
     *  entries at its own landing site (`prepare-context-lane.ts`'s `landStaleResultClears`) through the
     *  SAME function this seat calls, on its `transmissions-gone` arm (the guard trim's dropped tool results and attachment frames too):
     *  ONE retirement mechanism, several ways for content to leave. Taken as a claim about every SHRINK mechanism this sentence was true
     *  of the lanes it named and silently false of the one it did not. */
    onCompactionApplied?: (preserveReadState: ReadonlyArray<string>) => void;
    /** The live diagnostics lane (present only when the gate passed — manager w/ registry +
     *  write hands + not opted out). `registry` is drained by runtask at turn boundaries; `nudge` is
     *  called (fire-and-forget) after each successful edit/write so the language server re-analyzes. */
    lspDiagnostics?: {
        registry: import("../lsp-diagnostics.js").LspDiagnosticsRegistry;
        nudge: (rawPath: string) => void;
        /** This run's key into the registry's delivered set (the registry is DEPLOYMENT-scoped — one per
         *  `NodeLspManager` — so "already delivered" has to be qualified by run). runtask passes it to every
         *  `drain` and calls `releaseRun` with it at the run's terminal. */
        runIdent: string;
        /** The files of a drain the run's read face withholds (`lspListedWithheld`: every view, fail-closed; kept files absent). */
        withheldOf: (uris: readonly string[]) => Promise<ReadonlyMap<string, unknown>>;
    };
    /** The ctx `requestStopAfterTurn` primitive's run-local mirror (one-way, set when a tool asked for a
     *  clean stop after the current turn). The harness latch itself is private to the loop; the turn
     *  boundary reads THIS to know that no next request follows — a boundary bundle collected there
     *  would be steered into a queue the loop never drains, and every one-shot announcement in it
     *  (listing frames, the once-per-session MCP arms) would be committed as delivered while it was not. */
    stopRequestedRef: {
        current: boolean;
    };
    envRefusal: {
        arm(): void;
        note(failure: Error & {
            readonly code: `env.${string}`;
        }): void;
        readonly read: Error | undefined;
    };
    /** Whether prepare's ONE read of the branch's announced snapshot succeeded (see
     *  `AnnounceOnceLedger.recovered`). False ⇒ the run loop must not flush the once-per-session arms
     *  as a whole-snapshot append on this leg (it would replace the branch's record with a partial
     *  one); the leg's announcements then simply repeat next run. */
    announcedSnapshotRecovered: boolean;
    /** The date-flip detector seam: `legDate` = the date frozen
     *  into this leg's system prefix; `today()` = the boundary-time LOCAL date (user-zone-bound closure).
     *  The run loop feeds both to the `date_change` attachment producer; the prefix itself never
     *  re-renders mid-leg (cache preservation, CC parity). Present only when the prompt carries a date.
     *  `anchor` = the session's date anchor as prepare read it (undefined ⇒ the branch was unreadable
     *  and the leg writes none); the settle lane persists it when it is new or the announced date moved. */
    dateChange?: {
        legDate: string;
        today: () => string;
        anchor: DateAnchorRead | undefined;
    };
    /** The leg's epoch-anchor seat: the anchor prepare read (undefined ⇒ the branch was unreadable, nothing is written) and
     *  the leg's request head as it stands when read (`tools` is the table as mounted, after the leg's activations and
     *  roster refreshes, before any request's view). The settle lane
     *  writes the anchor when the head is not the recorded one (`owedDateAnchor`). `memory` = the name of the store content
     *  this leg read live, when it is not the one the segment's anchor names (present ⇒ the settle lane anchors it). */
    prefixAnchor?: {
        read: DateAnchorRead | undefined;
        head: () => PrefixHeadDigests;
        memory?: MemoryTailSnapshot;
    };
    /** The `workflow_size_guideline_change` lane's seam, the {@link dateChange} shape one lane over:
     *  `legGuideline` = the RESOLVED guideline this leg's Workflow tool card was built with (the card is
     *  a per-mount snapshot, so it never re-renders mid-leg — the model learns a retune from the tail
     *  frame instead); `current()` = the boundary-time resolved guideline, read live off
     *  `RunnerDeps.workflowLimits` so a deployment retuning it mid-run is observable without a re-prepare.
     *  Present only when the Workflow tool is actually MOUNTED — a run with no workflow card has no
     *  guideline to change. The direct-construction face (`RunWorkflowToolDeps.sizeGuideline`) is out of
     *  scope by construction: this mount never passes it, so the deps channel is the lane's only source. */
    workflowSizeGuideline?: {
        legGuideline: WorkflowSizeGuideline;
        current: () => WorkflowSizeGuideline;
    };
    /** External-change scan (a turn boundary's, and a leg's first request's — `scanChangedFiles`) over the ≤`maxFiles` most-recently-READ
     *  files. Stats each via `env.fileInfo` and reports paths whose `mtimeMs` moved past the recorded
     *  `lastReadAt` + 2s epsilon (CC getChangedFiles shape: readFileState needs NO new field; the agent's
     *  own write-backs refresh `lastReadAt`, so self-edits are immune). ENOENT evicts the readFileState
     *  entry (CC evict-only-on-ENOENT — transient stat failures skip, never evict). Present only with
     *  hands; its callers ask it ONLY when `spec.attachments.changedFiles` opted in (OFF ⇒ zero stat). */
    detectExternalChanges?: (maxFiles: number) => Promise<{
        changed: Array<{
            path: string;
            mtimeMs: number;
        }>;
    }>;
    /** The instruction files of the task root's level and of the directories the run accesses (the family
     *  `NESTED_MEMORY_LANE.declaration` names): primed at the end of prepare (the manifest's `instructions`), then the leg's first
     *  request, each continuing boundary and a landed compaction ask it what the read state owes. Present only with hands and the
     *  declaration. */
    nestedMemory?: import("./nested-memory-lane.js").NestedMemoryLane;
    /** G1 通告层 — deferred tools MATERIALIZED (rematerialized) but not yet announced at a
     *  turn boundary. Appended by the rematerialize diff (newly-activated names only — the announced set
     *  is seeded with prepare-time actives INCLUDING resume-reseeded ones, so a resume never replays);
     *  DRAINED by the run loop only when the `tools_delta` attachment actually survived the byte cap.
   *  Present when the task has deferred tools at all.
     *
     *  The same frame's MCP arms, filled by the SAME rematerialize seam and drained by the same intact-survival predicate:
     *  - `pendingRemoved`: previously-ANNOUNCED tool names that left the live roster (a RefreshMcpTools
     *    re-splice whose server withdrew them). CC `removedNames`.
     *  - `pendingReadded`: names in `pendingRemoved`'s history that came back on a later refresh. CC
     *    `readdedNames`. */
    toolsDeltaRef?: {
        pending: string[];
        pendingRemoved: string[];
        pendingReadded: string[];
    };
    /** The `mcp_unavailable` frame's pending servers: declared servers whose dial failed at materialize (`statuses`), name/error
     *  neutralized + bounded at intake, MINUS the pairs this session's record already announced (a serving layer runs prepare once
     *  per user message, so the per-run set alone would re-announce every message). Present when at least one is pending — a
     *  task whose every MCP tool went missing with its server is exactly the one that must say so. Carried by the leg's first
     *  request (a fresh leg's first message, a resumed leg's continuation) and drained by that message's receipt (`settleMcpUnavailable`). */
    mcpUnavailable?: {
        pending: import("../mcp-failure.js").McpUnavailableEntry[];
    };
    /** G1 通告层续批 (CC `agent_listing_delta` parity) — the mounted delegation tool's agent-type roster
     *  (read off `ToolSpec.agentListing`, filled by createSubagentTool), plus the tool's mounted name for
     *  the roster headers. [c209-C]: this seam is now the roster's ONLY model-facing carrier —
     *  the run loop delivers the initial full frame ON THE FIRST USER TURN (prompt-adjacent) and
     *  boundary drift deltas after. `models` (Q4, read off `ToolSpec.agentModels`) rides the initial
     *  frame's tail line. `seedAnnounced` = a durable-resume leg: the run loop seeds the producer's
     *  announced set from the checkpoint's `announcedListings.agents` name-set when present (drift
     *  since suspend IS delta-announced), else the MED-3② transcript probe (delivered ⇒ seeded as
     *  the current entries; unconfirmed ⇒ the resume leg re-announces the initial listing). Present
     *  only when such a tool is mounted AND its roster is non-empty. */
    agentListing?: {
        entries: ReadonlyArray<{
            name: string;
            description: string;
        }>;
        toolName: string;
        seedAnnounced: boolean;
        models?: readonly string[];
        budget: ResolvedSkillListingBudget;
    };
    /** [c209-C] skills_listing counterpart of {@link agentListing} — the normalized skills METADATA
     *  projection (names/descriptions/attachment paths, never bodies; the exact list `createSkillTool`
     *  serves). Initial full `<skills>` frame on the first user turn, drift deltas at boundaries,
     *  same seeding contract. Present only when `spec.skills` is non-empty (post 1MB-gate). */
    skillsListing?: {
        entries: ReadonlyArray<SkillListingEntry>;
        seedAnnounced: boolean;
        budget: ResolvedSkillListingBudget;
    };
    /** [c209-C] Q5 — the run loop's live mirror of the listing frames' announced NAME-SETS (updated at
     *  every commit point: first-frame delivery, intact boundary survival, resume seed). Read by the
     *  suspend-time checkpoint serializer (`CheckpointState.announcedListings`) so a resume leg can
     *  diff the then-current roster/skills against what the model actually saw. Always present (empty
     *  object when nothing announced / no listing faces mounted). [c209-C] R2 C7: `models` mirrors the
     *  ANNOUNCED model catalog the same way (advanced only when a committed frame carried one), so a
     *  catalog change across a suspend is re-announced as a "Models available…" drift line.
     *  `mcpFailed` / `advisories` are the once-per-SESSION arms of the same snapshot (see
     *  announce-once-ledger.ts): seeded at prepare from the branch's record, advanced by the run loop
     *  on delivery of the mcp_unavailable frame / intact delivery of the mcp_dropped_tools frame. */
    announcedListingsRef: AnnouncedListingSnapshotInput;
    /** The frame-receipt ledger — the ONE commit point of every engine frame that rides a user message
     *  (the git-status frame, the agent and skills listing frames). Always present; per leg. */
    frameReceipts: FrameReceiptLedger;
    /** The run's engine text reading, bound to its locale (`TaskSpec.promptLocale`) once at prepare: every engine-minted
     *  text the runner's own lanes send (the MCP frame on both lanes) reads through it. */
    engineText: EngineText;
    /** env-tail migration — the git-status frame lane's run-local state: this leg's
     *  resolved frame (probe outcome rendered + hashed at prepare), the announced `(kind, hash)`
     *  mirror the checkpoint serializer reads, the trim-protection slot the request-build context
     *  handler matches on, and the re-assert closure the compaction landing + boundary retry call.
     *  Always present (empty object on a hands-less leg — the lane is then out of scope). */
    gitStatusRef: GitStatusLaneRef;
    /** The posture composition's run-local half (the newest carrier's protection slot; the row last composed for). */
    postureFrameRef: import("../auto-mode-directive.js").PostureFrameRef;
    /** The request's irreducible core for this leg: the objective input the guard trim never drops (written by the objective
     *  lane before the first request) and the typed terminal a request-build guard parks when a core cannot fit. */
    requestCoreRef: import("../context-guard.js").RequestCoreRef;
    /** The limit-approach notice's seat: the turn boundary writes the crossing, the request-build handler carries it ({@link LimitApproachSeat}). */
    limitApproachRef: LimitApproachSeat;
    /** G1 通告层 — narrow getter over the process task registry: THIS run's visible live background tasks
     *  (pending / running / parked under the same owner/scope/session identity the TaskStop tool
     *  uses), EVERY one (`TaskRegistry.liveTasks`), as a projection (id/description/status and the row's read handle,
     *  `TaskRegistry.readHandleOf` — never handles/env/abort). Read by the post-compact listing (which caps what it
     *  renders), the resume's orphan diff and the stop hook's `backgroundTasks` view. `{ settled: true }` = the same rows with
     *  the finished ones too (`TaskRegistry.list`) — the whole-session notification loss's table, where a finished task's
     *  lost frame is the likeliest loss and its read handle the one way back. */
    listBackgroundTasks: (opts?: {
        settled?: true;
    }) => Array<{
        id: string;
        description?: string;
        status: string;
        read?: string;
    }>;
    /** One task's read handle under the same identity (`TaskRegistry.readHandleOf`) — a live or terminal row this leg reaches;
     *  `undefined` for an unreachable id or a row with nothing to read. Read by a dropped notification's disclosure line. */
    taskReadHandleOf: (taskId: string) => string | undefined;
    /** The parent-run subagent-retain ledger (present ONLY when `spec.retainSubagentSessions`
     *  is enabled). The Runner disposes it (abort in-flight resumes + unpin + release every retained child
     *  session) in the task's terminal `finally` — same UNCONDITIONAL posture as the background-agent reap:
     *  retain is NOT durable (a suspend leg's in-memory ledger cannot survive a re-prepare), so releasing on
     *  every exit path is hygiene, never a loss. */
    subagentRetain?: SubagentRetainLedger;
    /** Run-scoped consecutive-`summaryProvider`-reuse counter, OWNED by the Runner and
     *  SHARED across both compaction call sites (within-task turn boundary + `finish()`), so the
     *  `maxConsecutiveProviderReuse` drift guard is enforced over the whole task — incremented when a
     *  compaction reused the provider's summary, reset to 0 on a real (LLM) summary. */
    compactionReuseRef: {
        consecutive: number;
    };
    /** Trim→compaction pressure propagation (16k live sawtooth root cause): set by the
     *  context hook when `trimToBudget` actually DROPPED messages from a request view (request-only trim
     *  + usage-anchor mismatch deflates the next boundary's estimate → the trigger and floor are both
     *  deceived → full-size request spikes alternate with trimmed troughs). The next turn boundary's
     *  `maybeCompact` consumes it as `force: true` (bypasses the auto threshold AND the §25.2 anti-thrash
     *  floor — "the request layer was forced to drop history" is direct evidence compaction is overdue).
     *  One-shot: cleared on consumption; a failed compaction does NOT re-arm it (existing breaker path).
     *  Content-only clears (`clearStaleToolResults`) never set it — only real message drops do. */
    trimPressureRef: {
        droppedMessages: boolean;
    };
    /** The microCompact machine state this run: the selected clearing
     *  machine, the cleared-projection ledger (request-view application, durable decisions — see
     *  `context-edit.ts`'s ledger note; seeded from the session's record at the run's first request
     *  build and recorded back after a build that changed it — `cleared-results-record.ts`), the last request's projection seat (what the provider actually
     *  saw — the MC-R rejection arm computes its candidates and savings on THIS view, never on the
     *  raw session rebuild), the MC-R knob, and the slice-3 arm-B seat. */
    microCompact: PreparedMicroCompact;
}
/** What the in-turn forced compaction did for a request over its guard: `landed` (the harness rebuilds and re-sends), or why it
 *  did not — `off` (the run's automatic compaction is off), `paused` (the consecutive-failure breaker is open), `suppressed` (the
 *  last landing freed too little and the conversation has not grown past it since), `noop` (nothing older to summarize), `failed`
 *  (the summary did not land), `cut` (the turn, the run or its caller stopped). The guard trim's account to the person names it. */
export type InTurnCompactionVerdict = "landed" | "off" | "paused" | "suppressed" | "noop" | "failed" | "cut";
/** See {@link Prepared.microCompact}. */
export interface PreparedMicroCompact {
    /** The frontier-machine selection — `"off"` = no proactive frontier clearing (the machine
     *  instead gets its one blocking-point shot, slice-3 arm A). */
    machine: MicroCompactMachine;
    /** MC-R: one-shot clear-and-retry on a provider input-too-long rejection.
     *  Default true since the slice-3 flip. */
    clearOnRejection: boolean;
    /** The in-turn forced-compaction seat: runtask wires a closure
     *  that runs the SAME forced-compaction pass the prompt-too-long recovery uses (gates included)
     *  and answers what it did ({@link InTurnCompactionVerdict}: `landed` in the session, or why not). The context hook calls it when the
     *  pre-send estimate breaks the guard budget and then returns `adoptSessionRebuild` so the
     *  harness adopts the reduced transcript. `signal` is the TURN-scoped abort of the request
     *  build (r3): a turn interrupt must be able to cut the summary call short instead of waiting
     *  it out. `anchoredEstimate` is the chain's estimate at scale 1 (the floor's coordinate) — the seat consults the
     *  §25.2 anti-thrash floor against it (an ineffective landing must not be repeated per request
     *  build; the chain's arm C owns the bounded fallback). Unwired (pure-prepare callers) ⇒ arm B
     *  declines and the chain falls to the trim last resort — same posture as a compaction-disabled
     *  run. */
    inTurnCompactionRef: {
        current?: (signal?: AbortSignal, anchoredEstimate?: number) => Promise<InTurnCompactionVerdict>;
    };
    /** The request-build seat of the automatic threshold: the automatic compaction is judged before a request, never after
     *  one. The turn boundary wires a closure that runs its OWN automatic pass (the natural threshold, the anti-thrash floor,
     *  the breaker, the preCompact hook, the same landing and frames) and answers whether a compaction landed; the context hook
     *  calls it when a judgment is `owed`, consuming the mark on entry. `owed` is `"leg-start"` at the leg's first build (the
     *  automatic switch alone admits it) and `"boundary"` at the build after a boundary (which only measured; the within-task
     *  switch admits it); a boundary no request follows leaves its mark unread. `signal` is the turn's abort (an interrupt cuts
     *  the pass and is no compaction failure), `fork` the request that build is about to send (the reuse form's main request;
     *  `undefined` ⇒ the independent form). Unwired ⇒ the request goes as built. */
    turnStartCompactionRef: {
        owed?: "leg-start" | "boundary";
        current?: (owed: "leg-start" | "boundary", signal: AbortSignal | undefined, fork: () => Promise<CompactionForkContext | undefined>) => Promise<boolean>;
    };
    ledger: ClearedProjectionLedger;
    projectionRef: {
        current?: {
            /** The FINAL projected view of the last provider request (post trim/sweep). */
            messages: AgentMessage[];
            /** Occurrence coordinates of that view (object-identity first, unambiguous-group fallback). */
            keyOf: OccurrenceIndex["keyOf"];
            /** The line a resend of that request is trimmed to after a refusal (the refusal's error text in), or none when the
             *  trim can shed nothing more from it — the guard chain's reading of its own trim. */
            lineAfterRefusal: (failureMessage: string | undefined) => number | undefined;
        };
        /** The rejection lane's answer to that request when the provider refused it and the forced pass found nothing to
         *  fold: the line the resend is trimmed to, for the turn whose request it answers (`turn`, that turn's signal). The next
         *  request build consumes it, and only the resend reads it — a build of another turn drops it: its guard line is the lower
         *  of the window's and this one, and its forced pass has had its shot. */
        resendLine?: {
            readonly line: number;
            readonly turn: AbortSignal | undefined;
        };
    };
    /** The run's ONE offload persist (write-once, idempotent): the frontier pass, the blocking-point arm and the MC-R arm all clear
     *  through it, so they compose identical markers. Absent when no offload store is configured. */
    offloadPersist?: import("../tool-result-store.js").OffloadPersist;
}
/**
 * Resume inputs threaded into {@link prepareTask} to continue a suspended task. The Runner
 * builds it from the persisted {@link Checkpoint}: rewind the branch to the suspension leaf, skip the
 * suspended batch during wake-reconcile, and re-seed the §4.bis per-task correctness state so the
 * resumed run is in the **same state space** it suspended in.
 */
export interface PrepareResume {
    /** The session leaf to rewind to (the suspension point) BEFORE reconcile — discards the abort's
     *  off-branch "Operation aborted" writes so the resume engine resolves the pending batch cleanly. */
    leafId: string;
    /** The session rows the parked leg's port held past that leaf (`Checkpoint.heldRows`): the resumed harness's queue starts with
     *  them and writes them at the transcript's first legal point. Absent ⇒ the park held none. */
    heldRows?: readonly AgentMessage[];
    /** Batch tool-call ids of the suspended turn — wake-reconcile SKIPS these (they are resumed, not
     *  crash-interrupted; closing them with `[INTERRUPTED]` would DESTROY the suspended batch, §15.2 #7). */
    suspendedBatch: ReadonlySet<string>;
    /** The §4.bis correctness-state snapshot to re-seed (activeTools / outputRef / nestedStats /
     *  readFileState). */
    seed: CheckpointState;
    /** The decision this resume carries (the gate word and, for a review, approve / edit / reject) — read by the mode seed
     *  (`modeRequestAfterResume`: an approved or edited `plan_review` exits a recorded plan to its pre-plan word). Absent on a prepare that resumes nothing. */
    outcome?: ResumeRun["outcome"];
    /** A `tool_approval` card's call (its tool name and parked arguments), read by the leg's adoption step (`resumedWorkflowCallOf`). */
    pendingCall?: {
        readonly toolCallId: string;
        readonly toolName: string;
        readonly args: unknown;
    };
    /** Present when the resume opens this leg with inputs it hands over — a wake: the newest of them (its message, else the parked
     *  entry delivered last; `wakeOpening`): its run-origin word (absent = it said none) is the leg's word instead of the row's. */
    opening?: {
        readonly word: unknown;
    };
    /** The leg's mods bus, when the resume entrance already admitted it (a wake message's screen raises
     *  `classic.UserPromptSubmit` before this leg prepares): prepare adopts it instead of admitting a second time. */
    legMods?: LegMods;
    /** How many times this task already suspended (the resumed checkpoint's
     *  `suspendCount`). The next suspend mints `priorSuspendCount + 1`; past `maxSuspends` it fails
     *  (`suspend.loop`) instead of re-suspending. Absent/0 ⇒ no prior suspends. */
    priorSuspendCount?: number;
    /** The cross-slice {@link ResourceLedger} carried by the resumed `resource_limit`
     *  checkpoint (cumulative spend + the frozen human totals). The next slice's effective budget is
     *  `min(maxCostUsd, totalBudget − spent)`, and its own suspend debits onto this. Absent ⇒ the first slice. */
    priorLedger?: ResourceLedger;
    /** The accumulated human-review burden carried by the resumed checkpoint
     *  ({@link import("../checkpoint-store.js").Checkpoint.humanReview}) — the gates resolved up to and including
     *  the suspend BEFORE this one. Seeds the per-task accumulator so the resumed leg ADDS this suspend's own
     *  latency (`now() − cp.suspendedAt`) on top, reporting the WHOLE chain's burden. Absent ⇒ no prior human time. */
    priorHumanReview?: {
        count: number;
        totalWaitMs: number;
        gates: HumanReviewGateRow[];
    };
    /** When the suspend ran with a remote workspace, the {@link CheckpointState.workspaceHandle}
     *  to restore — prepare rebuilds the per-task env via `deps.executionEnvFactory` then `resumeVM(snapshotId)`
     *  + `postResumeInit()` (instead of running on a fresh, empty env). Threaded HERE (not via `ResumeTaskConfig`)
     *  so the factory stays a deployment-level `RunnerDeps` capability and never pollutes `TaskSpec` — preserving
     *  the "untrusted caller can't inject an env" red line ({@link import("../remote-env.js").ExecutionEnvFactory}'s
   *  own contract states it: "Lives on `RunnerDeps` (deployment-level) — NOT on `TaskSpec`"). */
    workspaceHandle?: import("../remote-env.js").WorkspaceHandle;
    /**
     * The call id of the CONTENT ask whose answer an operator's approval was spent on, when
     * that is what this leg redeems. Scoped as an id, not a leg-wide flag: an `unavailable` outcome on
     * THAT call must become a coded failure (the approval bought a question nobody answered), while a NEW
     * question raised later on the same leg had no approval spent on it and keeps the ordinary
     * continuation. Absent when the resumed pending action is not a question.
     */
    redeemedContentAskCallId?: string;
    /** Digest of that question's batch — the id alone can repeat, so the pairing is what keeps a LATER
     *  question from inheriting the claim that an operator approved it. */
    redeemedContentAskQuestionsHash?: string;
    /** true iff this resume will EXECUTE an approved pending tool (`tool_approval`
     *  checkpoint × an `allow` winner). The divergent-restore fail-closed guard keys on THIS, not on the
     *  batch being non-empty: a deny winner executes nothing, so a workspace-root divergence must not
     *  wedge the refusal (it proceeds under the path-state rebase and records the deny). */
    executesApprovedAction?: boolean;
}
/**
 * Parent effective-policy inheritance (tighten-only, {@link RunInternals.inheritedGate}): the spawning
 * chain's already-evaluated FINAL gate, split into two halves —
 *
 * - **Data half** (`ancestorRules`, `shellGate`, `permissionMode`): serializable snapshots. Each ancestor's per-session
 *   permission rules ride as (sessionId, principal, rev, rules) so the child's prepare can re-read them
 *   LIVE (rev-monotonic — a lagging replica never loosens the snapshot) and re-compile them against the
 *   CHILD's own env/root/effects as extra deny-narrowing layers. `shellGate` is the operator floor
 *   (`"always"`): a child inherits it and cannot lift it. `permissionMode` is the ceiling a child's own
 *   declaration is clamped under.
 * - **Opaque half** (`parentConstraints`): each ancestor's live caller `ToolPolicy` plus its FROZEN
 *   `onAsk`, ancestors first — and, for a mods-wired ancestor, a SECOND entry: its installation (the bus
 *   its admission mounted, `installation`), carrying its own frozen approver/mandate/env axes. A caller
 *   policy is folded AFTER the child's own caller policy and BEFORE the trailing deny-narrowing re-check,
 *   each wrapper resolving its own `ask` via the ancestor's frozen approver — so a parent `ask` never
 *   widens into a child auto-allow, and a parent `allow{updatedInput}` rewrite is still re-checked by the
 *   child's narrowing layers. An installation judges the child's calls at the child's gate, on the
 *   installation's own bus (`classic.PreToolUse` at phase 1, `tool.check` at the verdict read), its
 *   question settled under the same frozen axes. NOT serializable: a durable resume must re-supply it via
 *   `resumeStream(..., internals)` (see {@link CheckpointState.inheritedGate}).
 *
 * Chain assembly is single-sited in prepareTask's ctx injection (`inheritedGateForChildren`): upstream
 * chain + THIS task's own contribution (its session-rule snapshot, its RESOLVED caller policy —
 * `spec.toolPolicy ?? deps.toolPolicy`, the same slot its own gate enforces — + frozen onAsk, its
 * effective shellGate, and — when this task resolved a PreToolUse hook — a screening entry for that
 * hook, deduped by full installation so a deps-level hook is consulted once per call at any depth).
 * Depth-N delegation is therefore a linear chain, each layer evaluated at most once per tool call.
 */
export interface InheritedGate extends InheritedAutoModeFace {
    /** Serializable ancestor session-rule snapshots (data half), ancestors first. */
    ancestorRules?: ReadonlyArray<{
        sessionId: string;
        principal?: string;
        rev: number;
        gen?: number;
        rules: SessionPermissionRules;
    }>;
    /** The chain's shell floor (`"always"`) — a child inherits it; its own spec cannot lift it. */
    shellGate?: ShellGateDoctrine;
    /**
     * The chain's EFFECTIVE permission mode at spawn (data half, session-wide like every mode): the CEILING a
     * child's own declaration is clamped under (`TaskSpec.permissionMode` absent ⇒ inherit; declared ⇒ adopted only
     * where the rank table admits it, else folded and disclosed). Persists on the checkpoint's data half
     * (`CheckpointState.inheritedGate.permissionMode`) so a redemption in another process resumes under the same
     * declared mode — and re-judges the deployment's deny bits for its own leg.
     */
    permissionMode?: PermissionMode;
    /**
     * The parent's live mode ceiling (opaque half; never serialized): the parent leg's mode while that leg runs, its
     * SESSION's current leg after it — the child's effective mode is DERIVED from it on every read, so a parent's steer
     * reaches a running child on the child's next arbitration without a forwarding frame, and the session's next leg
     * reaches a child that outlived the leg that spawned it (a session-scoped background child). `sessionId` is the
     * parent's, the address of the user notice a folded child declaration is announced on. `hold` (the engine's own
     * ceiling): the child is re-judged at each move of the ceiling, and a fold that produces is announced as at prepare.
     */
    permissionModeCeiling?: {
        readonly current: PermissionMode;
        readonly observed?: LegModeCeiling["observed"];
        readonly sessionId: string;
        readonly hold?: LegModeCeiling["hold"];
    };
    /**
     * Org-memory admission freeze (ruled 2026-08-05): the spawning chain's FROZEN admitted org-scope
     * set — every org memory scope the parent actually mounted (deployment-origin + admitted request).
     * A delegated child's REQUEST-origin org scopes must be a subset (intersection ≠ request ⇒ the
     * child's prepare refuses, `memory.admission_denied`); deployment-origin scopes circumvent the freeze
     * (operator authority is deployment-wide). ALWAYS emitted by chain assembly (empty array = parent
     * mounted no org plane), so an ABSENT field discriminates an older-shape chain — which the child
     * side reads fail-closed as the empty set. Serializable (plain strings): persists on the
     * checkpoint's data half and folds seed ∩ live on resume (tighten-only).
     */
    admittedOrgScopes?: readonly string[];
    /**
     * The MONOTONIC org-governance provenance bit: `true` when any leg of this
     * tree ran with an org-admission surface configured (resolver / deployment scope list) or
     * inherited the bit. It never clears once set (a governed tree stays governed), and it counts as
     * governance evidence at the admission door EVEN when every admitted set en route is empty — a
     * governed parent's org-less child, resumed on a surface-less worker, must still refuse
     * org-shaped non-v2 scopes instead of mounting them as opaque keys. Absent on trees that never
     * had a governance surface (their opaque posture is untouched). Serializable; persists on checkpoints.
     */
    orgAdmissionGoverned?: true;
    /** The chain's one reading of the `sharedArtifactReads` setting (in-process; never on a checkpoint): a leg an engine lane bears takes
     *  it instead of reading the seat again, so a run has one reading; a root leg ignores it, and every wake hands none (`wakeGate`). */
    sharedArtifactReads?: import("../shared-artifact-reads.js").ResolvedSharedArtifactReads;
    /**
     * The chain's TOP leg's root and environment home (data half, serializable; persists on the checkpoint's data half):
     * the anchors of the person's global and session path rows and of every `~/` row on this chain — a child judges them
     * where the chain was installed, not at its own root (a project row anchors at its own scope root). Emitted by every leg
     * that hands a chain down (a top leg emits its own). Absent on an older chain ⇒ the child is its own top. A child placed
     * in ANOTHER filesystem namespace (its environment did not put it where it was asked, outside the caller's tree) ignores
     * it and takes its own leg as the top.
     */
    pathRuleAnchors?: {
        readonly root: string;
        readonly home?: string;
    };
    /**
     * Where each `parentConstraints` entry was INSTALLED (data half, serializable; persists on the checkpoint's data half):
     * position for position with `parentConstraints`, the root and home its path rules are anchored at (`null` for an entry
     * with no path rules). A chain re-supplied with uninstalled policies (a resume in another process, a host-built chain)
     * installs each where this records — never at another leg's anchors. Absent on an older chain: an uninstalled entry is
     * installed at the chain's top leg (`pathRuleAnchors`).
     */
    pathRuleInstallations?: ReadonlyArray<{
        readonly root: string;
        readonly home?: string;
    } | null>;
    /** The kinds of persisted-rule bucket the legs above read (data half, serializable; persists on the checkpoint's data half): each
     *  leg that hands a chain down joins its own to the chain's. A leg whose Runner cannot read one of them is refused at prepare
     *  (`config.persisted_rule_bucket_missing`, `refuseUnreadAncestorBuckets`). Absent (no leg above read one, or an older chain) ⇒
     *  this chain asks nothing; present in another shape ⇒ refused with the same code (`readRuleBuckets`). */
    persistedRuleBuckets?: import("../persisted-rule-buckets.js").PersistedRuleBuckets;
    /** Live ancestor caller-policy constraints (opaque half), ancestors first. `policy` is the ancestor's
     *  RESOLVED caller policy (`spec.toolPolicy ?? deps.toolPolicy` — the same slot the ancestor itself
     *  enforces, so a deps-level baseline is inherited too).
     *
     *  ⚖️ A-005.13 (ruled with the F-012 family, 2026-08-09): the ancestor's per-run BUDGET LEDGER does
     *  NOT travel this chain — by design, not by omission. An inherited policy's `check` receives the
     *  CHILD run's own `ToolCallRequest.budget` snapshot (the child's durable resource ledger), so a
     *  SELF-LIMITING ancestor policy ("allow N escalations, then ask") sees a fresh ledger in each
     *  delegated child rather than a continuation of the ancestor's counts. Freezing/snapshotting the
     *  ancestor ledger was considered and rejected: a frozen ledger goes stale the moment the ancestor
     *  keeps running (a stale ledger is a NEW wrongness surface, not a fix), and the durable resource
     *  ledger's identity is per-run by contract. A deployment wanting cross-delegation budget coherence
     *  carries it in its own policy state (the closure travels the chain intact — a closure-counter
     *  policy DOES aggregate across the tree, since every layer evaluates the same instance).
     *
     *  `onAsk` is the ancestor's frozen
     *  `spec.onAsk ?? deps.onAsk` — an ancestor `ask` resolves at that ancestor's own approver
     *  (headless ⇒ deny), never at the child's. `durableMandate` is frozen at chain-assembly time when the
     *  ancestor ran under a durable-approval regime that would actually PARK its own plain asks — a
     *  `forceDurableGate` entitlement, or `durableApproval` with NO live onAsk frozen (with a live approver
     *  the ancestor's own plain asks resolve synchronously there, so a descendant's ask resolves at that
     *  same frozen `onAsk` — no mandate). It is a CONSERVATIVE descendant-side mandate: whether or not a given ask would actually
     *  have parked at the ancestor (the regime may be scoped), the durable-park semantics cannot be
     *  reconstructed in a delegated child's context — so a wrapper seeing `ask` under this flag denies
     *  fail-closed (tighten-only holds) instead of resolving synchronously.
     *
     *  Each entry is exactly ONE of two kinds: a caller policy (`policy`), or a screening installation
     *  (`installation` — the bus a leg's admission mounted, or {@link import("../mods/stations.js").admitModChain}'s on a
     *  cross-process re-supply). A chain naming both, neither, or an installation no engine admission mounted is refused.
     *
     *  `kind` names what the entry is (`installation` / `taskPolicy` / `deploymentPolicy`): stamped where the entry is minted
     *  (`legConstraintLayers`, constraint-layers.ts — one leg's contribution, at birth and at a revival's rebuild alike), carried
     *  verbatim down the chain, recorded on a park's chain entry and bound by its digest. A resume on a runner that holds no live
     *  chain for the row rebuilds each layer from it; an entry handed without one is compared without it, so it matches only a row
     *  an engine before kinds recorded. */
    parentConstraints?: ReadonlyArray<({
        policy: ToolPolicy;
        installation?: undefined;
    } | {
        installation: LegModBus;
        policy?: undefined;
    }) & {
        kind?: import("../tool-policy.js").ConstraintLayerKind;
        /** `true` on a layer the chain's ROOT leg minted (the leg nothing handed a chain and nobody delegated), stamped beside `kind` at
         *  the same assembly ({@link import("../tool-policy.js").ConstraintChainEntryMeta.rootLeg}, #5125): a rebuild replaces only such a
         *  `taskPolicy` layer with the host's `rootPolicy`. */
        rootLeg?: true;
        onAsk?: OnAsk;
        durableMandate?: boolean;
        /** The CONTENT-ask twin of `durableMandate`, frozen from the QUESTION seat (`spec.onQuestion ??
         *  deps.onQuestion`) on the same rule: a `forceDurableGate` entitlement, or `durableApproval` with no
         *  LIVE question face frozen (absent, or the reserved resume placeholder — neither can answer). A
         *  wrapper seeing an `ask` on the question tool consults THIS bit, never the permission one: the two
         *  asks are answered by two different faces, and a run with a live `onQuestion` and no permission
         *  approver can answer a delegated question perfectly well. When it IS set the delegated question is
         *  marked unresolvable and takes the child gate's park / honest-refusal leg, exactly as an inherited
         *  permission ask does under `durableMandate`. */
        contentMandate?: boolean;
        /**
     * F-012 — the ancestor's FROZEN auto-mode classifier: the same decider instance the
         * ancestor's own gate consults for a surviving ask (`ToolGateInput.autoMode`). Without it the
         * ancestor's ask DECISION CHAIN did not travel — the wrappers resolved an inherited ask straight
         * at the frozen approver, so an ask the ancestor's classifier would have BLOCKED executed in the
         * child on the frozen approver's allow. The wrapper runs it BEFORE the frozen approver, in the
         * ancestor's own gate order (classifier → approver): `block` ⇒ deny (`decisionReason:"classifier"`),
         * `allow` ⇒ the classifier's auto-allow (the frozen approver is not consulted), anything else
         * falls through to the approver chain. Never consulted for the reserved question tool nor under a
         * durable mandate (a marked call must reach the park with no synchronous decision-maker between).
         */
        autoMode?: {
            decider: AutoModeDecider;
            /**
             * The ancestor's per-run DENIAL-LIMIT tracker, frozen beside its decider (same owner). The
             * wrapper arms count the frozen classifier's blocks on it and, at a bound, resolve the fallback
             * ask at the frozen approver instead of denying (`requiresRealApproval` set, sandbox admission
             * excluded). Live-only, like the decider: a cross-process redemption starts a fresh count.
             */
            denialTracking?: AutoModeDenialTracker;
            /**
             * The SERIALIZABLE criteria half of this classifier (assembly inputs + knobs + the
             * deployment's settings epoch), present when the arming deployment opted in
             * (`RunnerDeps.autoMode.persistArming`). A durable park records it on the chain entry so a
             * CROSS-PROCESS redemption can rebuild an equivalent decider over its own model leg instead of
             * answering `unavailable` forever; the constraint-chain digest binds it, so a resume re-supplies
             * exactly what the row carries. It never affects THIS process's decisions — the live `decider` is
             * the one every gate consults, here and on every descendant.
             */
            arming?: AutoModeArmingRecipe;
            /**
             * The ancestor's live mode ceiling (opaque, never serialized; the chain's `permissionModeCeiling`): the classifier
             * answers the ancestor's asks only while this reads `auto` — else they go to the frozen approver. Absent (a
             * re-supplied entry) ⇒ the classifier answers as recorded.
             */
            liveMode?: {
                readonly current: PermissionMode;
            };
        };
        /**
         * The environment this installation was installed against — the source of the `HookEnvCapabilities` face its
         * `classic.PreToolUse` e carries (`env`), compared BY REFERENCE, `undefined` when the installation had no env. The
         * installation identity (`sameInstallation`) is the chain its bus's admission recorded plus the context its questions are
         * settled in — the frozen approver, the two durable mandates, this environment, the classifier instance — the
         * CONSERVATIVE test: two chains over the same registrations in a different order, or a re-built registration object,
         * compare unequal. Chain assembly does not re-append a leg already on the chain; a descendant's own gate stands in for an
         * installation only when that identity holds under no mandate; any other is judged on both events under its own context
         * — judged twice rather than skipped, never toward a missed one. Part of the
         * installation's identity for the same reason the frozen approver is (HIGH): a face that
         * resolves paths through `ctx.env` answers a different question in a different environment, so an
         * ancestor running against the deployment's tree and a descendant running in an isolated worktree are
         * two screenings, not one. A deployment with a per-task `executionEnvFactory` therefore has its face
         * consulted once per environment on the chain rather than once overall — which is the point: the
         * ancestor's environment is the only place the ancestor's verdict can be reproduced.
         *
         * ⚠️ RECORDED BOUNDARY (delegation provenance): the approver half of the key compares
         * through {@link askApproverIdentity}, which by its own contract answers "the same decision-maker",
         * collapsing a `withDelegationProvenance` wrapper onto the approver it forwards to. Two installations
         * whose approvers differ ONLY in the provenance they attach therefore count as one. Raw reference
         * equality is not an available alternative: a delegated child's approver is ALWAYS a fresh wrapper
         * over its parent's, so raw equality would collapse nothing and a deployment-level face would be
         * consulted once per ancestor level on every leaf call. The exposure is bounded on the side that
         * matters — the pass-through arm hands the frame to the DESCENDANT's own gate, whose approver carries
         * the descendant's own provenance (strictly more context, never less). What a chain-assembly collapse
         * can drop is one intermediate installation's provenance on an ask: an approver that DECIDES on
         * `req.delegation` would see the surviving installation's rather than both.
         */
        hookEnv?: unknown;
    }>;
}
/** The runtime feature flags the stable prompt's harness-context block gates its sections on
 *  (claim only what the task has). Spread into the assembly's StablePromptContext
 *  by the prompt-assembly phase, which re-derives `orchestrationEnabled` against the post-exclusion roster and derives
 *  `orchestrationDeferred` there from the leg's deferred set (the set the request's placeholders are minted from). */
export interface PromptFeatureFlags {
    policyEnabled: boolean;
    hooksEnabled: boolean;
    isolationEnabled: boolean;
    reminderMark: string;
    readFaceOpen: boolean;
    writeFaceOpen: boolean;
    orchestrationEnabled: boolean;
    goalEnabled: boolean;
    awarenessEnabled: boolean;
    worktreeIsolated: boolean;
    withinTaskCompactionEnabled: boolean;
    isSubagent: boolean;
    /** No store to persist through, on the run that holds the user's conversation (the memory phase's verdict). */
    memoryStoreAbsent: boolean;
}
/**
 * A TRUSTED, run-scoped internal channel into {@link prepareTask}, set
 * ONLY by a trusted CORE caller (`runRepairLoop` via the Runner's internal `runTaskStream` arg) — NEVER from
 * a {@link TaskSpec} field (the untrusted-caller surface). It is the live-state counterpart
 * of {@link PrepareResume.seed}: where `resume.seed` re-seeds correctness state RESTORED from a checkpoint,
 * this carries the LIVE per-task state the Runner cannot otherwise see (it lives in the caller's closure).
 *
 * Originally it carried only the repair loop's live {@link RepairBundle}: `runRepairLoop` is a thin composition
 * OVER `runner.runTask`, so when an orthogonal durable suspend (resource/HITL) interleaves a repair attempt,
 * the bundle (failureTrace/diagnostics/attemptCount/oracleTier) sits in the loop's closure and was being lost
 * — the minted checkpoint serialized `repairBundle: undefined`. Threading it here lets
 * {@link prepareTask}'s `serializeCheckpointState` source the LIVE bundle so a resume re-seeds `attemptCount`
 * MONOTONICALLY. Mirrors how `nestedStats`/`resume.seed` thread trusted
 * run-scoped internals through the Runner without touching `TaskSpec`.
 *
 * @contract prepare.deps-read-stable — the `RunnerDeps`, `RunInternals` and `ExecutionEnv` handles a host
 * passes into {@link prepareTask} are READ-STABLE for the duration of the call: prepare reads them at the
 * points its phases need them, and a host that mutates them between microtasks while prepare is in flight
 * is outside the contract (the Runner is constructed over its deps; a mid-prepare rewrite is a race the host
 * made). Phase boundaries are scheduling points — an `await` on a phase that carries its own awaits adds a
 * microtask between that phase's last continuation and the driver's next read — and such a host can observe
 * them; the engine does not defend against it. The untrusted surface is {@link TaskSpec}, whose pre-first-
 * await latch is a separate, pinned guarantee (prepare-task-phase-pins T1).
 */
export interface RunInternals {
    /** The spend account this leg hangs under: the seat of the run that started it or woke it — a delegating tool hands on its
     *  `ToolExecuteContext.spendSeat` as it is — and how it hangs there (`task` — bound to that run's end; `session` — outlives it).
     *  Absent ⇒ the leg is a root of its own account. A `seat` that is not one the engine handed out (absent included) is
     *  refused (`config.invalid_argument`). Trusted, never a TaskSpec field. */
    spendParent?: import("../spend-account.js").SpendParent;
    /** This leg's host seats by declaration name: a `{ kind: "host" }` server of `TaskSpec.mcp` / `ResumeTaskConfig.mcp` dials through the
     *  pipe its seat opens for each dial (mcp-host-seat.ts; a request-level seat rides `hostSeatOfRequests`); a declaration with no seat fails its dial (`config.mcp_host_seat_missing`), a seat with no declaration is
     *  announced once (`config.mcp_host_seat_undeclared`). The leg's own: a delegated child is handed the seats of the host servers it
     *  inherits (a definition declares none: its door refuses one), a retained child's snapshot keeps none (its waker's seats ride each wake). Trusted, never a TaskSpec field. */
    mcpHostSeats?: ReadonlyMap<string, import("../mcp-host-seat.js").McpHostSeat>;
    /** A workflow agent's leg the host's durable-approval opt-in was withheld from: the stores the workflow lacked (`WORKFLOW_PARK_GAPS`).
     *  Read once, by the leg's refused-ask notice (`detail.workflowParkGap`, where no park lane was armed). Trusted, never a TaskSpec field. */
    workflowParkGap?: readonly import("../ask-unresolvable-notice.js").WorkflowParkGap[];
    /**
     * The tool-selector layers of the run that spawned this leg — its ceiling ({@link ToolFaceSnapshot.selector}`.layers`): this
     * leg's selector is these layers plus its own `allowTools` / `excludeTools`, so nothing a child names can widen what its
     * parent could use. Present on every leg an engine lane spawns (an empty list when the parent was unbounded). A host may write it on
     * a root run it starts (`runTask(spec, { toolCeiling })`): the task-start doors judge it as a host-written workflow ceiling is judged (another spelling of a tool the run carries refuses: `config.tool_face_control`, `near_miss`); its rows record it. Trusted, never a TaskSpec field.
     */
    toolCeiling?: readonly import("../tool-face.js").ToolSelectorLayer[];
    /** The run's member ledger book (`TaskSpec.runLedger`) — always the run's own lane's (its notification lane mints it and hears the
     *  run's frames into it); undefined on a run without a ledger. Trusted, never a TaskSpec field, never handed to a child. */
    runLedgerBook?: import("../run-ledger.js").RunLedgerBook | undefined; /** This leg is a worker of a run that keeps a member ledger, handed no tool that starts agents (the spawn says so): its SendMessage refuses a revival saying why and who can. */
    agentStartersWithheld?: true; /** The dispatching manager's seat (`TaskSpec.managerApproves`): a fresh spawn's only, read by no resumed leg, and only as the engine minted it. */
    managerSeat?: import("./manager-seat.js").ManagerSeat | undefined;
    /** Set by the delegation lane when the spawning run's prepare judged this leg's own tool lists (its spec's `allowTools` /
     *  `excludeTools` — a definition's or the delegation tool's) against a pool it could list: their digest (`toolListsDigest`), the
     *  evidence bound to exactly those lists. A prepare whose own lists digest to it does not judge them again, and its rows record it
     *  (`CheckpointState.toolListsJudged`) so a resume that hands no internals keeps the judgment. Absent (a delegation tool whose pool
     *  cannot be listed, a workflow agent, a team member, a host's direct `runTask`), or lists that digest differently ⇒ the leg judges its own lists. */
    toolListsJudged?: string;
    /** Set by the delegation lane: whose lists this leg's own are — the delegation tool that spawned it (its declared name, its mounted one), the
     *  agent definition it was spawned as (absent ⇒ the tool's tool-level list) and `lists`, the digest of exactly the lists it wrote. A refusal
     *  at the leg's prepare names that list (`delegationListWhere`), and the tool's name is a name of this leg's lineage: its own lists are
     *  asked of a universe that carries it. Held only for the lists it wrote ({@link boundOwnToolLists}): other lists are the host's own
     *  `TaskSpec` seats. Absent ⇒ no delegation tool behind the leg's own `TaskSpec` seats. */
    ownToolLists?: {
        readonly toolName: string;
        readonly definition?: string;
        readonly lists: string;
    };
    /** Set by the workflow lane when it launches an agent as an agent type whose definition writes tool lists: the definition's name and its
     *  two lists as one selector layer. The leg's selector reads it between the ceiling it was spawned under and its own lists (the
     *  definition bounds which tools the leg is handed, as a delegated child's does; the leg's own lists stay the deployment's), its prepare
     *  judges it once as a definition's lists are judged (`config.agent.unknown_tool`, told to the operator), and its rows record it with
     *  the ceiling. Trusted, never a TaskSpec field. */
    definitionToolLists?: {
        readonly agentType: string;
        readonly layer: import("../tool-face.js").ToolSelectorLayer;
    };
    /** Set only on an observer sidecar's legs: the leg kind whose protocol is the observer's report tool. */
    observerLeg?: true;
    /** Set by an engine lane that HOLDS this leg's parks — a background lane that can park the child (a durable row store, the store the
     *  child parks in, durable child sessions) and a workflow whose park lane is armed (a run store and its checkpoint store), on every leg
     *  they run (the first start, a revival, a parked-resume drive). A leg this run started on an engine lane ({@link isDelegatedChild},
     *  {@link observerLeg}) WITHOUT it is a leg nobody resumes: none of its parks is minted (`approvalParkNotResumableOf`, source `lane`).
     *  Never on a retained agent's snapshot: its wake cycle settles a pause as failed and holds no park. Trusted, never a TaskSpec field. */
    parkLaneHeld?: true;
    /** The live repair bundle from a `runRepairLoop` attempt in flight (attemptCount>0). Serialized onto a
     *  checkpoint minted MID-attempt so a resume re-seeds it; undefined for any non-repair run. */
    repairBundle?: RepairBundle;
    /**
     * The ENGINE deliberately stripped the spawn turn's per-request `onQuestion`
     * face from this leg's spec (a long-lived background/retained/revived child must not hold a
     * callback torn down with the turn that spawned it). Minted ONLY by the subagent lanes'
     * `stripSpawnTurnQuestionFace` helper, PAIR-PRODUCED with the strip itself — never inferred from
     * spec shape. Consumed by the wiring manifest (`question.wired: "stripped_bg_lane"`) and by the
     * interaction-posture door (the strip is core's correct design, not a configuration lie, so an
     * `"interactive"` tree's engine-stripped legs are exempt). TRUST POSTURE (ruled 2026-08-05):
     * RunInternals is a public trusted-caller parameter, so this flag is an honesty channel, not a
     * security gate — a caller forging it is a deployment lying to itself; resource-face safety
     * stays with its own fail-closed mechanisms. INHERITS DOWN THE TREE: a stripped leg's descendants are faceless by
     * the same engine act (the trusted ctx carries it as `ToolExecuteContext.questionFaceStripped`, the Workflow mount as
     * `parentQuestionFaceStripped`), so the posture-door exemption travels with the facelessness it explains; a leg
     * that strips on its own mints the same flag.
     */
    questionFaceStripped?: true;
    /**
     * The SPAWNING run's resolved interaction posture, carried
     * into engine-built children over the trusted internals channel (never copied onto the child
     * SPEC — the §8.3 rule). The child's door resolves `spec ?? THIS ?? deps`, so a root's per-run
     * posture override governs its whole engine-built tree instead of every child falling back to
     * the deps-level default. Filled by the delegation lanes' `childInternals` and the workflow
     * spawn attribution; rides `internalsSnapshot`, so retained/revived legs keep it.
     */
    parentInteractionPosture?: "interactive" | "headless";
    /**
     * The trusted post-consume hook for the PARKED-RESUME drive: called by `resumeStream` after its resolve CAS WON (the token
     * is consumed — the master arbitration is decided) and BEFORE the resumed leg starts. The parked-resume caller uses it to
     * flip the reserved row `parked→running` (guarded CAS) + adopt the live handle/lane — the ONLY legal site for that flip (a
     * pre-consume flip would let TaskStop hit the plain running arm and circumvent the checkpoint arbitration). A THROW aborts
     * the resume (propagates out of `resumeStream`): the checkpoint is already consumed, so the caller's compensation
     * (`rollbackParkedClaim`) reads `resolved` and settles the honest failed/outcome-unknown terminal — never a silent run
     * without an adopted row. Trusted-caller channel only, like every RunInternals field. STATING `{ cycleSeq }` says this claim
     * OPENED that cycle (the number it wrote on the row): the resumed leg runs as it ({@link RunInternals.cycleSeq}) and the
     * engine mints the cycle's `task_started` and lifecycle `spawn`. So never state the parked cycle's number (to continue that
     * cycle, state nothing: the leg keeps the `cycleSeq` handed in), and never mint a start frame of your own (a second start,
     * same number). The runner never computes a number; `void` leaves the internals as is.
     */
    afterCheckpointResolve?: () => Promise<void | {
        cycleSeq: number;
    }>;
    /**
     * Parent effective-policy inheritance (tighten-only): the spawning parent's already-evaluated FINAL
     * gate, threaded into a child task so the child inherits it as ADDITIONAL constraint layers — a child
     * can only ever be narrowed by this, never widened (its own session rules / skill rows / caller policy
     * still apply in full). Filled ONLY by core delegation callers (`createSubagentTool`'s execute via
     * `ToolExecuteContext.inheritedGateForChildren`, the workflow spawn legs) — NEVER a {@link TaskSpec}
     * field (the untrusted-caller surface), mirroring `inheritedSkillGrants`'s ctx-injection posture.
     * Absent ⇒ no inheritance (a top-level task; fully backward-compatible).
     */
    inheritedGate?: InheritedGate;
    /**
     * The own caller policy (`TaskSpec.toolPolicy`, as its resume input holds it now) of the chain's FIRST leg — the leg that inherits
     * no chain; a cascade rung is such a leg — not the session root task's; handed by a host that drives a parked delegated leg back
     * (`parkedResume.rootPolicy`). That leg's layer (`taskPolicy`, `rootLeg`) on a live chain (its regime kept) and on a rebuilt one alike
     * (`constraint-layers.ts`); none handed ⇒ a live chain keeps it as registered (`permission.revival_root_policy_unrestated`), a rebuild refuses. A policy is asked with the facts of the call it judges (the calling leg's
     * `cwd`, roots, target and budget), never with the session it was born in. Neither an opaque policy nor the leg a layer came from
     * can be told apart (KL-5107-f): hand that leg's own, never a substitute.
     */
    rootPolicy?: import("../tool-policy.js").ToolPolicy;
    /**
     * The delegation RUNTIME-PROVENANCE channel. Minted by the spawning delegation
     * tool when the parent chain is armed (the parent mounts a memory session, or is itself recording
     * for ITS parent): `ref` is the child's monotonic aggregate — the child's recorder writes into it
     * as the run progresses (live faces read the current bits; the terminal attestation reduces from
     * it); `contentSafety` is the chain's FROZEN classification snapshot — the child may narrow it
     * with its own config, never widen. Trusted internals chain only, same posture as
     * {@link inheritedGate}. Absent ⇒ the child records nothing (its deliveries then read `unknown`,
     * and every judgment falls back to the static floor — fail-closed by construction; whether the
     * floor's verdict MARKS the judging session follows that run's deployment evidence standard,
     * {@link RunnerDeps.memoryDelegationEvidence}).
     */
    delegationProvenance?: {
        ref: {
            current: import("../memory-engine/delegation-provenance.js").DelegationProvenanceAggregate;
        };
        contentSafety: import("../memory-engine/delegation-provenance.js").DelegationContentSafety;
    };
    /** The run TREE's cross-boundary token — the tree's ONE state is reached from it by the engine alone: the spawning leg hands its
     *  own down (the delegation and workflow lanes), so a bit any leg sets is read by every other at its next judgment; a root leg mints one. */
    crossBoundaryTree?: import("../cross-boundary-taint.js").CrossBoundaryTreeToken;
    /** The external-content-target fold's later-leg seat: `true` ⇒ this leg treats what its environment produces as content from outside
     *  the deployment's trust boundary, whatever the environment declares — a join beside the environment's declaration and a resumed
     *  row's record, never a downgrade. A composition hands it to the legs it runs after a leg whose result carries
     *  `TaskResult.effectiveExternalContentTarget` (the verify gate's verifier and fix legs). Read `=== true`, as the other flags of
     *  this trusted seat are. */
    externalContentTarget?: true;
    /**
     * The SESSION-scoped org-admission freeze for a SAME-SESSION continuation
     * that is NOT a checkpoint resume: a retained background child revived through the in-process resume
     * leg. The checkpoint plane already freezes the session's own verdict
     * ({@link InheritedGate.ownAdmittedOrgScopes}); this leg has no checkpoint, so without a carrier it
     * re-adjudicated from scratch and a resolver whose answer WIDENED between the two legs remounted a
     * tenant layer the session had already lost.
     *
     * A REF, not a value: the revival replays a spread COPY of the spawn-time internals, so a plain field
     * could only ever carry the value that existed at spawn (always `undefined`). The prepare reads
     * `current` as its `priorOwnVerdict` — intersected with any checkpoint seed, so the fold can only ever
     * narrow — and writes this leg's own verdict back, which is ⊆ the prior one by construction.
     *
     * TRUSTED internal, filled by `createSubagentTool`'s `childInternals` (one ref per spawned child, never
     * shared across generations — a child's own children build their own). Absent ⇒ no session freeze from
     * this channel, byte-identical to a deployment with no governance surface.
     */
    ownOrgAdmissionRef?: {
        current: import("../memory-admission.js").OwnOrgAdmissionVerdict | undefined;
    };
    /**
     * This run's LATE-BOUND peer-identity carrier (a REF, same family and reason as
     * {@link ownOrgAdmissionRef}: revival replays a spread copy of spawn-time internals, and the axes
     * a run wears are born at different points — a* handle at registration, session/task at prepare's
     * session acquisition). Created at internals assembly (delegation lanes; runtask normalizes one
     * in for a top-level run); axes recorded through the single monotonic `addAxis`; the canonical
     * key freezes at the first recorded axis (h→s→t by call-site ordering). Read by the SendMessage
     * mount (sender key + hop token) and paired into children as {@link parentPeerRef}.
     */
    peerSelfRef?: import("../../agents/peer-admission.js").PeerSelfRef;
    /**
     * This run's INBOUND peer-chain ref: overwritten at the harness consumption boundary
     * with the chain of the peer message the model just consumed (enqueue-time writes would leak a
     * not-yet-seen message's chain into outbound sends); seeded by the L3/L4 wake legs; empty
     * otherwise. Not checkpointed in v1 (recorded honest boundary: a cross-process resume forwards
     * from an empty chain — fail-open on loop suppression only).
     */
    peerInboundChainRef?: import("../../agents/peer-admission.js").PeerInboundChainRef;
    /**
     * The PARENT run's peer-identity ref, PAIR-MINTED with {@link parentNotify} at every
     * trust point that binds the uplink callback (spawn assembly, the resume face's replacement): the
     * callback is opaque and the parent AXES deliberately keep the original spawner on the revive arm
     * while the callback points at the WAKER — so the uplink's admission identity can only travel
     * with the binding itself. Consumed by the SendMessage mount as `uplinkRecipient`.
     */
    parentPeerRef?: import("../../agents/peer-admission.js").PeerSelfRef;
    /**
     * 🔴 The workflow **nesting depth** for this run, a TRUSTED
     * cross-process channel (worker/script can NEVER set it — it is not a {@link TaskSpec} field nor a
     * `run_workflow` tool param). When a deployment initiates a workflow on behalf of a parent run that is
     * itself inside a workflow (e.g. service's `/v1/workflows`), it threads `workflowDepth = parentDepth + 1`
     * into `startWorkflow`/`runWorkflow` so the one-level nesting guard fires across the process boundary.
     * In-process nesting needs nothing here — the engine's `AsyncLocalStorage` propagates depth automatically.
     * Mirrors how `repairBundle`/`inheritedSkillGrants` thread trusted run-scoped internals the Runner cannot
     * see from `spec`. Consumed by the `run_workflow` tool wiring (S8c), not by `prepareTask` itself.
     */
    workflowDepth?: number;
    /**
     * The host's DECISIONS for cards that finished workflow runs parked on (`wa*` rows with `status:"parked"`), a TRUSTED run
     * channel like `workflowDepth` (never a `TaskSpec` field, never a tool argument — a model cannot decide an approval). A host
     * that has a person's decision for such a card starts any run of the run's session with the decision here — `runId` the run
     * holding the card, `decisionId` the host's own id for this decision (a new one each time a person decides), `outcome` the
     * decision — and at that leg's run-body opening the engine continues the run once (`workflow-park-adoption.ts`): no model
     * call, no Workflow ask while the leg's gate answers that call with only an ordinary ask; whatever stops it is said on
     * `workflow.parked_decision_unused`. A model's own `Workflow({resumeFromRunId})` never reads these. `inheritedGate` is the
     * re-supply of the checkpoint's opaque parent constraints (else the leg's own chain is handed). Consumed by the Workflow
     * tool's continuation, not by `prepareTask` itself.
     */
    workflowParkedResume?: ReadonlyArray<{
        runId: string;
        token: CheckpointToken;
        decisionId: string;
        outcome: ResumeOutcome;
        inheritedGate?: InheritedGate;
    }>;
    /** The deployment's credential for the claim this run acts under (an opaque grant id — `encodeGrantHolder`; a TRUSTED channel like
     *  the decisions above). A resume handed one carries it into its CAS as `expect.holder`, and so does every Workflow drive this run
     *  makes. On a leg the host started, every session write the leg makes carries it too (`SessionWriteOptions.holder`); a leg an engine
     *  lane started (a delegated child, a workflow member, an observer) stamps none, even when a drive handed it one for its CAS. A grant
     *  the store does not hold current is `holder.superseded`: nothing written or applied, the leg stops — do not retry it. Every store
     *  seat the run writes must declare `fence = { holder: "writes" }` (`config.invalid_checkpoint_store` / `config.invalid_session_store`
     *  at the door otherwise). Never inherited by children. */
    holder?: string;
    /** The deployment's credential for the session TREE this run works in (opaque, a TRUSTED channel; a non-empty string). Opt-in: absent,
     *  nothing changes. Present, it rides the one holder slot of every durable write an engine lane of this tree makes (a delegated child,
     *  a revival, an observer, a workflow member — each inherits it; a retained child keeps the one it was born with), the writes of a
     *  host-started leg that has no `holder`, and every resume claim that has no `holder` (`writeHolderOf`, `claimHolderOf`). A session
     *  seat must declare `fence`, or — for an engine lane's leg — `durableFence` with a storage that answers for itself; refused otherwise. */
    treeHolder?: string;
    /**
     * Set ONLY by the Agent tool's fork route (`Agent(subagent_type:"fork")`, a core caller) on the
     * child it spawns: this run IS a forked child. `prepareTask` threads it to tool ctx as `insideFork` so the
     * child's own Agent tool refuses a nested fork (nesting guard — mirrors CC's "fork is not available inside a
     * forked worker"; a fork can still delegate via `Agent`, just not fork again). TRUSTED internal (NOT a
     * `TaskSpec` field — the untrusted-caller surface), mirrors `inheritedSkillGrants`.
     */
    insideFork?: boolean;
    /**
     * The PARENT's reminder provenance mark, set ONLY by the Agent tool's
     * fork route on the child it spawns ("one declaration, one mark": a fork runs under the parent's
     * byte-identical system-prompt declaration, so its own engine mints must carry the PARENT's mark;
     * a spawn/clone context mints its own). Verified through the mint home's verify port at adoption
     * (`isValidReminderMark` — an unrecognized value re-mints, fail-safe); the forked SESSION's own
     * `reminder_mark` entry is the primary carrier (a store fork copies committed history), this
     * channel is the in-process belt over it. TRUSTED run-scoped channel (NOT a {@link TaskSpec}
     * field), mirroring `insideFork`.
     */
    reminderMark?: string;
    /**
     * Set UNCONDITIONALLY by every core spawn path (`createSubagentTool`'s
     * `childInternals` — shared by all four spawn legs sync/steer/background/fork, its persisted
     * `internalsSnapshot` for revive, and the workflow orchestrator's `spawnAttribution`), regardless
     * of whether a NAMEABLE `parentTaskId`/`parentToolCallId` exists. A directly-started workflow (no
     * launching tool call, e.g. cron-triggered) has neither of those — "no id is ever fabricated" for
     * attribution — but its spawned agents are still delegated children for consent-notice purposes.
     * Drives `isSubagent` below: do NOT use `parentTaskId` presence alone as the child-ness signal,
     * that under-covers exactly this case. TRUSTED run-scoped channel (NOT a {@link TaskSpec} field),
     * mirroring `insideFork`.
     */
    isDelegatedChild?: boolean;
    /** The project seat its spawner (or waker) hands the leg, a DEFAULT: its id only when the leg declares none and has no marker, its texts only
     *  when the leg's verdict is its id (`resolveSessionProject`); screened and copied at the call's internals door (a refused one ends the leg). Trusted internals. */
    parentProject?: import("../project-seat.js").ProjectSeat;
    /** Who wrote this leg's objective ({@link import("../input-author.js").InputAuthor}), stated by the seat that mints it; absent = the public
     *  entry's caller, `operator`. Only the operator's objective passes `classic.UserPromptSubmit`; a non-member reads `unknown`, is screened and
     *  reported once (`onError`, `"config"`). Never inherited — each seat says its own. TRUSTED run-scoped channel (NOT a {@link TaskSpec} field). */
    objectiveAuthor?: import("../input-author.js").InputAuthor;
    /**
     * Subagent transcript persistence — the child transcript session's PLACEMENT declaration, minted
     * by the background delegation lane (the trusted spawner: it knows the a* handle, scope and root)
     * and forwarded verbatim by this prepare's session acquire, so the session store CREATES the
     * child's transcript into its declared subagent partition (see {@link SessionStore.placements}).
     * Deliberately a TRUSTED internals seat and never a {@link TaskSpec} key: a public key would let
     * any caller push arbitrary sessions into the partition and poison store-side retention/
     * enumeration. Absent (sync children, forks, observers, every non-delegated run) ⇒ the acquire
     * carries no placement. The placement says where the row lives, never whose it is: the row's owner rides the acquire's own
     * `owner`, which prepare reads from {@link delegationOwner} for every leg that holds a spawner's seat, placed or not.
     */
    sessionPlacement?: import("../session.js").SessionPlacement;
    /**
     * The catalog WORD that chose the model this engine-spawned child was handed on its spec.
     *
     * The two halves of one fact travel on two channels on purpose: the spec carries the RESOLVED `Model`
     * object, so nothing re-resolves between the spawn's judgement and this child's prepare (the model the
     * spawn frames name is the model that runs); this carries the word that object came from, so the child
     * is not PINNED by having been handed an object — its own children inherit the word in turn, and the
     * deployment's per-model window overlay (keyed by word) still reaches it. Absent ⇒ no word exists for
     * this child's model (a caller-pinned object, a `select` criteria), and such a leg is deliberately never
     * re-resolved and never overlaid. Trusted channel, never a `TaskSpec` field: it is the engine's own
     * statement about a model the engine itself resolved, and a caller cannot author it.
     */
    inheritedModelRef?: ModelRef;
    /**
     * GOAL MODE flag, a TRUSTED internal channel set ONLY by `runGoal` (a core caller),
     * NEVER a {@link TaskSpec} field. It drives `featureFlags.goalEnabled` → injects `GOAL_COMPLETION_GUIDANCE`.
     * Why internal (not a public `TaskSpec.goalMode`): the guidance promises "declaring done STOPS iteration and
     * surfaces" — a promise only `runGoal`'s loop makes real. A public field would let a caller inject that
     * prompt with no loop behind it (§6.3 honesty violation). `runGoal` injects the `declare_done` tool itself;
     * this flag only governs the PROMPT (injection-ownership split).
     */
    goalMode?: boolean;
    /**
     * The skill grant rows the PARENT task held at the moment it spawned this child (its `allowed-tools` / `disallowed-tools`
     * rows of the run, whatever wrote them), captured by `createSubagentTool`'s `execute` from the parent's
     * `ctx.activeSkillGrants()` and seeded into this child's table as `inherited` rows: they hold until THIS child ends
     * (the parent's run ending ends the parent's rows, not this copy), beside the child's own activations.
     *
     * A TRUSTED, run-scoped channel (never a {@link TaskSpec} field — TaskSpec is the untrusted-caller surface), in the
     * posture `repairBundle` / `resume.seed` keep. A capture the delegation could not read refuses the spawn rather than
     * seeding nothing (it carries refusals too). Absent or empty ⇒ nothing inherited.
     */
    inheritedSkillGrants?: readonly SkillGrantRecord[];
    /** The parent's request allow entries at the spawn (`ctx.activeRequestAllowedTools()`), seeded as this child's own request rows until it ends — the channel of {@link inheritedSkillGrants}. */
    inheritedAllowedTools?: readonly import("../allow-entry.js").AllowListEntry[];
    /**
     * When this task runs as a SUB-AGENT spawned under a parent task's
     * tool call, the spawning tool's `ToolExecuteContext.toolCallId`. The Runner stamps it onto this task's
     * stream content events as {@link TaskEvent.parentToolCallId} so a consumer can attribute the child's live
     * content to the delegation subtree WITHOUT core merging the child stream into the parent (lightweight
     * message-identity, not stream-merge). A TRUSTED, run-scoped channel filled by a core caller
     * (`createSubagentTool`'s `execute`) — NEVER a {@link TaskSpec} field (the untrusted-caller surface),
     * mirroring `inheritedSkillGrants`/`workflowDepth`. Absent for a top-level (non-delegated) task.
     */
    parentToolCallId?: string;
    /**
     * A SUBAGENT's human display NAME, threaded at spawn so the
     * child's `task_progress` ticks carry a readable label (a Fleet child row otherwise shows the raw `taskId`).
     * Filled by `createSubagentTool`'s `execute` = the explicit `taskName`, else the selected agent-type
     * (`AgentDefinition.name`). TRUSTED run-scoped channel (NOT a {@link TaskSpec} field), mirroring
     * `parentToolCallId`. Absent for a top-level run / a bare delegation with neither label — the child's
     * `task_progress` then carries NO `name` (it keeps its taskId; it deliberately does NOT fall back to the raw
     * objective, which could leak a delegated secret). Untrusted (`taskName` is model-chosen) →
     * the consumer sanitizes via `inlineUntrusted` at emit.
     */
    agentName?: string;
    /**
     * The EXPLICIT `Agent({name})` spawn identity — set
     * ONLY when the spawn carried a `name` parameter, unlike {@link agentName} (a DISPLAY label:
     * description or agent-type, present on nearly every spawn). Teammate semantics (hierarchy clamp,
     * teammate addendum, uplink attribution) key on THIS field; keying on the display label made
     * every described child a "teammate" (clamp over-wide, addendum over-composed).
     */
    explicitAgentName?: string;
    /**
     * The RESOLVED subagent type this child was spawned as (`"general-purpose"` / `"fork"` / a roster
     * definition's name — the same word the fleet row's `agentType` column carries; never the
     * description). Read by the hook identity envelope (`identity.agentType`) so a process-level hook
     * seat can tell WHAT kind of child it is serving without parsing display text. Trusted run-scoped
     * channel (NOT a {@link TaskSpec} field); absent on a top-level run and on the default workflow subagent (#4598).
     */
    spawnAgentType?: string;
    /**
     * The SPAWNING run's taskId, threaded at spawn (from the parent's
     * `ToolExecuteContext.taskId`) so this child's `task_progress` ticks carry `parentTaskId`. Lets a UI build the
     * live nested-agent tree directly (child.parentTaskId === parent.taskId) at any depth. TRUSTED run-scoped
     * channel (NOT a {@link TaskSpec} field), mirroring `parentToolCallId`. Absent for a top-level run.
     */
    parentTaskId?: string;
    /** The spawning run's sessionId (paired with parentTaskId; see
     *  ToolExecuteContext.parentSessionId). */
    parentSessionId?: string;
    /** The registry row this leg runs as (a background child's `a…` handle, the id `TaskStop` / `SendMessage` take), which the leg's
     *  one task-id mint reads first. Set by the background lanes (plain, fork, retained snapshot); absent on a top-level run, a
     *  synchronous child and a workflow agent. Stamped as `CheckpointState.rowTaskId`. Trusted seat, NOT a {@link TaskSpec} field. */
    rowTaskId?: string;
    /**
     * The memory-capture opt-out FLOOR: TRUE ⇔ the spawning session was under an
     * opt-out when this child spawned. The child then runs opted-out itself (its prepare mints its
     * own one-way record, reason naming the floor) — NOT re-adjudicated against the child's
     * entitlement (the floor is the parent's already-granted opt-out tightening the tree; a
     * re-adjudication that could answer "no" would be a loosening door). Trusted internals channel
     * on purpose (the parentInteractionPosture law): never a child-spec field, so no chosen
     * AgentDefinition and no spec surgery can shed it; rides `internalsSnapshot`, so retained
     * revivals keep it. Grandchildren inherit through each generation's own live seat (an opted-out
     * child forwards TRUE to its children in turn — monotone by construction).
     */
    memoryCaptureFloor?: true;
    /**
     * The floor's THIRD state: the spawning session's
     * capture state was INDETERMINATE at spawn (its record store faulted at the getter read).
     * Neither boolean is honest there — no floor runs a possibly-recorded lineage captured, a coined
     * floor mints an IRREVERSIBLE record off an unreadable state — so the lane carries the fault
     * itself and the child's prepare resolves it against the live record query (found ⇒ floor;
     * still faulting ⇒ the child runs indeterminate — mechanical restrictions, no mint; readable
     * and clean ⇒ clean). Same trusted-channel law as {@link memoryCaptureFloor}; mutually
     * exclusive with it at the spawn site (the floor wins when the state IS known).
     */
    memoryCaptureFloorIndeterminate?: true;
    /** The spawning session's write-plane control dir (the coordinate its capture
     *  opt-out record is keyed under), so a child on a DIFFERENT memory plane can still run the
     *  record-query leg against the parent's own carrier. Trusted chain, rides internalsSnapshot. */
    memoryCaptureQueryDir?: string;
    /** The ancestor chain's capture coordinates (root first, one
     *  row per generation, appended by each spawner's ctx seat). The child's harvest closures walk
     *  every row, so a mid-run flip ANYWHERE up the tree suppresses every in-flight descendant.
     *  Trusted chain; rides internalsSnapshot. */
    memoryCaptureAncestors?: ReadonlyArray<{
        sessionId: string;
        controlDir?: string;
    }>;
    /**
     * The FLEET-task kind of this run, declared by the lane that spawned it and stamped onto every
     * `task_progress` tick the run mints (`TaskEvent`'s `taskType`). A consumer merging progress ticks
     * with task notifications into one ledger could otherwise only key on "it showed up on the fleet
     * stream, so it must be an agent" — an inference that has already produced a row for a task that
     * was never an agent. Same vocabulary as `TaskNotificationPayload.task_type`, so the merged ledger
     * has ONE type axis rather than two spellings of one.
     *
     * Set by the BACKGROUND delegation lanes (plain + fork), whose runs own a registry `a*` row, and by
     * both of the workflow orchestrator's spawn legs. A SYNCHRONOUS delegated child declares nothing —
     * it has no registry identity (INTEGRATION-CORE §1.6a), so absence is a fact, not a stamping gap — save on a delegated
     * child's checkpoint a host redeems without the lane's internals (KL-3824-a). TRUSTED run-scoped channel (never a {@link TaskSpec} field).
     */
    delegationTaskType?: import("../types.js").DelegationTaskType;
    /**
     * The workflow member this leg runs as: the run's id, the member's label, and `askedAgain` when this call runs a step again that the run it
     * resumes already took up (its card there lapsed undecided — expired or removed — or the same call completed there). Set by both of the workflow
     * orchestrator's spawn legs on the member's own leg — a child the member spawns builds its own internals and is no member.
     * Every ask the leg raises ({@link import("../tool-policy.js").AskRequest}.workflowRunId) and every row it parks
     * (`CheckpointState.workflowMember`) carries it. TRUSTED run-scoped channel (never a {@link TaskSpec} field).
     */
    workflowMember?: import("../leg-identity.js").WorkflowMemberIdentity;
    /**
     * The stop-cycle number this run executes as — a background child's row number (spawn 1; a wake: what its claim wrote; a
     * parked resume: what its consume hook states), a synchronously born child's wake count (its wake face's) — threaded by
     * the lanes, so the leg's `task_started` and every `task_progress` tick carry it as `seq` (the axis of
     * `TaskNotificationPayload.seq` / `BackgroundChildEvent.seq`). Absent on a first synchronous cycle, workflow agents and
     * top-level runs (INTEGRATION-CORE §1.6a), and on a delegated child's checkpoint a host redeems without the lane's
     * internals unless it hands one here or a consume hook states one (KL-3824-a). TRUSTED run-scoped channel (never a TaskSpec field).
     */
    cycleSeq?: number;
    /** The ROOT host session of the whole delegation tree (fixed point: the spawner passes its own `ctx.rootSessionId ?? ctx.sessionId`, so a
     *  leg running in the host session hands the host session and every leg below it hands it on verbatim). `parentSessionId` is the IMMEDIATE
     *  spawner — the two coincide only when the spawner ran in the root session itself, and neither says how deep a leg is.
     *  After a restart those intermediate sessions are dead ends, and a recovery face enumerating "everything under this host session" needs
     *  the root anchor, not an alias walk. A host composing legs (`runCascade`, `runWithVerification`) that wants the background children those
     *  legs start to belong to its session hands the root's whole address — this member with {@link rootSessionIncarnation} and
     *  {@link rootSessionScope}, all three or none — and {@link rootPrincipal} where its legs share the root's session rules; the composition forwards it to every leg. */
    rootSessionId?: string;
    /** The occupant of {@link rootSessionId}'s row (`SessionMetadata.incarnation`) as the tree's root run acquired it — the other half of the
     *  root anchor's ADDRESS, carried beside it by the same fixed point (the spawner passes its own `ctx.rootSessionIncarnation`; a background
     *  spawn persists it on its row, `BackgroundAgentRecord.rootSessionIncarnation`, and a revival reads it back with the anchor). Absent =
     *  unknown: a revival of a row that recorded none and a row written before occupants were minted; a frame the notification lane escalates to
     *  the root anchor is then addressed to an unknown occupant, which a root holding a token is not — so a host handing {@link rootSessionId}
     *  hands this beside it. TRUSTED run-scoped channel (never a TaskSpec field). */
    rootSessionIncarnation?: string;
    /** The scope {@link rootSessionId}'s legs mount its durable box in, as the tree's root leg mounted it (its registry scope) — the
     *  third member of the root anchor's address, carried beside the other two by the same fixed point and persisted on a background
     *  spawn's row (`BackgroundAgentRecord.rootSessionScope`). A Runner on which no leg of the root runs judges the root's box at it. Absent = a
     *  tree whose root recorded none: no box is judged for the root. A host handing {@link rootSessionId} hands this beside it (its leg's registry scope). TRUSTED. */
    rootSessionScope?: string;
    /** The principal name of the tree's root leg, stated by the anchor's producer and carried beside {@link rootSessionId} by the same fixed point (the
     *  root leg's tool context mints it from its own principal; a spawn hands it on verbatim; a revival's row records none). A leg shares the root's
     *  session-scope permission rules iff this is a name equal to its own principal (`ruleSessionOf`); absent = not stated, so no leg shares. TRUSTED. */
    rootPrincipal?: string;
    /** The delegation tree's owner seat ({@link import("./delegation-owner.js").DelegationOwnerSeat}): a fixed point like
     *  {@link rootSessionId} — the spawning run hands its own seat down by reference (the delegation and workflow lanes), so the tree
     *  reads its root row's owner once. Present ⇒ the run's create-capable session acquire names the owner it binds (`opts.owner`; an
     *  anonymous tree names none), read before the acquire — a seat that does not bind refuses the run `delegation.owner_unbound` with
     *  no row created — and the row is read back and must record it (`delegation.owner_mismatch` otherwise); a host composing legs
     *  (verify, cascade, a repair loop, goal, a direct `runWorkflow`) that hands one gets the same for every leg; a revival (a park
     *  resumed through the revival arm too) holds its reviver's — it judges in the tree it runs in, its row keeps its owner. Absent ⇒
     *  nobody's child here (a top-level run, a park resumed on its own): its prepare mints a seat over the row it acquired. TRUSTED. */
    delegationOwner?: import("./delegation-owner.js").DelegationOwnerSeat;
    /** The leg's `spec.sessionId` is its spawning lane's mint, not its author's (the delegation tool's retained / background / observer legs, a workflow agent or a goal loop whose spec named none): its owner read-back's refusal over an ownerless row then says the store does not record owners ({@link delegationOwner}). TRUSTED. */
    sessionIdMintedBySpawner?: true;
    /** Told once by the leg's prepare that its session may now be named: the row's owner was read back and is this tree's ({@link delegationOwner}), or the leg holds no owner to judge. A spawning lane names, anchors and records the leg's session only from here (birth frames excepted). TRUSTED; must not throw or wait. */
    onSessionVerified?: (sessionId: string) => void;
    /**
     * The run tree's PLACEMENT root: the fixed point a target-bound env factory keys
     * its placement lookup on ({@link import("../remote-env.js").ExecutionEnvFactoryContext.placementRootSessionId}).
     * A SEPARATE axis from {@link rootSessionId}: that field means "member of this host session's
     * DELEGATION tree" and is consumed by the registry access/recovery faces; this member says only "place me
     * where this session was placed". The composition entries (`runCascade` / `runWithVerification`) set only
     * this one: they declare no delegation root of their own and forward `rootSessionId` /
     * `rootSessionIncarnation` / `rootSessionScope` as given to every leg. A host that wants the background
     * children a leg starts to belong to its session hands all three together (with the id alone the occupant
     * and the box scope read as absent, and a frame sent to the root is dropped as addressed to a previous
     * occupant). Producers: the
     * orchestration entries (`runCascade` / `runWithVerification` family) after their first leg's
     * sessionId receipt, and — C12 — the delegation/workflow spawn chains, which re-thread a parent's
     * EXPLICIT value verbatim into child internals (ToolExecuteContext.placementRoot → childInternals;
     * workflow deps → shared internals base), so every descendant of a placed leg keeps the fixed
     * point; prepare's mint reads it first (`placementRoot ?? rootSessionId ?? sessionId`). Absent
     * everywhere else — the delegation lanes' `rootSessionId` fixed point then becomes the placement
     * root through the middle segment, unchanged. DURABLE: the suspend mint stamps the resolved fixed point as
     * `CheckpointState.placementRootSessionId`, and a bare durable resume restores it into this
     * member (live internals win when re-supplied; a CONTRADICTING re-supply refuses pre-CAS,
     * `resume.placement_mismatch`). TRUSTED run-scoped channel (never a {@link TaskSpec} field).
     */
    placementRoot?: string;
    /** The placement FENCE this leg is minted under: the target of the leg that hands it work (a spawner, a waker, a composition's
     *  first leg), folded at the mint into {@link import("../remote-env.js").ExecutionEnvFactoryContext.placementTarget} — whose
     *  contract lists every producer; one hop, re-read at every leg (unlike the tree's fixed point {@link placementRoot}). An
     *  unreadable value is refused at the mint (`config.placement_not_honored`). TRUSTED run-scoped channel (never a {@link TaskSpec} field). */
    placementTarget?: PlacementTarget;
    /**
     * Which composition this leg is a leg of, and whose run it belongs to ({@link CompositionLeg}): minted ONLY by a composition
     * entry when it hands the leg out (`runCascade` / `resumeCascade` for each rung, the verification gate for each verifier leg),
     * never by the engine. The suspend mint stamps it on the row as `CheckpointState.compositionLeg`, so a card a leg parks says
     * itself which leg of which composition it is and which host session it belongs to; one value, read ONCE at prepare (the live
     * member, else the row's; an `entry` outside the closed set is refused there, `config.invalid_argument`). On a resume the same rule as the
     * placement fixed point: a live value wins, a live value that CONTRADICTS the row's is refused pre-CAS
     * (`resume.composition_mismatch`, the row stays pending), an absent one is restored from the row — and a live value over a row
     * that records none (a card minted before the member, or by a leg nobody labelled) is that row's first record, never refused.
     * Not threaded to the leg's children: a child is not a rung, its card is filed by its own lane. TRUSTED run-scoped channel
     * (never a {@link TaskSpec} field).
     */
    compositionLeg?: CompositionLeg;
    /**
     * The REGISTRY SCOPE this run's own background row lives in: the domain its registry-facing
     * tools (TaskStop / SendMessage / AgentTranscript / Monitor, and the announce listing)
     * must mount in to see it. Filled by the delegation tool at spawn, which is the party that CHOSE the
     * domain when it registered the row — the spawning run's isolation scope (its `isolationScope`, else its
     * principal) when it has one, else the delegation mount's declared `background.scope`, and on a revival the
     * claimed row's own scope.
     *
     * Why this is not just the isolation scope: a deployment may declare its domain at MOUNT time and run its
     * tasks with neither `TaskSpec.isolationScope` nor `TaskSpec.principal`. The row then lands in the declared domain while the child runs
     * with no scope at all, and isolation scope ?? `"default"` sends every one of its registry-facing tools
     * to a domain the row is not in — scope is fail-closed on both access predicates, so such a child
     * cannot see its own row, its siblings, or the children it spawns. Carrying the domain as its own
     * trusted axis keeps `principal` the IDENTITY it is: the identity also keys the durable
     * approval / checkpoint namespace of a root leg (`checkpointScopeOf`), the runtime-capability lookup and the
     * MCP principal header, and a mount's registry scope has no business moving any of those (a child's checkpoint
     * scope is its own fact — {@link checkpointScope} — and a registry domain is never it).
     *
     * TRUSTED channel (never a {@link TaskSpec} field, never a model argument), like the parentage axes
     * above. When a deployment sets both, they agree by construction: with a principal present the
     * delegation tool resolves this axis TO that principal.
     */
    registryScope?: string;
    /** The spawning leg's checkpoint scope, filled by the delegation tool off the parent's ctx seat on every spawn lane (a
     *  resume that hands none fills the rung from the row's `CheckpointState.legScope`): the top rung of `checkpointScopeOf`,
     *  so a child's rows are listed with its parent's. Scope only, never park capability. TRUSTED channel; `""` is absence. */
    checkpointScope?: string;
    /** The spawning run's ADOPTED center artifact, threaded down the
     *  trusted internals chain so every child in the tree composes the SAME closure (a child must
     *  never spontaneously adopt the live candidate while its parent runs an older pin — that is the
     *  exact mixed-version state the epoch exists to prevent). Resolved by-digest through the
     *  verified store at child prepare; a miss is the same fail-loud `prompt.snapshot_unavailable`. */
    parentCenterArtifactDigest?: string;
    /** Publish provenance companion of {@link parentCenterArtifactDigest} (audit only). */
    parentCenterSourceRevision?: string;
    /**
     * An OPT-IN, DISPLAY-ONLY event sink a deployment sets on the TOP run to
     * receive a subagent's live `task_progress` ticks (which otherwise stay in the child's ISOLATED stream). Threaded
     * recursively down the delegation tree (via `ctx.forwardEvent`), so every nested subagent's ticks bubble to the
     * SAME sink. The Runner's ctx wrapper forwards `task_progress` always; when the run's spec sets
   * `forwardSubagentEvents: true` it ALSO forwards the child's content events (`text_delta` / `text_end` /
     * `reasoning_delta` / `tool_start` / `tool_end` — the subagent viewing pane, carrying the same UNTRUSTED-RAW/consumer-must-redact
     * contract as the main stream's tool events). Either way the child stream is NEVER merged into the parent's
     * MODEL context (this is purely a render channel). Absent unless the deployment opted in. CONTAINED at
     * one door: every engine site feeding this seat goes through `forwardSafely` (`forward-sink.ts`), so a
     * sink that throws — or, since an `async` function satisfies this `=> void` type, one that returns a
     * REJECTING promise — drops its frame and nothing else, never awaited
     * (`@contract runtask.forward_sink_never_faults_the_run`).
     */
    onForwardEvent?: (event: TaskEvent) => void;
    /**
     * The subtree-activity seat: "this run — or something running under it — just did work." Not {@link onActivity} (that one hands a
     * run's OWN tool starts and ends, with their identity, to whoever observes that run; a descendant's calls never reach it). This one
     * carries no identity, only the beat: the engine tells it at each of the run's tool calls' start and end (in the one place a run
     * pushes its content; not at a `tool_progress` heartbeat, which says only that a silent call is still in flight) and at each MCP progress
     * notification of its tool calls; a delegation hands it to every foreground child
     * (`ToolExecuteContext.onSubtreeActivity`), so a grandchild's tool work reaches the same seat at any depth — beyond what the display
     * channel forwards, which is filtered. A background lane that owns a registry row sets it to that row's beat
     * (`TaskRegistry.noteBackgroundAgentActivity`) and so replaces, not extends, the one it inherited: a background child's work is its
     * own row's, not its spawner's. TRUSTED spawn-side channel, never a {@link TaskSpec} field; the call is a timestamp write and must not
     * throw or wait.
     */
    onSubtreeActivity?: () => void;
    /**
     * The DRAINED-LEG FRAME SEAT: a leg the engine drains itself — entered through `Runner.runTask` or `Runner.resume`, as
     * every leg a composition entry (the verify gate, the cascade) dispatches is — hands its own frames of the closed set
     * `DRAINED_LEG_FRAME_TYPES` (`status`, `wiring_manifest`, `message_committed`,
     * `workspace_changed`) to this seat, because the caller holds no stream for that leg. Branch on `frame.type`.
     *
     * ONE FRAME, TWO DELIVERIES, ONE ORDER: `frame` is the very object the leg's queue received, shallow-frozen before the
     * push (its own members cannot be reassigned; nested objects such as `manifest`, `entered`, `session` are the same objects
     * the stream frame carries and are not frozen by this rule — read them, do not write them), offered at the push and only
     * when the queue accepted it, so this seat sees the leg's frames in the order the stream holds them. `at` is
     * {@link LegAt}: the leg's `taskId`, `sessionId` and `runId` (engine facts, on every frame; `runId` is the one two legs of one
     * session do not share) and `leg`,
     * the composition's label for the leg when the dispatcher bound one — absent means nobody labelled the leg, never
     * "implementation" (a plain `runTask` and a workflow agent call carry none; the verify gate labels `impl` / `verifier` /
     * `fix`, the cascade labels each rung `rung` with its place on the ladder).
     *
     * DRAINED LEGS ONLY: `Runner.runTaskStream` / `Runner.resumeStream` hand the caller the stream, where these frames ride,
     * and REFUSE this seat (`config.invalid_argument`) before anything is read — on a resume, before the checkpoint is read
     * or claimed (it stays pending; resume again without the seat). The draining entries mark the object they hand on; a
     * copy of it is not marked. A child the leg delegates to, and a workflow agent leg, run on a bag the engine builds, which
     * never carries this seat: their frames reach the parent through {@link onForwardEvent}, not here.
     *
     * Observe-only and failure-isolated through the run's ONE notifier (a throw, or an `async` seat's rejection, is
     * contained, disclosed once per run, counted after, and never faults the leg). A TRUSTED run-scoped channel, never a
     * {@link TaskSpec} field.
     */
    onLegFrame?: (frame: DrainedLegFrame, at: LegAt) => void;
    /** The run-local per-tool-call detach hub. runtask creates it and exposes
     *  `TaskStream.detach(toolCallId)`; the hands Bash tool threads `signalFor(toolCallId)` into env.exec. */
    detachHub?: import("../tool-detach.js").ToolDetachHub;
    /** The run's forwarding-failure bookkeeping for {@link onForwardEvent} — ENGINE-owned and opaque,
     *  minted once per run by `Runner.runTaskStream` and carried by every later COPY of this object (the
     *  prepare re-spread, a placement-root rebind, a child's snapshot), which is what makes "announced once
     *  per run" true across the lanes that forward. A caller value is overridden like the refs beside it;
     *  absent ⇒ the door mints a per-object one, so containment never depends on the threading. */
    forwardScope?: import("./forward-sink.js").ForwardSinkScope;
    /** This leg's receipt of its spec (`mcp` / `a2a`, each per-task definition whole, the tool roster) — ENGINE-owned, taken by
     *  `Runner.runTaskStream` at the call for every leg (a caller value is overridden): every door of the leg's prepare judges this copy,
     *  and the references it names are what the leg holds (leg-receipt.ts, peer-seat.ts). */
    receivedPeers?: import("./leg-receipt.js").LegReceipt;
    /**
     * The Runner's per-session read-file-state seats (CC parity: readFileState is
     * session-scoped). Always set by the Runner's own prepare call (overriding any caller value, like
     * the peer refs beside it); absent on a standalone prepareTask, where the transcript-replay rung
     * covers alone. A CACHE, never an authority — see {@link SessionReadFileStates}. Trusted internals
     * channel, same posture as every other field here.
     */
    sessionReadStates?: SessionReadFileStates;
    /**
     * The MCP pools of the process's session trees (`processSessionMcpPools()`, mcp-connection-pool.ts — every Runner reads the one table):
     * a leg that declares a server leases from the pool of its session TREE, found by the tree root's address (root-session-lane.ts
     * `treeRootAddressOf`: a descendant's {@link rootSessionId} anchor, a root's own address under its task scope), so a server whose
     * connection attempt failed is not dialed again by the session's next message, nor by any leg the session spawns, whichever Runner
     * runs it — among Runners holding the same peer seat copy (the pool is also the seat's: `SessionMcpPools.of`). Nothing else names a leg's pool. Always set by the Runner's own prepare call (overriding any caller value, like the seats
     * beside it); absent on a standalone prepareTask, whose leg makes a pool that dies with it. A CACHE, never an authority.
     */
    sessionMcpPools?: import("../mcp-connection-pool.js").SessionMcpPools;
    /**
     * The Runner's per-session permission-mode seats ({@link SessionModeSeats}): the chain a leg hands its children
     * carries its SESSION's seat as the children's ceiling, and each leg binds itself to that seat once its prepare
     * commits — so a session-scoped background child follows the session's current leg. Always set by the Runner's own
     * prepare call (overriding any caller value); absent on a standalone prepareTask, which mints a seat of its own.
     */
    sessionModeSeats?: SessionModeSeats;
    /**
     * The Runner's per-session fast-mode facts ({@link import("./fast-mode-seat.js").SessionFastModeSeats}): a leg's fast mode
     * reads and writes its tree root's facts (`rootSessionAddressKeyOf`: scope, id, occupant), so a child leg shares its parent's
     * cooldown. Always set by the Runner's own prepare call; absent on a standalone prepareTask, which keeps them for its leg only.
     */
    sessionFastModeSeats?: import("./fast-mode-seat.js").SessionFastModeSeats;
    /** The Runner's per-session prompt facts (session-prompt-seats.ts), by tree root as {@link sessionFastModeSeats}; same posture. */
    sessionPromptSeats?: import("./session-prompt-seats.js").SessionPromptSeats;
    /** Trusted system-injection sink (`Runner.runLocked` wires it to the live TaskStream queue plus the current harness lanes; never a public TaskSpec field),
     *  ADDRESSED TO THE SESSION rather than to this run: a producer wired here (a background shell, a watch, a delegation settle) keeps the closure long after the
     *  run that mounted it ended, and its frame is then routed to whatever run the SESSION has live — at that run's next turn boundary, the seat a steer lands on;
     *  only a session with NO live run parks it. As an OBSERVER (the Runner wraps it: this function first, then the route) it is called each time a frame is handed
     *  into this leg's sink: once by the producer, again by a later leg's sink when the frame came through the session box drain (two in all), never again through the in-process park's turn-open hand-out or a live leg (one). */
    onTaskNotification?: (notification: TaskNotificationPayload, 
    /** Injection tier (the ladder is LIVE): "next" = the running turn's next boundary
     *  (arrival order, consecutive frames batch); "later" = the run's would-otherwise-stop seat
     *  (never folded into work in progress); "now" = class-head + earliest natural boundary on this
     *  lane (interrupt authority belongs to the steer face, never to notifications). Internal
     *  producers declare their tier explicitly (§3.7 census — completion-class lanes are "next");
     *  the parameterless default "later" serves the external verb's omitting callers only. */
    opts?: {
        priority?: import("../task-notification.js").SystemInjectionPriority;
    }) => void;
    /** The ASSISTANT SEAT (the type's own doc is the contract): host-handed on every leg the host starts for the scope's assistant, a
     *  resumed one included; the engine hands no child this member and a checkpoint does not carry it. */
    principalInboxAssistant?: import("../../agents/org-delivery-gate.js").PrincipalInboxAssistantSeat;
    /**
     * The PARENT run's notification injector (its runtask-wrapped
     * `injectTaskNotification`), threaded into a CHILD's internals at spawn time so the child's
     * SendMessage("main") uplink lands in the parent's queue at a turn boundary (the CC
     * "delivered automatically" parent half). DELIBERATELY a separate field from
     * {@link RunInternals.onTaskNotification}: that one is "inject into the run's own SESSION" (runtask
     * wraps it as upstream-observer + session route), and reusing it for the child would tee every
     * internal child notification (grandchild completions, monitor events) into the parent — double delivery.
     */
    parentNotify?: (notification: TaskNotificationPayload, opts?: {
        priority?: import("../task-notification.js").SystemInjectionPriority;
    }) => unknown;
    /**
     * The ONE address `SendMessage("main")` names for this child — the session that hosts this child's
     * lifecycle — paired with {@link parentNotify} at the same mint, three arms:
     *  · a fresh spawn: the SPAWNER's session, whose live injector is `parentNotify`;
     *  · a revival by that tree's ROOT (or any top-level session): the REVIVER's session, its injector;
     *  · a revival by a SIBLING child, or by a host verb with no session: the row's ROOT session, and
     *    NO `parentNotify` — a sibling is a peer the child addresses by name, not its main, and there is
     *    no live callback into the root from either reviver. Such a child's "main" send reads the
     *    honest not-deliverable text; its terminal still reaches the root through the root-anchor arm.
     * The uplink receipt names this id so the model knows WHICH conversation "main" is. Absent on a
     * top-level run. Trusted run-scoped channel (never a {@link TaskSpec} field).
     */
    uplinkSessionId?: string;
    /**
     * The PARENT run's subagent-retain ledger, threaded to a CHILD so its
     * SendMessage can continue a RETAINED SIBLING (the sibling's retain entry lives on the parent's
     * ledger — without this, sibling resolution succeeds but delivery always reads not-retained).
     * TRUSTED chain; read-only use (the sibling leg resumes through the same fenced resume face).
     */
    parentRetainLedger?: import("../../agents/retain-ledger.js").SubagentRetainLedger;
    /**
     * Hands THIS run's notification injector back to the SPAWNER once the lane is
     * live (runtask calls it with its wrapped `injectTaskNotification`). The spawner stores it on the
     * child's registry handle so a parent/sibling SendMessage can deliver TO the RUNNING child at its
     * next turn boundary (the in-memory `pendingMessages` pedestal,
     * messaging-runtime.md §2.5). The injector outlives its run safely: once this lane is over the frame
     * is routed to whatever run the SESSION has live, and only a session with no live run parks it
     * (PendingSessionNotifications) — exactly CC's durable-mailbox posture for an idle teammate (§2.4).
     * TRUSTED chain (core spawner only); never reachable from TaskSpec.
     */
    onNotifyInjectorReady?: (inject: (notification: TaskNotificationPayload, opts?: {
        priority?: import("../task-notification.js").SystemInjectionPriority;
    }) => Promise<import("../task-notification.js").NotificationInjectionOutcome>) => void;
    /**
     * Per-task ISOLATION hint, a TRUSTED run-scoped channel filled ONLY by a core caller
     * (the workflow's `ctx.agent` when the SCRIPT passed `{ isolation: "worktree" }` as an OPTION) — NEVER a
     * {@link TaskSpec} field (the untrusted-caller surface). Forwarded to
     * {@link ExecutionEnvFactory} via {@link ExecutionEnvFactoryContext.isolation} so the trusted control-plane
     * factory mints a git-worktree-rooted env for this agent; and it makes root resolution use the worktree
     * env's own cwd (the worktree dir), bypassing `deps.rootPath`. Isolate-ONLY: the runtime never merges
     * — the orchestrator script reads each worktree's result and decides verify/merge in userland.
     * FAIL-CLOSED: a request the deployment cannot honor (no factory, or an observably non-isolated env)
     * throws at prepare time — the child never starts; there is no silent fallback to the shared tree.
     */
    isolation?: "worktree";
    /**
     * Sub-agent cwd inheritance (CC parity, 2026-07-03): the PARENT task's effective working root,
     * filled ONLY by core delegation callers (the workflow's `ctx.agent` / `createSubagentTool`'s execute —
     * NEVER a {@link TaskSpec} field). Forwarded to {@link ExecutionEnvFactory} via
     * {@link ExecutionEnvFactoryContext.parentCwd} so a single-user/TOC factory can root the child env at the
     * parent's cwd instead of an empty per-task sandbox. `isolation: "worktree"` wins over this when both set.
     */
    parentCwd?: string;
    /**
     * The spawning run's file-history LINEAGE — the scope it records first-touch edits into and the
     * TREE those records' keys are minted against (the canonical root spelling + the filesystem
     * identity of {@link fileHistoryFilesystemIdentity}) — threaded VERBATIM by core delegation
     * callers from {@link import("../types.js").ToolExecuteContext.fileHistoryLineage} (NEVER a
     * {@link TaskSpec} field). {@link resolveFileHistoryScope} is the ONE reading: this run records
     * into the lineage's scope iff its own tree coordinates BOTH equal the lineage's (a run at its caller's root, {@link callerRoot}, on the lineage's filesystem keys against the lineage's root — a `workspace: null` caller's is its session's root, not where it stands), and then
     * re-exposes the SAME triple on its own ctx, so every same-tree descendant of a root session — at
     * any depth — lands in the root session's scope (the fixed point), while a descendant on another
     * tree (worktree isolation, explicit `cwd`, a fresh per-task sandbox) becomes the root of its own
     * subtree's history. Absent on a top-level run, on a run that records no file history, and on a
     * tier-3 revival (the reviver's lineage says nothing about the revived row's tree).
     */
    fileHistoryLineage?: {
        scope: string;
        root: string;
        fs: string;
    };
    /**
     * [c209-D] — the EXPLICIT Agent.cwd request, distinct from the best-effort `parentCwd`
     * inheritance hint above: inheritance may be silently ignored by a factory (or absent without one),
     * but an explicit cwd the model asked for MUST either take effect or fail loud. prepareTask enforces
     * the contract: no `executionEnvFactory` ⇒ throw `config.cwd_unsupported`; after env creation the
     * env's actual cwd must canonically equal this path or the task fails `config.cwd_not_honored`; the
     * task root follows the env's cwd (never `deps.rootPath`) when set. Filled ONLY by core delegation
     * callers (ctx-injection posture, same as `parentCwd`).
     */
    requestedCwd?: string;
    /**
     * The SPAWNING run's own root, filled ONLY by core delegation callers beside `parentCwd` (ctx-injection posture): with
     * it the child's prepare judges where its environment actually placed it against where it was asked
     * (`childPlacementOf`, child-tree.ts: honored / inside the caller's tree / elsewhere) — the fact the
     * worktree request below and the anchors of the rules the child inherits read. Absent ⇒ no placement is judged (a top
     * leg, a caller that does not delegate through core).
     */
    callerRoot?: string;
    /**
     * The checkout the SPAWNING run writes in when it has switched to a tree other than its root (an EnterWorktree tree — it can
     * lie outside {@link callerRoot}, since a managed tree hangs at the repository root): a child placed inside it is placed in the
     * caller's own tree as well. Filled ONLY by core delegation callers beside {@link callerRoot}; absent when the caller writes in its root.
     */
    callerCheckout?: string;
    /**
     * `parentCwd` is a worktree the caller minted for THIS child (the delegation tool's `isolation: "worktree"`): a child
     * its environment placed inside the caller's own tree instead is refused before it starts (`isolation.unavailable`).
     * Filled ONLY by the core delegation tool; never a {@link TaskSpec} field.
     */
    worktreeOffered?: true;
    /**
     * Subagent steer verb (dogfood finding 2026-07-03, "中途插话"): the host run's opt-in
     * SUBAGENT-STEER-HANDLE sink. When set, `createSubagentTool` runs each child via `runTaskStream`
     * and emits a steer handle here (the model never sees the handle — same host-context-isolation
     * posture as `onWorkflowAgentSpawn`). A deployment registers it by `taskId` to route a human steer
     * into the running child (fenced-marker semantics matching the workflow agent handle). Threaded to
     * the tool ctx as {@link ToolExecuteContext.onSubagentSpawn} and recursively down the delegation
     * tree. Absent ⇒ children run non-steerable (prior behavior, zero overhead).
     * SCOPE: only SYNC delegations emit a handle — a
     * `run_in_background` child does not (its completion notification carries the result; TaskStop stops it); wiring the background
     * lane is a recorded follow-up, not an oversight a deployment should discover at runtime.
     */
    onSubagentSpawn?: (handle: import("../../agents/subagent.js").SubagentSteerHandle) => void;
    /**
     * A TRUSTED run-scoped tool-ACTIVITY sink, filled ONLY by a core caller (the workflow's
     * `ctx.agent`, to render a per-agent "last N tool calls" drill-down). Called synchronously at each tool start +
     * end with structural data (name/phase/ids) — NEVER args/output (those carry untrusted/host data). NEVER a
     * {@link TaskSpec} field. Absent ⇒ no activity capture (default).
     *
     * Reaches activity on FRESH and RESUMED runs alike — the durable-resume entry (`resumeStream`) threads
     * `internals` too (see its parent-constraint re-supply snapshot), so a resumed leg's SUBSEQUENT tool calls
   * hit this sink. One real boundary remains: the resume's already-approved pending call itself is
     * executed by `applyResumeDecision`'s own callback, outside the frame-minting harness, so THAT one call
     * emits no activity.
     */
    onActivity?: (activity: ToolActivity) => void;
    /**
     * A TRUSTED run-scoped WORKSPACE-observation sink, filled ONLY by a core caller
     * (the workflow's `ctx.agent` / `ctx.agentStream`, to record an isolated agent's worktree directory on the
     * persisted run record). NEVER a {@link TaskSpec} field — same posture as {@link onActivity}.
     *
     * WHY the engine must hand this out: for `isolation: "worktree"` the worktree path is minted INSIDE
     * {@link RunnerDeps.executionEnvFactory} and lands only on the per-task env's `cwd`; no runner-outward face
     * (TaskEvent union / TaskStream / TaskResult) carries it back. An orchestrator therefore could not record
     * WHERE its isolated agent worked — the recovery path after an interrupted run had to enumerate the
     * worktrees directory and guess, which is exactly the contradiction recorded against the
     * "isolate-only, userland decides verify/merge" intent.
     *
     * Called at most ONCE per prepared run with the task's FINAL working root (see {@link ResolvedWorkspace}),
     * after the durable-resume restore may have re-rooted it and after the session's checkout has placed it: a leg of a
     * session with a tree of its own (`TaskSpec.workspace`) reports its place in that tree, never the base checkout it
     * isolates. A leg the checkout REFUSES (its record cannot be read, its tree is gone, the checkout was released, or it asked for
     * an isolated worktree on a session that holds a checkout — `isolation.unavailable`) reports the root its environment put it at,
     * before the checkout (`isolated` as requested: the worktree its factory minted, which the refused leg does not use). Observe-only:
     * a throwing sink is swallowed (an observation must never fault a prepare that already minted a workspace).
     *
     * Like {@link onActivity}, this seat rides `internals` on FRESH and RESUMED runs alike (`resumeStream`
     * threads it too) — a resumed leg's restore re-fires the observation with the settled root.
     */
    onWorkspaceResolved?: (workspace: ResolvedWorkspace) => void;
    /**
     * Set by a delegation lane that can hold this leg's park: the leg's prepare reports, once, whether it can suspend
     * durably (`ready` — the same readiness its manifest's `suspendLane` reports), so the spawner's yield seat knows what a
     * yield of this leg will come to. The leg's `TaskSpec.preemptSignal` is the spawner's fresh per-leg yield signal; the
     * report is the moment that signal is handed over (after the resume entry's strip of an already-raised one). Fresh and
     * resumed legs alike. A throwing seat is swallowed — an observation must not fault prepare.
     */
    reportSuspendLane?: (lane: {
        readonly ready: boolean;
    }) => void; /** Set by a delegation lane that owns a registry row for this leg: the run driver hands it, once per leg, a READER of the leg's own tool-occurrence table — the calls the leg holds at its gate for an approver right now (`approvalHeldCalls`, the counts `tool_progress.gate` reads). The row keeps the latest leg's reader and reads it when a face states the agent's state (`AgentState.approvalWait`). A throwing seat is swallowed; not handed to a child's leg (each reports to its own row, or none). */
    reportApprovalHolds?: (read: () => readonly import("../agent-state.js").ApprovalHeldCall[]) => void;
    /** Set by a composition that runs more legs as the same work (a verifier, a fix leg, a later cascade rung): the leg's prepare reports,
     *  once, the identity it was admitted under (`principal` and its own `isolationScope`, an absent member left out) — on a resumed leg,
     *  after the resume restored from the row what the config omitted, so the later legs never run as nobody. Fresh and resumed legs
     *  alike; a throwing seat is swallowed. */
    reportAdmittedIdentity?: (identity: Readonly<Pick<TaskSpec, "principal" | "isolationScope">>) => void;
}
/**
 * The payload of {@link RunInternals.onWorkspaceResolved}: the working root this task actually
 * runs on, plus whether that root is the task's OWN isolated workspace.
 *
 * `isolated: true` means "`cwd` is this agent's own git worktree": it is reported only when
 * {@link RunInternals.isolation} was requested AND the fail-closed worktree enforcement accepted the env AND the leg works in
 * that worktree (a session that holds a checkout places the leg in the session's tree, which is not the leg's own: the request is
 * then refused `isolation.unavailable` before the model, and the receipt names the worktree the factory minted, `isolated: true`,
 * which the refused leg does not use and its owner removes — never the session's tree), so a
 * consumer may treat the path as private to this agent (safe to diff / merge / remove in userland). A
 * non-isolated run reports its plain root with `isolated: false` — the observation face stays complete, while
 * the honest non-claim keeps a consumer from mistaking a SHARED tree for its own worktree.
 */
/** Where a delegated child's environment placed it against where its caller asked (`childPlacementOf`, child-tree.ts):
 *  `honored` — where it was asked; `caller_tree` — elsewhere inside the caller's own tree; `elsewhere` — another
 *  filesystem namespace. */
export type ChildPlacement = "honored" | "caller_tree" | "elsewhere";
export interface ResolvedWorkspace {
    /** The task's effective working root — the same value every fence / LSP / prompt consumer uses. */
    cwd: string;
    /** True only for an accepted `isolation: "worktree"` request (⇒ `cwd` is this agent's own worktree). */
    isolated: boolean;
    /** True when the task's execution env does not declare its paths the host's (`pathsAreHostLocal` is false — whatever
     *  interface drives it): `cwd` then names a path INSIDE that target (a per-task sandbox on the shape-(d) exemption leg,
     *  e.g. `/workspace`), which does not exist — or names an unrelated directory — on the host. A host lane driven through
     *  the remote seam reads `false`. `isolated && !remote` is the only combination under which `cwd` is a host path a
     *  consumer may diff / merge / remove. */
    remote: boolean;
    /** Where a delegated child's environment placed it against where its caller asked; absent on a leg no delegation
     *  caller placed. */
    placement?: ChildPlacement;
    /** The target this leg's env reported as it settled — the fence of every leg it hands work to; absent when it reported none. */
    target?: PlacementTarget;
}
/**
 * The resolver's answer, with the WITHHELD cause beside the value.
 *
 * The old signature returned a bare `unknown`, which collapsed three different worlds into one
 * `undefined`: "this tool declares no preview at all", "the projection threw / could not be
 * serialized", and "the projection declined to speak for these args". The middle one is the case an
 * approval surface must be told about — a person is being asked to approve something whose display
 * projection could NOT be produced — and it was indistinguishable from the other two.
 *
 * `withheld` names the cause; it is ORTHOGONAL to `preview` presence, deliberately: the oversize arm
 * still ships its truncation stub (a surface that renders it tells the person the size, which is more
 * useful than nothing), and the stub alone never carried the fact that the real projection is missing.
 */
export interface ResolvedApprovalPreview {
    /** The display projection, when one could be produced (or the oversize truncation stub). */
    preview?: unknown;
    /** Present ⇔ the tool DECLARED a preview and the gate could not present a usable one:
     *  `"oversize"` — produced but past the 16KiB display bound (the stub rides `preview`);
     *  `"unavailable"` — the projection threw, or its value has no JSON serialization.
     *  ABSENT covers both "no preview declared" and "the projection returned nothing to show" — neither
     *  is a withholding, and claiming one would make every preview-less tool look suppressed. */
    withheld?: "oversize" | "unavailable";
}
/** The in-stream ask lane: the six closures the park closure and the gate station consume. Built as ONE value so
 *  "the lane exists" is one fact, not six independently-undefined seats. */
export interface AskLane {
    /** The shared run+call signal composition, bound to this task's run signal once. */
    composedCallSignal: (callSignal: AbortSignal | undefined) => AbortSignal;
    /** The abort-bound policy check, or undefined when no policy is wired (→ the gate reads allow). */
    adjudicate: ((req: ToolCallRequest, callSignal?: AbortSignal) => Promise<PermissionResult>) | undefined;
    /** The approval display projection over the live roster (alias-aware; oversize/unavailable named). */
    approvalPreviewOf: (toolName: string, args: unknown) => ResolvedApprovalPreview;
    /** THE synchronous ask mint: resolves a surviving `ask` through the live seat, books the ledger. `req` is the gate's delivered call (its landing rides to the request). */
    resolveAskBound: ToolGateInput["resolveAsk"];
    /** The pre-wrapped deny observer, or undefined when the deployment wired no `permissionDenied` hook. */
    notifyPermissionDenied: ((payload: PermissionDeniedPayload) => Promise<void>) | undefined;
    /** The deployment-facing half of a crashing PreToolUse hook (swallow-guarded). */
    notifyHookError: (err: unknown) => void;
}
/**
 * What one boundary-family suspend request (`suspendForResource` / `suspendForPlatformLimit`) came to — the
 * mint's own answer, so the turn boundary reads the cause's fallback off ONE fact instead of guessing from a
 * boolean:
 *  · `committed`   — a resumable checkpoint exists; the pause is published and the loop stops cleanly;
 *  · `not_written` — no row exists and the world is as it was (no store, a cancelling run, no committed leaf,
 *                    a refused `suspendVM`, a store that refused the write with the paused VM restored):
 *                    continuing is safe, and `reason` says why in one clause;
 *  · `fatal`       — the mint stopped the run itself (the slice cap, a paused VM that could not be restored,
 *                    a write whose outcome is unknown): the boundary never continues past it.
 */
export type BoundarySuspendOutcome = {
    readonly tag: "committed";
} | {
    readonly tag: "not_written";
    readonly reason: string;
} | {
    readonly tag: "fatal";
    readonly reason: string;
};
/** How the put-commit + put-failure saga ended (see `commitSuspendSaga` inside the phase for each arm's meaning). */
export type SuspendSagaOutcome = {
    tag: "committed";
    writes: ParkWrites;
} | {
    tag: "superseded";
    reason: string;
} | {
    tag: "cut";
} | {
    tag: "absent";
    reason?: string;
} | {
    tag: "unknown";
    reason: string;
} | {
    tag: "compensation_failed";
    reason: string;
};
/** The durable settlement machinery the boundary parks and the park closure consume. Built as ONE value so "the saga
 *  exists" is one fact, not eight independently-undefined seats. */
export interface SuspendSaga {
    /** THIS leg's spend so far in micro-USD (own + nested delta), read at mint time. */
    inFlightSpendMicroUsd: () => number;
    /** The §4.bis correctness-state whitelist, serialized from the live values at suspend. */
    serializeCheckpointState: (workspaceHandle: WorkspaceHandle | undefined, parkedSpendMicroUsd?: number) => SerializedCheckpointState;
    /** The shared paused-VM compensation, bound to this task's failure ledger and error face. */
    compensatePausedVM: (remoteEnv: RemoteExecutionEnv, snapshotId: SnapshotId) => Promise<{
        ok: true;
    } | {
        ok: false;
        reason: string;
    }>;
    /** The put-commit + put-failure split — the point of no return, tagged. */
    commitSuspendSaga: (token: CheckpointToken, cp: Checkpoint, remoteEnv: RemoteExecutionEnv | undefined, remoteHandle: WorkspaceHandle | undefined, cutSignal?: AbortSignal) => Promise<SuspendSagaOutcome>;
    /** The shared suspend-loop-cap guard (safety state first, diagnostic second). */
    suspendLoopCapHit: (count: number, cap: number | undefined, detail: string) => boolean;
    /** The `suspendVM` target by CAPABILITY, or undefined. */
    suspendableEnv: RemoteExecutionEnv | undefined;
    /** The park-only remote target (declares `suspendable: false`: externally durable), or undefined. */
    parkOnlyRemoteEnv: RemoteExecutionEnv | undefined;
    /** The park-only identity capture (snapshotId stripped, `restoreMode: "park_only"`). */
    parkOnlyHandle: (env: RemoteExecutionEnv) => WorkspaceHandle;
    /** The leg's workspace sync at a park (`turn_end`), waited for no longer than `cut` stays unaborted: called by every park
     *  lane after its last refusal check and before the pause or the park-only identity capture; the caller reads `cut` again
     *  after it. Never throws. */
    syncBeforePark: (cut: AbortSignal) => Promise<void>;
}
/** The park closure and the content-ask routing closure the gate station hands to `runToolGate`. Built as ONE value so
 *  "the park lane's closures exist" is one fact; `suspendAsk` stays optional INSIDE it because the park predicate (a store,
 *  and something to park for) is a narrower condition than the gate machinery's activation. */
export interface ParkAsk {
    /** The gate's content-ask routing closure (total by construction; answers `unavailable` with no live face). */
    resolveContentAsk: NonNullable<ToolGateInput["resolveContentAsk"]>;
    /** The durable park closure (twelve positional seats then the structural carry), or undefined when the park
     *  lane is not armed (the gate then keeps the synchronous onAsk path). */
    suspendAsk: ToolGateInput["suspendAsk"];
}
/**
 * `runLocked`'s per-run mutable state, EXPLICIT. These fields started as loose
 * `let`/`const` bindings in the R2 declaration hub; the extraction kept every assignment at its
 * original site and order (binding-form-only rewrite — the event-snapshot pin held the run
 * byte-identical), and later work has since added fields directly here (see the per-field notes).
 * Grouped by lifecycle semantics per the B15 pre-recon partition. Function members start as inert
 * placeholders and are assigned at their ORIGINAL declaration sites (the original code could not
 * call them earlier either — TDZ proved it). Not on the npm face; this extraction is what enabled
 * createTurnBoundary / createHarnessHandlers (both are run lanes of their own).
 *
 * WRITERS, by group (the driver mints the zero value, initial-run-state.ts, and hands it to every
 * lane as a borrowed-mutable seat): `telemetry` / `degrade` / `limits` / `budget` initial values and function
 * members — the telemetry-and-budget-seats lane; `counters` / `attach` initial values — the attachment-seats lane
 * (the clock lane zeroes `counters.walltimeSyncBackstopFired`; the tool-mount facts only read); the per-turn writes — the harness-handlers lane
 * (`turn`, `counters`, `limits`, `budget`), the turn-boundary lane (`counters`, `attach`, `budget`) and the
 * recovery lane (`counters.compactionFloor`, `attach.attachState`); the settle-time reads stay the driver's.
 */
export interface RunState {
    telemetry: {
        /** The model the main loop requests — the task's, then the near-budget target once the switch fires. `cacheFamily`,
         *  `pricing` and `pricingConfigured` are ITS price facts; an answer the model lane served from a fallback hop, and every
         *  hop left behind, is priced at its own model ({@link RunState.degrade.priceOf}). Set at the telemetry lane. */
        requestedModel: Model | undefined;
        cacheFamily: ReturnType<typeof cacheFamilyOf>;
        pricing: ModelPricing;
        /** Whether the requested model has a configured price table (a
            *  `RunnerDeps.pricing` entry or a `Model.cost` declaration). When neither exists,
            *  `modelCostToPricing(undefined)` yields an all-zero table and every computed cost is a
            *  fabricated 0 — indistinguishable from "declared free". This flag keeps the two apart so
            *  the DISCLOSURE faces (trace frames, public stats) can go absent instead of lying; the
            *  internal budget coordinate (`stats.costMicroUsd`) stays numeric either way. */
        pricingConfigured: boolean;
        /** Sticky — some spend was ACCOUNTED while `pricingConfigured` was false (a mid-task
         *  model switch can flip pricedness, so per-call state isn't enough for the task total). Once
         *  true, the task-level cost total is an undercount and its faces are omitted. Written only by `noteUnpricedSpend`. */
        unpricedSpend: boolean;
        /** The first unpriced settlement's cause, as a refusal over a money ceiling says it (`unpricedCallCause`); set with `unpricedSpend`. */
        unpricedCause: string | undefined;
        tracer: TaskSpec["tracer"];
        taskId: string;
        /** The run's engine-minted identity, so the task.start/task.end pair carries it from ONE
         *  seat (the same place taskId is published). Empty only before the run body assigns it. */
        runId: string;
        taskStart: number;
        taskStartMonotonic: number;
    };
    degrade: {
        degradeToModel: Model | undefined;
        /** The run's FIRST switch away from the requested model (a main-loop fallback walk, or the near-budget switch) — an audit
         *  record only (`TaskResult.degraded`); no pricing reads it. */
        degraded: TaskResult["degraded"];
        /** The near-budget switch fired — its own bit, so a fallback walk earlier in the run does not latch it. */
        budgetSwitched: boolean;
        outputErrorStreak: number;
        outputInvalid: boolean;
        /** Record the run's first switch (audit: `degraded`, the `task.degraded` trace, the operational `onError`); once. */
        recordDegraded: (info: NonNullable<TaskResult["degraded"]>) => void;
        /** The price facts of a model a call was billed at: the requested model's are the telemetry's; any other's are read
         *  from the deployment's table (or the model's `cost`) at the call, through the price-table door. */
        priceOf: (model: Model) => {
            pricing: ModelPricing;
            pricingConfigured: boolean;
            cacheFamily: ReturnType<typeof cacheFamilyOf>;
        };
        /** The leg's `model.fallback` announcement (the main loop's and the side-call book's one seat). */
        fallbackSeat: ModelFallbackSeat;
    };
    limits: {
        turnsExceeded: boolean;
        budgetHit: "exceeded" | "precall" | undefined;
        /** WHICH budget axis tripped, set at the same instant as {@link budgetHit} so the
         *  terminal can name it (`limits.max_tokens_exceeded` vs `limits.max_cost_exceeded`). Tokens
         *  outrank cost when both are over at the same boundary (the documented attribution order). */
        budgetAxis: BudgetAxis | undefined;
        /** The TYPED terminal an EXTERNAL cause (a dying execution environment, an
         *  exhausted governance window) recorded when it could not suspend the run durably. Set together with
         *  the abort it triggers, and adopted as the run's `threw` once the loop settles, so the caller gets
         *  `env.lifetime_expired` / `usage.window_exhausted` instead of the anonymous error an abort produces.
         *  Same carrier shape as `brainCallGuardrailRef.timedOut`, and for the same reason: the harness turns a
         *  loop throw into an error assistant message that strips the error object. */
        platformTerminal: (Error & {
            code?: string;
            retryAfterMs?: number;
        }) | undefined;
        outputRetryCap: number;
        effectiveMaxTurns: number | undefined;
        /** The ms the walltime window read as passed at the first turn boundary that found it passed (the boundary's own reading of the
         *  monotonic clock, taken where the park decision reads it) — the figure `TaskResult.limitCrossed` reports for the walltime axis, so
         *  work done after the answer cannot move it. `undefined` = no boundary has found the window passed. */
        walltimeCrossedMs: number | undefined;
        /** The budget axis over its ceiling at the instant a turn REACHED the turn cap — the turn-end handler records the cap and runs its budget check only on the other arm, so
         *  a turn that does both leaves `budgetHit` unset; this is that same check, read where the cap is recorded, for `TaskResult.limitCrossed` alone. */
        budgetOverAtTurnCap: BudgetAxis | undefined;
        /** The spend account's refusal that ended the leg's loop, read off the refusal the loop's own request was answered with (the
         *  ceiling that held, or a closed account) — the terminal reads it, since a request the account never sent is no message. */
        spendStop: import("../spend-account.js").SpendStop | undefined;
    };
    budget: {
        remainingMicroUsd: number | undefined;
        maxCostMicroUsd: number | undefined;
        /** Tokens still available on the cross-slice allocation (`resourceSuspend.totalTokens`
         *  minus everything earlier slices spent), or `undefined` when no total is set. */
        remainingTokens: number | undefined;
        /** This slice's EFFECTIVE token ceiling = `min(limits.maxTokens, remainingTokens)`. The exact mirror
         *  of `maxCostMicroUsd`. `undefined` = no token ceiling; `0` is a real, exhausted ceiling. */
        maxTokensWindow: number | undefined;
        /** The axis that is over its ceiling right now, or `undefined` when neither is — a predicate that
         *  ALSO carries the attribution, so no caller can set `budgetHit` without an axis. */
        overBudget: () => BudgetAxis | undefined;
        streamCancel: boolean;
        callOutputChars: number;
        lastStreamBudgetCheck: number;
        projectedOverBudget: () => BudgetAxis | undefined;
        /** A spend estimate's rates for `model`: the tier the `next` call / the main call `inFlight` goes at. Set at the telemetry lane. */
        estimateRatesOf: (model: Model, call?: "next" | "inFlight") => ModelPricing;
        /** The money ceiling's stop for spend it cannot count (`config.limit_invalid`), or `undefined`. Set at the telemetry lane. */
        uncountedSpendStop: () => (Error & {
            code?: string;
        }) | undefined;
    };
    turn: {
        callStartAt: number | undefined;
        firstTokenAt: number | undefined;
        turnUsage: {
            inputTokens: number;
            totalInputTokens: number;
            outputTokens: number;
            cacheReadTokens: number;
            cacheWriteTokens: number;
            costMicroUsd: number;
            apiDurationMs: number;
            speed?: "fast";
        } | undefined;
        turnUsageMissing: boolean;
        /** The turn's cache marks as `turn_end` carries them (some call of the turn did not report its cache reads / writes;
         *  `cache-hit-account.ts` decides them), reset with the rest of the per-turn bookkeeping. */
        turnCacheMarks: {
            cacheReadUnreported?: true;
            cacheWriteUnreported?: true;
        };
        turnStopReason: string | undefined;
        /** The PROVIDER-REPORTED model name of this turn's LAST assistant message, when it differed from the
         *  requested id — surfaced on `turn_end.responseModel`, reset with the rest of the per-turn
         *  bookkeeping. Same shape as `turnStopReason`: last-message-wins, absent by default. */
        turnResponseModel: string | undefined;
        /** B15 三期使能:postToolBatch 的本回合聚集批(每回合边界消费并重置 — 回合语义,故归 turn)。 */
        toolBatch: PostToolBatchCall[];
        /** The leg's last assistant message a provider produced (never reset per turn): the leg's last message when its loop ended
         *  on a request the spend account refused before sending it — that refusal produced nothing, so it is neither a turn nor
         *  the run's last message. */
        lastProduced: import("../../internal/llm.js").AssistantMessage | undefined;
        completed?: readonly import("../mods/lifecycle-stations.js").CompletedTurn[];
    };
    counters: {
        /** How many distinct LIMIT-APPROACH sentences a request has carried this run (0..2): one per threshold, counted by the
         *  first request that carries it (a crossing straight past the second threshold counts 1). */
        approachNoticesSent: number;
        /** B15 三期使能:R9 引用的 R3/压缩区 latch(walltime 收尾 latch — preemptIgnoredReported 同族)。 */
        walltimeSyncBackstopFired: boolean;
        /** B15 三期终件补遗:压缩地板/背压 latch — rs.counters.compactionFloor 跨 drainManualCompact(写)/R9(读写)/收尾(读)三方共享,rs.counters.trimForceBackoff 为 R9 跨调用 latch(同款只改绑定不改时机)。 */
        compactionFloor: number;
        trimForceBackoff: boolean;
        /** Landed compactions (boundary + prompt-too-long lanes) and the last one's kind — the `TaskResult.compaction` source (the breaker state is read off the breaker itself). */
        compactionPasses: number;
        compactionKind?: import("../task-notification.js").CompactionKind;
        repetitionCuts: number;
        repetitionSpared: number;
        repetitionEvents: Array<{
            turn: number;
            action: "cut" | "spared";
            rule: "char-run" | "unit-loop";
            period: number;
            reps: number;
            segment: string;
        }>;
        REPETITION_EVENTS_CAP: number;
        preemptIgnoredReported: boolean;
        wroteThisRun: boolean;
        finalVerifyInjections: number;
        groundingSignalPreR9: boolean;
        groundingSignalPostR9: boolean;
        cadenceTurns: number;
    };
    attach: {
        attachmentsCfg: TaskSpec["attachments"];
        agentListingOn: boolean;
        skillsListingOn: boolean;
        attachState: ReturnType<typeof createAttachmentState> | undefined;
        dateState: {
            announcedDate: string;
        } | undefined;
        /** The Workflow tool card's advisory size guideline as last ANNOUNCED to the model,
         *  plus the live boundary-time read (Prepared.workflowSizeGuideline). Same deliberate posture as
         *  `dateState`: NOT an AttachmentState member, one field, zero reducers. */
        sizeGuidelineState: {
            announcedGuideline: WorkflowSizeGuideline;
            current: () => WorkflowSizeGuideline;
        } | undefined;
        /** B15 三期使能:boundary 注入计数(→ stats.mechanisms.attachmentsInjected;attachState 注入族语义,故归 attach)。 */
        attachmentsInjected: number;
    };
}
/**
 * Config handed to {@link Runner.resume}: the {@link TaskSpec} members the resumed leg runs with. The session comes from the checkpoint,
 * so the config names none of the members that live and die with a session (`SessionBoundSpecMember`, the member table's one column:
 * `sessionId`, `requireExistingSession`, `resumeAt`, `resumeAtMode`, `restoreFiles`, `acceptPartialRestore`, `unplacedHistoryRecordedUnder`, `rewindFilesTo`); a
 * resume sends no new human message, so it takes no objective, `userAttachments` or `runOrigin` (either present is refused before the
 * claim; a wake states its leg's word on the input it hands over). The row records no tool, hand band or server list: `tools`, `mcp`,
 * `a2a` and the `skills` specs are the deployment's CURRENT ones as this resume hands them (the leg dials these lists as the config doors
 * judge them; absent declares none) — a host replaying the parked run's lists re-dials a server its user removed. The parked call is
 * judged against what this resume mounts: its server no longer declared ⇒ `resume.tool_unavailable` (never dialed, not run, the row
 * reopened `pending`); a replacement ⇒ `resume.tool_contract_mismatch`; a moved face or declaration ⇒ `resume.target_moved`. Identity is
 * kept instead: a contradicting `principal` is refused (`resume.principal_mismatch`), an absent one inherits the row's.
 */
export type ResumeTaskConfig = Omit<TaskSpec, "objective" | "userAttachments" | "runOrigin" | SessionBoundSpecMember>;
/**
 * A composition leg's identity ({@link RunInternals.compositionLeg}, `CheckpointState.compositionLeg`): which entry handed the
 * leg out, which leg of it this is, and the host session the composition runs for. One member per entry; `entry` is a closed
 * set, and a word outside it is refused wherever the identity is read (`config.invalid_argument`), never stamped on a card.
 *  · `entry: "cascade"` — `leg` is the ladder rung's index (0-based); `hostSessionId` is the caller's `TaskSpec.sessionId`,
 *    the session a host files the composition's run under. A rung runs in its OWN session (the card's `sessionId`), so a host
 *    links a rung's card back to its run by `hostSessionId`, never by the card's session. A cascade whose caller named no
 *    session mints none: that rung's card cannot be linked by composition.
 *  · `entry: "verify"` — the verification gate's VERIFIER leg (`verifyCompleted` and every entry built on it): `leg` is the
 *    verification iteration (1-based, the number `onRound` reports); `hostSessionId` is the implementation's session (the result
 *    the gate verifies, which every fix leg continues). Only the verifier leg is handed one — a fix leg continues the
 *    implementation session itself, so its card already sits in the host's session. A verifier runs in a session the gate
 *    minted, so its card is one no resume of the host's own run reaches: a host reads this entry to tell it from a card it
 *    can decide, and settles it by its token — `runner.resume`, or `Runner.voidVerifierPause` to void it and unpin the
 *    verifier session. An implementation result with no session id mints none.
 *  · `entry: "repair"` — a repair loop's CLEAN RESTART leg (`runRepairLoop`): `leg` is the number of attempts the loop had used
 *    when it dispatched the restart; `hostSessionId` is the session those attempts worked in (the caller's, or the one the engine
 *    minted for them). Only the restart is handed one — an attempt continues that session itself, so its card already sits in the
 *    host's session. The restart runs in a session of its own and does the same work, so its identity names where that work is.
 *    It is not `verify`: that word names the gate's VERIFIER leg (a host reads it to settle the card as a verifier's, and
 *    `Runner.voidVerifierPause` refuses any other), and a card is linked back to its composition by `entry` and `leg` — a restart
 *    belongs to no verification run and has no verification iteration. A loop whose attempts worked in no session mints none.
 * Three identities beside each other on one card, never merged: the card's `sessionId` (what a resume continues),
 * `placementRootSessionId` (where the work is placed), and this (whose run it is, and which leg).
 */
export type CompositionLeg = {
    readonly entry: "cascade" | "verify" | "repair";
    readonly leg: number;
    readonly hostSessionId: string;
};
/** Resume plan threaded from {@link Runner.resume} into the shared run loop. */
export interface ResumeRun {
    cp: Checkpoint;
    /**
     * Did the APPROVED ACTION actually begin executing?
     *
     * The reopen compensation used to key on an error-code whitelist (`resume.env_failed` /
     * `resume.session_not_found` / `resume.tool_unavailable`). That is a proxy for the thing that actually
     * matters, and every time a NEW way to exit without running the action appeared, the whitelist did not
     * know about it: a caller's abort landing anywhere between the CAS and `tool.execute` — across
     * `SessionStore.acquire` (pluggable, cross-network on a durable backend), the MCP reconnect, the env
     * rebuild, `resumeVM`, tool materialization — produced a `failed` result with NO errorCode, no reopen,
   * and a human approval consumed for work that never happened. Two rounds of fixes each
     * moved that window rather than closing it, because both extended the whitelist.
     *
     * This binds the compensation to the FACT instead: set the instant before `tool.execute` for the gated
     * call (the same `onExecuteStart` signal the orphan-reconcile split already trusts). Every terminal —
     * throw OR returned result — asks one question: was the checkpoint consumed while this stayed false?
     */
    pendingActionStarted?: boolean;
    /** Validated against `cp.gate.kind` at the resume entry: human/irreversible_ask→`policy_ask`,
   *  resource_limit→`resource_limit`, needs_review→`dry_run_review`,
     *  plan_review→`plan_review`. The gate-match guard in `resumeStream` enforces the
     *  correlation. `wake` is the NON-GATE arm — only a checkpoint awaiting NO gate
     *  decision passes the resume entry with it (gate purity, `wake.gate_pending`); the run loop skips
     *  `applyResumeDecision` for it (no pending action to resolve) and re-enters via the continuation +
     *  pendingSteer tail alone. */
    outcome: Extract<ResumeOutcome, {
        gate: "policy_ask" | "resource_limit" | "dry_run_review" | "plan_review" | "wake";
    }>;
    /** The wake's own operator message, validated (`validatePendingSteer`) at the
     *  resume entry and carried SEPARATELY from the checkpoint's parked `pendingSteer`: a message-bearing
     *  wake of a checkpoint that ALSO holds a parked steer must deliver BOTH (park order: parked first,
     *  wake message second), each under its own trusted framing — the old merge-into-the-slot shape
     *  silently DISPLACED the parked (undelivered) supervisor steer. Wake outcomes only. */
    wakeMessage?: Omit<PendingSteerEntry, "seq">;
    /** The userPromptSubmit screen's `additionalContext` for {@link wakeMessage},
     *  captured at the resume ENTRY (the message is screened once, pre-CAS, on the resuming process's
     *  hook) and delivered by the drain as the engine's own reminder AHEAD of the wake frame — carrying
     *  it forward is what keeps the hook single-run (re-screening at the drain would be the double-run
     *  §4.3-3 reserves for the cross-process parked leg). Present only when a wake message passed a
     *  screen that supplied context. */
    wakeMessageHookContext?: string;
    /** Who rewrote {@link wakeMessage}'s text at that screen (`prompt.submit`), in the order they did — its applied
     *  `human_input` account names them. Absent ⇒ nobody rewrote it. */
    wakeMessageRewrittenBy?: readonly string[];
    /** The resumed leg's bus when the wake-message screen admitted it before the claim — prepare adopts it. */
    legMods?: LegMods;
    /** The claim's reversal, bound to THIS resume's token and scope by `resumeStream` — REQUIRED, as the store's
     *  `reopen` is: called when the claimed leg ends before its approved action started (a failed restore, a
     *  refusal at the leg's prepare, an abort, a leg that returned failed), it returns the row `resolved → pending`
     *  under the failure's reason (`reopenReasonOf`), recorded on the row so the next re-resume validates per
     *  reason — an `env_failed` reopen replays the persisted winner, the fresh-redecision reasons take a new
     *  decision. Answers the store's own answer — `"reopened"` (it flipped the row) or `"declined"` (`reopen`
     *  answered `false`) — and rejects only with what the store threw (the row's state is then unproven unless
     *  {@link claimedRowPending} shows the reopen landed);
     *  every exit reads it through `compensateUnstarted` (resume-startup-cause.ts), the one reading. */
    reopenUnstarted: (reason: ReopenReason) => Promise<"reopened" | "declined">;
    /** The row read that can show a reopen landed, bound to THIS resume's token like {@link reopenUnstarted} and REQUIRED beside it:
     *  `true` when the row reads `pending` at a generation past the one the claim won at. `compensateUnstarted` asks it only after a
     *  `reopen` that threw — a write that may have landed — and any other reading, or a read that throws, leaves the state unproven. */
    claimedRowPending: () => Promise<boolean>;
    /** The row's execution-record verb, bound to THIS resume's token and scope by `resumeStream` (the
     *  same closure form as {@link reopenUnstarted}, and REQUIRED for the same reason: the store contract requires the
     *  verb, so there is no store this seat could be absent for). The pending-call resolver calls it
     *  exactly once per resolution, right after it emits the resolved call's `tool_end` frame, with the
     *  {@link import("../gate-outcome.js").GateOutcome} that frame carried — every disposition, the
     *  executed allow included (see `CheckpointRow.executionOutcome`: absence means unknown, never
     *  allowed). The word it answers is read through `EXECUTION_RECORD_LEAVES_ROW_UNRECORDED`; a
     *  conflict throw propagates (an engine defect, not a store condition). */
    recordExecutionOutcome: (gate: import("../gate-outcome.js").GateOutcome) => Promise<ExecutionOutcomeRecordWord>;
    /** Set right after `applyResumeDecision` completes (`policy_ask`), and at the continuation's own receipt for `plan_review` / `dry_run_review`
     *  (its decision rides only that message): the negative-decision twin of `pendingActionStarted`. A reject/deny consumes its gate BY BEING DELIVERED, and
     *  this bit is the delivery fact — every throw-arm cause (prepare failure, `session_not_found`, a
     *  pre-delivery abort) and the walltime-exhausted settle fire BEFORE it is set, so an undelivered
     *  negative decision still reopens, under its failure's reason (`env_failed` replays the persisted decision, `config_refused` takes a fresh one),
     *  closing the loss class the first cut reopened; the reason's reading weighs it too (`unstartedFailureOf`: an `env.` refusal after it is `env_failed`). */
    decisionDelivered?: boolean;
    /** Its claim OPENED a cycle (the consume hook, {@link RunInternals.afterCheckpointResolve}, stated the number the leg runs as): the spawn station
     *  starts it. Absent ⇒ the parked cycle continues; a `cycleSeq` handed without a stating hook names that one. Written by the post-claim rung only. */
    opensCycle?: true;
}
/**
 * What {@link TaskStream.destroy} needs to reap a SUSPENDED task. Captured (stashed) onto
 * the stream handle the moment a run assembles `status:"suspended"` — `finish()` deliberately left the
 * paused env + committed checkpoint alive for resume, so without this stash they'd be unreachable (the
 * `Prepared`, and its `ownedEnv`, are GC'd once the run promise settles). `env` is `undefined` for a
 * process-local suspend (no remote env to reap — only the checkpoint is expired).
 */
export interface SuspendReap {
    env: Prepared["ownedEnv"];
    token: CheckpointToken;
    scope: string;
    store: CheckpointStore;
    /** The grant holder the park's put carried ({@link ParkWrites}): the reap's expire is issued in the run's name with it. */
    holder?: string;
    /** The suspended task's session — for onError correlation only (the `token` is a capability and must
     *  NEVER be logged, checkpoint-store.ts §6). */
    sessionId: string;
}
/** B15 三期终件 — R9(回合边界全域:压缩/attachments 注入/提醒节律/预算判决)工厂。
 *  正文自 runLocked 逐字搬迁(this 面经 runnerHooks 闭包打包,B13 #coreView 同款);模块级符号
 *  同文件直见不经 deps;可变运行态全在 rs(B15 二期),deps 全部为 const 稳定引用。 */
export interface TurnBoundaryDeps {
    spec: TaskSpec;
    legYield?: import("../runner-drain.js").LegYield | undefined;
    queue: PushQueue<TaskEvent>;
    /** The run loop's own latch — read for `userHalted` (the `TaskStream.halt()` verb sets the harness stop latch directly,
     *  not through the ctx primitive `Prepared.stopRequestedRef` mirrors: a halted boundary has no next request either, so
     *  the bundle is not collected there) and for `callerStop`, the gate the boundary's compaction pass admits on and carries. */
    loopLatch: {
        readonly userHalted: boolean;
        readonly callerStop: import("./caller-stop-gate.js").CallerStopGate;
    };
    manualCompactRef: Pick<ManualCompactRef, "requested" | "waiters">;
    todoToolMounted: boolean;
    taskToolsMounted: boolean;
    walltimeMonotonicDeadline: number | undefined;
    timeout: {
        fired: boolean;
        latenessMs?: number;
        clear: () => void;
    };
    ident: () => {
        eventId: string;
        parentToolCallId?: string;
        sourceTaskId?: string;
    };
    /** Whether a handler hangs on `classic.PostToolBatch` (the batch is collected only then). */
    postToolBatchArmed: boolean;
    batchArgs: Map<string, unknown> | undefined;
    compactionBrain: Brain;
    withinTaskCompaction: () => boolean;
    compactionBreaker: {
        failures: number;
    };
    rapidRefill: RapidRefillState;
    drainManualCompact: (outcome: CompactOutcome) => void;
    /** The leg's display (a top-level leg's), waited on at each boundary before its work. */
    display: import("../mods/message-display.js").MessageDisplay | undefined;
    runnerHooks: {
        onError: RunnerDeps["onError"];
    };
    /** The Runner's deployment deps, read LIVE ({@link RunnerDepsSeat}): the compaction seams (compaction-seams.ts) the
     *  boundary's compaction pass reaches down for read the summary provider, the hooks slot and the error sink through it
   *  on every pass — the three Runner methods that used to sit on `runnerHooks` as delegates. */
    runner: RunnerDepsSeat;
}
/** R5(harness 事件处理器族)的依赖包。全部为 runLocked 内声明顺序早于
 *  工厂调用点的 const 稳定引用 + 三个 runLocked 形参;this 面(deps.onError)经 runnerHooks 打包
 *  (B13 #coreView / R9 TurnBoundaryDeps 同款)。*/
/** What a PRODUCER of a `tool_progress` frame knows: the FACTS it observed. The frame minus everything only
 *  the run supplies — its discriminator, its {@link TaskEventIdentity} stamp, the elapsed time, which the
 *  lane computes from its own per-call origin, and the gate phase, which it reads off the call's occurrence. Derived from
 *  the union member, so seat and frame cannot drift. */
export type ToolProgressBody = Omit<Extract<TaskEvent, {
    type: "tool_progress";
}>, "type" | "elapsedTimeSeconds" | "gate" | keyof TaskEventIdentity>;
/** The run's TOOL-PROGRESS lane: the ONE mint of `tool_progress` plus the heartbeat over the calls in flight —
 *  the leg's occurrences (`Prepared.toolOccurrences`), read, never a set of its own. Declared on the FLOOR because
 *  both registry-side readers sit above its implementation (the driver builds it, the harness-handler lane drives
 *  it) and the Prepared seat that carries it to the tool band is here too. `createToolProgressLane`
 *  (tool-progress-lane.ts, layer 1) is its one implementation. */
export interface ToolProgressLane {
    /** Offer ONE frame — from a tool that observes its own progress (the shell's per-second tick) or from the lane's own heartbeat.
     *  The lane stamps the elapsed time, DROPS an offer inside the cadence floor, resets that call's beat clock when it keeps one, and
     *  beats the leg's activity seat when a producer's `totalBytes` advanced (never for the heartbeat). NEVER THROWS: a tool calls this
     *  from inside an environment output callback, where a throw kills the command it is describing. */
    emit(body: ToolProgressBody): void;
    /** The heartbeat stops covering every call in flight and disarms (turn end / teardown): no beating into the next
     *  turn. The occurrences stay — a later end must still know its start went out. */
    clear(): void;
}
/** The run's one `message_committed` mint ({@link runClockAndContent}): a tool result names its `toolCallId` (the join key to the
 *  call already rendered); a user row names its source (`userRow`, {@link UserRowSource} — what the row is and, for a person's input,
 *  which `human_input` key it carries); an assistant message names neither. Naming one where it does not belong is refused. */
export type EmitCommitted = (entryId: string, role: "user" | "assistant" | "toolResult", toolCallId?: string, userRow?: import("../user-row-origin.js").UserRowSource) => void;
export interface HarnessHandlersDeps {
    spec: TaskSpec;
    queue: PushQueue<TaskEvent>;
    internals: RunInternals | undefined;
    ident: () => {
        eventId: string;
        parentToolCallId?: string;
        sourceTaskId?: string;
    };
    pushContent: (e: TaskEvent) => void;
    /** The leg's display (a top-level leg's): an assistant message's text deltas and block closes are written into it instead of
     *  pushed (it pushes them, or what its handlers show of them). */
    display: import("../mods/message-display.js").MessageDisplay | undefined;
    emitCommitted: EmitCommitted;
    startedToolCallIds: Set<string>;
    toolStartAt: Map<string, number>;
    /** The run's tool-progress lane: the handlers tell it when a call enters and leaves execution, and
     *  clear it with the rest of the per-call bookkeeping at turn end. */
    toolProgress: ToolProgressLane;
    writeFamilyOf: (name: string) => WriteFamily | undefined;
    toolLabels: Map<string, string>;
    /** Whether a handler hangs on `classic.PostToolBatch` (the batch is collected only then). */
    postToolBatchArmed: boolean;
    batchArgs: Map<string, unknown> | undefined;
    runnerHooks: {
        onError: RunnerDeps["onError"];
        onNotice: RunnerDeps["onNotice"];
    };
    mediaBudgetBase64Chars: RunnerDeps["mediaBudgetBase64Chars"];
    /** The run's ONE isolation scope for the {@link RunInternals} observation sinks, minted by the
     *  identity-wiring lane (which calls the first of them) and shared with these handlers, so the
     *  "first failure per site" disclosure is one account for the whole run rather than one per lane. */
    internalsNotifier: SafeNotifier;
}
/**
 * The Runner as the modules it drives and the compositions over it see it — the delegation tools
 * (Agent / SendMessage / AgentTranscript), the repair, verify and cascade loops, the
 * workflow and goal orchestrations, the HTTP server, `warmResume`, and the
 * orchestrator's own trusted `runnerSelf` seat. Every one of them used to name the `Runner` CLASS
 * through `import type`, which is a type edge from below the runner back up into it — a cycle the
 * direction gate could only carry as an exemption, and one that reached the orchestrator through the
 * delegation tools (prepare-task → send-message-tool → runtask).
 *
 * THE MEMBER SET IS MEASURED, NOT DESIGNED: it is exactly the union of what those consumers read off a
 * Runner today (a TS-Program census over `src/`, pinned in test/runner-self-seat.test.ts so a member
 * nobody reads reds as dead weight and a consumer reaching for a member outside it reds as a widening).
 * `swapDeps`, `sideQuery` and the constructor are NOT here — no consumer reaches them; a host that
 * needs them holds the class. The class implements this interface, so the two cannot drift apart.
 *
 * Signatures are spelled out (not `Pick<Runner, …>`), because naming the class from here would be the
 * very edge this seat exists to remove.
 */
/**
 * The Runner's deployment deps as a LIVE read for the lanes that read them after an await (the resume ladder's
 * rungs). `Runner.deps` is not a constant: `swapDeps` replaces the object, so a lane handed the object at its
 * call would read a stale catalog — and a stale anything — where the one-function ladder read `this.deps.x` at the
 * instant of the read. The seat is the Runner's own view (a getter over the private field), so `runner.deps.x`
 * in a lane is exactly `this.deps.x` in the method it came from.
 */
export interface RunnerDepsSeat {
    /** The deps object the Runner holds RIGHT NOW — never cache it across an await. */
    readonly deps: RunnerDeps;
}
export interface RunnerSelfSeat {
    /** The session store this Runner was constructed over — the delegation tools acquire / release / fork through it. */
    readonly sessions: SessionStore;
    /** The deployment agent + model catalog, READ-ONLY (a fresh copy per read; the definitions are the shared objects); `roles` = `RunnerDeps.roles` (the delegation seat's `childModelSeat` reads `roles.subagent`). */
    readonly agentCatalog: {
        agents?: AgentDefinition[];
        builtinAgents?: boolean;
        models?: Record<string, Model>;
        roles?: ModelRoles;
    };
    /** The context-window overlay a leg on `ref` reads RIGHT NOW (`RunnerDeps.contextSettings`, tier aliases followed
     *  against the catalog in force): prepare hands its leg a call-time reader over it, because this is the one seat a
     *  running leg re-reads (geometry, not route — see `context-settings.ts`). */
    contextOverlayOf?(ref: import("../model-seat.js").ModelRef | undefined): import("../context-settings.js").ContextWindowOverlay | undefined;
    /** The deployment-level gating baseline (deps toolPolicy) as a delegate wrapper — for assemblers that compose with it. */
    readonly gateBaseline: {
        toolPolicy?: RunnerDeps["toolPolicy"];
    };
    /** Whether a child task THIS runner runs can be placed in a tree other than the caller's (an explicit cwd, a worktree):
     *  true only when its deps carry an `executionEnvFactory` (live read — `swapDeps` replaces the deps). The delegation tool asks
     *  the runner that will run the child, not the one that ran the parent leg. Absent on a hand-built seat ⇒ read as "cannot say" ⇒ no; a hand-built seat answers for the runner its `runTask` forwards to. */
    canRerootChild?(): boolean;
    /** A completion addressed to a delegation tree's root, through THIS runner's notification route: the route's sink when the
     *  deployment judges the root a durable box at `root.scope` that takes engine frames (the sink then reaches the root's live run
     *  here, else its seat here, else that box), or why not. Asked by a drive that carries no run lane and whose task registry holds
     *  no park of the cycle. `unkept` = where a frame goes when the box of a root seated nowhere here failed it twice. The route
     *  judges again at each delivery. Absent on a hand-built seat ⇒ read as "no route" (the drive keeps the mount's sink). */
    sessionCompletionLane?(root: SessionAddress, unkept?: TaskNotificationSink): SessionCompletionLane;
    /** Fire `RunnerDeps.onTaskOutcome` through the swallow-guarded chokepoint (thin compositions emit at their terminal state). */
    emitTaskOutcome(outcome: TaskOutcome): void;
    /** Announce a fact of a composition's own (the verification gate's `verify.verifier_is_implementer`) on `RunnerDeps.onNotice`, live-read,
     *  through the one delivery form every notice leaves by (`deliverEngineNotice`: the same-principal text pass, the session lift, a
     *  throwing sink contained). Absent on a hand-built seat ⇒ the composition cannot say it, and says nothing; the Runner always has it. With
     *  a leg's `route` (`noticeAddressOf`) the Runner delivers under that route's admission (`legNoticeAdmission`, its own destination judge). */
    emitNotice?(notice: import("../engine-notice.js").EngineNotice, route?: import("../leg-identity.js").NoticeRoute): void;
    /** A hold, on the peer seat THIS runner's legs ask, of the references `declared` names — taken by a keeper of declarations outside a
     *  leg (which they are: peer-seat.ts's module note), released by it once (peer-seat.ts `holdPeerDeclarations`). */
    holdDeclarations(declared: import("../peer-seat.js").PeerDeclarations): import("../peer-seat.js").PeerDeclarationHold;
    /** Run a task to completion. `internals` is the TRUSTED run-scoped channel (never a TaskSpec field). */
    runTask(spec: TaskSpec, internals?: RunInternals): Promise<TaskResult>;
    /** Streaming form of {@link RunnerSelfSeat.runTask}; `resume` is the run loop's resume plan, `internals` the trusted channel. */
    runTaskStream(spec: TaskSpec, resume?: ResumeRun, internals?: RunInternals): TaskStream;
    /** Resume a suspended task from its checkpoint token with the caller's decision, to completion. */
    resume(token: CheckpointToken, outcome: ResumeOutcome, taskConfig: ResumeTaskConfig, internals?: RunInternals): Promise<TaskResult>;
    /** Streaming form of {@link RunnerSelfSeat.resume}: the pre-CAS guards and the CAS run first, then the live stream is returned. */
    resumeStream(token: CheckpointToken, outcome: ResumeOutcome, taskConfig: ResumeTaskConfig, internals?: RunInternals): Promise<TaskStream>;
}
/**
 * The orchestrator's entry (`prepareTask`, prepare-task.ts) as ONE contract: the notification lane's
 * `prepareTask` seat names it, and the orchestrator pins its own declaration against it (`PrepareTaskIsTheContract`), so a
 * signature change reds at the declaration — not at the driver's hand-in, and not as a seat spelled a second time. It lives
 * on the floor because a lane may not name the orchestrator (docs/LAYERING.json: layer 4 sits above the lanes). Positional,
 * exactly as the entry is declared — the seat carries the orchestrator's function itself, not a lane Input.
 */
export type PrepareTaskFn = (spec: TaskSpec, deps: RunnerDeps, sessions: SessionStore, resume?: PrepareResume, internals?: RunInternals, runnerSelf?: RunnerSelfSeat, runIdSink?: Pick<TaskIdRef, "runId" | "rowVerified" | "rewind" | "legEnvForRow">, holdSessionLock?: (sessionId: string) => Promise<void>, legWrites?: LegWrites, noticeDestinations?: import("../task-notification.js").NoticeDestinationJudge, promptSubmitRef?: import("../input-author.js").PromptSubmitRef, runEnd?: import("./end-of-run.js").RunEnd) => Promise<Prepared>;
/** One leg's view of the Runner's session write ledger — `session-write-ledger.ts` states `startAt`, `issue`, `close` and what the close reads. */
export interface LegWrites {
    startAt(leaf: string | null): void;
    issue<T>(sessionId: string, what: string, start: () => Promise<T>, leafAfter: string | null, parent?: string | null): Promise<T>;
    close(): {
        readonly inFlight: boolean;
        readonly lastLanded: string | null | undefined;
        readonly strayed: string | undefined;
    };
}
/**
 * The Result of an INSTALLING phase: a lane whose every product is installed on a seat it borrowed
 * (the harness's stop gate and recovery chain, the run state's counter groups, the stream's result setter, the claimed
 * row's registries) hands nothing back, and says so by extending this marker. The marker is machine-read by gate:phase-api
 * a Result with no members MUST extend it, a Result with members MAY NOT, and no Result
 * inherits anything else — so an empty Result is a stated fact about the phase, never an interface someone forgot to
 * fill, and a phase that starts handing a product back must drop the declaration in the same edit. Six lanes carry it:
 * the attachment seats, the stop gate, the recovery lanes, the settle and teardown (run-), the preflight and the claim
 * (resume-).
 */
export interface InstallingPhaseResult {
}
/** The live-task handle `runLocked` publishes once the harness exists: the harness + abort controller, the loop latch
 *  (`ended` flips when the single `harness.prompt` settles; `userInterrupted` / `userHalted` are the interrupt and halt
 *  verbs' attribution seats; `callerStop` is the run's caller-stop gate the three stop verbs trip), the run's reminder
 *  mark, its session and engine-minted run id, and the bus + identity envelope the steer entrance screen runs on. */
export interface LiveHandle {
    harness: AgentHarness;
    abortController: AbortController;
    loop: {
        ended: boolean;
        userInterrupted: boolean;
        userHalted: boolean;
        callerStop: import("./caller-stop-gate.js").CallerStopGate;
    };
    reminderMark: string;
    sessionId: string;
    /** The run body's engine-minted run id, so the stream-layer verbs can name the run their disclosures are about. */
    runId: string;
    hookIdentity: HookInvocationIdentity;
    /** The leg's mods bus (the steer entrance raises `classic.UserPromptSubmit` on it). */
    modBus: LegModBus;
    /** The leg's decision-screen seat (`Prepared.hookScreens`): the steer entrance's screen is framed through it. */
    hookScreens: Prepared["hookScreens"];
    /** The leg's live permission-mode seat (`TaskStream.setPermissionMode` steers it). */
    permissionMode: PermissionModeController;
    /** The leg's fast mode (`TaskStream.setFastMode` steers it). */
    fastMode: import("./fast-mode-seat.js").FastModeLeg;
}
/** The run body's backstop CARRIER: the effective ids and the post-prepare
 *  observations the run body publishes as they are minted, so the stream layer's failure backstop names the
 *  same run, session and observations the frames the run body already emitted did. */
/** What the one assembly of a result's posture seats reads (`resultPostureSeats`): the prepared leg's own resolutions. */
export type PostureSeatsSource = Pick<Prepared, "effectiveReadFace" | "effectiveWriteFace" | "effectiveReadDenyPatterns" | "callerPlaces" | "effectiveBlockReadsOutsideRoots" | "effectiveSandbox" | "effectiveExternalContentTarget">;
export interface TaskIdRef {
    current?: string;
    sessionId?: string;
    runId?: string;
    effectiveMemoryScopes?: TaskResult["effectiveMemoryScopes"];
    effectiveReasoning?: TaskResult["effectiveReasoning"];
    delegationTerminalOwed?: {
        readonly identity: HookInvocationIdentity;
        readonly receipt: () => Pick<Extract<import("../types.js").DelegationLifecycleEvent, {
            phase: "terminal";
        }>, "stations" | "origin">;
    };
    editedFiles?: () => TaskResult["editedFiles"];
    /** The leg's byte-floor latch ({@link Prepared.readFloorUnkept}), read live: the backstop's `TaskResult.readDenyFloor`. */
    readFloorUnkept?: {
        readonly current: import("../../tools/fs/read-floor.js").ReadFloorRows | false;
    };
    /** The prepared leg's postures, published with the observations above: the backstop's posture seats, by the one assembly. */
    posture?: PostureSeatsSource;
    /** `false` from the moment a leg holding an owner seat starts until its row's owner is verified ({@link RunInternals.onSessionVerified}): a result minted meanwhile names no session (`""`). */
    rowVerified?: boolean;
    /** Whether the leg's prompt message was committed: `{ committed: false }` from the carrier's creation, replaced at the prompt
     *  receipt by the commit's reading (`intakeOfCommit`; `undefined` when the store handed back no usable entry id). */
    intake?: TaskResult["intake"];
    writesAtClose?: ReturnType<LegWrites["close"]>;
    /** The env a resume leg sent back to its row's workspace was minted, when the leg's prepare refused it and its restore seat did not
     *  disprove that the env stands there, or when the leg left because its approved tool is absent or replaced (`runLeg`): handed here
     *  instead of destroyed, so the backstop keeps it (the row came back, or may have: let go through the env's `releaseToRow` seat when it carries one) or destroys it (the row did not), by the one answer of the compensation (`rowKeepsWhatItsRetryNeeds`, resume-startup-cause.ts). */
    legEnvForRow?: ExecutionEnv;
    /** The leg's record of what its rewind did (`./rewind-outcome.ts`), published at prepare's first statements on a leg that asks for
     *  one — the backstop's `terminal.rewind` and `fileRestore` (the same object {@link Prepared.rewindOutcome} names). */
    rewind?: RewindOutcome;
}
/** The manual `/compact` request seat: the `requested` flag, the parked waiters (each with its
 *  caller's cancel signal and per-call instructions) and the run body's mooted-frame channel. Whether a new request may
 *  park at all is not kept here: it is the stream's input judge ({@link TaskStreamLiveSeat.bodySettled} is its run-end fact). */
export interface ManualCompactRef {
    requested: boolean;
    /** `requestedBy`: the extension a `$.session.compact` request came from (absent on a host `compact()` request) — the
     *  pass that claims it carries it on the frame that ends it. */
    waiters: Array<{
        resolve: (outcome: CompactOutcome) => void;
        signal?: AbortSignal;
        instructions?: string;
        requestedBy?: import("../task-event.js").ExtensionRequester;
    }>;
    emitMooted?: (reason: string) => void;
}
/**
 * The notification lane's BINDINGS: the run-notification-lane's own `let`s as ONE seat (getters and setters over the lane's
 * variables, never a copy). The identity-wiring lane binds `harness` / `sessionId` / `ident` the moment `prepared` exists; the
 * leg lane flips `live` in its finally, from which point every notification parks per session for the next run.
 */
export interface NotificationLaneBindings {
    harness: AgentHarness | undefined;
    /** The leg's session address (its session id and the occupant it acquired), bound by the identity lane once prepared. */
    address: import("../task-notification.js").SessionAddress | undefined;
    ident: () => {
        eventId?: string;
        parentToolCallId?: string;
        sourceTaskId?: string;
    };
    /** This lane hands a frame it will not deliver (the harness's displacement and end-of-run sweep) to the park seat: the one hand-away. */
    handOff: (payload: TaskNotificationPayload) => void;
    live: boolean;
}
/** The `notify()` bridge: `runLocked` binds `inject` the moment the task-notification lane exists. */
export interface NotifyRef {
    inject?: (n: TaskNotificationPayload, opts?: {
        priority?: SystemInjectionPriority;
    }) => void;
}
/** The capture opt-out flip verb's binding; bound only when the run mounted a memory session. */
export interface CaptureOptOutRef {
    flip?: (reason?: string) => Promise<{
        outcome: "created" | "existed";
    }>;
}
/** The MCP re-dial verb's binding; bound only when the run declared MCP servers — a leg with
 *  none has nothing to re-dial, and the stream verb then refuses TYPED rather than answering about a
 *  materialization that was never made. Same shape and same law as {@link CaptureOptOutRef}. */
export interface McpRedialRef {
    redial?: (server: string) => Promise<import("../mcp.js").McpReconnectResult>;
}
/**
 * The stream's LIVE state as the verb lanes read it — a view over the driver's own locals (getters, and one
 * setter), never a copy: `resultValue` is written by the run body's `setResult` callback and by the failure
 * backstop, `handle` by the run body's `onReady`, `reapHandle` by its `onSuspend`; every lane reads each of them
 * at the instant of its own read, exactly as the one-function façade read the closure variables.
 */
export interface TaskStreamLiveSeat {
    /** The assembled result once the run settled (the run body's `setResult`, or the failure backstop's mint). */
    resultValue: TaskResult | undefined;
    /** The live-task handle once `runLocked` published it; `undefined` before, and forever when prepare threw. */
    readonly handle: LiveHandle | undefined;
    /** The run body has settled (normally or by a throw): set once, in the run's own `finally`, before its last drain of
     *  parked compaction requests. The one run-end fact for a run that never published a handle — without it a stream whose
     *  prepare threw would read "not started yet" until its result lands. */
    readonly bodySettled: boolean;
    /** What `destroy()` reaps when the run SUSPENDED; unset for every other terminal state. */
    readonly reapHandle: SuspendReap | undefined;
}