/**
 * PrepareTask's CONTEXT-LANE phase, verbatim from the driver: the edit/guard budgets, the
 * microCompact machine state with the trigger-window clamp's one loud outlet, the model's chars-per-token coordinate,
 * and the `context` handler registered on the harness — heal → ledger replay → aggregate tool-result and media caps →
 * frontier clear → the guard chain (arms A/B/C) → the git-frame guard → the lossy-projection flag → the projection
 * seat — and the harness's sink for the provider boundary's tool-turn repairs (`engine/llm/tool-turns.ts`, the one
 * law every request builder reads): the run's `context.tool_turn_repaired` seat, and the lossy flag's second half —
 * a request the law left recorded content out of is lossy too. The four module-level helpers only this lane called
 * moved with it (the machine-state builder, the frontier-clear recorder, the observation-buffer flush, the guard chain
 * with its two types). The interface is the dependency list the segment had implicitly.
 *
 * SYNCHRONOUS FUNCTION, SYNCHRONOUS CALL: the stretch has no await of its own (the handler it registers is async and
 * runs per provider request), so the phase adds no yield between the gate stations before it and the turn wiring after
 * it. Read-stability of the host handles: {@link RunInternals} (`@contract prepare.deps-read-stable`).
 *
 * REGISTRATION SIDE EFFECT, OWNED: this phase registers the ONE `context` handler on the harness and sets its
 * `onToolTurnRepaired` sink; the harness owns both for the run's life (never unregistered — the harness is per
 * prepare). No other station registers on that hook or sets that sink.
 */
import { type AgentHarness, type AgentMessage } from "../../internal/harness.js";
import { type Model } from "../../internal/llm.js";
import { type CopyProjectionInput } from "../request-copy-projection.js";
import { type ClearedProjectionLedger, type MicroCompactMachine, type OccurrenceFingerprint, type OccurrenceIndex } from "../context-edit.js";
import { type ContextWindowOverlay } from "../context-settings.js";
import { type RequestCoreRef, type RequestSize, type RequestSizing } from "../context-guard.js";
import { type ToolResultSeat } from "../tool-result-store.js";
import { type RunnerDeps } from "../types.js";
import type { InTurnCompactionVerdict, Prepared, PreparedMicroCompact } from "./contracts.js";
import type { CompactionForkContext } from "../auto-compaction.js";
import type { TurnPromptSnapshot } from "../../prompt-assembly/turn-snapshot.js";
import { type GitStatusLaneRef } from "./git-status-frame.js";
import type { ReadFileState } from "../../tools/fs/safety.js";
import { type ToolRosterDeltaSeat } from "../tool-roster.js";
import { type MediaBudgetRecord } from "./media-removed-seat.js";
import { type ClearedResultsSession } from "./cleared-results-record.js";
export interface PrepareContextLaneInput {
    /** borrowed-readonly — the task model: the budgets, the trigger-window geometry and `charsPerToken` are read off it. */
    model: Model;
    /** borrowed-readonly — the deployment seats, whole: `onNotice` (the clamp outlet, the offload-loss announcement, the
     *  tool-turn repair seat, the media-removed seats), `tracer` (the cap / clear / trim frames), `mediaBudgetBase64Chars` (the
     *  media trim), `onError` (the git-frame degrade) — the guard chain and the machine-state builder read the whole record. */
    deps: RunnerDeps;
    /** borrowed-mutable — the session's announced record and the leg's receipt ledger: the media budget's account records
     *  the blocks it told of and parks the record's write ({@link createMediaBudgetSeat}). */
    announced: MediaBudgetRecord;
    /** borrowed-readonly — the acquired session id (the offload persist key; every disclosure's attribution). */
    sessionId: string;
    /** borrowed-readonly — the run's invocation id (the clamp notice's per-run claim). */
    runId: string;
    /** borrowed-readonly — the per-task identity (the trace frames' taskId). */
    hostTaskId: string;
    /** borrowed-readonly — the run's offload store, or undefined (the caps' and the machine's persist seat). */
    offloadStore: ToolResultSeat | undefined;
    /** borrowed-readonly — the leg's live roster: a recorded tool name is judged as the wire name it resolves to. */
    toolRosterDeltas: ToolRosterDeltaSeat;
    /** borrowed-readonly — the doors' RESOLVED microCompact knob (immutable values, never the deps bag). */
    microCompactKnob: {
        machine: MicroCompactMachine;
        clearOnRejection: boolean;
    };
    /** borrowed-mutable — the built harness. Writers here: `on("context", …)` — the ONE registration of the request-build
     *  handler (the harness owns the listener; nothing unregisters it) — and `onToolTurnRepaired`, the provider boundary's
     *  repair sink. */
    harness: AgentHarness;
    /** borrowed-readonly — the request-build pass's main request: the request the loop is about to send for a view, rendered with
     *  no side effect (`undefined`: none to reuse — the pass keeps the independent form). Absent ⇒ never one. */
    renderTurnStartRequest?: (view: AgentMessage[], signal?: AbortSignal) => Promise<CompactionForkContext | undefined>;
    /** borrowed-mutable — the turn's halt fact (`Prepared.batchHaltRef`). Writer here: the handler CLEARS it at every new
     *  provider request (a new request means the halted boundary was legitimately passed). The judgment site sets it. */
    batchHaltRef: Prepared["batchHaltRef"];
    /** borrowed-mutable — the git-status lane ref. Writers here: the git-frame guard's degrade latch (`overBudgetShrunk`) inside
     *  the handler; the prompt-inputs phase seeds it. */
    gitStatusRef: GitStatusLaneRef;
    /** borrowed-mutable — the posture directive's newest engine carrier (the first-turn mint and each post-compaction restatement write it); the clip guard reads it. */
    postureFrameRef: {
        protectedText?: string;
        unwritten?: string;
    };
    /** borrowed-mutable — the limit-approach seat (`Prepared.limitApproachRef`). The turn boundary writes the crossing; the
     *  handler appends its sentence to the end of every request, runs (then clears) the crossing's echo on the first one, and
     *  records where it carried it (`carried`), declaring the move when the next request carries it elsewhere. */
    limitApproachRef: Prepared["limitApproachRef"];
    /** borrowed-mutable — the per-request lossy-projection flag. Writers here: the handler re-derives it at every request
     *  build, and the repair sink raises it when the provider boundary's law left recorded content out of the same request
     *  (the boundary runs after the handler, before the recording shim); the shim reads it immediately after. */
    requestLossyRef: {
        current: boolean;
    };
    /** borrowed-readonly — the leg's declaration seat (the turn snapshot): a clear that lands and a guard trim that drops declare `history_rewrite`. */
    turnSnapshotRef: {
        readonly current?: Pick<TurnPromptSnapshot, "declare">;
    };
    /** borrowed-mutable — the hands' read-state map, or undefined without hands. Writer here: a landed stale-result
     *  clear RETIRES the entries whose transmission it just replaced with a marker — the same retirement the compaction
     *  lanes run through the SAME function (`applyContextShrinkToReadFileState`), because a Read body taken off the wire
     *  is off the wire whichever mechanism took it. Without it the edit gate admits an edit of a file whose contents the
     *  request carries only as a cleared marker. The budget arm retires the entries its pointer copies witnessed the same
     *  way. */
    readFileState?: ReadFileState;
    /** borrowed-mutable — the trim-pressure flag (`Prepared.trimPressureRef`). Writer here: the guard chain's trim arm sets
     *  `droppedMessages`; the run loop's boundary reads and clears it. */
    trimPressureRef: {
        droppedMessages: boolean;
    };
    /** borrowed-readonly — a CALL-TIME getter for the deployment's per-model window overlay in force for this
     *  leg ({@link RunnerDeps.contextSettings} keyed by the leg's catalog word). A getter and not a value: this
     *  is the one deployment seat an in-flight leg re-reads, and the request-layer frontiers below are asked
     *  per request. Absent (a standalone prepare exercise, no Runner behind it) ⇒ no overlay, ever. */
    contextOverlay?: () => ContextWindowOverlay | undefined;
    /** borrowed-readonly — the leg's startup seed table (`seededCopies` of the hands phase; filled before the first
     *  request): the request's copy projection carries a whole copy of a seeded, unchanged file as the "already in your
     *  context" sentence. Absent ⇒ no seed. */
    seededCopies?: ReadonlyMap<string, string>;
    /** borrowed-readonly — the session's reminder mark, for the projection's marked sentences. */
    reminderMark?: string;
    /** borrowed-readonly — a CALL-TIME getter for the fixed prompt (system prompt and tool schemas) a request carries beside its
     *  messages: the same count the compaction trigger adds to an estimate with no usage report (`Prepared.promptOverheadTokens`,
     *  which a boundary may change). The guard adds it where no report holds it. Absent ⇒ 0. */
    promptOverheadTokens?: () => number | undefined;
    /** borrowed-mutable — the leg's session: the cleared-results record is read at the first request build and appended after a
     *  build that changed the ledger (`cleared-results-record.ts`); the media-item limit likewise (`media-item-limit.ts`). */
    session: ClearedResultsSession;
}
/**
 * The request's copy projection as one request build reads it (`request-copy-projection.ts`): the lane measures the view
 * as it will be sent, and the provider boundary renders the same projection after the tool-turn law. One per run; the
 * budget arm's pointer identities are the CURRENT request's (reset at every build, read by the boundary right after).
 */
export interface RequestCopies {
    /** The projection's input for the request being built. */
    input(): CopyProjectionInput;
    /** What each message of `view` costs as the request sends it, and the anchored total of that view (with no usage report
     *  anchoring it, the messages' estimate and `fixedTokens`, the fixed prompt — which the estimate's refusal floor reads too,
     *  {@link estimateContextTokens} — at `scale`, {@link judgedTokens}). */
    measure(view: readonly AgentMessage[], cpt: number, fixedTokens?: number, scale?: number): {
        sizeOf: RequestSize;
        anchoredTokens: number;
    };
    /** The budget arm: when the core alone cannot fit `line` (the guard line), the identities of its copies carried as pointers
     *  (oldest lose their contents first) — recorded for this request, and the read-state entries their copies witness retired. */
    degradeCore(view: readonly AgentMessage[], held: ReadonlySet<AgentMessage>, line: number, cpt: number): void;
    /** The copy identities the budget arm carries as pointers on this request (their contents left out); empty when none. */
    pointed(): ReadonlySet<string>;
    /** A new request build: no pointer identities yet. */
    reset(): void;
}
export declare function createRequestCopies(seat: {
    seeded?: ReadonlyMap<string, string>;
    mark?: string;
    readFileState?: ReadFileState;
}): RequestCopies;
/**
 * The stale-result clear's savings as the request sends them: the structural savings, less what the projection had
 * already taken off the cleared results (a repeated attachment frame is one sentence on the request) and less what the
 * clear puts back on the others (the next frame of a cleared chain head carries the contents now).
 */
export declare function clearNetSavingsFor(view: readonly AgentMessage[], cpt: number, copies?: RequestCopies): (cleared: readonly number[], structural: number) => number;
export interface PrepareContextLaneResult {
    /** owned — the per-run microCompact machine state (`Prepared.microCompact`): machine, MC-R flag, ledger, the projection
     *  and in-turn-compaction seats the handler and the runtask arms fill. */
    microCompact: PreparedMicroCompact;
    /** owned — the PREPARE-time model's structural coefficient (`charsPerToken ?? DEFAULT`), the coordinate the
     *  prompt-overhead term downstream is computed in. The per-REQUEST defenses read the CURRENT model's
     *  instead (`requestGeometry`), beside the window they compare against — one snapshot, one coordinate. */
    charsPerToken: number;
    /** owned — the request's irreducible core for the leg (`Prepared.requestCoreRef`): the objective lane names the input the
     *  guard trim holds; both request-build guards park their typed terminal on it. */
    requestCoreRef: RequestCoreRef;
}
/** The M21 phase body — prepareTask's context-lane stretch, verbatim (see the module header). */
export declare function prepareContextLane(input: PrepareContextLaneInput): PrepareContextLaneResult;
/** Record a cc-machine pass's clears into the ledger + emit the G11
 *  frame (one frame per firing pass; the replay of these markers on later requests emits nothing —
 *  cardinality is per CLEAR, not per request). `trigger` names the arm: `"frontier"` = the
 *  proactive request-build pass, `"blocking"` = the slice-3 arm-A pre-guard pass (the machine's
 *  one shot when the frontier hook is off). Marker bytes are read back off the edited array
 *  (the machine composed them, ref/media notes included) so the ledger replays EXACTLY what went
 *  on the wire; an occurrence the index cannot key (pathological same-id-same-timestamp ambiguity)
 *  is simply not recorded — its clear stays request-local, the safe (full-text-returns) direction.
 *  `at.fp` is the occurrence's fingerprint in the PRE-CAP replayed view (the same bytes the next
 *  session rebuild presents) — the replay-side mis-paint guard's comparand. */
/**
 * The ONE landing of a set of stale-result clears: the ledger entry that makes the marker survive every
 * later rebuild, and the retirement of the read-state entries those transmissions carried. The pair is
 * inseparable — a ledger entry WITHOUT the retirement leaves the read state saying the model holds contents every
 * later request carries as a marker (the edit gate would admit an edit of a file the model no longer sees) — which
 * is why it is a function rather than two statements repeated at each of the two clear sites (the
 * frontier/blocking pass and the provider-rejection recovery arm, which used to write the ledger
 * independently, so only one of them retired anything). Posture: a ledger entry means the marker is
 * repainted on every later request build, so the occurrence is cleared for good even when the
 * projection that produced it is discarded — which is why the retirement belongs here and not in the
 * per-request observation buffer.
 */
export declare function landStaleResultClears(args: {
    ledger: ClearedProjectionLedger;
    cleared: ReadonlyArray<{
        key: string;
        marker: string;
        groupCount: number;
        fp: OccurrenceFingerprint;
        toolCallId?: string;
    }>;
    readFileState?: ReadFileState;
    /** The leg's declaration seat: a clear that lands is a `tool_result_clear` (the ledger replays it byte-stably after). The
     *  declaration names who changed the request and how; where it changed is the prefix ledger's byte measurement. */
    seat: Pick<TurnPromptSnapshot, "declare"> | undefined;
}): void;
/** See {@link runGuardChain}. */
export interface GuardChainArgs {
    /** The post-frontier view the chain starts from. */
    edited: AgentMessage[];
    /** The pre-cap counterpart view (arm A's clearSource — durable composition seat). */
    replayed: AgentMessage[];
    index: OccurrenceIndex;
    /** The run's machine state — arm A clears through its one persist (`offloadPersist`, absent when the run has no store). */
    microCompact: PreparedMicroCompact;
    guardAt: number;
    charsPerToken: number;
    taskId: string;
    toolNameOf?: (recorded: string) => string;
    deps: RunnerDeps;
    trimPressureRef: {
        droppedMessages: boolean;
    };
    /** Arm B is closed for this build, with what compaction already did: `landed` (the recheck after an adoption) or `noop` (the resend
     *  of a refused request, whose forced pass found nothing to fold). Absent ⇒ arm B is open. */
    closedBy: "landed" | "noop" | undefined;
    signal: AbortSignal | undefined;
    /** The r7 per-request observation buffer — the chain DROPS it on its early returns (a discarded
     *  provisional projection must not narrate itself). */
    pendingProjectionObservations: Array<() => void>;
    /** The hands' read-state map, or undefined without hands — arm A's clear retires the entries its
     *  cleared transmissions carried (see `PrepareContextLaneInput.readFileState`). */
    readFileState?: ReadFileState;
    /** The rows of the run's objective input in THIS view (`objectiveInputRows`): with the summaries, the request's
     *  irreducible core, which the trim never drops (the verdict on a core over the line is the caller's — `overLine`).
     *  Absent ⇒ only the summaries are core (an exercise of the chain without a run behind it). */
    held?: ReadonlySet<AgentMessage>;
    /** The request's copy projection ({@link createRequestCopies}): every size the chain reads is the view's as the
     *  request sends it, and the trim's budget arm records its pointer identities there. Absent ⇒ structural sizes. */
    copies?: RequestCopies;
    /** The leg's declaration seat: arm A's landing and the guard trim's drop declare their `history_rewrite` on it. */
    seat: Pick<TurnPromptSnapshot, "declare"> | undefined;
    /** The fixed prompt (system prompt and tool schemas) the request carries beside its messages — in a view's judged size when
     *  no usage report holds it, and in every size the trim reads. Absent ⇒ 0. */
    overheadTokens?: number;
    /** How this build sizes a request (the run's reading, {@link createRunSizing}): the trim's room and the scale a view no report anchors
     *  is judged at. Absent ⇒ read off `edited` ({@link requestSizingOf}: an exercise of the chain without a run behind it). */
    sizing?: RequestSizing;
    /** Where the previous trimmed request of this run's stretch started, an index into `edited`: the trim never starts before it. */
    notBefore?: number;
    /** The frontier pass's clear on this build: the size the view it cleared was judged at, and what the clear saved. */
    cleared?: {
        before: number;
        saved: number;
    };
}
export type GuardChainOutcome = {
    earlyReturn: {
        messages: AgentMessage[];
        adoptSessionRebuild?: boolean;
    };
} | {
    working: AgentMessage[];
    trimmed: AgentMessage[];
    trimDroppedMessages: boolean;
    /** the trim left out of THIS request what the next one carries again unless trimmed again — messages it dropped, or core
     *  copies its budget arm carried as pointers (both re-decided at every build): the reply to it states the request's
     *  estimate (`trimmedRequestTokens`) and never anchors the context estimate */ partial: boolean;
    /** the request reached the trim over the guard line — its core is then the caller's to judge */ overLine: boolean;
    /** how many messages the trim left out (zero: the view fits) — absent on the stand-down, whose view is never announced */ omitted?: number;
    /** how the trim sized the request — present when the view reached it over the line */ sizing?: RequestSizing;
    /** what compaction did for this request over its guard — absent when arm B was not reached or its seat is unwired */ compaction?: InTurnCompactionVerdict;
    /** the line a resend of this request is trimmed to after a refusal (see {@link resendLineOf}) */ lineAfterRefusal: (failureMessage: string | undefined) => number | undefined;
};
/**
 * The GUARD CHAIN over one request build (D-7 case-ii transfer table). Whether a request is over the line is judged
 * on the EDITED array from the latest usage report (the anchor) plus the rows after it, or — with no report in the view —
 * from every row plus the fixed prompt at the build's scale, bounded by what this build's clear saved (the frontier pass's,
 * {@link GuardChainArgs.cleared}, or arm A's); a request the line is crossed by is trimmed by sizing each candidate directly
 * (`scale × (fixed prompt + its rows)`, {@link requestSizingOf}): a report measures the request it answered, not one the trim
 * makes. The opt-out machine = the pre-374 backstop order byte-identical
 * (trim as the ordinary second line); otherwise arm A (blocking machine run, only when the
 * frontier pass is off) → arm B (in-turn forced compaction behind the adopt seam) → arm C (trim,
 * the disaster-only last resort and this chain's sole `context.trim` emitter). Returns either the
 * post-chain view for the pipeline tail, or an EARLY hook result the context handler must return
 * verbatim (arm-B adoption / the r8 dead-turn stand-down).
 */
export declare function runGuardChain(args: GuardChainArgs): Promise<GuardChainOutcome>;
