@sema-agent/core
Version:
Stateless, task-oriented AI agent core
3,013 lines • 254 kB
TypeScript
import { CheckpointError, type CheckpointConfigRefusalCode, type CheckpointErrorField, type CheckpointErrorReason } from "./checkpoint-features.js";
import { type CallRiskAxes } from "./ask-origin.js";
import type { GateOutcome, HostDecisionFacts } from "./gate-outcome.js";
import { type ExecutionOutcomeRecordWord } from "./checkpoint-execution-record.js";
import { type HolderJudge, type StoreHolderFence } from "./checkpoint-generation.js";
import { type CheckpointPause } from "./pause-registry.js";
import { type CheckpointDeleteGuard, type CheckpointOverdueCursor, type CheckpointOverdueQuery, type CheckpointPage, type CheckpointRowRead, type CheckpointSessionCursor, type CheckpointSessionQuery } from "./checkpoint-queries.js";
import type { SystemInjectionPriority } from "./task-notification.js";
import { type SteerSource } from "./steer-replay.js";
import type { QuestionResponse } from "./ask-question.js";
import type { ReadEntry } from "../tools/fs/safety.js";
import type { RepairBundle } from "../agents/repair-loop.js";
import type { WorkspaceHandle } from "./remote-env.js";
import type { SessionPermissionRules } from "./session-policy-store.js";
import type { NestedUsageAccum, PermissionMode, ShellGateDoctrine, TaskResult } from "./types.js";
import type { ActiveWorktreeSession, AgentMessage } from "../internal/harness-types.js";
import type { ReopenReason } from "./resume-startup-cause.js";
import { type RetentionDeclaration } from "./retention.js";
import { MAX_PENDING_STEER_CHARS } from "./input-author.js";
import { type IdentityRekeyInput, type IdentityRekeyPlan, type RekeyDone } from "./identity-rekey.js";
export { MAX_PENDING_STEER_CHARS };
export { CHECKPOINT_CONFIG_REFUSAL_CODES, CHECKPOINT_ERROR_CODES, CHECKPOINT_FEATURES, CheckpointError, checkpointVersionOf, encodeAtFidelity, isCheckpointConfigRefusalCode, isCheckpointErrorCode, isPlainRecord, MAX_SUPPORTED_CHECKPOINT_VERSION, normalizeProbeCause, safeDataValue, SPAWN_RESUME_REFUSAL_CODES, type CheckpointConfigRefusalCode, type CheckpointErrorCode, type CheckpointErrorField, type CheckpointErrorReason, type CheckpointFeature, type CheckpointFeatureRow, type SpawnResumeRefusalCode, } from "./checkpoint-features.js";
/**
* design/45 — the **durable-checkpoint** primitive: cross-process / resumable `suspend`/`resume`.
*
* A {@link CheckpointStore} is a pluggable durable seam (alongside `ToolResultStore`): a token-addressable store of "enough state to resume a suspended task", with an
* **atomic CAS `resolve`** so a token is acted on **exactly once** even across replicas / double
* approvals. Two profiles share this one seam (design/43 原语 4, proven by two service instances):
*
* - **F4** (`gate.kind === "human"`) — a running task hit a tool-policy `ask` that no in-process
* approver can answer (headless / long / cross-replica), so it persists a checkpoint and returns
* `status:"suspended"`. Later `runner.resume(token, {gate:"policy_ask", decision})` continues it.
* This is the cross-process version of the synchronous `onAsk` gate (design/37).
* - **1C** (`gate.kind === "task_done"`) — design/38 Path A persists a background sub-task handle here
* so a caller can `get` its outcome across replicas. v1 stores the handle only; the parent does NOT
* mid-task suspend (Path A unchanged) — `runner.resume()` does NOT serve this gate in v1.
*
* **opt-in, default-off**: with no `CheckpointStore` wired (and no durable approval mode requested), a
* policy `ask` still resolves the 1.63 way (synchronous `onAsk` / headless auto-deny) — behavior
* unchanged. Default {@link InMemoryCheckpointStore} is process-only (single instance / tests); a
* durable backend (service's `tidb-approval-store` / `tidb-run-store`) makes it cross-replica.
*
* See `design/45-durable-checkpoint原语-suspend-resume.md`.
*/
/**
* A high-entropy, single-use checkpoint token. Branded so it can't be confused with a `sessionId` /
* `taskId` (council Question #2): the token doubles as the resume capability (token-as-auth, §6), so a
* mix-up would be a security bug, not just a type slip. Mint with {@link mintCheckpointToken}.
*/
export type CheckpointToken = string & {
readonly __brand: "CheckpointToken";
};
/** Mint a CSPRNG 128-bit checkpoint token (token-as-auth, §6/Q5): unguessable, never logged/in-URL. */
export declare function mintCheckpointToken(): CheckpointToken;
/**
* Mint the NON-SECRET stable checkpoint identity — identification and capability are separate
* axes (settledBy/approvalId precedent): `checkpointId` is safe to log, render, and correlate across
* frames (tool_approval cards, replay, resume, snapshots); {@link Checkpoint.token} stays the secret
* resume capability and never rides a display surface. Minted independently (NOT a token digest —
* a digest would make the id derivable only where the token is held, and the projection surfaces
* that need it most are exactly the token-less ones). Legacy rows have no id (absent, additive).
*/
export declare function mintCheckpointId(): string;
/**
* Who resumes a checkpoint, and how the resume `outcome` is interpreted. The `kind` is the discriminant
* that {@link ResumeOutcome} must match at the resume entry (council #3: prevents a `task_done` gate
* being resumed with a `policy_ask` outcome → type confusion / corruption).
*/
import { type ResourceLimitReason } from "./resource-limit-reasons.js";
export { RESOURCE_LIMIT_REASONS, PLATFORM_LIMIT_REASONS, isResourceLimitReason, type ResourceLimitReason, type PlatformLimitReason } from "./resource-limit-reasons.js";
/**
* design/80 D-2: which SAFETY axis of THIS call caused an `ask` to mint an {@link CheckpointGate}
* `irreversible_ask`. Derived by the gate (`safetyAxisOf`) from the tool's static marks plus the engine's own
* per-call facts — never from a decision member a policy composes (forgeable). Persisted on the gate so a
* network budget/escalation resolver reads WHY this is a safety ask FROM THE DURABLE RECORD. Both can be true.
*/
export interface SafetyAxis {
/** design/70: the tool is egress-marked (`ToolSpec.egress` — an external write: push, open PR, send). */
egress?: boolean;
/** design/77 §4: an irreversibility MANDATE **of the TOOL's own** (its `always`/`maybe` tier); a SHELL SEAT raise is NOT this axis, see {@link shell}. */
irreversible?: boolean;
/** The engine's SHELL SEAT raised this ask. Its question is about TEXT — not about undoing an act — so
* the two axes are mutually exclusive. */
shell?: boolean;
}
/**
* design/80 §D-E: a DETERMINISTIC, REDACTED risk summary attached AT MINT to an escalation
* {@link CheckpointGate} (`human` / `irreversible_ask` — the tool-call approval escalations) so a supervisor
* INBOX can sort/triage by TRUE severity without re-deriving risk. **Display/triage metadata ONLY** — core
* NEVER reads it to gate / budget / suppress anything (structural ask strictly wins via `combinePolicies`;
* no mint suppression reads it). The profile/inbox READS it; core only ATTACHES it. Pure function of the
* call (no clock/random) — same call ⇒ identical descriptor.
*/
export interface RiskDescriptor {
/** ToolEmu-style severity tier 1..5 (5 = most severe). The inbox sorts DESC by this. Deterministic — the
* pure {@link riskSeverity} of {@link axes}. The ORDERING is what matters (the inbox's triage key). */
severity: 1 | 2 | 3 | 4 | 5;
/** Which safety axes tripped — for `irreversible_ask`, derived from the D-2 {@link SafetyAxis} (+ the shell
* seat). `shell` marks a tighten by the engine's shell seat (read-boundary judge and/or `shellGate` doctrine,
* NO explicit per-tool egress/irreversible mark). Empty `{}` for a plain budgetable `human` ask. */
axes: {
egress?: boolean;
irreversible?: boolean;
shell?: boolean;
};
/** What the call IS ({@link CallRiskAxes}: the live card's `AskRequest.riskAxes`, same type, same projection, read when the call parked) — not {@link axes}, which axes TRIPPED the gate. Absent when neither was judged and on rows parked before it existed. */ riskAxes?: CallRiskAxes;
/** The tool whose call is gated (mirrors the gate's `toolName`). */
toolName: string;
/** The operator's shell floor (`"always"`), present ONLY when this ask was minted through the engine's shell
* seat AND a floor was in force. Absent for a shape-tier ask with no floor, and for per-tool safety-axis /
* plain policy asks. Answers "was an operator floor live when this gate fired" from the persisted row alone. */
shellGateDoctrine?: ShellGateDoctrine;
/** A REDACTED, length-capped ONE-LINE summary of the call (the command for a shell gate; a brief key-arg
* digest otherwise) for the inbox preview. NEUTRALIZED via
* {@link import("./permission-rule-model.js").renderUntrustedCommandText} + length-capped (it is
* persisted + shown to a human inbox, so a crafted tool arg carrying a `</system-reminder>` variant /
* newline / huge string must NOT inject into the render or bloat storage — and, since #438, a
* directional/zero-width `\p{Cf}` marker cannot ride into the render either: the display baseline
* STRIPS the format class, so what the line shows is what the args carry, in the order they carry it).
* GENERATIONAL, like every mint-time seat: the summary is minted ONCE at park mint and persisted, so
* rows minted before the #438 render change keep their old bytes (which may carry `\p{Cf}`) forever —
* a consumer must not assume one byte-form across row generations, and the display obligation
* (render through the baseline, or screen) is the same for both. One benign visible consequence on
* new rows: an emoji ZWJ sequence in a command displays decomposed here (raw bytes stay in
* `pendingAction.args`/`toolInput` — this seat is DISPLAY, not identity).
* NEVER raw secrets / full args / env. Deterministic. Optional (omitted when nothing safe to summarize). */
summary?: string;
/** Best-effort file paths the action touches (fs-tool `path` args; shell parsing is deliberately NOT
* attempted — over-reaching a shell parse risks a wrong/forgeable path). Each path rendered through the
* same {@link import("./permission-rule-model.js").renderUntrustedCommandText} baseline as
* {@link summary} (a path name can carry the same reordering hazard as a command) + capped.
* Omitted when none derivable. */
touchedPaths?: string[];
/** The allow-layer members that MATCHED this call and could not clear the ask — one record per member (the member and
* the entries it matched), threaded to the mint so the durable-park route carries the gate's own disclosure (not an ancestor
* station's on a question the leg's gate takes up after its allow layer, KL-delegated-station-shadow-a): "alive, just outranked".
* Each entry is rendered through the same display baseline as {@link summary} and capped (the bytes may be a person's
* stored text, a skill's or a deployment's list — model-authored or a custom provider's — and can carry `\p{Cf}`; this
* durable seat strips what the synchronous card keeps, the safe direction, and carries no cross-face same-value
* contract, so a byte-pinning consumer reads per face). */
allowRuleShadowed?: readonly import("./allow-rule-shadow.js").AllowRuleShadow[];
/** WHY the reversibility probe did not clear this call, in the probe's own
* words — the cause the tighten acted on, which until now existed only inside the probe and left the
* card showing WHAT is gated with no account of WHY. Present only for a `"maybe"`-tier tighten whose
* probe supplied a cause (an `"always"`-tier tighten runs no probe; a timeout/throw yields no verdict).
* Neutralized + capped at {@link PROBE_REASON_MAX} — it is deployment-authored text on a human trust
* boundary, so it is DISPLAY/TRIAGE metadata only, never adjudication input.
*
* The UNSTRUCTURED face: a deployment's own probe writes prose here and this engine cannot say what it
* means. An engine-minted cause uses {@link probeCause} instead — see that field for why.
*
* RESIDUAL, disclosed (#438): unlike the descriptor-owned display family above, this seat does
* NOT strip the `\p{Cf}` display-reordering class — a directional/zero-width marker in the
* probe's prose survives here byte-for-byte, because the seat carries a documented SAME-VALUE
* contract with its synchronous `AskRequest.probeReason` twin (one string, two faces) and a
* one-face re-render would break it. A consumer rendering this seat owes its own screen (or the
* descriptor family's display baseline). */
probeReason?: string;
/** The STRUCTURED cause, for a probe whose verdict this engine understands —
* the built-in shell probe is the first. Carries a machine-readable {@link ProbeCause.code} and the
* operand families as ARRAYS with honest totals, so a consumer renders its own sentence in its own
* language instead of receiving one this engine had to write in advance.
*
* The prose sibling above is what this replaces for engine-minted causes, and the reason is not
* aesthetic: a sentence asserting what a command DOES is false for the demotion's documented
* over-fire, a sentence asserting what its OPERANDS are is false when the check synthesizes one, and
* serializing a variable-length multi-part disclosure into one length-capped string silently deletes
* whichever part sorts last. A code cannot be false and an array cannot be truncated into a lie. */
probeCause?: ProbeCause;
}
/** One operand family inside a {@link ProbeCause} — the entries a card may NAME, plus how
* many the family really has. `shown.length` ≤ {@link total}, and a consumer that renders only `shown`
* is still obliged to tell the person when `total` exceeds it: the count is the part that cannot be
* cut, and "there is a second unreviewed operand" is exactly what a reader cannot recover from the
* command text. */
export interface ProbeCauseOperands {
/** The named entries. Each `inlineUntrusted`-neutralized and capped at {@link PROBE_CAUSE_PATH_MAX}
* INDIVIDUALLY, so one pathological entry costs only itself. Bounded in count by the minting probe.
* RESIDUAL, disclosed (#438): `inlineUntrusted` does NOT strip the `\p{Cf}` display-reordering
* class the descriptor's own display family strips — a directional/zero-width marker in a path
* survives on this seat (cross-face byte parity with the synchronous `AskRequest.probeCause`
* twin; see that same-value contract for why a one-face re-render is off the table). A consumer
* rendering these entries owes its own screen (or the descriptor family's display baseline). */
readonly shown: readonly string[];
/** How many entries the family has in total — `shown.length` when nothing was elided. A non-negative
* integer; never a lie by omission. */
readonly total: number;
}
/**
* An ENGINE-MINTED, structured account of why a reversibility probe did not clear a call.
*
* DISPLAY/TRIAGE metadata, exactly like the rest of {@link RiskDescriptor} — nothing reads it to gate,
* budget or suppress anything, and it deliberately never reaches the ask's `message` (that string is
* handed to the auto-mode classifier, which may answer an ask with `allow`; a probe must not own an
* input to the decider that clears it).
*
* STRUCTURE IS THE CONTRACT. The entries are model-influenced text, so a consumer must render them as
* DATA — never re-derive structure by splitting or joining them. Structural characters are
* percent-encoded at the mint precisely so that a path cannot spell whatever grammar it is rendered
* into, but the array is the boundary that makes that guarantee cheap to keep.
*/
export interface ProbeCause {
/** Machine-readable cause id, `<domain>.<snake_case>` like this codebase's other notice codes. The
* consumer maps it to its own prose. A code is the one part of a cause that cannot become false as
* the check's edge cases are discovered. */
readonly code: string;
/** The paths the check TOOK as traversal roots — deduplicated and resolved, which is why they are
* described by what the check did with them rather than by what the caller wrote: a lexical operand
* walk has no option-value table (`du -d 2 sub` takes `2`), and it synthesizes the working directory
* when no operand is written at all (`du --help`). */
readonly roots: ProbeCauseOperands;
/** Operands the SAME verdict left unreviewed for a different reason (an unexpanded glob). Present only
* when non-empty. Named separately so a card can say what else this one approval clears — a partial
* account of an approval's reach is worse than none. */
readonly further?: ProbeCauseOperands;
}
/** The bloat ceiling on {@link RiskDescriptor.probeReason} — re-exported from the leaf neutralizer module
* for the same reason its `PROBE_CAUSE_PATH_MAX` sibling is homed there (a value import from tools/fs
* back into this module closes an ESM cycle), so mint, gate and persist read ONE cap. */
export { PROBE_REASON_MAX } from "./untrusted-text.js";
/**
* design/80 §D-E: the DETERMINISTIC severity tier (1..5) for an escalation checkpoint, a PURE function of the
* tripped {@link RiskDescriptor.axes} (NO LLM, NO clock/random) so the inbox's sort order is stable and
* unit-testable in isolation. The ORDERING is the contract; the absolute numbers map to ToolEmu's 5 tiers:
* - irreversible AND egress → **5** (the most severe — an external, irreversible write)
* - irreversible only → **4**
* - egress only → **3**
* - shell-gated tighten → **3** (a coarse shellGate ask with no explicit egress/irreversible mark — the
* command MAY be benign, so it is not auto-graded as high as a marked tool)
* - plain `human` ask → **2** (no safety axis tripped — a budgetable approval)
* - (1 reserved — least-severe / informational; not expected from these gates.)
* `egress` dominates the shell coarse-grade (an explicitly egress-marked shell tighten is still ≥3). A future
* arm may refine this — but only with a stated reason, and the ORDERING must stay monotone in risk.
* Total over what a stored row can hold, never a throw: a value that is not a plain record ({@link isPlainRecord}) has
* no tier (`undefined`); a mark that is neither absent nor a boolean contributes nothing, the valid `true` marks give
* their floor, and "nothing tripped" (tier 2) is not claimed past a damaged mark. A caller projecting a stored row
* discloses the damage ({@link summarizeCheckpoint}'s `disclose`).
*/
export declare function riskSeverity(axes: {
egress?: boolean;
irreversible?: boolean;
shell?: boolean;
}): 1 | 2 | 3 | 4 | 5;
export declare function riskSeverity(axes: unknown): 1 | 2 | 3 | 4 | 5 | undefined;
/** design S1e: the char cap for the {@link CheckpointSummary.toolInput} BOUNDED raw preview of a
* `tool_approval` pendingAction's `args` (`JSON.stringify`-ed). Caps the `listByScope` payload size; over-cap
* is truncated with a trailing `…`. Bounded raw (NOT neutralized) — redaction is the consumer's job (echo-only). */
export declare const MAX_TOOL_INPUT_PREVIEW_CHARS = 512;
/**
* design/171 §6.3 — the BYTE budget the whole parked-steer queue must fit inside, measured on its JSON
* serialization (the form every backend actually persists).
*
* 48,000 bytes sits under a MySQL `TEXT` column's 65,535-BYTE ceiling with room for UTF-8 expansion: the
* per-entry cap above counts CHARACTERS, and 16,000 CJK characters serialize to ~48,000 bytes, so a
* char-only cap does not bound the column at all.
*
* It is the queue's ONLY capacity bound: there is no entry-count cap. The measure includes every entry's
* field names, metadata and `seq`, so many tiny entries are bounded by the same bytes as a few large ones;
* an entry that fits is taken. Crossing it is a fail-loud `steering.queue_full` — never a silent drop of the
* oldest entry (a dropped operator instruction is exactly the failure this queue exists to remove).
*/
export declare const PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES = 48000;
/**
* design/171 §6.3 — the FROZEN field set of a persisted {@link PendingSteerEntry}. `validatePendingSteer`
* copies by this set and REFUSES an unknown key, so a producer one release ahead of this worker gets a
* loud rejection instead of having its new field silently dropped on the parked leg. Consumers (other
* repos' backends) read it to assert they round-trip every field rather than hand-listing their own copy.
*/
export declare const PENDING_STEER_FROZEN_FIELDS: readonly ["text", "trusted", "actor", "seq", "inputId", "priority", "runOrigin", "reply", "source"];
/**
* The answer a parked steer was already given (`prompt.submit`'s `{ reply }` to a `later` steer, before the pause took it):
* the resume lands it as a turn of its own — the input row, then this answer — instead of handing the input to a model, and
* does not screen it again. `text` is the answer, `by` the registration that gave it, `entered` the text the input entered as
* when the screen rewrote it (absent ⇒ the entry's own `text`). The engine writes it when a pause carries such a steer; the
* classic screen's `additionalContext` is not carried with it.
*/
export interface PendingSteerReply {
text: string;
by: string;
entered?: string;
}
/**
* design/171 §6.1 — WHO a piece of human input came from, as an attribution label. ONE definition:
* the shape lives at its layering-legal home (`engine/llm/types.ts`, where `UserMessage.actor`
* carries it and the engine cannot import core) and this module re-exports it — the live message
* seat and the parked entry can never drift apart. Normative clauses (never authority; ingress-only
* `hostAsserted`) are on the definition.
*/
import type { ActorAssertion } from "../internal/llm.js";
export type { ActorAssertion } from "../internal/llm.js";
/**
* design/171 §5.3/§6.3 — one entry of the parked-steer QUEUE. Replaces the former single seat, whose
* last-writer-wins overwrite silently destroyed an undelivered operator instruction whenever two people
* steered the same suspended run.
*/
export interface PendingSteerEntry {
/** The operator's instruction text (validated exactly like the pre-queue single seat). */
text: string;
/** Frozen at append time from the SERVICE's verified-principal check; never recomputed on resume. */
trusted: boolean;
/** Attribution only (see {@link ActorAssertion}) — absent = the caller supplied none (anonymous). */
actor?: ActorAssertion;
/** Queue-monotonic ordering key, minted by the store on append (first entry = 1). Drain order. */
seq: number;
/** Caller-supplied correlation/idempotency id (a service passes the message id it already minted);
* a uuidv7 is minted when absent. Re-appending the SAME `inputId` is a no-op, which is what keeps
* `setPendingSteer` retry-safe now that it appends instead of overwriting. Because the id lives on
* the PERSISTED entry and every replayed drain of this row carries it verbatim, `(notice code,
* sessionId, detail.inputId)` is the parked family's cross-replay OCCURRENCE key — consumers dedup
* on it directly; no per-delivery key exists or is needed. (Write-path guarantee: a row written by
* a non-conforming store may lack it, and read points do not re-validate.) */
inputId: string;
/** Carried VERBATIM for the serving layer; it does NOT reorder the drain (drain is `seq` order). */
priority?: SystemInjectionPriority;
/** What brought this input, when its host says so ({@link import("./run-origin.js").RunOrigin}): its `human_input` frame
* reports it, and the newest input a wake hands over states the woken leg's word with it. Attribution only; absent = the host said nothing. */
runOrigin?: import("./run-origin.js").RunOrigin;
/** The answer this input was already given ({@link PendingSteerReply}): a resume lands such an entry as the answered `later`
* steer it was taken as — at the resumed leg's would-otherwise-stop seat, after the continuation's work — not inside the
* continuation that carries the queue's other entries. */
reply?: PendingSteerReply;
/** Who the sender says wrote it ({@link SteerSource}; absent reads as `"steer"`): a resume delivers a `"system"` entry as the
* sender's own text — no speaker label, no person's mid-turn frame — and names it `system` on its `human_input` frame and
* on the redelivery screen's `e.source`, as the live verb does. */
source?: SteerSource;
}
/** design/171 §6.3 — the caller-supplied half of a {@link PendingSteerEntry}: everything except `seq`,
* which only the store may mint. `inputId` is optional on the way in (minted when absent). */
export interface PendingSteerInput {
text: string;
trusted: boolean;
actor?: ActorAssertion;
inputId?: string;
priority?: SystemInjectionPriority;
runOrigin?: import("./run-origin.js").RunOrigin;
/** Written by the engine's park of an answered steer ({@link PendingSteerReply}); a host relaying a caller's statement writes
* only the caller's own fields. */
reply?: PendingSteerReply;
/** Who the sender says wrote it ({@link SteerSource}), carried as the sender stated it; absent reads as `"steer"`. */
source?: SteerSource;
}
/**
* design/80 §D-E: build the DETERMINISTIC, REDACTED {@link RiskDescriptor} for an escalation checkpoint at
* MINT. Pure — a function ONLY of (`toolName`, `args`, the D-2 `safety` axis, the `shellGated` flag, the mint's `riskAxes`); it reads
* NO clock/random, so the SAME call ⇒ an IDENTICAL descriptor (pinned by a test).
*
* **Determinism contract = plain-DATA args** (the real flow: model-JSON / hook-rewritten plain objects). A
* Proxy whose `ownKeys` trap returns a DIFFERENT key set per call is OUT OF CONTRACT — JS cannot detect a
* Proxy, so its (display-only) digest may vary. This NEVER affects a security/budget/mint
* decision: `riskDescriptor` is INERT (no core path reads it to gate), so an out-of-contract input can at worst
* degrade an inbox preview, never a permission outcome.
*
* **Redaction is load-bearing** (the `summary`/`touchedPaths` are PERSISTED + surfaced to a human inbox):
* every model-controlled value in the DESCRIPTOR-OWNED display family (`summary` both arms,
* `touchedPaths`, `allowRuleShadowed`) goes through
* {@link import("./permission-rule-model.js").renderUntrustedCommandText} — which STRIPS the `\p{Cf}`
* format class (directional controls / zero-width formatters, the display-reordering hazard the
* `hasBidiControls` bit warns about; #438) and then applies the shared inline form (folds CR/LF/Unicode
* separators to one space, defuses `</system-reminder>` variants + `<<<`/`>>>` fence sentinels) — AND a
* length cap, so a crafted arg carrying a break-out tag / newline / huge string / RLO can neither inject
* into the inbox render nor display as something other than what runs nor bloat the durable row.
* TWO SEATS ARE DELIBERATELY NOT IN THE FAMILY: `probeCause` and `probeReason` carry a documented
* SAME-VALUE contract with their synchronous `AskRequest` twins (their docs say so verbatim), so
* changing their bytes here alone would break that cross-face contract — they keep the shared
* `inlineUntrusted`/`normalizeProbeCause` treatment their twins read, so both faces move together. NEVER dumps full
* args / env / secrets — only a bash command string or a short `name=value` digest of the SHOWN args.
*
* `summary` for a shell gate = the `command` string (capped 200 cp); otherwise a `name=value` digest of the
* call's top-level string/number/boolean args (each value capped), omitted when nothing safe to summarize.
* `touchedPaths` reads ONLY the obvious fs `path` arg (read_file/edit_file/write_file) — shell parsing is
* deliberately NOT attempted (over-reaching a shell parse risks a wrong/forgeable path, so OMIT for bash).
*/
export declare function buildRiskDescriptor(input: {
toolName: string;
args: unknown;
/** The D-2 {@link SafetyAxis} threaded to the mint (egress/irreversible), or `undefined` for a plain ask. */
safety?: SafetyAxis;
/** True ONLY when this is a shell call whose tier is the engine's shell seat's (read-boundary judge and/or
* `shellGate` doctrine, no explicit per-tool egress/irreversible mark) — drives the `shell` axis + severity 3. */
shellGated?: boolean;
/** The resolved doctrine to persist when `shellGated` (see {@link RiskDescriptor.shellGateDoctrine}). */
shellGateDoctrine?: ShellGateDoctrine;
/** The matched-but-not-cleared allow-layer members to persist (see {@link RiskDescriptor.allowRuleShadowed}). */
allowRuleShadowed?: readonly import("./allow-rule-shadow.js").AllowRuleShadow[];
/** The reversibility probe's cause for not clearing this call (see
* {@link RiskDescriptor.probeReason}). Re-neutralized here like its shadowed-rule sibling: this
* function is exported, so a caller reaching it directly must get the same redaction the gate applies. */
probeReason?: string;
/** The STRUCTURED cause (see {@link RiskDescriptor.probeCause}). Re-validated here for
* the same reason the prose sibling is re-neutralized — this function is exported, so a caller
* reaching it directly must not be able to persist a shape the gate would have rejected. */
probeCause?: unknown;
/** The call's risk-axes judgment in the live card's type, read by the park's mint when it parked: copied (a member only when boolean), never judged here. */ riskAxes?: CallRiskAxes;
}): RiskDescriptor;
/**
* The durable record of an ask's `requiresRealApproval` bit, which used
* to DIE at the park: the mint keyed the gate kind on the static tool marks only, so an org-governed
* ask on an unmarked tool minted a plain `{kind:"human"}` — the one kind a network budget resolver may
* auto-approve — and the org's "only judgment clears this" demand was silently budgetable after the
* durability boundary. Present ⇒ the mint escalates to `irreversible_ask` (non-budgetable) and the row lists the
* `realApproval` reader-requirement word. `origin` additionally records WHY, for the resume belts:
* · `"org_rule"` — an org ASK rule fired (governance was READABLE at mint). Resume keeps the strict
* posture: org unavailable at resume still refuses (newly-blind ⇒ fail-closed).
* · `"org_unavailable"` — governance could NOT be read at mint and the gate's own message promised
* "every allow tightens to a real approval until it can". A person approving THIS park IS that real
* approval — so a resume that finds org still unavailable executes instead of refusing and burning
* the approval (the park-only livelock #131 closed). The durable row itself — this origin plus the
* recorded human outcome — is the audit record of that passage; the resume emits no extra notice.
* · `"policy"` — a policy/hook minted the bit (e.g. the always-on classifier-parity rule); no org
* semantics, the resume belts treat it as a plain non-budgetable approval.
* Both org origins double as the #120 governed mark: a resuming worker with NO org adjudication wiring
* refuses to redeem such a row (the governed boundary must not vanish with a deployment's wiring).
*/
export interface RealApprovalGateBit {
/** The parked ask's ORIGIN word — a projection of the same closed set the card, the observer and the
* `tool_end` frame carry ({@link import("./ask-origin.js").AskOrigin}), never a second vocabulary. It
* is the ask's ROUTING word: a marked call reads `ancestor_marked` even when the org governs it, because
* the ladder routes a marked call to the park before anything else. Rows minted before the projection
* carried a three-word subset of this set (`org_rule` / `org_unavailable` / `policy`), so every stored
* value is still a member. */
origin: import("./ask-origin.js").AskOrigin;
/** The ORG FACT the ask was minted under (`"rule"` = an org rule asked, `"unavailable"` = org adjudication
* unreachable), kept beside the routing word because routing can outrank the word (a marked call reads
* `ancestor_marked`) while the governance stays. The #120 governed mark and the resume belts read THIS
* member through {@link realApprovalOrgFact} (absent on rows minted before it: the org words imply it). */
org?: "rule" | "unavailable";
}
/** The ONE read of a bit's governed fact (the member; the two org origin words for rows minted before it). */
export declare function realApprovalOrgFact(bit: RealApprovalGateBit | undefined): "rule" | "unavailable" | undefined;
export type CheckpointGate =
/** F4: a human (or any external authority) must allow/deny a pending tool call. design/80 §D-E:
* carries an OPTIONAL display-only {@link RiskDescriptor} (severity/axes/summary) for the supervisor
* inbox to triage by — INERT (core never reads it to gate/budget).
* Both approval arms carry `approvalCard`: which card the pending call renders under (the call's face's card,
* copied at the park). It is also the row's question mark — `"question"` is the reserved question tool, whose
* deadline voids it instead of denying it (`facetOf`). Absent on a row parked before the member (read as no
* card, never as a question) and on a call that carried no face. */
{
kind: "human";
reason: string;
toolName: string;
approvalCard?: import("./tool-face.js").ToolApprovalCard;
riskDescriptor?: RiskDescriptor;
}
/** design/77 §4 (Gate 4) + design/80 D-2: a PRE-ACTION human approval before a SAFETY-tightened tool runs —
* an IRREVERSIBLE tool (send money/email, file a return) OR an EGRESS tool (push, open PR, send). Same
* approval family as `human` (a pending tool call to allow/deny → suspendRef → `status:"suspended"`, resumed
* with a `policy_ask` outcome). **design/80 D-2 (load-bearing):** minted whenever an `ask` is for a tool
* carrying the egress / irreversibility (`always`/`maybe`) SAFETY MARKS — regardless of how the ask arose
* (a gate tighten OR a policy/hook that already asked; round-1 council fix: keying on the per-call
* `decisionReason` missed the policy-ask case AND was forgeable) — **EVEN WHEN `durableApproval` is wired**
* (`durableApproval` supplies scope/ttl, NOT the kind). The DISJOINT-from-`human` kind is what a
* network budget resolver keys on to NEVER auto-approve a safety ask (a budget may only down-budget a plain
* `human` ask). {@link SafetyAxis} records which axis(es) tightened. NOT a dry-run review. */
| {
kind: "irreversible_ask";
reason: string;
toolName: string;
approvalCard?: import("./tool-face.js").ToolApprovalCard;
safetyAxis?: SafetyAxis;
realApproval?: RealApprovalGateBit;
riskDescriptor?: RiskDescriptor;
}
/** design/74: a resource slice limit (budget/walltime/turns) was reached — suspend (resumable) instead of
* fail. There is NO pending tool to adjudicate; resume just continues the run with the next slice's
* allowance (sized from {@link Checkpoint.resourceLedger}). The matching {@link ResumeOutcome} arm is
* `{ gate: "resource_limit"; decision: "continue" }`.
*
* design/164 件五: `resumeAfterMs` is the RESUME-TIMING hint that pairs with {@link Checkpoint.deadline}
* — how long the driver should wait before resuming, because resuming sooner would only re-suspend.
* **In-scope condition**: present ONLY for `reason: "usage_window"` (the one cause that knows when it
* clears); every other reason omits it, so a consumer must not read its presence as "this is
* resumable". Additive on the existing checkpoint version — a reader that ignores it is unchanged. */
| {
kind: "resource_limit";
reason: ResourceLimitReason;
resumeAfterMs?: number;
}
/** design/76 §2.5 (dry-run / shadow): a POST-PREDICTION REVIEW pause. A profile's dry-run interception ran a
* predicted action and produced a buffered state-diff a human (or judge) must REVIEW before it is applied —
* so the task suspends to the durable `needs_review` TERMINAL (`TaskStatus:"needs_review"`) instead of
* finishing. **DISJOINT from the approval family** (`human`/`irreversible_ask`): those are PRE-ACTION
* *approvals* (suspendRef → `status:"suspended"`, resumed with a `policy_ask` outcome); this is a
* POST-prediction *review* (reviewRef → `status:"needs_review"`, resumed with a `dry_run_review` outcome).
* The split is load-bearing — reusing the approval family would make assemble-result report `"suspended"`
* and the `needs_review`/`review.pending` branch dead code (v4 MAJOR-A). It is ALSO disjoint from the
* `RepairTerminal.needs_human_oracle` (design/78) — a different type space; never cross-use the two.
* The state-diff itself is a PROFILE concern (a REF, not stored here — design/76 §9 / §2.5); core only
* owns the gate/status/discriminant plumbing. NOT a pre-action approval. */
| {
kind: "needs_review";
reason: string;
}
/** design/80 D-B (plan-gate): a PRE-ACTION human PLAN REVIEW. Before an agent acts on a high-blast-radius
* plan (a profile's plan-gate fires on shell⇒gate + an irreversible/egress/finance mark present + a
* blast-radius trigger — NOT every task), the run pauses so a human can **approve / edit / reject the
* proposed PLAN** before any step runs. It is its OWN gate kind (r2 ruling — do NOT reuse `needs_review`,
* whose gateMatch arm forces a `dry_run_review` outcome; reusing it would make a plan resume a
* type-confusion mismatch), but it shares the **review-pause** machinery: it routes to `reviewRef` +
* `status:"needs_review"` (a human-review pause), resumed with a `plan_review` outcome.
*
* **THREE-WAY SPLIT (load-bearing):**
* - the APPROVAL family (`human`/`irreversible_ask`) → PRE-ACTION *approvals* of a pending TOOL CALL
* (suspendRef → `status:"suspended"`, resumed with a `policy_ask` outcome bound to a tool call);
* - `needs_review` → a POST-prediction *review* of a buffered state-diff (reviewRef →
* `status:"needs_review"`, resumed with a `dry_run_review` outcome);
* - `plan_review` (this) → a PRE-ACTION *review* of a PLAN (reviewRef → `status:"needs_review"`, resumed
* with a `plan_review` outcome). It binds NO tool call — the human reviews the PLAN, not a pending arg —
* so it carries no `tool_approval` pendingAction (its pendingAction is `{kind:"plan_review"}`, with no
* tool fields) and the `policy_ask` decision-action binding machinery never touches it. The plan/diff
* artifact is a PROFILE concern (a REF, not stored here — design/76 §9); core owns the
* gate/status/discriminant plumbing only. NOT a pre-action approval, NOT a dry-run review. */
| {
kind: "plan_review";
reason: string;
}
/** 1C: the checkpoint tracks a background sub-task's completion (design/38 Path A). v1 = handle only. */
| {
kind: "task_done";
};
/**
* The outcome a caller supplies to `runner.resume(token, outcome)` — a **discriminated union** keyed by
* `gate`, validated against `checkpoint.gate.kind` at the entry (council #3). **v1 implements only the
* `policy_ask` arm**: `task_done` is a dead branch under 1C Path A (the caller orchestrates, never
* mid-task `resume()`), typed here for completeness and the v2 join-suspend option.
*/
export type ResumeOutcome = {
gate: "policy_ask";
/**
* design/80 D-1 (decision-action binding): the `toolCallId` the human actually saw/approved. The
* resume is REJECTED (`checkpoint.invalid_outcome`, fail-closed, pre-CAS) unless it matches the
* checkpoint's pending tool call (`pendingAction.toolCallId`) — this closes the TOCTOU re-suspend
* wrong-apply: a stale `yes` minted against pending call X must not resolve a DIFFERENT pending call
* Y (approve vendor-A $5k applied to vendor-B). The decision must name the action it bound to; the
* runner never trusts that the caller matched the correct pending call (design/77 doctrine —
* deterministic structural backstop, not a model self-report).
*
* The correct value is the resumed checkpoint's `pendingAction.toolCallId`; the caller has it via the
* `suspendRef` / pending record it is answering.
*/
boundCallId: string;
/**
* design/80 D-1 §2 (slice 1a.2): the **server-minted opaque** hash of the pending tool call — its tool and the input
* that the human actually saw/approved (`PendingAction.tool_approval.boundInputHash`, computed by the
* engine at suspend-mint via {@link import("./canonical-json.js").exactBoundInputHashOf} over the call's `toolName` and
* post-hook `args`). The caller echoes it VERBATIM — it is opaque; the SDK/service NEVER re-canonicalize args
* (a second runtime's serialization could diverge → false mismatch → fail-closed a
* legitimate approval). The resume verifies it by **string equality** against the checkpoint's
* persisted value (`checkpoint.invalid_outcome`, fail-closed, pre-CAS) — closing the TOCTOU "same call
* id, different input" variant that `boundCallId` alone misses (a re-mint that swapped the input under
* the same tool-call id). It binds the SHOWN input, NOT `updatedInput`: an `allow` edit is the same
* operator's authorized rewrite, applied AFTER this binding check (design/37,末位应用), so the echoed
* hash is always the pending record's value regardless of any edit. (Legacy pre-1a.2 checkpoints have
* no persisted hash → the resume skips this check, binding on `boundCallId` alone; new mints enforce.)
*/
boundInputHash: string;
/** `allow` → execute the pending tool call; `deny` → inject a denial result, then: a person's deny with no (or an empty) `reason` on a leg that is not a delegated child ends the turn awaiting the user (the run completes with `haltedOnUserRejection`) unless the resume also delivers a parked steer, which the model answers; any other deny continues. */
decision: "allow" | "deny";
/** A re-written arg payload (design/37 policy `allow` rewrite); re-validated on execute. */
updatedInput?: unknown;
/** Model-readable reason attached to a `deny` (else a default is used). */
reason?: string;
/**
* What the approving PERSON wrote in the card's "and tell the agent what to do next" input — the `allow`
* arm's counterpart of a `deny`'s {@link reason}. The resumed run's continuation user message carries it to
* the model as the user's own words, after the batch's tool results, once, verbatim apart from the outer
* whitespace: no fence, no wrapper sentence, no length bound. PRESENT only when the person wrote something
* (blank — empty or whitespace-only — delivers nothing; a host whose card has no input omits the key).
* ARM- AND DECIDER-SCOPED like `answer`: a written value on a `deny` or on a decide whose `hostDecision.decidedBy`
* is not `"person"`, a non-string, or text carrying a `<system-reminder>` tag (opening or closing) is refused pre-CAS.
*/
feedback?: string;
/**
* The ANSWER to a CONTENT-ASK (the reserved AskUserQuestion tool), carried by the decide itself
* (ruled 2026-08-04). A content-ask is a question TO the user: `allow` alone says "let the tool
* run" but supplies nothing to run it AGAINST, and the only pre-existing answer seat was the
* resumed leg's `onQuestion` config closure — a seat an OFFLINE background child has no operator
* on, because its resume config is rebuilt from the parked row rather than handed in. With the
* answer on the decision payload, the same `/decide`-shaped call serves both arms: the resume
* binds it as the resumed leg's answering face, so the pending call executes against the SAME
* tool, the SAME `selected ⊆ options` fence and the SAME untrusted free-text framing (design/80
* D-F) as a live answer — one support surface, not two.
*
* TRUST: untrusted wire data. It is NEVER read as instructions — the tool splits it into the
* trusted selections (which must be the model's own option labels) and a fenced free-text
* remainder. Off-list `selected` values and `note` are exactly the "Other" free-text path.
*
* ARM-SCOPED, like `updatedInput`/`reason` on this same arm: only a `policy_ask` `allow` whose
* pending call IS the reserved tool may carry one. Supplying it anywhere else is rejected
* pre-CAS (`checkpoint.invalid_outcome`, `detail.field: "answer"`) rather than silently dropped,
* and OMITTING it on a content-ask allow with no live answering face is rejected the same way —
* consuming the approval to hand the model a fabricated "no human available" default is the
* silent-continue this seat exists to end. It takes what a live face returns for a person: an answer, or the decline.
*/
answer?: QuestionResponse;
/**
* The host's DECISION FACTS — who ended this wait: a person (`"person"`, the decide an operator made
* through the deployment's approval channel, with the attribution that channel reports), the
* host's own SLA sweep at the row's deadline (`"sla_timeout"` — FACET A of the deadline contract; only
* a sweep may say it), or the deployment's OWN POLICY (`"policy"` — a machine decided, either way: an
* unattended seat answering by class, no interactive approval surface for this row, a standing posture;
* the durable spelling of the synchronous leg's `AskOutcome.settledBy: "policy"`, so ONE decision reads
* the same on both faces). A person and a policy may each `allow` or `deny`; `"sla_timeout"` names a wait
* that ended with nobody answering and cannot `allow`.
* REQUIRED: a decide that names nobody is not a record of anything that happened, and core does not guess.
*
* The host supplies FACTS, never the settlement WORD: core mints the record
* ({@link import("./gate-outcome.js").GateOutcome} — `human_allowed` / `human_refused` / `policy_allowed`
* / `policy_refused` / `park_sla_expired`, joined with the row's persisted `origin`) at the resume entry, writes it onto the resolved row
* (`resolvedOutcome.gateOutcome`) and projects it onto the resolved call's `tool_end` frame. A caller
* that supplies `gateOutcome` itself is refused pre-CAS.
*
* `approver` — the attribution the approval channel reports for the party that ended the wait. Core
* AUTHENTICATES NOTHING: the identity work is the deployment's (its card, its signature check, its
* console). What core owns is that the claim is well-formed: a plain string, bounded, free of control
* characters, refused pre-CAS (`checkpoint.invalid_outcome`) otherwise — refused rather than dropped,
* because a settlement that silently lost its attributed party reads as unattributed.
*
* `decidedVia` — which machine seat answered a `"policy"` decision ({@link import("./gate-outcome.js").DECIDED_VIA}); the
* captured facts carry it to the resumed leg (refusal sentence, reminder's decider); refused pre-CAS outside the set or beside another decider.
*
* SCOPE — the facts ride the settlement, not the persisted winner: `winnerFromOutcome` records what an
* `env_failed` replay must reproduce exactly, and who reported a settlement is not part of that
* authorization; a replay states its own facts.
*/
hostDecision: HostDecisionFacts;
/**
* CORE-MINTED, on the persisted twin only: the settlement record this decide produced. Present on
* the row's `resolvedOutcome` after the resolve, and on the `tool_end` frame of the resolved call.
* Never accepted from a caller (refused pre-CAS) — the host does not mint words.
*/
gateOutcome?: import("./gate-outcome.js").GateOutcome;
}
/** design/74: continue a resource-suspended run with the next slice's allowance. NO decision payload and
* NO budget figure — the allowance is computed from {@link Checkpoint.resourceLedger}, so money never
* reaches the caller or the model. Matches `CheckpointGate.kind === "resource_limit"`. */
| {
gate: "resource_limit";
decision: "continue";
}
/** design/76 §2.5 (dry-run / shadow): resolve a `needs_review` suspend after a human/judge reviewed the
* buffered predicted state-diff. `decision:"approve"` → the profile applies the buffered diff (atomically,
* invalidating `readFileState` on touched paths — design/76 §2.5; the apply itself is PROFILE, not core)
* then continues; `decision:"reject"` → the prediction is discarded and the run continues without it. Kept
* DISJOINT from `policy_ask` (the approval family) so the resume-side discriminant never confuses a
* post-prediction review with a pre-action approval (the third `needs_review`/`dry_run_review` gateMatch arm).
* No money/diff payload reaches the caller here — the diff lives in the profile's REF store (design/76 §9). */
| {
gate: "dry_run_review";
decision: "approve" | "reject";
reason?: string;
}
/** design/80 D-B (plan-gate): resolve a `plan_review` PRE-ACTION plan pause after a human reviewed the
* proposed PLAN. `decision:"approve"` → proceed with the plan as-is; `decision:"edit"` → proceed with the
* human's `editedPlan` (a TYPED sibling of the plan — NEVER a raw tool `updatedInput`; a plan is not a tool
* arg, so this binds NO action and never enters the `policy_ask` boundCallId/boundInputHash machinery);
* `decision:"reject"` → the plan is discarded; a PERSON's refusal stops the model to wait for the user (a `reason` is their direction, fenced; with none the wait stands), a deployment POLICY's is attributed and the model re-plans.
* Kept DISJOINT from `policy_ask` (approval) AND `dry_run_review` (post-prediction review) so the
* resume-side discriminant never confuses the three (the `plan_review`/`plan_review` gateMatch arm). It
* binds no TOOL CALL, but since RB-64 it does record a winner: `winnerFromOutcome` returns the decision
* (plus `editedPlan` as `updatedInput` and the reviewer `reason`) under the synthetic `gate:plan_review`
* marker, so an `env_failed` reopen can replay it. The `boundCallId`/`boundInputHash` TOOL-CALL binding
* is what stays `policy_ask`-only. No plan/diff payload (beyond the human's
* `editedPlan` text) reaches core — the plan artifact lives in the PROFILE's REF store (design/76 §9). */
| {
gate: "plan_review";
decision: "approve" | "edit" | "reject";
editedPlan?: string;
reason?: string;
/** The mode the approved plan runs under — the approver's choice, on `approve` / `edit` only: any mode but `plan` (an approved
* plan is not kept open). Absent ⇒ the resume config's mode (a config of `plan` reads as none), else the mode the leg had before
* the plan. Recorded on the decided row (`ResolvedOutcome.permissionMode`), so an `env_failed` retry replays it. Refused before the
* claim (`checkpoint.invalid_outcome`, the row pending): a word outside the set, `plan`, a mode on a `reject`, or a mode the
* resume config contradicts (a config naming another mode but `plan`). */
permissionMode?: PermissionMode;
/** Who ended this wait — the tool-approval arm's member, same shape, closed set, validation and refusals; REQUIRED.
* `reject` is the refusal direction; `"sla_timeout"` is refused here (a plan pause expires, a sweep never resolves it). */
hostDecision: HostDecisionFacts;
/** CORE-MINTED on the persisted twin only (origin `"plan_review"`; a plan pause has no `tool_end`, so the row is its only face); a supplied one is refused pre-CAS. */
gateOutcome?: import("./gate-outcome.js").GateOutcome;
}
/** design/144 §3 (message-wake): wake a PARKED (non-gate) checkpoint and drive it to continue — a pure
* un-park verb, **NOT a gate decision**: it never allows/denies/approves anything. Governance-gate
* purity is enforced at the resume entry (fail-closed, pre-CAS): a checkpoint awaiting ANY pending
* gate decision (`gate.kind` ∈ {human, irreversible_ask, needs_review, plan_review, resource_limit} —
* i.e. the tool_approval / dry_run_review / plan_review / resource_limit decision families) REJECTS a
* wake with `wake.gate_pending`, so wake can never become a side door around an approval. Only a
* non-gate park (e.g. a deployment-minted approval-timeout park / pure suspend) is wakeable.
*
* `message` (optional): operator content delivered to the resumed run — the ATOMIC equivalent of
* `setPendingSteer` + resume in one verb (same `validatePendingSteer` persist-time guards, same
* trusted/untrusted delivery framing as {@link CheckpointState.pendingSteerQueue}). It rides the resume
* continuation's steer tail as its OWN segment, appended AFTER any already-parked queue entry
* (X5: both are delivered — the wake message never displaces a parked, undelivered supervisor steer;
* each segment is framed under its own `trusted` semantics, never one merged trust domain). Under a held
* `inputId` it is judged by {@link judgeParkedSteerRepeat}: identical ⇒ that entry, once. WITHOUT a
* `message`, the checkpoint must already carry a parked steer — a wake with nothing to
* deliver is rejected (`wake.nothing_to_deliver`, anti spin-wake). Idempotency rides the existing
* resolve CAS: a second wake of the same token loses the CAS (`checkpoint.already_resolved`). */
| {
gate: "wake";
message?: PendingSteerInput;
} | {
gate: "task_done";
result: TaskResult;
};
/**
* The pending action a checkpoint suspends *before* — a **discriminated union** keyed by `kind`. Every
* consumer that reads the tool fields MUST branch on `kind` first: the `resource_limit` arm (design/74)
* has none (a resource slice suspend has no pending tool to resolve).
*
* `tool_approval` (§4): a tool call adjudicated `ask` in durable mode, captured with its **post-hook args**
* (the design/37 rewrite already applied) so resume executes the exact same call without re-running
* PreToolUse hooks (§11 M2). `batchToolCallIds` / `completedCallIds` capture the **mid-batch** position
* (§4.ter): one assistant turn can emit a batch of tool calls; if call #k hits `ask`, calls #1..k-1 already
* executed (in `completedCallIds`) and #k+1..N are still pending. ID-based (a `Set<toolCallId>`), not
* positional — immune to reordering / off-by-one (council Question #1), and it doubles as the reconcile
* suspended-batch discriminant (§15.2 net-add #7) so wake-reconcile never closes a suspended call.
*/
export type PendingAction = {
kind: "tool_approval";
toolCallId: string;
toolName: string;
/** Post-hook (design/37-rewritten) args to execute on `allow`. */
args: unknown;
/** (additive) — the tool's approval display projection of `args`, minted alongside the
* row (see AgentTool.approvalPreview; control-char-sanitized + 16KiB-clamped at mint).
* **UNTRUSTED, ADVISORY**: inboxes must escape contextually and surface `args` alongside.
* NEVER read by the resume path (args + boundInputHash stay the sole execution contract). */
preview?: unknown;
/** #457 ② (additive; no checkpoint-version bump — the `hasBidiControls` precedent below: an
* optional field an older reader ignores and the resume path never reads) — the PARK twin of
* `AskRequest.previewWithheld`: present ⇔ this tool declares an approval preview and the mint
* could not present a usable one, `"oversize"` (produced but past the 16KiB display bound — the
* stub still rides {@link preview}) or `"unavailable"` (threw / no JSON serialization). ABSENT
* covers "no preview declared", "the projection declined" and "it worked" — read presence, never
* absence. A DISCLOSURE for the approval inbox's card, never a verdict: {@link args} and
* {@link boundInputHash} are carried either way and the resume contract is untouched. Judged over
* THIS row's fidelity-projected args snapshot, so it can honestly differ from the synchronous
* face on a shape-changing backend — exactly as {@link hasBidiControls} can. */
previewWithheld?: "oversize" | "unavailable";
/** (additive; no checkpoint-version bump — the {@link previewWithheld} precedent above) — the PARK twin of
* `AskRequest.existingTarget`: what the write's target held for this ask — the live card's member when the live card
* read it (a card answered `unavailable`, then parked), else read by the parking run before it released its
* environment — under the live ask's one rule (present on every row of a tool whose roster row writes a file on the
* execution environment; `text` exactly when the model's own `Read` of the path would have been served). One read per
* ask. A SNAPSHOT as of the ask — the approved write may meet a changed file. NEVER read by the resume path (a resumed run
* does not read the target again) and not projected to the summary; the text is the target's own bytes, unredacted —
* a store or inbox that forwards it owns its redaction. */
existingTarget?: import("./existing-target.js").ExistingTarget;
/** design/179 §4, re-formed by design/375 §3.1/§3.3 (BREAKING — replaces the retired
* `ruleSuggestions` seat; a pre-375 inbox reading a new row simply finds no offers and renders
* no "don't ask again" option, fail toward asking) — the persistable allow-rule OFFERS this
* parked call could be covered by, minted from the SAME post-hook args the row executes.
* Advisory display metadata for the approval inbox's "stop asking me this" option; never read
* by the resume path, and never a rule by itself (minting one goes through the approval-record
* protocol). Absent when no rule lane is armed, the command is one the lane cannot speak for,
* or the parked ask is one a persisted rule could not clear (mandated marks / a real-approval
* demand / a shadowed matching rule).
* CONTRACT (same as the synchronous `AskRequest.ruleOffers` — see
* {@link import("./permission-rule-model.js").RuleOffer}): at most 2 offers, the whole-string
* EXACT single always index 0 when present, the BATCH offer (choosing it is one yes to ALL of
* its 1..5 per-segment rules at once) always last; selection indices are keyed against this
* order (redemption TICKETS are keyed on the consent record's flat CANDIDATE list instead —
* a chosen offer is redeemed via `redeemRuleBatch`), per-element parse with single-row
* degrade on an unknown `kind` and
* original-index preservation. design/382 B3: a batch offer's members are the
* {@link import("./permission-rule-model.js").RuleOfferBatchMember} discriminated union
* (`command` | `directoryRead`), and the member-level degrade is the union's own normative
* arm — an unknown MEMBER kind drops the WHOLE batch offer (never one member: a conjunction
* silently one member short renders "yes to N" as "yes to N−1"), while the sibling single
* offers stay rendered. The park→resume redemption chain walks the same consent
* protocol as the synchronous card — there is no second form. */
ruleOffers?: readonly import("./permission-rule-model.js").RuleOffer[];
/** #490 修② (additive; no checkpoint-version bump — the `previewWithheld`/`hasBidiControls`
* precedents above: an optional field an older reader ignores and the resume path never reads)
* — the PARK twin of `AskRequest.ruleOffersAbsence`, minted by the SAME one factory as
* {@link ruleOffers} so the parked card and the live card cannot answer differently. Present ⇔
* the rule-offer lane is in play for this call and has nothing to give, naming which door
* closed, one word of {@link import("./ask-origin.js").RULE_OFFERS_ABSENCES} per reason (`"mandated"`:
* an inbox must NOT point at rule-writing nor at a directory grant on this arm — confirming the call
* is the whole of what a person can do about it). Mutually exclusive with {@link ruleOffers}.
* ABSENCE is not a claim — it also covers "there are offers" and the structural doors (no lane
* wired, another tool, a task that cannot hold a rule) — so read presence. See the synchronous
* seat's doc for the full contract. */
ruleOffersAbsence?: import("./ask-origin.js").RuleOffersAbsence;
/** design/382 §2.4 (adversarial-review r3; additive — no checkpoint-version bump, the
* `previewWithheld` precedent: an optional field an older reader ignores and the resume
* path never reads) — the PARK twin of `AskRequest.execCwd`, minted by the SAME factory as
* {@link ruleOffers}: the relative-cd resolution base those offers were minted with (the
* live tracked cwd at park time). An approval inbox reconstructing the authoritative
* consent record threads it as `prepareCardApproval`'s `execCwd`. Present only beside
* {@link ruleOffers} when the run had a tracked cwd; echo-only, never a control input. */
execCwd?: string;
/** The PARK twin of `AskRequest.commandSandbox` (additive, no checkpoint-version bump — the `previewWithheld` precedent: an
* optional field an older reader ignores and the resume path never reads): which side of the run's OS sandbox the parked
* call's commands run on, from the same plan reading on the parked args. Display only. */
commandSandbox?: "inside" | "outside";
/** The PARK twin of `AskRequest.destination` (additive, no checkpoint-version bump — the `previewWithheld` precedent): where the
* parked A2A skill call goes, from the same reading of the peer's declaration. Display only; the resume path never reads it. */
destination?: import("./mcp-server-spec.js").AskDestination;
/** #557 (additive; no checkpoint-version bump — the `previewWithheld` precedent: an optional
* field an older reader ignores and the resume path never reads) — the PARK twin of
* `AskRequest.requiresRealApproval`: present (`true`) ⇔ this parked ask demanded real human
* judgment (the gate's `realApproval` bit was minted — the SAME fact, restated where a card
* reader looks for it, so an inbox needs no gate-kind decoding to say "only a person can clear
* this"). Absent otherwise (never `false`). Display metadata: the resume belts keep reading the
* gate's own bit. */
requiresRealApproval?: true;
/** #1079 (additive, no checkpoint-version bump — the {@link requiresRealApproval} precedent) — the PARK
* twin of `AskRequest.mandated`: present (`true`) ⇔ no persisted allow rule and no standing answer may
* retire this parked question; absent otherwise (never `false`; a pre-#1079 row reads absent = unreported).
* Minted from the SAME facts object the row's rule-offer factory reads, through
* {@link import("./ask-origin.js").askMandateMember} (the live card's derivation). Three independent
* facts: {@link requiresRealApproval} (only a person — implies this one), this one (no rule), and
* {@link ruleOffersAbsence} (what the offer lane has to give: silent off its tool and wiring, `"ask_rule_matched"`
* when a person's rule also speaks — never a substitute for this one). Display metadata: no gate, CAS or
* resume path reads it. */
mandated?: true;
/** The PARK twin of `AskRequest.authoredBy`: the deployment's own governance layer minted this parked question — a
* person's under every mode, whatever grant or rule the redeeming host holds. Display / seat metadata. */
authoredBy?: "deployment";
/** The PARK twin of `AskRequest.fromApprovalList` (off the card's one disclosure mint): the deployment's approval list raised
* this parked question — `true` or ABSENT (a row parked before it, or an ask the list did not raise). DISPLAY only, not
* `authoredBy`: no gate, CAS, seat or resume path reads it, and it is outside the row's digest (a reader of it trusts its
* store's bytes). */
fromApprovalList?: true;
/** The PARK twin of `AskRequest.mandate` (same derivation, same precedent): the table word the bit stands on,
* present only when it is the whole reason. Written only as a member of the closed set. */
mandate?: import("./ask-origin.js").PersistedRuleMandate;
/** The PARK twin of `AskRequest.denialLimitFallback`: present
* ⇔ this parked ask is the classifier DENIAL-LIMIT fallback, carrying the counts that tripped
* the bound. Its `autoDenyAfterMs` is ALWAYS `0` on a row: the window is a fact of the ask's
* route, armed only at a hand-out to a live approver, and nothing counts down on the parked lane
* — a park's expiry is the row's own `deadline`/ttl, the engine arms NO timer off this row, and
* its settlement never reads as the fallback's auto-deny (see `tool_end.autoDenied`). A durable
* card renders the counts and the limit; it has no countdown to render. Echo-only. */
denialLimitFallback?: import("./auto-mode.js").DenialLimitFallback;
/** (additive) The PARK twin of `AskRequest.classifierNoRuling`, written only as a member of its closed set. Display metadata. */
classifierNoRuling?: import("./auto-mode.js").AutoModeFallbackCause;
/** (additive, same precedent) — the PARK twin of `AskRequest.origin`: WHICH AUTHORITY raised the
* parked ask, one word from the closed {@link import("./ask-origin.js").AskOrigin} set, the same
* word the synchronous card is rendered by (engine-stamped at the gate, never a policy's claim).
* Written only when it is a member of the set; a pre-existing row reads absent (unreported).
* Display metadata — the resume belts keep reading the gate's own bit. */
origin?: import("./ask-origin.js").AskOrigin;
/** (additive, same precedent) — the PARK twin of `AskRequest.askClass`: the parked ask's class, the first member of
* {@link classes}, from the same classification the gate arbitrated it by — so a durable approval seat can answer by
* class exactly as a synchronous `onAsk` does. Written by the park mint only as a well-formed pair with
* {@link classes} (both or neither). A row parked by an engine before this member existed reads ABSENT
* (unclassified), and a resume does not fill it in: a seat answering by class treats absence as a class it will
* not answer. A row written by another release may spell the set under that release's order with its own first member as the
* word; a reader takes the pair through `screenAskClassMembers`, which answers the pair this release would have written for
* the same set (the word a member of it, the first in today's order). Display / seat metadata — no gate, CAS or resume path
* reads it (the resumed call reads {@link classes}). */
askClass?: import("./ask-origin.js").AskClass;
/** The PARK twin of `AskRequest.classes`: every class of the parked ask, in `ASK_CLASSES` order
* (`classes[0] === askClass`). Present exactly when {@link askClass} is. Read by the resumed call: on a PERSON's decide it
* is the class set of the question that person answered, and the obligations the call meets after the decide — the
* cross-boundary exit (`cross_boundary`), the org's and the PreToolUse hook's current question (`org_rule` / `hook`), an
* edit's re-check (its own classes) — stand on that answer only when this set carries their classes. A row without it
* answers none of them: an obligation it does not answer refuses the decide. A host store round-trips it with the row. */
classes?: readonly import("./ask-origin.js").AskClass[];
/** The PARK twin of `AskRequest.askReasons` (the synchronous card's value, through the park's one carry): written only as a
* list of well-formed entries; a row parked before it reads ABSENT. Display metadata — no gate, CAS or resume path reads it. */
askReasons?: readonly import("./ask-origin.js").AskReason[];
/** The PARK twin of `AskRequest.message` (the synchronous card's question, through the park's one carry): control
* characters neutralized and past 16KiB replaced by an account naming the size; a row parked before it reads ABSENT. No
* gate or CAS path reads it; a refused resume quotes it as stored (through `approvalMessageOf`), as the synchronous refusal quotes the ask's. */
cardMessage?: string;
/** The PARK twin of `AskRequest.headline`, under the same name: the card's first line for a person, minted at the park off
* the class word this row keeps ({@link askClass}), in the parking run's language (a resume does not re-mint it). For people
* to read, never a branch input; ABSENT on a row with no class word, on the agent's own question and on a row parked before
* it (show {@link cardMessage}). No gate, CAS or resume path reads it. */
headline?: string;
/** The PARK twin of `AskRequest.matchedAskRule` (off the same disclosure mint as {@link cardMessage}): the written ask rule
* this row's card stands for, as written; present only when the decision stamped a non-empty string. **UNTRUSTED**
* display metadata — no gate, CAS or resume path reads it. The card and the row spell the two values differently on
* purpose: a row member's name is read nowhere but at its own mint. */
cardAskRule?: string;
/**
* design/80 D-1 §2 (slice 1a.2): the server-minted **opaque** boundInputHash of {@link toolName} with {@link args} — a SHA-256 (hex)
* via {@link import("./canonical-json.js").exactBoundInputHashOf}, computed ONCE here at suspend-mint and persisted on the row, which says
* so with its `tool_binding` requirement word (a row that does not, intact, is an earlier release's: `reading_changed`). The operator sees it (surfaced on the pending record) and
* echoes it back as {@link ResumeOutcome} `boundInputHash`; the resume verifies opaque string equality
* against THIS value (never re-serializing the args — see the field's doc). Absent only on a legacy
* pre-1a.2 checkpoint (deserialized without it), in which case the resume skips the hash check.
*/
boundInputHash: string;
/** A parked `Skill` call's binding to its card — the skill's name and its two lists ({@link import("./skill-grant.js").skillGrantDigest}, judged by {@link import("./skill-grant.js").parkedSkillApprovalRefusal}); only that row carries it. */
boundGrantDigest?: string;
/** The value {@link boundGrantDigest} hashes — the card's twin of `AskRequest.boundGrants`, minted by the same factory; written exactly when the digest is. Display metadata (additive, no version bump): the resume judges the digest alone. */
boundGrants?: import("./skill-grant-binding.js").BoundSkillGrants;
/** The PARK twin of `AskRequest.boundGrantAbsence`, minted by the same factory: written exactly when the digest is not. Display metadata. */
boundGrantAbsence?: import("./skill-grant-binding.js").BoundGrantAbsence;
/**
* design/388 §2.5 boundary ② (B18; additive — no checkpoint-version bump, the `previewWithheld`
* precedent: an optional group an older reader ignores): the IDENTITY of the row the park minted
* this action against, read off the leg's tool roster at the suspend station — `capabilityId`
* (engine-minted over {source, peer, name, contractId, remote?}), `contractId`, `shapeDigest`,
* `implementationRevision`. With the face below they are the TOOL member of the row's approval object
* (`judgeApprovalObject`): an identity member that differs from the same-name row on the resuming leg is a replacement
* wearing the name (`resume.tool_contract_mismatch`, a reopen); a face or declaration that differs vetoes the call
* (`resume.target_moved`). Any of them ABSENT (or the family, or the declaration digest) ⇒ the row binds no tool.
*/
capabilityId?: string;
contractId?: string;
shapeDigest?: string;
implementationRevision?: string;
/**
* design/388 B6 × B18 (additive; the identity group's precedent): the FACE the parked call was judged under —
* display `family` + declared `pathTarget` — off the same roster row at the same mint. The pre-CAS resume-edit
* recheck has no roster yet; it rebuilds the call face from these (`parkedCallFaceOf`) and judges the edit as
* the live gate judged the original (merge-seam H1: without them a caller slot fell to the catalog's slot for
* the NAME). Read only on a whole tool member: an absent `pathTarget` (or resolution member) is then the declaration's own silence.
*/
family?: import("./tool-face.js").ToolFamily;
pathTarget?: import("./tool-face.js").ToolRosterPathTarget;
/** The URL slot the parked call's host rules were read on (`ToolCallFace.hostTarget`), off the same roster row at the same
* mint: the pre-CAS recheck judges an edit on it, and the approval object binds it (a resume whose tool now names another
* slot is vetoed, `resume.target_moved`). Absent ⇒ the tool declared none, or a row minted before the member: a deny or an
* ask by host is then judged on the catalog's slot for the name, and no allow by host reaches the call. */
hostTarget?: import("./tool-face.js").ToolHostTarget;
/** The names the parked call answered to, copied from the face the gate judged it under (`ToolCallFace.names`: the
* model's spelling first, then the wire name and the other aliases that resolve to it; a row minted before the
* spelling led carries the wire name first) — the pre-CAS recheck judges an edit against rules written on any of
* them, as the live gate judged the original, and the resume re-mints its face under the spelling while it still
* resolves to the row's tool. Absent on a row minted before it ⇒ the row's `toolName` alone. */
names?: readonly string[];
/** `true` iff one of the engine's own mount sites mounted the parked tool (the roster entry's fact `ToolCallFace.engineMounted`
* carries): what the identity members above cannot say (a host-mounted engine definition has the same ones). The pre-CAS recheck rebuilds the face from the row (`parkedCallFaceOf`); absent ⇒ judged as an ordinary tool. Word `mount_site`. */
engineMounted?: true;
/** The shell the parked call's text runs on where not bash (the roster row's face member `startedShell`), by value: read back by `parkedCallFaceOf`; a live row whose shell differs vetoes the call. Absent ⇒ bash. Word `started_shell`. */ startedShell?: "zsh";
/** The digest of the roster row's DECLARATION members (`toolDeclarationDigestOf`): a live row whose declaration differs vetoes the call (`resume.target_moved`). Word `tool_declaration`. */
declarationDigest?: string;
/** The approval object's TARGETS (`approvalTargetsOf`): per reading of the path slot, where it resolved when the card
* was asked; absent ⇒ not judged. A role resolving elsewhere at the execution vetoes the call (`resume.target_moved`). */
targets?: import("./approval-object.js").ApprovalTargets;
/** The same member's shell reading (`approvalTargetsOf`): per read candidate the shell read station judged for the parked bytes, where it landed (digests); absent ⇒ not judged. A read landing elsewhere at the execution vetoes the call (`resume.target_moved`). Word `approval_target_reads`. */
targetReads?: import("./approval-object.js").ApprovalTargetReads;
/**
* #438 (additive; no checkpoint-version bump — the `reminderMark` precedent: an optional field an
* older reader ignores. Unlike that precedent seat — which resume DOES read, through its
* verify-then-adopt port — nothing reads THIS bit at all, per the echo-only clause below):
* PRESENCE ONLY — the row's execution
* payload carries at least one DIRECTIONAL format control. The durable twin of the synchronous
* {@link import("./tool-policy.js").AskRequest.hasBidiControls} (ONE contract, two faces — that
* field's doc owns the character class, the hazard and the warning-not-verdict posture; everything
* there applies here unchanged). What is stated per face:
*
* - JUDGED AT THE PARK MINT over THIS ROW's materialized payload: the fidelity-projected `args`
* snapshot (the bytes a human approves and a resume executes) plus the row's own `preview`
* projection and the row's `existingTarget` — the one card scan the synchronous face runs
* ({@link import("./tool-policy.js").cardCarriesBidiControls}). The row's bit describes the row's bytes — on a shape-narrowing backend (a Map key
* under a JSON codec) a marker the synchronous face detected can be GONE from the row, and the
* honest bit for the row is then ABSENT: the inbox renders the row's snapshot, and the bit
* agrees with what it renders. The two faces coincide whenever the projection is shape-preserving.
* - `true` or ABSENT, never `false` (absence = "not detected": clean, or the bounded scan did not
* reach it — a `false` would claim a proof the scan does not offer).
* - A DEPLOYMENT-WRITTEN park row (the design/144 convention's deployment half) may carry `true`
* (taken at its word — over-warning is the safe direction, and a writer with row access holds
* the args themselves already) or omit it (the summary projection then runs its own bounded
* backfill scan — see {@link CheckpointSummary.hasBidiControls}). A written `false` is
* out-of-contract and is read as ABSENT everywhere; it never reaches a projection.
* - ECHO-ONLY, like {@link CheckpointSummary.toolInput}: NO resume / gate / CAS /
* `winnerFromOutcome` path reads it — it is a display warning, never a control input.
*/
hasBidiControls?: true;
/** All tool-call ids in the suspending assistant message, in emission order. */
batchToolCallIds: string[];
/** Ids of calls already executed (results in the session) when the suspend fired — #1..k-1. */
completedCallIds: string[];
}
/** design/74: suspended at a resource slice boundary — there is NO pending tool to resolve. Consumers
* that read the tool-approval fields above MUST branch on `kind` first (this arm has none). */
| {
kind: "resource_limit";
reason: ResourceLimitReason;
}
/** design/76 §2.5: paused at a POST-PREDICTION REVIEW (`CheckpointGate.kind === "needs_review"`). There is NO
* pending tool to resolve — a human/judge reviews the buffered predicted state-diff (a PROFILE-held REF, never
* stored here) — so this arm has no fields. Its OWN member: before the pause registry a `needs_review` row
* borrowed another arm's seat, and the gate × pendingAction pairing lived in a comment. */
| {
kind: "review";
}
/** design/80 D-B (r3 — an EXPLICIT arm, NOT a reused `resource_limit` placeholder): paused at a PRE-ACTION
* PLAN REVIEW (`CheckpointGate.kind === "plan_review"`). There is NO pending tool to resolve — the human
* reviews the PLAN, not a tool call — so this arm has no tool fields. Every consumer that reads the
* `tool_approval` fields above MUST branch on `kind` FIRST: a `plan_review` checkpoint must never flow into
* a `resource_limit`- or `tool_approval`-shaped continuation (a contract test pins this). The plan artifact
* is a PROFILE concern (a REF — design/76 §9); core stores no plan here.
*
* `requestedByCallId` is the id of the tool call that ASKED for this pause (the `ExitPlanMode` call for the
* first-party plan tool): which transcript call carries the plan awaiting a decision, so a card can join the pause to
* the call that presented it instead of guessing by adjacency. It is PROVENANCE, not a binding — the pause
* still gates no call, `toolCallId` stays absent on this arm, and nothing on the resume path reads the id. Written
* once, at the park mint, from the engine-bound call id (a tool cannot name another call's id); the paused
* cause and the inbox summary echo it. ABSENT for a pause whose requester carried no call id (a revive context,
* a row a deployment minted itself, a row from an engine before this member).
*
* `planContentHash` answers one question: is the text a reader holds the text SHOWN to the person at this pause? It is
* the `textContentHashOf` value of the `plan` string on the `exit-plan-mode` card the requesting call's `tool_end`
* CARRIED (`structured.plan` — not the fenced model text, not the plan file's bytes, not the arguments): a reader
* digests the string it received, before any display normalization, and compares. It says what was shown, whoever
* asked (a caller tool returning that card carries one too); written once at the park mint, never rewritten; not the
* gate's identity (equal text, equal values, different `checkpointId`s) and never read by a resume. ABSENT when that
* frame carried no plan card (an error, a withheld result, a card left off for size), on a deployment-minted row and on
* an earlier engine's row: "nothing to compare", never "an empty plan". Unsalted: never in a trace, a metric or a log. */
| {
kind: "plan_review";
requestedByCallId?: string;
planContentHash?: string;
}
/** design/144 §3 (X2) — the NON-GATE arm: nothing pends a decision. The shape of a deployment-minted
* PARK checkpoint (approval-timeout park / pure suspend; paired with `gate.kind === "task_done"`, the
* non-gate gate arm) and of a 1C `task_done` handle row. It is the ONLY pendingAction kind the `wake`
* resume entry accepts — every other kind above is a pending GATE decision, and the wake gate rejects
* it (`wake.gate_pending`) via an EXHAUSTIVE switch (a future kind added here without classifying it
* there is a compile error, and an unknown kind on a deserialized row fails closed at runtime). Core
* never mints this arm itself (the park convention is the deployment half); the pre-existing doc
* references to "a task_done pendingAction" (`getCheckpointSummary` et al.) name exactly this shape. */
| {
kind: "task_done";
};
/**
* The per-task correctness state a checkpoint must carry so a resumed task runs in the **same state
* space** it suspended in (§4.bis, the jury head must-fix). An **explicit whitelist** of serializable
* correctness fields — never a blind `JSON.stringify(Prepared)`, which would silently corrupt the 9+
* non-serializable runtime objects (`harness`/`session`/`abortController`…) it holds (round-2 BUG#1).
*
* Round-trip fidelity of every field is covered by tests; runtime objects are **forbidden** here.
* The session's prefix ledger is deliberately **excluded** — observation-only: a resumed leg's first request
* reads `no-baseline` (the leg start's anchor comparison speaks for it), never correctness state.
*/
export interface CheckpointState {
/** design/36: deferred-tool activation set — else resume re-discloses / diverges from history. */
activeTools: string[];
/** 1.41 submit_output: the validated structured output set pre-suspend, else it's lost on resume. */
outputRef?: {
value?: unknown;
set?: boolean;
};
/** design/38: nested sub-agent cumulative cost — else pre-suspend child cost evaporates (§4.bis/Q7). */
nestedStats: NestedUsageAccum;
/** design/44: the hand's read-file state (content hashes), serialized from the hands-toolkit closure
* (NOT part of Prepared — §15.2 net-add #8). Without it a resumed `edit_file` is rejected "not read". */
readFileState?: Array<[string, ReadEntry]>;
/**
* design/199 — the READ-face containment state at suspend (reader-requirement word
* `face`): the RESOLVED face (a leg that narrowed only its own hands, `TaskSpec.ownHandsReadOnly`, records "open" where the face it
* hands its children is open — not on a hands-less leg's re-park; its spec re-applies the narrowing on every leg) plus the NORMALIZED deny-set ADDITIONS in
* force (deployment ∪ task layers; the built-in table is engine code under the RESUMING deployment's
* own tier selection — empty unless it made one — never frozen here). Written ONLY when the posture
* is non-default (face "open", or additions present) — an absent section IS the default posture and
* resumes as roots plus whatever built-in tiers the resuming worker selected. Resume folds STRICTER-WINS: face = roots unless the
* section says open AND the live resolution says open; deny additions = frozen ∪ live (add-only,
* monotone — a resume can never widen what the cut leg could read).
*
* The design's r3/r4 rounds carried a third key (the workspace domain at cut) to evaluate
* domain-scoped deny entries under their frozen domain; the D-4 ruling (2026-08-13) removed the
* scoped tier entirely, leaving that key without a consumer — it is deliberately NOT persisted
* (dead fields in a durable format are the drift surface the liveness gate exists to catch).
*/
readFace?: {
face: "open" | "roots";
denyEntries?: Array<{
pattern: string;
caseSensitive: boolean;
}>;
/** REDUNDANT governance marker: `true` iff the row's gate was minted WITH a
* {@link RealApprovalGateBit}. v8's bit-required invariant was version-keyed and v9 (face)
* outranks v8 in the stamp, so without this a v9 GOVERNED row whose `gate.realApproval` member
* was dropped in storage would pass pre-CAS and be redeemable on an unwired worker — the exact
* #130/#120 corruption/downgrade hole, reopened one version up. The resume pre-CAS ladder
* refuses a v9+ row whose section says `realApproval: true` while the gate carries no
* well-formed bit (same protection level as v8: a coherent rewrite of BOTH sites remains out of
* scope for any in-row invariant). Absent = the row was minted ungoverned. */
realApproval?: true;
};
/**
* The WRITE-face containment state at suspend: the RESOLVED write face (a narrowing leg: "open" only where the deployment's seat opened the face it
* hands its children), written when it is "open", or "roots" when a seat or a clamp DECLARED the fence. An absent section declares no fence:
* the resumed leg's own seats and mode decide (`bypassPermissions` opens it). Resume folds STRICTER-WINS on the seats: a recorded "roots"
* stays roots, and a seat's "open" holds only where the section says open. No deny half and no governance marker.
*/
writeFace?: {
face: "open" | "roots";
};
/**
* The leg refused reads outside its declared directories (`TaskSpec.blockReadsOutsideRoots`, the leg's resolved value):
* written ONLY when it did — `true` or absent. Its reader requirement (`read_block`) makes a worker that cannot honor it
* refuse the row rather than resume the leg reading wider; the resume reads it as the declaration (the row's ∨ the spec's
* — a resume never lifts it). Any other value damages the row.
*/
readBlock?: true;
/** The grant rows the run grew ({@link import("./skill-grant.js").frozenSkillGrants}); absent = none, damaged = refused pre-CAS. */
skillGrants?: import("./skill-grant.js").SkillGrantRecord[];
/** The skills active on the leg whose hooks were open (`SkillSpec.mods`; {@link import("./mods/spec-seats.js").SkillScopes}`.frozen`):
* the resumed leg reopens them at its admission. Absent = none; damaged = refused pre-CAS. */
skillScopes?: string[];
/**
* design/319 (A ticket) — the session's reminder provenance mark
* ({@link import("./reminder-mint.js").mintReminderMark}), persisted so a durable resume keeps
* minting the SAME mark its transcript's engine reminders and system-prompt declaration carry
* ("resume reuses" — one declaration, one mark). Additive on the existing checkpoint version —
* a reader that ignores it is unchanged (the :646 precedent; no version bump). Resume goes
* through the VERIFY port ({@link import("./reminder-mint.js").isValidReminderMark}): a missing
* field (pre-319 row) or an unrecognized value-shape (corrupt / foreign / old-scheme after a
* scheme change) RE-MINTS instead of adopting — the declaration stays strict, and the historic
* legs' reminders simply read as data (fail-safe downgrade, design/319 a-2).
*/
reminderMark?: string;
/**
* design/78 Slice-1: the SAFE-tier self-repair loop's durable state (`failureTrace`/`diagnostics`/
* `rejectedHypotheses`/`attemptCount`/`oracleTier` — all JSON/`structuredClone`-safe, no fn/Date). Set ONLY
* when an orthogonal durable suspend (resource/HITL) interleaves a `runRepairLoop` run — the happy path is
* in-memory only. On resume it re-seeds `RepairLoopConfig.resumeBundle` so `attemptCount` advances
* MONOTONICALLY (never reset). `baselinePassTests` is deliberately NOT carried here (grader-computed
* out-of-process — a worker must not be able to shrink the ratchet). Absent for a run with no repair loop.
*/
repairBundle?: RepairBundle;
/**
* design/49 v1.5: the remote workspace's serializable identity (E2B sandbox id / provider / mount path /
* snapshot id). Set ONLY when the suspended task ran with a remote, suspendable {@link WorkspaceHandle}
* (a per-task `executionEnvFactory` env that was `suspendVM()`-paused rather than destroyed). Resume
* rebuilds the env via the factory and `resumeVM(snapshotId)` so the restored workspace matches the
* `readFileState` above. All-string fields → JSON/`structuredClone` round-trips safely (consistent with
* this whitelist's "no runtime objects" rule). Absent for a process-local (non-remote) suspend.
*/
workspaceHandle?: WorkspaceHandle;
/**
* design/171 §5.3 — the BOUNDED, ORDERED queue of parked operator steers for a DURABLY-SUSPENDED task,
* drained in `seq` order on resume with every entry framed under its own trust semantics. Live
* `TaskStream.steer` (runtask.ts) is unreachable while the harness is idle, so a supervisor's guidance is
* parked HERE via {@link CheckpointStore.setPendingSteer} and injected on resume (after the
* resume-continuation prompt). It is GUIDANCE ONLY — never an approval channel (§3 inv #4) and never
* parsed into control state (§3 inv #5); a budget/autonomy/gate-threshold is CONFIG, not steer text.
*
* `trusted` is FROZEN at `setPendingSteer` from the SERVICE's verified-principal check (an operator-role
* check, NOT a client header) and NEVER recomputed on resume (§3 inv #1). A `trusted:false` entry reaches
* the model as a PLAIN user message with NO `<system-reminder>` wrapper (§3 inv #3); a `trusted:true`
* entry MAY ride the reminder. `text` containing `</system-reminder>` is REJECTED at `setPendingSteer`
* (`steering.invalid_content`) so a dirty steer never enters this state (§3 inv #2).
*
* Delivery is BEST-EFFORT, at-most-meaningfully-once: an entry rides EVERY resume of THIS checkpoint
* that runs a turn (a faithful reopen→re-resume re-shows it), is NOT carried onto a re-suspend
* checkpoint (serializeCheckpointState stamps `undefined`), and is DROPPED on a resume that runs no
* turn. A supervisor re-issues `setPendingSteer` if a steer did not land.
*
* The bound is fail-loud, never lossy: an append whose queue would serialize past
* {@link PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES} bytes is rejected with `steering.queue_full` rather than
* evicting an already-accepted instruction (no entry-count cap: an entry that fits is taken).
*
* Absent when nothing is parked. {@link readPendingSteerQueue} is the single read point; a row that
* still carries the retired pre-queue single seat (`pendingSteer`) is refused there
* (`checkpoint.unsupported_version`, `seat_retired`), never folded in.
*/
pendingSteerQueue?: PendingSteerEntry[];
/**
* SR-7 (orphaned-background-task notice, resume leg
* under the `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` gate — the cloud-worker restart
* leg, exactly sema's durable-resume shape): the background tasks (pending/running, this run's
* owner triple) still ALIVE at suspend. Background processes never survive a suspend (design/103
* §3.7 unconditional dispose + killed receipts), so on resume any snapshot entry NOT
* alive in the resume leg's registry is an ORPHAN — aggregated into ONE "The container
* was restarted…" reminder appended to the resume continuation (single message: header +
* `- description (task id)` list + re-create instruction; never a per-task barrage). A survivor
* (session-resident shell / in-window monitor) is excluded — its output file and TaskStop
* still reach it, it needs no obituary. CC's per-orphan `Ku(task_id,"stopped")` status write (:707399)
* is N/A here: the suspend teardown already settled them killed with receipts. Absent for a run
* with no live background tasks at suspend, and for pre-1.262 checkpoints (deserialized without
* the field) — both resume silently, exactly like CC with an empty list.
*/
runningBackgroundTasks?: Array<{
id: string;
description?: string;
}>;
/**
* the hands band's LOGICAL working directory at suspend (`handsCwdRef.current` —
* moved by `cd` and by EnterWorktree). Without it a resume silently reset the task cwd to the task root:
* relative Read/Edit/Write paths and Bash commands then operated somewhere else than the model believes.
* Absent when the task has no tracked cwd (no real shell / read-only hands). The directory itself is
* plain on-disk state that survives a process-local suspend (worktrees included — the tree stays on disk).
*/
handsCwd?: string;
/**
* The hands band's ROOT at suspend (the canonical root its tools resolve a root-relative spelling against — the
* `root` every adjudicated request of the leg carries). Read by ONE seat: the pre-claim recheck of an edited parked
* call, which has no environment yet and judges the edit at the row's coordinates (`handsRoot` + {@link handsCwd}).
* After the claim the resumed leg uses its own live root. Absent on a row written before this field (that recheck then
* reads the root as unknown, as before) and when the task has no hands. An ignorable optional field: an older reader
* that does not know it resumes the row as it always did, so it raises no row format.
*/
handsRoot?: string;
/**
* The home the leg's caller policies installed their `~/` words at (the execution environment's declared home, absolute),
* beside {@link handsRoot}: the pre-claim recheck installs the edit-base policy at the row's root and this home, the way
* the leg did. Absent on a row written before this field, on a hands-less task and on an environment that declares no
* absolute home — a `~/` row then reads unanchored there (never the engine process's home). Ignorable, like `handsRoot`.
*/
handsHome?: string;
/**
* the ACTIVE EnterWorktree session at suspend (worktree.ts keeps it in a shared
* serializable ref, not a closure-only var, precisely so it lands here). Without it a resume LOST the
* session: ExitWorktree became a no-op (the unchanged worktree could never be removed), a second
* EnterWorktree was wrongly accepted, and `handsCwd` pointed into a worktree the tooling no longer
* owned. All-string fields; the worktree directory survives the suspend on disk (managed under the
* task root, `git worktree` metadata intact).
*/
activeWorktree?: ActiveWorktreeSession;
/**
* Parent effective-policy inheritance (tighten-only): the durable projection of the run's
* {@link import("./runner/contracts.js").InheritedGate}. Only the serializable DATA half persists —
* `ancestorRules` (each ancestor's session-rule snapshot: sessionId/principal/rev/rules, re-compiled on
* resume against the resumed leg's env), `shellGate` (the chain's operator floor) and `permissionMode`. The OPAQUE
* half (`parentConstraints` — live ToolPolicy/onAsk closures) CANNOT persist; `requiresParentConstraint`
* records its PRESENCE and `constraintChain` each layer's record (its `kind` among them), from which a resume that holds
* no live chain rebuilds the layers or refuses pre-CAS (`resume.parent_constraint_unrebuildable`, checkpoint stays
* `pending`). Absent for a task that inherited nothing (pre-1.294 checkpoints included)
* — distinguishable from `requiresParentConstraint: false` with data-only inheritance, which resumes
* without any re-supplied internals. All-data fields → JSON/`structuredClone` round-trips safely.
*/
inheritedGate?: {
ancestorRules?: ReadonlyArray<{
sessionId: string;
principal?: string;
rev: number;
gen?: number;
rules: SessionPermissionRules;
}>;
shellGate?: ShellGateDoctrine;
/** The chain's DECLARED permission mode at suspend (data half, same law as `shellGate`): the suspended leg's
* own effective declaration — its request clamped under its parent's ceiling — before the deployment's fold.
* A resume leg reads it as the REQUEST a re-passed spec without a mode word falls back to — never a ceiling (the
* ceiling is the live chain's: a parent's seat, or a rebuilt chain's word) — and re-judges the deny bits and the
* classifier face for its own leg: a `bypassPermissions` row does not revive the mode where the redeeming
* deployment denies it, and an `auto` row arms only where a face is wired. Absent on a task that declared nothing and inherited nothing (`default`). Rows written before this
* member carried `autoModeRequested` / `approverPosture` / a doctrine `shellGate`; no engine since 7.39.0 reads
* them — such a row is refused before the claim (`retiredModeSeedRefusal`, checkpoint-row-verdict.ts). */
permissionMode?: PermissionMode;
/** Beside a recorded `plan`: the declared word the leg had when a steer or the model's `EnterPlanMode` moved it into
* plan — the mode an approved or edited `plan_review` resumes under ({@link import("./mode-policy.js").modeRequestAfterResume}). */
prePlanMode?: PermissionMode;
/** Org-memory admission freeze (ruled 2026-08-05): the chain's admitted org-scope set at
* suspend (data half, plain strings). The resume leg folds it seed ∩ live (tighten-only) and
* re-runs admission under it — a resume must never widen the delegation freeze. Absent on
* older checkpoints ⇒ the live channel (or, for a delegated child, the fail-closed ∅) stands.
* Cross-VERSION enforcement (an older worker resuming a newer checkpoint ignores fields it
* does not know) is the deployment's server/core version-gate concern, not a per-field fence. */
admittedOrgScopes?: readonly string[];
/** THIS task's OWN admitted org verdict at suspend (adversarial-review adoption, 2026-08-05):
* distinct from {@link admittedOrgScopes} (the incoming PARENT constraint). The resume leg
* applies it as the SESSION freeze on the final admitted projection — regardless of origin
* (deployment-origin scopes circumvent the chain freeze, never the session freeze) — so a session's
* verdict can only NARROW across suspend/resume: re-adjudication still runs every leg (a
* revoked grant refuses the resume), but a policy widened mid-session cannot widen THIS
* session's mount or the chain its children inherit. Present (possibly EMPTY — an adjudicated
* empty verdict is not "org-less") iff the suspend leg adjudicated an org plane; absent on
* older checkpoints / org-less tasks. Checkpoints carrying this state list the `orgAdmission`
* reader-requirement word. */
ownAdmittedOrgScopes?: readonly string[];
/** The WRITE half of the session freeze: the org write grant this session held at suspend —
* `null` = the org write face was read-only (a resume must not gain write authority the
* suspend leg did not hold); a scope string = the explicit grant. Present iff
* {@link ownAdmittedOrgScopes} is (same adjudication record). */
ownAdmittedOrgWriteScope?: string | null;
/** The MONOTONIC org-governance provenance bit (falsification-style round 5): `true` when any leg of
* the suspended tree ran with an org-admission surface (or inherited the bit). A resume worker
* missing the surface still treats the leg as governed — org-shaped scopes respelled outside
* the v2 contract are refused, even when every admitted set en route was EMPTY. Absent on
* trees that never had a governance surface. */
orgAdmissionGoverned?: true;
/** The chain's top leg's root and home at suspend (data half): the anchors of the person's global / session path rows
* and of every `~/` row on this chain (a project row anchors at its own scope root). Absent on older checkpoints and on
* a top leg ⇒ the resumed leg is its own top. Rebased with the workspace on a restore elsewhere; a value that is not
* an absolute path anchors nothing (the rows it would anchor read `unreadable`). */
pathRuleAnchors?: {
readonly root: string;
readonly home?: string;
};
/** Where each parent constraint the suspended leg ran under was installed, position for position (data half; `null`: an
* entry with no path rules). A resume that re-supplies the chain uninstalled installs each entry there. Rebased with the
* workspace; a value that is not an absolute path installs nothing (the entry is installed at the chain top). */
pathRuleInstallations?: ReadonlyArray<{
readonly root: string;
readonly home?: string;
} | null>;
/** The kinds of persisted-rule bucket the legs above the suspended one read (data half): a resumed leg whose Runner cannot read
* one of them is refused at prepare (`config.persisted_rule_bucket_missing`) and the row stays pending. Absent on older rows and
* where no leg above read one ⇒ the row adds nothing to compare (the chain the resume runs under still applies); present in
* another shape ⇒ the resume is refused at prepare with the same code and the row stays pending (`readRuleBuckets`). */
persistedRuleBuckets?: import("./persisted-rule-buckets.js").PersistedRuleBuckets;
requiresParentConstraint: boolean;
/** How many opaque parent constraints the suspended leg ran under (present iff `requiresParentConstraint`).
* The resume pre-CAS ladder rejects a re-supply whose `parentConstraints.length` differs
* (`resume.parent_constraint_mismatch`) — a partial re-supply is a typed error, never a silently
* thinner chain. Absent on older checkpoints ⇒ only the non-empty check applies. */
parentConstraintCount?: number;
/**
* F-012 L1 — the persisted CONSTRAINT PROJECTIONS of the inherited chain, one ordered entry per
* `parentConstraints` layer: the layer's deterministic deny data
* ({@link import("./tool-policy.js").ToolPolicyProjection} content) or an explicit `{opaque:true}`
* placeholder for a layer that exports none. The resume leg EXECUTES these persisted projections
* (extra deny-narrowing layers + the pre-CAS edit re-adjudication) rather than trusting a
* re-supplied policy's execution half for the frozen deny data — a re-supplied closure that
* matches the digest but behaves differently cannot un-deny what the suspend froze. Present iff
* `requiresParentConstraint` on new mints; absent on PRE-F-012 checkpoints (⇒ no frozen deny data —
* the count-only contract governs, and an EDIT resume is refused for want of a validatable chain).
* Chain and digest are one write, so on a row that requires parent constraints the pair is REQUIRED — its
* absence is a damaged row and the resume ladder refuses it pre-CAS rather than falling back to the
* count-only contract. */
constraintChain?: ReadonlyArray<import("./tool-policy.js").ConstraintChainEntry>;
/**
* F-012 L1 — the content digest over `constraintChain` ({@link import("./tool-policy.js").constraintChainDigest}):
* binds the ordered chain topology (layer boundaries + opaque placeholders) and each projection's
* content. The resume pre-CAS ladder recomputes the digest over the RE-SUPPLIED chain's
* projections and rejects a mismatch (`resume.parent_constraint_mismatch`) — replacing the
* count-only shape check with a content contract (a same-length chain of different frozen deny
* data no longer passes). Present iff `constraintChain` is — and on a row that requires parent
* constraints both are required (see {@link constraintChain}: the pair is minted together). */
constraintDigest?: string;
};
/**
* [c209-C] Q5 — the listing frames' announced NAME-SETS at suspend (agent types / skills the model
* has actually been shown this run, committed on first-frame delivery or intact boundary survival).
* A resume leg seeds its producers from these names and DIFFS the current roster/skill set against
* them, so cross-leg drift (web-admin roster change between suspend and resume) is announced as
* a delta frame at the first boundary instead of silently swallowed — the exact event the listing
* eviction from the cached prefix exists to serve. Names only, never contents (a description change
* on a surviving name is deliberately not re-announced — name-keyed diff, agent_listing parity).
* Schema ADDITION (backward-compatible, B-5): an older checkpoint without the field resumes via the
* MED-3② transcript probe (delivered ⇒ seeded as the CURRENT entries, drift undetectable there;
* not found ⇒ full re-announce at the first boundary — conservative direction preserved).
*
* [c209-C] R2 C7 — `models`: the model CATALOG names announced (the agent_listing initial frame's
* "Models available for the 'model' parameter:" tail, Q4). The resume seed feeds it to the
* producer; a differing current catalog ⇒ the first boundary's agent_listing frame re-carries the
* full line — without this a catalog swap between legs was never re-disclosed anywhere (the
* catalog left the tool description with Q4). Absent (older checkpoint / never announced) ⇒ drift
* undetectable, silent (conservative, same B-5 direction).
*/
announcedListings?: import("../internal/harness.js").AnnouncedListingSnapshot;
/**
* The git-status frame's announced `(kind, hash)` state at suspend (env-tail migration: the
* run-loop-maintained mirror, advanced at every frame receipt). The LOWEST rung of the resume
* read ladder — the session branch walk is the authority (a nearest PENDING mirror there, or an
* announced mirror whose frame entry is off the active branch, forces a re-announce regardless of
* this field); the checkpoint seeds only when the branch carries no mirror at all, and its
* `entryId` must itself sit on the active branch to count as announced. Schema ADDITION
* (additive, old readers ignore it — the Q5 posture): an older checkpoint without the field re-announces
* conservatively — the frame is a tail append, so a duplicate costs bytes, never a prefix break.
*/
gitAnnouncement?: {
kind: "full" | "degraded" | "unavailable" | "non-repo";
hash: string;
entryId?: string;
pending?: true;
};
/**
* design/180 R-4 (R-2 cross-process variant) — the armed delegation child's MONOTONIC runtime-provenance
* aggregate at suspend ({@link import("./memory-engine/delegation-provenance.js").DelegationProvenanceAggregate}:
* version + coverageStartTurn + the two never-cleared bits sawExternal/incomplete). Persisted so a
* resume — a cross-process one especially, which lost the in-memory ref — CONTINUES accumulating from
* the recorded bits instead of restarting a fresh aggregate that could prove "clean" on the post-resume
* segment alone. Plain data → JSON/structuredClone round-trips. Present ONLY when the suspended leg ran
* with a recorder armed; ABSENT on an unarmed leg AND on an older checkpoint — the resume side reads
* absence-on-an-armed-child fail-closed as `incomplete`. */
delegationProvenance?: import("./memory-engine/delegation-provenance.js").DelegationProvenanceAggregate;
/**
* #281 件B follow-up — `true` iff the suspended leg ran as a DELEGATED CHILD (the trusted
* `RunInternals.isDelegatedChild` fact, read off the leg's own minted
* {@link import("./runner/contracts.js").Prepared.hookIdentity} so a re-suspend chain carries it
* forward). Without it a deps-only resume (`resume(token, outcome, config)` — no trusted internals
* re-supplied) re-minted the resumed leg's identity with `isDelegatedChild: false`, so the
* delegation-lifecycle observer's emission gate stayed shut and the resumed leg emitted NEITHER
* frame — a deployment watching only that seat saw a human-approved delegation frozen at its
* park-leg `"suspended"` terminal forever. Live internals still win when re-supplied (the in-engine
* resume lanes all do); the checkpoint key is the fallback for the deps-only leg. Of the delegation
* axes this one, {@link fromSubagent}, the asks' display name ({@link sourceAgentName}) and the {@link legIdentity} section (the spawn name
* among it) persist — `insideFork`, the hook identity's `agentName` and `parentToolCallId` stay internals-only, honestly absent on a deps-only resume rather than guessed. `insideFork` needs no axis: no lane holds a fork leg's
* parks (`RunInternals.parkLaneHeld` is set only by a background lane that can park and an armed
* workflow), so a fork leg mints no row and no resume of one exists to read the facet back. Schema ADDITION (additive, old readers ignore it —
* the Q5 posture; no version movement): an older worker resuming a newer row keeps the pre-key
* behavior, and an older row without the key resumes frame-less by documented honest absence
* (see {@link import("./types.js").DelegationLifecycleEvent}). Absent = the leg was not a
* delegated child (never `false` — presence-coded like the other monotonic bits here).
*/
isDelegatedChild?: true;
/** The registry row the suspended leg ran as (`RunInternals.rowTaskId`), stamped at every mint and restored by a resume that
* hands no internals. Present only on a row-lane leg's park, which then requires `row_task_id` (an older engine refuses it). */
rowTaskId?: string;
/** The task id the parked leg's asks named it by (its prepare's one mint, `Prepared.taskId`: its registry row, else its spec's, else its
* session id), stamped at every mint; the summary's {@link CheckpointSummary.agentId} reads it, no resume does. Absent ⇒ minted before the member. */
legTaskId?: string;
/** The display name the parked leg's asks carried ({@link import("./tool-policy.js").AskRequest}.sourceAgentName: a named helper's spawn
* name — the same literal its fleet row carries — else, for an unnamed helper, its Agent call's description (the agent type when the call
* has none), which is NOT the literal its fleet row carries), stamped beside {@link legTaskId} at every mint; the summary echoes it
* ({@link CheckpointSummary.sourceAgentName}) and a resume handed no spawn facts reads it back into the leg's asks, so a re-park keeps it.
* UNTRUSTED display text (a model chose it): shown, never decided — no reading of the row judges it, and a value that is no string is left
* off. Absent on a leg that had none (a host's) and on a row minted before the member. */
sourceAgentName?: string;
/** The attribution bit the parked leg's asks carry ({@link import("./tool-policy.js").AskRequest}.fromSubagent: a nameable parent task issued the leg), stamped at every mint
* from the leg's one ask source; a resume handed no parent task reads it back. Not {@link isDelegatedChild} (a directly-started workflow's agent is delegated without it). */
fromSubagent?: true;
/** The workflow member the parked leg ran as (its asks' `workflowRunId` / `workflowAgentLabel` / `workflowStepAskedAgain`), stamped at
* every mint from the leg's one ask source — the values of the run that parked this row; a resume handed no member reads it back.
* Absent on a leg that is no workflow member and on a row minted before the member. Shown, never decided. */
workflowMember?: import("./leg-identity.js").WorkflowMemberIdentity;
/**
* design/380 O1③ — the run TREE's placement fixed point at suspend: the SAME three-segment fold the
* env-factory ctx mint uses (explicit `RunInternals.placementRoot` > the delegation lanes'
* `rootSessionId` > the leg's own resolved session), stamped from TRUSTED internals so a durable
* resume can restore it instead of falling back to the parked leg's own session (a target-bound
* factory keys its placement lookup on the fixed point — the self fallback read a resumed leg as a
* NEW placement). Restore is the `isDelegatedChild` posture replayed on the placement axis: an
* EXPLICIT live `internals.placementRoot` wins when re-supplied; otherwise THIS key restores into
* `internals.placementRoot` at prepare so descendants and the NEXT re-suspend mint inherit it too
* — outranking a supplied `rootSessionId`, which is DELEGATION IDENTITY (the peer/registry axis a
* revive leg re-supplies from its row), never a placement claim (reading it as one
* permanently stuck every parked agent spawned under an explicit placement root). The resume entry
* ALSO reads this key as an identity record: a resume whose supplied `internals.placementRoot`
* CONTRADICTS it is refused pre-CAS (`resume.placement_mismatch`); either side absent skips the
* check (an older row / a claim-less resume — the honest degradation arm), and `""` reads as
* absence (the identity fields' discipline). Schema ADDITION (additive, old readers ignore it — the Q5 posture;
* deliberately NOT version-gated: same rolling-deployment account as {@link Checkpoint.principal},
* whose doc records version-gating as a design candidate — any new stamp is a lattice-wide window
* rewrite, owned by that ticket, not ad-hoc here). Absent ⇒ minted before the field, or the fold
* resolved empty on a factory-less run (never persisted as garbage).
*/
placementRootSessionId?: string;
/**
* Which composition leg parked this row and which host session it belongs to
* ({@link import("./runner/contracts.js").CompositionLeg}): stamped at every mint from the ONE value the leg's prepare resolved
* (the live `RunInternals.compositionLeg`, else this member restored from the row being resumed), so a re-suspend chain carries
* it unchanged. A host links the row to its run by `hostSessionId` — the row's own {@link Checkpoint.sessionId} is the leg's
* session, not the host's — and settles it by `entry`: a `cascade` card goes back to the cascade's resume entry, which reads
* `leg` to know which rung it continues; a `verify` card is a verifier's own pause (resume it by its token, or void it with
* `Runner.voidVerifierPause`). A resume that hands a CONTRADICTING live value is refused pre-CAS (`resume.composition_mismatch`); a live value
* over a row without this member is that row's first record. Absent ⇒ the leg was not handed out by a composition entry, its
* composition minted none (a cascade whose caller named no session), or the row was minted before the member.
*/
compositionLeg?: import("./runner/contracts.js").CompositionLeg;
/**
* design/380 O9a — MONOTONIC presence bit: this run's hand-tool content fold was EXTERNAL-TARGET
* armed (the env declared `capabilities.externalContentTarget`, or an earlier leg of this suspend
* chain did). Stamped at the suspend mint from the run's RESOLVED fold state — never from first
* tool use, so a park landing BEFORE the first hand call is covered too. Presence-coded like
* {@link isDelegatedChild} (absent = never armed; never `false`). The resume side folds
* **persisted OR live declaration** (a monotonic join, never a downgrade): a run minted under a
* declaring adapter keeps its memory fold and its prompt disclosure when resumed on an
* undeclared/older adapter — the downgrade is closed in the derivation itself, deliberately
* WITHOUT a new refusal arm (one fewer failure path, same safety). ONE declaration, two readers: the content-class fold (the memory
* face, the prompt disclosure — the design/378 red line binds it: no gate/policy/roster reads it) and the tree's cross-boundary taint bit.
* Schema ADDITION (additive, Q5 posture; the version-gate residual is shared with
* {@link placementRootSessionId} above and owned by the same version-lattice ticket).
*/
externalContentTarget?: true;
/** The scope this LEG's rows land in (its prepare's one `checkpointScopeOf` reading), stamped at every mint: a resume
* that hands no live seat restores it, so the resume config cannot move the leg's next row. Not {@link Checkpoint.scope}
* (where THIS row is filed — a resource slice's own declared scope). Absent ⇒ minted before the member: derived as before. */
legScope?: string;
/** The word of the LEG that parked this row ({@link import("./run-origin.js").RunOrigin}: the word of the input that opened
* that leg, read once at its config doors), stamped at every mint and continued by a leg a decision resumes (a wake opens
* its leg with the input it hands over instead): an approved, resumed leg is still that leg's work. Absent ⇒ the host said
* nothing (or the row was minted before the member). Attribution only. A reader that lacks the word would resume the leg with
* its origin silently lost. */
runOrigin?: import("./run-origin.js").RunOrigin;
/** The tool-selector layers this LEG was spawned under (`RunInternals.toolCeiling`), stamped at every mint: a resume that hands
* no live ceiling restores it, so a resumed child can never use a tool its spawning run could not. Absent ⇒ the leg had no
* ceiling (a root run) or the row was minted before the member. A reader that lacks the word would run the leg unbounded.
* Each entry is a tool name in its canonical spelling (`persistedToolNameList`, `src/agents/tool-filter.ts`): a row restored with
* any other entry is refused before the claim (`checkpoint.config_refused`, `detail.code: config.tool_face_control`, `detail.field: inheritedGate`, the row pending). */
toolCeiling?: ReadonlyArray<{
readonly allow?: readonly string[];
readonly deny: readonly string[];
}>;
/** The evidence that the run that spawned this LEG judged its own tool lists (`RunInternals.toolListsJudged`: the digest of exactly
* those lists), stamped at every mint while it holds: a resume that hands no internals and the same lists keeps the judgment, one
* that hands different lists is judged again. Absent ⇒ the leg judged its own lists (or the row was minted before the member). A
* reader that lacks the word would judge again a list judged against a wider universe, and refuse a leg that was valid. */
toolListsJudged?: string;
/** Whose lists this LEG's own are (`RunInternals.ownToolLists`: the delegation tool that spawned it, by its declared name, the
* agent definition it was spawned as — absent ⇒ the tool's tool-level list — and `lists`, the digest of exactly the lists it wrote),
* stamped at every mint while it holds: a resume that hands no internals restores it while its own lists digest to `lists`, so the
* resumed leg asks its own lists of the same universe (which carries that tool's name — a name of its lineage, mounted or not at its
* depth) and a refusal names the same list; a resume that hands another table reads it as the host's own `TaskSpec` seats. Absent ⇒ the
* leg's lists were not written by a delegation tool (or the row was minted before the member): the leg judges them against its own
* roster as before. A reader that lacks the word would refuse a list the leg's lineage wrote, and refuse a leg that was valid. */
ownToolLists?: {
readonly toolName: string;
readonly definition?: string;
readonly lists: string;
};
/** The row's session holds a cross-boundary record (`CROSS_BOUNDARY_RECORD_TYPE`, written before the row is put): a reader must read
* that record to resume the leg under its tree's state. Presence-coded; a capability mark only — the bits live in the session. */
crossBoundaryRecorded?: true;
/** The command sandbox requirement the parked leg ran under (`TaskSpec.sandbox`, as judged — its `~/` paths unread): a resume
* runs under it as a floor beneath whatever its own config states (`resumedSandbox`), so a continuation never runs its commands
* looser than the leg it continues. Absent ⇒ the leg ran under none. A reader that lacks the word would resume the leg's
* commands without the sandbox it parked under. */
commandSandbox?: import("./command-sandbox.js").TaskSandboxSettings;
/** The configuration roots a task layer of the parked leg declared (not the deployment's own): a resume places the rows there again. */
agentConfigDirs?: string[];
/** The caller homes a task layer of the parked leg declared: a resume places the home-anchored rows there again. */
agentHomeDirs?: string[];
/** The parked leg's member ledger book (`TaskSpec.runLedger`; {@link import("./run-ledger.js").RunLedgerParked}): the members it
* dispatched, the calls a check may cite, the accepted claims and the snapshot numbering — the leg that resumes the row continues
* the same book. Written on every park of a leg that keeps a book; absent ⇒ the leg kept none, and a resumed leg that declares a
* ledger starts a new one. A reader that lacks the word would resume the leg with the members dispatched before the park gone
* from its ledger (an older engine refuses the row as newer); a section that does not read is a damaged row. */
runLedger?: import("./run-ledger.js").RunLedgerParked;
/** The parked leg's identity facts ({@link import("./leg-identity.js").LegIdentityRecord}: the task id its host declared, the task that
* spawned it, its tree's root and that root's occupant, its explicit spawn name), stamped at every mint; a resume reads each one
* the resuming call does not hand (live wins), so the resumed leg runs as the leg that parked. Absent ⇒ the leg had none of them, or
* an earlier release minted the row (each then reads as the resume hands it). A reader that lacks the word would resume the leg
* under the resuming call's identities (an older engine refuses the row as newer); a section that does not read is a damaged row. */
legIdentity?: import("./leg-identity.js").LegIdentityRecord;
}
/**
* {@link CheckpointState} with **every** field made required-PRESENT, while each value keeps its original
* type (so an absent optional field is still passed explicitly as `undefined`). The suspend-side
* serialization builds `state` as this type (design/45 P3 / design/51 §P3): adding a new per-task
* correctness field to {@link CheckpointState} is then a **compile error** at the serialization site until
* it is explicitly handled — it can never be silently omitted and lost on resume. (Keying off
* `keyof Required<…>` makes the mapped type non-homomorphic, so it forces presence of every key yet leaves
* each value's `| undefined` intact — `workspaceHandle: undefined` for a process-local suspend still type-checks.)
*/
export type SerializedCheckpointState = {
[K in keyof Required<CheckpointState>]: CheckpointState[K];
};
/**
* design/74 R3-B: cross-slice resource accounting carried by a `resource_limit` {@link Checkpoint}. The
* total budget is the human's allocation; `spent*` accumulate across the resume→re-suspend chain (debited
* at each suspend's `put`). A resumed slice's effective `maxCostUsd` = `min(window, totalBudgetMicroUsd -
* spentMicroUsd)`; the final {@link TaskResult} stats aggregate `spent* + this slice's stats` so a
* multi-slice run reports the whole, not just the last segment. Lives ON the checkpoint row so one
* `resolve`/`put` CAS covers status + ledger atomically (no cross-store split).
*/
export interface ResourceLedger {
/** The human's total $ allocation in micro-USD; `undefined` = no $ ceiling (only window/walltime bound). */
totalBudgetMicroUsd?: number;
/** design/164 — the human's total TOKEN allocation across the whole resume→re-suspend chain;
* `undefined` = no token ceiling (only the per-slice window binds). Replaces the retired wall-clock
* total: tokens are additive across processes, wall-clock across a suspend chain is not. */
totalTokens?: number;
/** Cumulative cost across all slices so far (micro-USD), debited at each suspend's `put`. */
spentMicroUsd: number;
/** Cumulative tokens across all slices so far. */
spentTokens: number;
/** Cumulative turns across all slices so far. */
spentTurns: number;
/** Cumulative wall-clock across all slices so far (ms; each slice measured on the monotonic clock).
* design/164: PURE ACCOUNTING — it is no longer a gate on anything (the wall-clock resource axis
* retired). Kept because "how long did this chain actually run" is a real observability question.
* Absent on checkpoints written before it existed; readers treat missing as 0. */
spentWalltimeMs?: number;
/** How many slices have run so far (the resource chain's suspend count). */
sliceCount: number;
}
export declare function debitLedger(prior: ResourceLedger | undefined, slice: {
costMicroUsd: number;
tokens: number;
turns: number;
walltimeMs?: number;
}, total?: {
totalBudgetMicroUsd?: number;
totalTokens?: number;
}, opts?: {
countSlice?: boolean;
}): ResourceLedger;
/** design/74 Slice 4: the $ budget (micro-USD) the NEXT slice may still spend = `totalBudgetMicroUsd -
* spentMicroUsd`, never negative. `undefined` when no total $ ceiling is set (the run is bounded only by the
* per-slice window / walltime). A resumed slice's effective `maxCostUsd` is `min(window, this)`. NB: `0` is a
* VALID, exhausted ceiling — NOT "unlimited" (only `undefined` is unlimited). Any spend then immediately trips
* `overBudget`, and the run loop fails an exhausted resume fast (runtask). Never falsy-test this value (a
* `if (remaining)` would skip a legitimate 0 ceiling and silently circumvent the budget). */
export declare function remainingBudgetMicroUsd(ledger: ResourceLedger | undefined): number | undefined;
/** design/164 (the TOKEN sibling of {@link remainingBudgetMicroUsd}): tokens the NEXT slice may still
* spend = `totalTokens − spentTokens`, never negative. `undefined` when no token total is set (the run is
* bounded only by the per-slice window / the $ axis). A resumed slice's effective `limits.maxTokens` is
* `min(window, this)` — a resume can't refresh the allocation. NB: `0` is a VALID, exhausted ceiling
* (only `undefined` is unlimited); the run loop fails an exhausted resume fast — never falsy-test it. */
export declare function remainingTokens(ledger: ResourceLedger | undefined): number | undefined;
/**
* design/80 D-1 (reopen-by-reason + persist-winner): the WINNING resume binding, recorded ON the
* checkpoint row the moment a {@link CheckpointStore.resolve} CAS wins (pending → resolved). It is the
* durable record of "which decision was approved against which pending action" so a later reopen→re-resume
* can be validated against it. A `policy_ask` resolve and BOTH review-gate resolves record a winner: only
* `policy_ask` is bound to a specific pending tool call, while `plan_review` / `dry_run_review` record
* their decision under the synthetic `gate:<kind>` marker instead (RB-64). A `resource_limit` / `wake` /
* `task_done` resolve records none (there is no decision to bind). `boundInputHash` (binding the exact executed bytes) is a SEPARATE
* later D-1 slice (1a.2) and is deliberately NOT part of this winner.
*/
export interface ResolvedOutcome {
/** The pending tool call this decision was bound to (design/80 D-1 slice 1a). A REVIEW gate binds
* no tool call, so it records the synthetic `gate:<kind>` marker instead — the replay guard compares the
* DECISION for those, never a call id. */
boundCallId: string;
/** The adjudication the operator made. RB-64 widens this to the review verdicts (`approve`/`reject`/
* `edit`) so a `plan_review`/`dry_run_review` winner can be persisted and replayed by the same
* env_failed reopen guard the approval gate has — previously review gates recorded NO winner, which is
* what left their reopen path with nothing to check a re-vote against. */
decision: "allow" | "deny" | "approve" | "reject" | "edit";
/** A re-written arg payload, if the `allow` rewrote the call (design/37). Carried so an `env_failed`
* re-resume (a system retry of the SAME approved action) must replay the identical `updatedInput`. */
updatedInput?: unknown;
/** The content-ask ANSWER the `allow` carried, if any (ruled 2026-08-04). Recorded for the same reason
* `updatedInput` is: the answer is the SUBSTANCE of a content-ask decision, not a decoration on it, so
* an `env_failed` re-resume — a system retry of the already-approved action — must replay the identical
* answer. Without it the replay could keep the verdict and swap the answer text going into the model's
* context (the shape the plan-edit replay guard closed for `editedPlan`). Omitted when absent so the
* replay equality check does not falsely diverge on `undefined`. A decline is recorded here the same way. */
answer?: QuestionResponse;
/** The operator's NOTE, if the decision carried one — the approval lane's deny `reason` and the review
* lanes' reject `reason` alike. Recorded for the same reason `updatedInput` and `answer` are: the note
* is the substance of the decision, not a decoration on it. It is the text the resume continuation
* fences into the model-facing reminder that carries the refusal, so a replay keeping the verdict and
* swapping the note delivers a different instruction under the same word. Omitted when absent.
*
* ADDITIVE and OPTIONAL by contract: rows persisted before this field existed carry no `reason` key,
* and the key's absence is read as "this dimension was never recorded" — the replay guard skips it —
* NEVER as "recorded as empty", which would refuse every legitimate retry of an existing row. Absence
* is therefore indistinguishable from a genuinely note-less decision, which is the accepted price of
* the additive shape: the binding starts with the rows that record it.
*
* RECORDED VERBATIM, and independently of the verdict: any supplied note is kept exactly as given —
* including `""`, and including a note on a verdict that never relays one (an `allow`, an `approve`, an
* `edit`). The winner is a record of the decision that was made, not of the subset of it the
* continuation happens to render, and `updatedInput` has carried the same property since D-1 (a rewrite
* on a `deny` is recorded and replay-compared although nothing executes it). Normalizing here would
* mean an empty note collapsed into the "never recorded" hole above and a note on a non-relaying
* verdict became free to change between the resolve and its replay — both weaken "the retry presents
* the same decision" for no delivery benefit, since a replay is produced by re-presenting the same
* outcome, not by reconstructing an equivalent one. */
reason?: string;
/** The approving person's FEEDBACK, if the `allow` carried any — recorded exactly as supplied (a blank value included)
* and bound by the replay equality on the same ADDITIVE rule as {@link reason}: absence means "never recorded". No
* reader requirement word guards it: `resolvedOutcome` is a store-written state-machine member, never minted with the row. */
feedback?: string;
/** The mode an approved or edited `plan_review` exits the plan to, as the approval named it (`outcome.permissionMode`): the
* substance of the approval, bound by the replay equality on the same ADDITIVE rule as {@link reason} (absence = never recorded:
* a winner of a decision that named none, or one written before the member, leaves the mode unbound on a retry). */
permissionMode?: PermissionMode;
/** The settlement record core minted for this decide ({@link import("./gate-outcome.js").GateOutcome}):
* the row's own copy of what the resolved call's `tool_end` frame carries, written with the winner so
* an audit reading the row reads the same record the stream carried. NOT part of the replay equality
* (`when` differs per replay; the record is a consequence of the decision, not its substance). */
gateOutcome?: import("./gate-outcome.js").GateOutcome;
}
/** Why a consumed checkpoint was reopened — declared beside the one table that picks it. */
export { REOPEN_REASONS, type ReopenReason } from "./resume-startup-cause.js";
/**
* design/80 D-1 (atomicity fix): the optimistic-concurrency precondition a {@link CheckpointStore.resolve}
* caller passes so its CAS is atomic with the validation it did against an earlier `get()` snapshot. The
* resume-side decision-action guards (boundCallId/boundInputHash) bind to per-token-IMMUTABLE fields, but the
* **reopen-by-reason** guard reads `reopenReason` + `resolvedOutcome` — which a concurrent
* {@link CheckpointStore.reopen}/{@link CheckpointStore.resolve} cycle mutates. Passing the monotonic
* {@link Checkpoint.rev} the caller observed makes `resolve` additionally require the LIVE row's `rev` to still
* equal it; ANY intervening resolve/reopen bumps `rev`, so a cycle in the get→resolve window loses the CAS
* (fail-closed), forcing a re-`get` + re-validate.
*
* **Why a counter, not the reopenReason value (round-2 BLOCKER fix):** `reopenReason` is a 2-valued enum, so a
* full `env_failed`→`tool_unavailable`→`env_failed` cycle (the `tool_unavailable` arm permits a fresh P-7
* re-decision) returns `reopenReason` to the SAME value while `resolvedOutcome` silently changed to a different
* (e.g. RETRACTED) winner — a classic ABA on the OCC key. A monotonic `rev` bumped on every resolve/reopen is
* ABA-proof: a returned-to-the-same-value `reopenReason` still has a strictly higher `rev`. Omit `expect`
* (legacy callers / direct store tests) → no OCC.
*/
export interface ResolveExpectation {
/** The monotonic {@link Checkpoint.rev} the caller observed at `get()`, read through {@link checkpointRevOf} (absent rev ⇒ legacy `0`). */
rev: number;
/**
* The deployment's credential for the claim the resolving run acts under (`RunInternals.holder`, carried verbatim — the engine
* never judges, stores or prints it). Every member of this object is a precondition the store evaluates in the SAME atomic step
* as the flip: the CAS wins only if the grant `holder` names is still the deployment's current one at that instant (no claim
* transfer may commit between the judgement and the flip). Judged only by a store that declares {@link CheckpointStore.fence}
* `{ holder: "writes" }`; any other store LOSES a CAS that carries one (never ignores it — `checkpointHolderMatches`). A miss is an ordinary
* loss: the row is untouched, so it reads `pending` at the generation the caller validated.
*/
holder?: string;
}
/** design/384 slice 2 / S-25-R1 — the terminal intents a claim can carry. Deliberately the
* TERMINAL pair only: `resolve` and `expire` are the two verbs that race one pending row to
* its end (the design/51 fence law). `reopen` (resolved→pending) is not terminal and `reap`
* is a bulk sweep — both stay on their own verbs. */
export type TerminalClaimIntent = {
kind: "resolve";
outcome: ResumeOutcome;
expect?: ResolveExpectation;
}
/** `expect.holder`: the expire arm's grant holder, the same precondition as {@link CheckpointStore.expire}'s `opts.holder` — a holder
* that is not current loses, the loss reading the row as it is (`pending` at its generation). */
| {
kind: "expire";
expect?: Pick<ResolveExpectation, "holder">;
};
/** The options of a checkpoint write that has no row expectation of its own (`put`, `setPendingSteer`, `expire`). */
export interface CheckpointWriteOptions {
/** The run's grant holder (`RunInternals.holder`, verbatim — the engine never reads it), judged by a store declaring
* `fence = { holder: "writes" }` in the write's own atomic step ({@link CheckpointStore.fence}); absent ⇒ nothing to judge. */
readonly holder?: string;
}
/** design/384 slice 2 / S-25-R1 — the single-round-trip answer: EITHER the claim won, OR it lost and
* the SAME atomic operation reports what the row is now. `current` reuses the row's own vocabulary
* (status / rev / resolvedOutcome) — no new value domain. `status:"pending"` on a loss is one of the
* two expectation arms: a `rev` other than `expect.rev` is the OCC arm (the row is still open — re-get +
* re-validate, zero backoff; a cleanly KNOWN state is never "unknown"); `expect.rev` itself means the
* row did not move and the claim holder (`expect.holder`) was not current. */
export type TerminalClaimOutcome = {
claimed: true;
} | {
claimed: false;
current: {
status: "pending" | "resolved" | "expired";
/** {@link checkpointRevOf} — the absent-rev-reads-as-0 rule the OCC key already uses. */
rev: number;
/** Row-field PASSTHROUGH on every present status: the row PRESERVES it across `reopen`
* (resolved→pending rows carry it), `expire` never clears it, and a winnerless resolve
* (resource/wake/task_done) does not overwrite an older value — so even
* `(status:"resolved", outcome present)` is only "the row is resolved AND this is its
* LAST RECORDED decision winner", never a store-level guarantee that THIS resolve minted
* it. Interpreting the pair as a current decision is the CALLER's discipline (the
* runner's gate-kind matching; a single-decision row schema like a deployment's ask
* rows). See {@link CheckpointStore.claimTerminal} law 6. */
resolvedOutcome?: ResolvedOutcome;
}
/** Row missing — OR wrong scope: the CAS predicate is the shared REF-A4 row match
* ({@link checkpointRowMatches}), and a wrong-scope claim must lose WITHOUT reporting the
* row's truth (multi-tenant isolation: cross-scope truth in a loss answer would be a read
* bypass of the scope WHERE). Absent is a KNOWN state (zero backoff): expire intent ⇒ moot;
* resolve intent ⇒ the caller's typed not-found path, no retry. */
| {
status: "absent";
};
};
/** A persisted suspension point: enough to resume a task on any replica. `status` drives the 3-state
* machine (pending → resolved | expired) that makes resume idempotent (§5). */
/** A durable checkpoint: the row's fields ({@link CheckpointRow}) plus its registry-bound pause pair. */
export type Checkpoint = CheckpointRow & CheckpointPause;
export interface CheckpointRow {
token: CheckpointToken;
/** Non-secret stable identity ({@link mintCheckpointId}) — the display/correlation twin of
* the secret `token` (identification vs capability, separate axes). Present on every row minted
* since its introduction; absent ⇒ legacy row (read compatibly, no backfill). It is the row's one question identity, and the
* join key to the card the row came from: the card's `AskRequest.checkpointId` is this value exactly when the approver answered
* `"unavailable"` and the row parks the bytes that answer was bound to (otherwise the row mints its own, {@link import("./runner/deferred-ask.js").parkedAskIdentity}). */
checkpointId?: string;
/** THE SYNCHRONOUS-CHILD BLOCK — four members ({@link parentSessionId}, {@link parentTaskId}, {@link rootSessionId}, {@link rootSessionIncarnation}),
* written by earlier releases onto every row a synchronous child parked, and absent from a root run's row, a background agent's and a
* workflow agent's. No release mints it now: a synchronous child's parks are not minted at all (nobody resumes that leg —
* `approvalParkNotResumableOf`), so the block survives only on rows parked before; their listing and decision faces refuse such a row
* (`checkpoint.unsupported_version`, reason `leg_not_resumable`: the row judge reads the block's presence). They name where the parked
* leg came from, in the spelling of the run internals they were read from.
* The session the parked leg was spawned by ({@link import("./runner/contracts.js").RunInternals.parentSessionId}). */
parentSessionId?: string;
/** The task the parked leg's parent ran as, ONLY when the leg is a synchronous child ({@link import("./contracts.js").RunInternals.parentTaskId}) —
* written beside {@link parentSessionId}, from the same leg facts. */
parentTaskId?: string;
/** The ROOT host session of the leg's delegation tree ({@link import("./runner/contracts.js").RunInternals.rootSessionId}) — the anchor a
* consumer addresses the tree's owner by when the immediate parent is no longer running. Part of the block ({@link parentSessionId}). */
rootSessionId?: string;
/** The occupant of {@link rootSessionId}'s row as the tree's root run acquired it ({@link import("./runner/contracts.js").RunInternals.rootSessionIncarnation}) —
* the other half of the root anchor's address. Part of the block; absent when the root run recorded none. */
rootSessionIncarnation?: string;
/**
* Schema version of this checkpoint (design/49 v1.5), FROZEN at the row format, 10: every live mint
* stamps 10 beside {@link requires}, and a segment added later adds a word there, never a number here. A row
* below it (absent ⇒ `0`) is refused pre-CAS as a retired seat, a row above it as newer. Read via {@link checkpointVersionOf}.
*/
version?: number;
/** The reader-requirement words of a v10 row: what a resuming worker must know to resume it right, derived from
* the row's own content at the mint (`checkpointRequirementsFor`, checkpoint-requirements.ts) — present on every
* v10 row (possibly empty), absent below. Typed as plain strings: a newer release's word is a word this one lacks. */
requires?: readonly string[];
/** The row digest of a v10 row: sha256 over the canonical JSON of every member a decision reads (`requirementsDigestOf`,
* checkpoint-requirements.ts) — a lost member, element or changed value is refused `requirements_damaged`. */
requirementsDigest?: string;
/** Multi-tenant isolation key (forced through `resolve`/`reap` WHERE, §2.1 service [4]). */
scope: string;
/** The session to resume (via the SessionStore). */
sessionId: string;
/** The session leaf the suspend happened at — the resume point (CAS write base, §5). */
leafId: string;
/** The conversation rows the leg had admitted but not yet stored when it parked (a note an extension added while the turn
* ran), in the order they were admitted — what the conversation owes after {@link leafId}. Written by the park's commit
* alone, in the same step as the row; the resumed leg writes each once, at its transcript's first legal point (after the
* parked batch's last result, before the continuation), never through the admission seat again. Absent ⇒ none were held;
* present ⇒ the row carries the `held_rows` requirement word. */
heldRows?: readonly AgentMessage[];
state: CheckpointState;
/** design/74 R3-B: cross-slice resource accounting. Present for a `resource_limit` gate (debited at the
* suspend's `put`; read on resume to size the next slice + aggregate the final stats). **design/80 D-E-core
* (A3):** ALSO attached to a human/irreversible_ask APPROVAL suspend — debited with that leg's spend — so a
* STATELESS policy can read durable cumulative spend across the resume chain via {@link ToolCallRequest.budget}
* (a fresh in-memory counter would reset every leg). On the approval path it is READ-CONTEXT ONLY: the final
* -stats aggregate fold (runtask) is gated to the `resource_limit` gate kind, so an approval resume is never
* double-counted. Absent for `task_done`. See {@link ResourceLedger}. */
resourceLedger?: ResourceLedger;
/**
* Absolute epoch-ms deadline for an awaiting-human checkpoint; past it, `reap` expires it (§6).
*
* **design/80 §D-D semantic contract (the DURABLE FIELD a reaper-loop consumes — read it on
* {@link CheckpointStore} too):** for an APPROVAL gate (`gate.kind` ∈ {`human`, `irreversible_ask`}) the
* deployment's reaper-loop treats this as an **SLA resolve-deny** time (FACET A — its fast path: at deadline
* it `resolve`s the checkpoint as a `deny` so the run ends cleanly), with a LATER `terminalAt` abandonment
* backstop the loop ALSO honors (crash-safe if the SLA timer never fired). For an UNATTENDED-TTL gate
* (`gate.kind` ∈ {`resource_limit`, `needs_review`, `plan_review`} — the resource + review-pause family) this
* is an **abandonment-TTL** → `expire`/{@link reap} ONLY, NEVER a resolve-deny (FACET B — those kinds resume
* only with their OWN outcome, so a `policy_ask` resolve-deny hits no `gateMatch` arm → `gate_mismatch`). The
* reaper-loop + the gate.kind policy + minting `terminalAt` are the DEPLOYMENT's job
* (its store impl + loop — owned service-side); CORE only guarantees this `deadline`
* field (for `human`/`irreversible_ask`) + the persisted {@link gate}.kind survive the round-trip so any
* reaper consumer (the service's TiDB loop OR a non-service Pg deployment) implements the SAME contract.
*/
deadline?: number;
status: "pending" | "resolved" | "expired";
createdAt: number;
/**
* How many times THIS task has suspended, counting this checkpoint (1 = first suspend; design/72
* §2.2 (B)). Carried forward across resume→re-suspend (each new checkpoint = the prior count + 1), so
* a restart-prone model that keeps re-issuing the gated/egress call — re-suspending every resume —
* is capped: past `maxSuspends` the run fails (`suspend.loop`) instead of minting another checkpoint
* and looping forever. Absent ⇒ legacy `0` (pre-§2.2 checkpoints; treated as "no prior suspends").
*/
suspendCount?: number;
/**
* design/91 — the wall-clock instant (epoch ms, from {@link import("./types.js").RunnerDeps.now}) this task
* suspended at a HUMAN-REVIEW gate. Resume derives the human-review latency for this leg as
* `now() − suspendedAt` and folds it into `TaskResult.stats.humanReview` (the design/89 §2.4 C2 burden axis).
* The human-review family is the APPROVAL gates (`gate.kind` ∈ {`human`, `irreversible_ask`}) — core stamps
* this automatically on the approval-suspend mint — AND the REVIEW-PAUSE gates (`needs_review` = a dry-run
* diff review, `plan_review` = a pre-action PLAN review). Review-pause checkpoints are minted by a PROFILE
* (core owns only the routing/resume discriminants), so a profile that wants the C2 wait counted MUST stamp
* `suspendedAt = deps.now()` at mint — the same injectable clock the resume reads, so a test pins the latency.
* Absent on a `resource_limit` suspend (a machine backstop, not a human wait), on a review-pause checkpoint
* whose profile did not opt in, and on a legacy pre-design/91 checkpoint (⇒ resume skips the durable latency
* for that leg — no undercount surprise, just no entry).
*/
suspendedAt?: number;
/**
* design/91 — the accumulated {@link import("./types.js").TaskResult.stats}`.humanReview` from all PRIOR legs,
* carried forward across resume→re-suspend (like {@link suspendCount} / {@link resourceLedger}) so a
* multi-leg suspend/resume chain reports the WHOLE human-review burden, not just the last leg's. It holds
* the gates resolved up to and including the suspend BEFORE this one — the latency for THIS suspend is added
* by the resume that wakes it (`now() − suspendedAt`). Every row the engine mints carries it, `count: 0` on a
* chain no gate waited on a person in yet ({@link import("./task-result.js").TaskResult.stats}`.humanReview`, one
* shape); absent only on a row an older engine minted, which a resume reads as zero. Budget-EXCLUDED side
* observable — never a cost/gate input.
*/
humanReview?: {
count: number;
totalWaitMs: number;
gates: import("./task-result.js").HumanReviewGateRow[];
};
/**
* design/80 D-1 (persist-winner): the winning resume binding, recorded by {@link CheckpointStore.resolve}
* when its CAS wins (pending → resolved) — present after a `policy_ask` resolve and after either REVIEW-gate
* resolve (`plan_review` / `dry_run_review`, RB-64); absent on a freshly minted pending checkpoint and on
* `resource_limit` / `wake` / `task_done` resolves. PRESERVED (never cleared) across a
* {@link CheckpointStore.reopen} so an `env_failed` re-resume can be validated against it. See
* {@link ResolvedOutcome}.
*/
resolvedOutcome?: ResolvedOutcome;
/**
* design/80 D-1 (reopen-by-reason): why this checkpoint was last reopened (resolved → pending), recorded
* by {@link CheckpointStore.reopen}. Drives re-resume validation (§3 invariant #1): `env_failed` ⇒ the
* re-resume must replay the persisted {@link resolvedOutcome} winner (a system retry of the approved
* action); `tool_unavailable` ⇒ a fresh operator decision is allowed (P-7 re-decide with the tool
* present). Absent on a never-reopened checkpoint (a first resume is unconstrained by reason).
*/
reopenReason?: ReopenReason;
/**
* design/80 D-1 (atomicity fix, round-2 BLOCKER): a **monotonic revision counter** bumped by exactly one by EVERY
* {@link CheckpointStore.resolve} (won) and {@link CheckpointStore.reopen}, by an identity re-key ({@link CheckpointStore.rekeyIdentity}), and by every queue entry
* {@link CheckpointStore.setPendingSteer} adds. It is the optimistic-concurrency key ({@link ResolveExpectation}): a resume reads it at `get()` and `resolve` requires the live `rev` to
* still equal it, so any write landing on the row in the get→resolve window — a resolve/reopen cycle, a re-key, an appended input — loses the CAS (fail-closed). The claim's
* compensation reads the same key: the generation a won resolve produced is one above the one it read
* (`checkpointClaimRevOf`), and `reopen` carrying it gives back only that claim's row.
* Unlike the 2-valued `reopenReason`, it cannot ABA back to a prior value. Absent ⇒ legacy `0` (a checkpoint
* minted before this field; treated as never mutated) — read it through {@link checkpointRevOf}.
*/
rev?: number;
/**
* design S1d (source-tag persistence): the issuing leg's session id, stamped at the APPROVAL and the
* plan_review suspend mints so a supervisor inbox can attribute a paused/awaiting checkpoint to the worker that
* raised it (the durable analog of {@link import("./tool-policy.js").AskRequest}.sourceSessionId — the durable
* suspend path does NOT invoke `onAsk`, so the synchronous source identity is captured here instead). It is
* the SAME value the synchronous ask carries, read from the same one mint. It names a conversation, never a
* task: the parked leg's agent id is {@link CheckpointSummary.agentId}, derived from the row.
*
* **Security invariant (carried verbatim from the 1.113.0 ask-bubbling contract):** for a Runner-created
* DELEGATED subagent this is **worker-unforgeable** (a child never sets its own sessionId — the Runner mints
* it); a top-level caller MAY continue its own session id via {@link import("./types.js").TaskSpec.sessionId},
* so this is NOT a global "never forgeable" run id — aggregation only aggregates delegated workers, where it
* holds. **ECHO-ONLY triage metadata, NEVER a gate input:** no gate / CAS / winner / resume-validation path
* reads it (a contract-test pins this). A row that carries it requires `source_session` (an older engine
* refuses it). Present exactly on an ask-origin row (`tool_approval` / `plan_review`), stamped since 7.61.0; absent on a non-ask gate (`resource_limit` / `needs_review` / `task_done`: no ask is behind them, the engine's `resource_limit` mint stamps none) and on a row an earlier engine parked (it named the member `sourceTaskId`); a consumer reads it on an ask-origin row only (INTEGRATION-CORE §1.6a).
*/
sourceSessionId?: string;
/**
* design S1d (source-tag persistence): the issuing task's authenticated end-user {@link
* import("./types.js").TaskSpec.principal} (design/62), stamped at the APPROVAL suspend mint — and, since
* #449 G2, at the `resource_limit` mint too — so an aggregating inbox can attribute a paused checkpoint
* per-user — the durable analog of {@link import("./tool-policy.js").AskRequest}.principal. Caller-set
* (never a tool/worker arg), and like {@link sourceSessionId} it is **NEVER a gate input**: no gate / CAS /
* winner path reads it. The RESUME ENTRY however does read it as the row's identity record (#449 G2):
* a resume config that omits `principal` inherits this value for the resumed leg (usage-ledger bucket,
* later mints' scope derivation, ask attribution — a dropped field must not silently move the leg onto
* the SHARED usage bucket), and a resume config carrying a DIFFERENT non-empty principal is refused
* pre-CAS (`resume.principal_mismatch`). Absent ⇒ no principal (a legacy checkpoint, an unauthenticated
* task, or a gate kind that predates the stamp). Rolling-deployment note (#449 G2 residual): the field
* is NOT version-gated — an older worker accepts a principal-bearing row and keeps its historic
* behavior (no fallback, no mismatch refusal); the identity-continuity guarantee holds once the fleet
* is on enforcing workers. Version-gating it is a recorded design candidate: the lattice's newest rung
* (design/199) encodes "v>=9 ⟺ face section present", so ANY new version above it must rewrite that
* guard's window form and add its own presence invariant — a lattice-wide change, not a stamp.
*/
principal?: string;
/**
* The issuing task's {@link import("./types.js").TaskSpec.isolationScope} — the partition of the person's work this
* row is working state of — stamped beside {@link principal} at the same mints, and only when it is present and
* differs from the principal (a row without it reads its partition as its principal, so the common shape records
* nothing new). Like `principal` it is never a gate / CAS / winner input; the RESUME ENTRY reads it the same way:
* a resume config that omits `isolationScope` inherits this value, and one carrying a DIFFERENT non-empty value is
* refused pre-CAS (`resume.isolation_scope_mismatch`). Unlike `principal` it IS gated: the row's requirement words
* name it (`isolation_scope`), so a worker that cannot read the member refuses the row instead of resuming it in the
* person's bucket. A member holding `undefined` is no member: the stamp writes the row without the key, the row judge
* and both resume readers read the VALUE, and a store of JSON fidelity (the file twin) never holds the key — no reader
* tells "written as undefined" from "absent".
*/
isolationScope?: string;
/**
* design/153 §7.4 (1.389.0, RB-42②③): the VERBATIM `TaskSpec.durableApproval` opt-in in force at this
* APPROVAL suspend's mint — the engine-recorded provenance of "this task was durable-approval armed, with
* this scope and this reaper TTL" (an identity re-key re-files its `scope` and nothing else of it). Consumed by the parked-resume drive's REVIVE-CONTINUITY re-derivation
* (subagent settle path): the drive spec carries no forwarding seat, so without this record a resumed leg's
* SECOND plain ask would headless-deny instead of re-parking. Reading it explicitly (instead of inferring
* the opt-in from `gate.kind === "human"`) covers a SAFETY-TIER first park (irreversible_ask — the kind
* alone never proved the spawn opted in) and carries `ttlMs` across the re-park so the re-minted
* checkpoint re-arms its reaper `deadline` (previously unbounded). Absent ⇒ the mint ran with NO
* `durableApproval` (an unattended safety suspend, a non-ask gate, or a legacy pre-1.389 checkpoint — the
* consumer then falls back to the human-kind scope-only inference for legacy rows and injects NOTHING for
* unattended parks, so a spawn that never opted in can never gain the opt-in through a resume). Engine-
* minted from the task's own spec — a worker/tool cannot self-declare it (`durableApproval` never rides tool args).
*
* `false` on a RESOURCE row: the host declared that this run's decision parks cannot be resumed (`TaskSpec.durableApproval: false`) —
* a resume whose config states no `durableApproval` keeps that word (the resume entry reads it back), and only a config that states an
* opt-in object lifts it. A decision park is never minted under that word, so no approval row carries it.
*/
durableApproval?: {
scope: string;
ttlMs?: number;
} | false;
/**
* @contract checkpoint.execution_outcome — the settlement record of how the DECIDED action was
* finally disposed on the resumed leg: the {@link GateOutcome} the resumed call's `tool_end` frame
* carried (an executed allow, a person's refusal delivered, or a post-CAS belt's veto of a person's
* yes), written by {@link CheckpointStore.recordExecutionOutcome} exactly once per row, on every
* resolution (an `allowed` disposition is recorded too — the column's absence has ONE meaning:
* the execution outcome is not known, never "it was allowed"). Independent of
* {@link resolvedOutcome}, which stays the immutable record of the DECISION: a row can read
* `resolvedOutcome.gateOutcome.disposition.kind === "allowed"` beside
* `executionOutcome.disposition = { kind: "denied", deniedBy: "policy" }` — the person approved,
* the deployment's belt refused the edited call — and a reader rebuilding the run from the row
* sees both facts instead of the pre-execution one alone. The record is physically immutable:
* a second write of a different record is a conflict, never an overwrite, and a row carrying one
* cannot be {@link CheckpointStore.reopen | reopened} (the action is settled; a reopen would
* re-run or re-decide work whose outcome is already on file). Read through
* `executionVerdict` (checkpoint-execution-record.ts). Present together with {@link executionAtMs}.
*/
executionOutcome?: GateOutcome;
/** Epoch ms the store stamped {@link executionOutcome} at. Present iff `executionOutcome` is. */
executionAtMs?: number;
}
/**
* The immutable, indexable facts of one checkpoint row: what core minted on it and nothing later moves but an identity
* re-key, which re-files `scope` ({@link CheckpointStore.rekeyIdentity}). A backend that keeps columns beside the stored row
* writes them from {@link checkpointIndexFacts} of the row it writes, the one derivation — at `put` and at the re-key alike. Not here: the
* state the CAS faces move (`status`, `rev`, `reopenReason`, the execution record), values a deployment mints (an
* abandonment backstop), display projections a deployment bounds or redacts, and the deadline FACET — a reading of the
* pause registry, which a stored copy would freeze ({@link import("./pause-registry.js").CARD_FACET_OVERRIDES}).
* Every member is present; `null` = the row carries none.
*/
export interface CheckpointIndexFacts {
readonly token: CheckpointToken;
readonly scope: string;
readonly sessionId: string;
/** `checkpointRunSessionOf` of the row (`null` = no run: never matched) — the column `CheckpointSessionQuery.axis: "run"` reads. */
readonly runSessionId: string | null;
/** {@link checkpointVersionOf}. */
readonly version: number;
readonly gateKind: CheckpointGate["kind"];
/**
* The approval gate's stored card word AS STORED: a member of `TOOL_APPROVAL_CARDS`, or a string outside it (kept, so
* a later engine that knows the word reads the column right); `null` for a non-string, no card, or a gate that is not
* an approval. Never a derived facet: a facet predicate over this column is generated from `CARD_FACET_OVERRIDES` (its
* keys `IN (…)` take the key's facet, anything else the gate kind's). Read off the gate alone — independent of the
* pending action's own members (offers, the absence word), so a backfill of one never presumes the other's.
*/
readonly approvalCard: string | null;
/** The pending tool call's name, id and bound input hash (a `tool_approval` pending action only). */
readonly toolName: string | null;
readonly toolCallId: string | null;
readonly boundInputHash: string | null;
/** The deadline as the reap verbs read it (`checkpointDeadlineColumn`): `null` = none; a deadline the row carries but that is not a
* finite number (a JSON-held `NaN` reads back as `null`) is `Number.MIN_SAFE_INTEGER`, past every cutoff — compare `deadline <= cutoff`. */
readonly deadline: number | null;
readonly createdAt: number;
/** The approval gate's descriptor, the row's own object (display only; serialize it, do not mutate it). */
readonly riskDescriptor: RiskDescriptor | null;
/** The park mint's directional-control bit, presence only: `true`, or `null` — not recorded, never "clean". */
readonly hasBidiControls: true | null;
}
/** Derive a row's {@link CheckpointIndexFacts}. Pure: reads no clock, writes nothing; the approval card is read
* through {@link parkedApprovalCardOf} (the one card reading), the tool fields only off a `tool_approval` action.
* Refuses (`config.invalid_argument`, naming the member) a row whose `gate` or `pendingAction` is not an object of plain data —
* absent, `null`, a scalar, a list, or a record that is an accessor, a Proxy or of another prototype — instead of throwing a bare
* `TypeError` from one read or deriving columns from a scalar's missing members; a gate or pending action of a kind this engine does
* not know is still derived (its words are kept for a later engine to read). */
export declare function checkpointIndexFacts(cp: Checkpoint): CheckpointIndexFacts;
/**
* A checkpoint row's own answer to "does anything in this row keep this engine from resuming it" — every refusal of the
* resume ladder the row and this engine decide alone, ahead of every deployment fact, resume input and decision
* (`judgeCheckpointRow`, checkpoint-row-verdict.ts). The resume throws it at its first rung; a listing carries it
* ({@link CheckpointSummary.rowVerdict}). `ok` is not "the resume will run": a deployment fact (an env factory, organization
* governance), a resume input or the decision can still refuse it then.
* - `lacking` ⇔ `code` `checkpoint.unsupported_version` with `reason` `version_newer`: a newer engine can resume it;
* `requires` names the reader words this engine lacks when the row's requirement list named them (words only, at most
* eight, never the row's token).
* - `damaged`: this engine does not resume these bytes; `code` / `reason` are the resume's refusal, `sentence` its fixed
* engine sentence (the resume's error `message` starts with it and goes on with the row's own diagnostic).
* `field` and `blockedBy` are the refusal's own `detail.field` and `detail.code` (the verdict's `code` is the error's), same words, same
* types, present exactly when the refusal states them: the recorded-word arms (a row whose `inheritedGate`, run origin or frozen tool
* names this engine does not read: `checkpoint.config_refused`, `field` `"inheritedGate"`, `blockedBy` the word a fresh run of the same
* bad value reports — `config.permission_mode_invalid`, `config.run_origin_invalid` or `config.tool_face_control`). Every other arm —
* named by its `reason`, or by its `code` where it has none — omits both.
* `terminal` (a boolean on every `lacking` / `damaged` verdict): `true` = no engine release resumes the row (the host's to expire); `false`
* = another release can (the sentence says which). Either way it is final on THIS engine (`kind`); `terminal` says only that.
* A consumer that meets a `kind` it does not know reads it as not `ok`.
*/
export type CheckpointRowVerdict = {
readonly kind: "ok";
} | {
readonly kind: "lacking" | "damaged";
readonly code: CheckpointError["code"];
readonly reason?: CheckpointErrorReason;
readonly field?: CheckpointErrorField;
readonly blockedBy?: CheckpointConfigRefusalCode;
readonly requires?: readonly string[];
readonly sentence: string;
readonly terminal: boolean;
};
/**
* design/80 assistant-scheduler seam #1: a LIGHTWEIGHT projection of one PENDING
* checkpoint, returned in bulk by {@link CheckpointStore.listByScope} so a supervisor scheduler can list a
* scope's suspended/awaiting tasks in ONE call (no N+1 `get`s, no full-{@link Checkpoint} payloads). It is a
* read-only DISPLAY/triage summary — every field is DERIVED from the persisted {@link Checkpoint}; nothing
* here is a new source of truth or a gate input.
*/
export interface CheckpointSummary {
/** The resume capability token ({@link Checkpoint.token}). */
token: CheckpointToken;
/** ALWAYS present — the row's own answer to whether anything in it keeps THIS engine from resuming it
* ({@link CheckpointRowVerdict}; `judgeCheckpointRow`): the verdict the resume throws at its first rung, so a row this engine
* refuses is not listed as an approvable card. `ok` is not "the resume will run": a deployment fact, a resume input or the
* decision can still refuse it at the resume. Engine text and closed words only — no row content.
*
* **A ROW THE PROJECTION CANNOT READ** (a record the row lacks or holds as something else, a member that throws when read) is
* still ONE row of the listing, never a failed page: its `rowVerdict` is never `ok` (the judge's verdict, else `damaged` /
* `requirements_damaged`), it carries `token`, `sessionId` and `scope`, and — each only when it reads — `gateKind`, `resourceLimit`,
* `createdAt` and `deadline`; it carries no other member. A consumer renders such a row by its `rowVerdict`. */
rowVerdict: CheckpointRowVerdict;
/** Non-secret stable identity ({@link Checkpoint.checkpointId}) — absent on legacy rows. */
checkpointId?: string;
/** The synchronous-child block of the row ({@link Checkpoint.parentSessionId} and its three companions): the session and task that spawned the parked leg and the
* delegation tree's root session with its occupant — each OMITTED when the row records none (a root run's, a background agent's or a workflow agent's row, a row an earlier engine parked). */
parentSessionId?: string;
parentTaskId?: string;
rootSessionId?: string;
rootSessionIncarnation?: string;
/** The suspended task / session id ({@link Checkpoint.sessionId}). */
sessionId: string;
/** The multi-tenant scope this checkpoint lives in ({@link Checkpoint.scope}) — always equal to the query's. */
scope: string;
/** The gate's discriminant ({@link CheckpointGate}.kind): which kind of pause this is. Present on every row the projection reads;
* OMITTED only on a row whose gate does not read (see {@link rowVerdict}), whose verdict is then not `ok`. */
gateKind?: CheckpointGate["kind"];
/** Why a resource park is parked: the gate's `reason`, a member of {@link RESOURCE_LIMIT_REASONS} — present ⇔ {@link gateKind} is
* `resource_limit` and the row's word is a member (on both forms). A word outside the set (an earlier engine's `budget`) or none
* reads as absent: a park whose cause this engine does not know — not a preempt, not a budget. `resumableAt` (epoch ms, as
* {@link createdAt}) only beside `usage_window`: `createdAt` + the gate's `resumeAfterMs` (the mint takes the hint, then stamps
* `createdAt`), absent when the gate has no hint, a number does not read finite, or the sum is past what a `Date` holds (|t| > 8.64e15).
* A resume before it is allowed: a bare continue that meets the window still closed parks again with a fresh hint, no model call.
* ECHO-ONLY ({@link resourceLimitOf}). */
resourceLimit?: {
readonly reason: ResourceLimitReason;
readonly resumableAt?: number;
};
/** The deterministic risk tier (1..5) when the gate carries a {@link RiskDescriptor} (the `human` /
* `irreversible_ask` approval escalations), derived via {@link riskSeverity} from the descriptor's axes —
* the SAME value as `gate.riskDescriptor.severity`, recomputed from the single source helper rather than
* re-stored. `undefined` for a gate with no descriptor (resource_limit / needs_review / plan_review / a
* legacy human ask minted before D-E). The inbox sorts DESC by this. Also `undefined` for a descriptor whose axes
* prove no tier (not a plain record, or damaged marks and no valid `true` one) — damage, not a low risk: the
* projection then calls its `disclose` once, so such a row does not sink below the graded rows unannounced. */
severity?: 1 | 2 | 3 | 4 | 5;
/** Cumulative spend debited to this suspend chain ({@link ResourceLedger.spentMicroUsd}) in micro-USD —
* present whenever the checkpoint carries a {@link Checkpoint.resourceLedger} (every resource_limit suspend,
* and every approval suspend on the D-E-core budget-read path); `undefined` when no ledger is attached. */
spentMicroUsd?: number;
/** The awaiting-human SLA / abandonment deadline ({@link Checkpoint.deadline}, epoch ms) when it is a finite number (a stored `NaN` or a value of another type is left off, not echoed). */
deadline?: number;
/** design S1d (source-tag): the issuing worker's session id ({@link Checkpoint.sourceSessionId}) — projected so a supervisor inbox attributes each pending checkpoint
* to its worker in ONE `listByScope` call (no N+1 `getCheckpoint`). ECHO-ONLY display/triage; present exactly on an ask-origin row (`tool_approval` / `plan_review`), absent on a non-ask gate and on a row an earlier engine parked ({@link Checkpoint.sourceSessionId}). */
sourceSessionId?: string;
/** The parked leg's agent id when it is a delegated child (the parked twin of {@link import("./tool-policy.js").AskRequest}.agentId): the ask's predicate
* over the row's {@link CheckpointState.legTaskId} and {@link CheckpointState.isDelegatedChild}, the value the leg's asks carried; absent on a host's row.
* A row minted before the task id member reads its registry row, else its session id (a workflow agent's declared `taskId` unread). ECHO-ONLY display/triage. */
agentId?: string;
/** The parked twin of {@link import("./tool-policy.js").AskRequest}.sourceAgentName: the row's record ({@link CheckpointState.sourceAgentName}),
* echoed as stored when it is a string: a named helper's spawn name (the literal its fleet row carries), an unnamed helper's Agent call
* description (not the literal its fleet row carries). Absent on a host's row, a row minted before the member, and one whose
* record is no string. UNTRUSTED display text (a model chose it): redact and bound before rendering; never a key or a decision input. ECHO-ONLY. */
sourceAgentName?: string;
/** The parked twin of {@link import("./tool-policy.js").AskRequest}.fromSubagent: `true` exactly when the row records it ({@link CheckpointState.fromSubagent}),
* on any gate kind; not `agentId`'s presence. Absent on a host's row, a directly-started workflow's agent's, and a row minted before the member. ECHO-ONLY. */
fromSubagent?: true;
/** The parked twins of {@link import("./tool-policy.js").AskRequest}.workflowRunId / `workflowAgentLabel` / `workflowStepAskedAgain`, from
* the row's record ({@link CheckpointState.workflowMember}): the run that parked this row (a later run of the chain may hold the
* park now — route a decision by `workflowParkHolderOf`, never by this), the member's label (not unique, never a key), and the
* re-ask bit (only `true`). All three absent on a row that is no workflow member's, on one minted before the member, and on a
* row whose state no longer reads. ECHO-ONLY display/grouping. */
workflowRunId?: string;
workflowAgentLabel?: string;
workflowStepAskedAgain?: true;
/** The parked twin of {@link import("./tool-policy.js").AskRequest}.sessionScope: the session the resumed leg reads and writes the person's
* session-scope rules at, so a session rule saved from this card lands there — the row's record (`legIdentity.ruleSessionId`), present only
* where it is not the card's {@link sessionId}; absent, it is that session (a row parked before the member, a leg that read its own). */
sessionScope?: string;
/** design S1d (source-tag): the issuing task's end-user principal ({@link Checkpoint.principal}) for per-user inbox attribution. ECHO-ONLY display/triage; absent when the checkpoint carries no principal. */
principal?: string;
/** The pending tool call's id ({@link PendingAction} `tool_approval.toolCallId`) when this is an approval
* suspend — projected so the inbox shows WHICH call awaits a decision without an N+1 `getCheckpoint`.
* `undefined` for a non-`tool_approval` pendingAction (resource_limit / plan_review / task_done).
*
* **ABSENCE SHAPE (contract)** — shared by every optional field on this projection: a
* tool-less park (`resource_limit` / `plan_review` / `task_done` — none of which binds a tool call)
* gets the key **OMITTED**, never `null` and never a present-but-`undefined` property. The
* `PendingAction` arms for those kinds declare no tool/binding fields at all, so there is nothing to
* project; `summarizeCheckpoint` spreads them conditionally for exactly this reason. A consumer reads
* presence by value (INTEGRATION-CORE reading rule 1; here key and value agree), and a re-projecting
* service (BFF / SDK wire face) must not materialize the keys as `null` on the way out. Pinned in
* `test/checkpoint-store.test.ts` ("tool-less park …"). */
toolCallId?: string;
/** The id of the tool call that asked for this plan pause ({@link PendingAction} `plan_review.requestedByCallId`) —
* present ONLY on a `plan_review` row whose requester carried a call id; OMITTED on every other row (the
* {@link toolCallId} absence-shape note applies). It names the call that PRESENTED the plan, not a call the pause
* gates: `toolCallId` stays omitted on a plan_review row. */
requestedByCallId?: string;
/** The digest of the plan shown to the person at this pause ({@link PendingAction} `plan_review.planContentHash`, read
* through `planReviewContentHashOf`) — present ONLY on a `plan_review` row that carries a well-formed one; OMITTED
* on every other row (the {@link toolCallId} absence-shape note applies). It says what was SHOWN, not who asked and not
* which gate: compare it with your own digest of the plan string you received; equal values on two rows mean equal text. */
planContentHash?: string;
/** `true` when approving or editing this pause asks the parked leg to leave plan mode: a `plan_review` row that recorded the
* leg's declared mode at the pause as `plan` ({@link CheckpointState.inheritedGate} `permissionMode`). OMITTED otherwise —
* never `false`: on every other gate, on a `plan_review` parked outside plan (a caller tool's `requestReview`, a leg switched
* out of plan after the call), and on a row this projection cannot read. Derived when read, never stored — the resume's mode
* request reads the same row through the same answer (`approvalRequestsPlanExit`).
* It names a REQUEST: the resumed leg asks for the word the resume re-passes (when it is not `plan`), else the one it had
* before plan, else its default; a host's root leg leaves plan, while a delegated leg that can park (a background child, a
* workflow member) stays clamped under its parent's mode — under a parent in plan it is still in plan after approval.
* Absence says only that this approval does not take the plan-exit path; a re-passed mode word still applies. ECHO-ONLY. */
approvalRequestsPlanExit?: true;
/** The pending tool's name ({@link PendingAction} `tool_approval.toolName`) when this is an approval suspend — the very name
* the row's `boundInputHash` was minted over (`exactBoundInputHashOf(toolName, args)`), as the row records it (an alias call
* records the tool's own name). With {@link toolCallId} it is the listing's half of the approval binding: two parks of one
* call id over the same arguments by two tools list two names and hold two hashes. The hash itself stays on the drilled-in
* row, opaque, echoed and never re-derived by a host.
* OMITTED (not `null`) for a non-`tool_approval` pendingAction — see {@link toolCallId}'s absence-shape note. */
toolName?: string;
/** Which approval card the pending call renders under — the gate's {@link CheckpointGate} `approvalCard` echoed when
* it is a member of the closed set `TOOL_APPROVAL_CARDS` (a stored word outside the set is no card). The one typed
* discriminant a shell routes on: `"question"` is a question TO the user (the reserved AskUserQuestion tool, whose
* typed questions ride the drilled-in Checkpoint's `pendingAction.args`, kept off this lightweight projection), not a
* side-effecting tool; the other words pick the card family. Present on an approval suspend (`human` /
* `irreversible_ask`) that carries one; OMITTED for a row parked before the member and for every non-approval park —
* see {@link toolCallId}'s absence-shape note. */
approvalCard?: import("./tool-face.js").ToolApprovalCard;
/** design S1e: when the checkpoint was created ({@link Checkpoint.createdAt}, epoch ms) —
* projected so a supervisor inbox can sort/age pending entries (oldest-first triage) in ONE `listByScope`
* call, no N+1 `getCheckpoint`. ECHO-ONLY display/triage; always present (a Checkpoint always has a `createdAt`). */
createdAt?: number;
/**
* design S1e: a **BOUNDED, UNREDACTED** raw preview of the pending tool call's input
* ({@link PendingAction} `tool_approval.args` `JSON.stringify`-ed, truncated to {@link
* MAX_TOOL_INPUT_PREVIEW_CHARS} chars with a `…` marker when over) — projected so a supervisor inbox shows
* WHAT a paused tool call will do without an N+1 `getCheckpoint`. `undefined` for a non-`tool_approval`
* pendingAction (resource_limit / plan_review / task_done — no args to preview).
*
* **Contract (load-bearing):**
* - **bounded raw preview** — length-capped to {@link MAX_TOOL_INPUT_PREVIEW_CHARS} so it cannot bloat the
* `listByScope` payload, but the chars within the cap are the RAW serialized args (no folding/escaping).
* - **redaction is the CONSUMER's responsibility** — core gives the inbox the unredacted bounded raw; the
* service/inbox decides what (if anything) to mask before showing a human. (Contrast {@link
* RiskDescriptor.summary}, which is the NEUTRALIZED+capped descriptor that DOES ride into a render —
* `toolInput` is the raw-data sibling for a consumer that wants the actual args.)
* - **same data as the full {@link Checkpoint}** — it is a projection of `pendingAction.args`, which the
* caller could already read via `get`; this adds NO new exposure, it only saves the round-trip.
* - **ECHO-ONLY, like {@link sourceSessionId}** — NO gate / CAS / resume / {@link winnerFromOutcome} path reads
* it (a contract test pins this); it is pure display/triage metadata, never a control input.
*/
toolInput?: string;
/**
* HOW this pause's remote workspace comes back, projected from
* `state.workspaceHandle.restoreMode` so a supervisor inbox can tell the two apart in ONE `listByScope`
* call. `"snapshot"` = the VM was paused into a snapshot (billing typically stops, memory state
* captured); `"park_only"` = a non-suspendable target (SSH host / ADB device) was never paused — the
* machine is still running and still costing, and resume just reconnects. OMITTED (see the
* {@link toolCallId} absence-shape note) for a process-local suspend, which captured no remote
* workspace at all. ECHO-ONLY display/triage — nothing gates on it. Mirrors `TaskResult.workspaceRestoreMode`.
*/
restoreMode?: "snapshot" | "park_only";
/** the tool's approval display projection ({@link PendingAction} `preview`),
* projected so the ONE-CALL inbox (`listByScope`) can render a rich confirmation without an N+1
* `get`. Same trust posture as `toolInput`: **UNTRUSTED, advisory display metadata** (strings are
* sanitized of control chars at mint but may still carry model-authored markdown — renderers must
* contextually escape), ECHO-ONLY (no gate/CAS/resume reads it), and surfaces SHOULD show the
* bound raw args (`toolInput`/`pendingAction.args`) alongside — the preview never replaces them. */
preview?: unknown;
/** #457 ② — the row's `PendingAction.tool_approval.previewWithheld`, projected BESIDE {@link preview}
* for the same reason that one is: without it the ONE-CALL inbox cannot tell "this tool declares no
* preview" from "the projection failed", which is the exact collapse the determinant exists to
* remove — and re-opening the row with an N+1 `get` just to answer it defeats `listByScope`.
* `"oversize"` (produced but past the 16KiB mint bound — the truncation stub still rides
* {@link preview}) or `"unavailable"` (threw / no JSON serialization). The {@link toolCallId}
* ABSENCE-SHAPE contract applies: OMITTED otherwise, never `null`/`false`/present-but-`undefined`.
* A pure echo of the row's own persisted value — unlike {@link hasBidiControls}, there is no
* projection-time backfill, because whether a tool DECLARED a preview is not knowable from the
* projection's own materials (a pre-#457 row therefore reads absent, which is honest: unreported).
* ECHO-ONLY display metadata; nothing gates on it. */
previewWithheld?: "oversize" | "unavailable";
/** The row's `PendingAction.tool_approval.requiresRealApproval`, projected so the ONE-CALL
* inbox can label "only a person can clear this" without an N+1 `get`. `true` or OMITTED (the
* {@link toolCallId} absence-shape contract); pure echo of the persisted bit — a pre-#557 row reads
* absent, which is honest (unreported), never a claim that budget may clear it. */
requiresRealApproval?: true;
/** The row's `PendingAction.tool_approval.mandated` (#1079), for the same one-call reason: `true` or
* OMITTED (the {@link toolCallId} absence-shape contract), screened to the literal `true` — a pre-#1079 row
* reads absent (unreported). ECHO-ONLY; nothing gates on it. */
mandated?: true;
/** The row's `PendingAction.tool_approval.authoredBy`, echoed as the one literal. ECHO-ONLY. */
authoredBy?: "deployment";
/** The row's `PendingAction.tool_approval.fromApprovalList`, echoed as the literal `true` (a stored `false` or any other value reads
* absent): the deployment's approval list raised this question. ECHO-ONLY display; nothing gates on it. */
fromApprovalList?: true;
/** The row's `PendingAction.tool_approval.mandate`, echoed ONLY as a member of the closed set. ECHO-ONLY. */
mandate?: import("./ask-origin.js").PersistedRuleMandate;
/** The parked ask's word for why its card offers no persisted rule (the row's pendingAction.ruleOffersAbsence), present only when that member is one of RULE_OFFERS_ABSENCES; any other value is left out, never echoed. */
ruleOffersAbsence?: import("./ask-origin.js").RuleOffersAbsence;
/** The row's `PendingAction.tool_approval.denialLimitFallback`, projected BESIDE the preview
* for the same one-call reason: a card that shows the fallback's counts and limit must not re-open
* the row to learn them (`autoDenyAfterMs` is `0` on every row — see the row member). Pure echo;
* OMITTED when the row carries none. */
denialLimitFallback?: import("./auto-mode.js").DenialLimitFallback;
/** The row's `PendingAction.tool_approval.classifierNoRuling`, echoed ONLY as a member of its closed set (else omitted). */
classifierNoRuling?: import("./auto-mode.js").AutoModeFallbackCause;
/** The row's `boundGrantDigest`, echoed (a string; else omitted): the hash of {@link boundGrants}. ECHO-ONLY. */
boundGrantDigest?: string;
/** The row's `boundGrants` — a fresh copy of the skill and its two lists, published only when it hashes to {@link boundGrantDigest} (never a list beside a digest that binds another). Deployment text: render with contextual escaping. ECHO-ONLY. */
boundGrants?: import("./skill-grant-binding.js").BoundSkillGrants;
/** Every `tool_approval` summary carries {@link boundGrantDigest} or this, never both: the row's word when it is a member and the row has no digest, else `unreadable` (the row does not say what it binds). ECHO-ONLY. */
boundGrantAbsence?: import("./skill-grant-binding.js").BoundGrantAbsence;
/** The row's `PendingAction.tool_approval.origin`, projected for the same one-call reason: a card
* rendered by the ask's origin word must not re-open the row to learn it. Echoed ONLY when the stored
* value is a member of the closed set ({@link import("./ask-origin.js").isAskOrigin}) — a bad value
* reads as absent, never as a word. OMITTED when the row carries none (a pre-existing row). */
origin?: import("./ask-origin.js").AskOrigin;
/** The row's `PendingAction.tool_approval.askReasons` (the live card's entries: who asked, in its own words), for the same one-call
* reason — present ⇔ the row carries a list of well-formed entries ({@link import("./ask-origin.js").receiveAskReasons}: one malformed
* entry publishes none), a fresh copy; OMITTED otherwise. **UNTRUSTED** display text; ECHO-ONLY. */
askReasons?: readonly import("./ask-origin.js").AskReason[];
/** The row's `PendingAction.tool_approval.cardMessage` (the card's question as the row keeps it), for the same one-call reason —
* present ⇔ the row holds a non-empty string, read through the screen the row's mint takes ({@link approvalMessageOf}); OMITTED
* otherwise. **UNTRUSTED, ADVISORY** display text; ECHO-ONLY. */
cardMessage?: string;
/** The row's `PendingAction.tool_approval.headline` (the card's first line for a person), present ⇔ a non-empty string read through
* {@link cardMessage}'s screen; OMITTED otherwise (show {@link cardMessage}). For people to read, never a branch input; ECHO-ONLY. */
headline?: string;
/** What opened the leg that parked this row — the row's `state.runOrigin` (`"scheduled"`: the deployment's scheduler, not a
* person submitting just now), for every gate kind, so an inbox shows it in the one listing call. Echoed only as a member of
* {@link import("./run-origin.js").RUN_ORIGINS} (the resume's screen refuses any other value loudly; this projection never
* invents one). OMITTED when the row carries none. ECHO-ONLY: attribution, never a gate input. */
runOrigin?: import("./run-origin.js").RunOrigin;
/**
* PRESENCE ONLY — this pending `tool_approval` row's payload carries at least one DIRECTIONAL
* format control (the {@link import("./tool-policy.js").AskRequest.hasBidiControls} character class;
* that doc owns the hazard). Only ever for a `tool_approval` pendingAction; OMITTED for every other
* kind (the {@link toolCallId} ABSENCE-SHAPE contract applies: never `null`, never present-but-
* `undefined`, never `false` — a re-projecting BFF must not materialize any of those on the way out).
*
* WHERE THE ANSWER COMES FROM: the row's own persisted bit when present (the park mint is the
* authority — one look, one answer, never re-derived); else a bounded BACKFILL scan run AT PROJECTION
* TIME over this projection's OWN bounded materials — the truncated {@link toolInput} string just
* derived plus the row's `preview`, under a small per-row budget — so a pre-#438 row and a
* deployment-written row still get a bit exactly where the inbox reads. The backfill judges THE BYTES
* THIS PROJECTION HANDS THE INBOX: a marker buried past the `toolInput` truncation point (or past the
* per-row scan budget) is honestly reported as absent — new-engine-minted rows carry the mint-time bit
* (judged over the full parked args) for exactly that reason. The backfill NEVER writes back to the
* row: `summarizeCheckpoint` stays a pure projection.
*
* HOW TO READ IT: `true` = core detected the class in this row's payload (or took a deployment row's
* own `true` at its word — over-warning is the safe direction); render a visible "the text below can
* display differently from what it runs" annotation. ABSENT = NOT DETECTED, never "clean" — it covers
* clean, budget-exhausted, and a `false`-writing out-of-contract producer (read as absent, never
* projected). The bit changes NO rendering obligation a surface already had: with or without it,
* `toolInput` / `toolName` / a summary string go through
* {@link import("./permission-rule-model.js").renderUntrustedCommandText} (or the surface's own
* screen) before a human reads them; for the structured `args`/`preview` the FIRST-CHOICE display
* material is the bounded projections core already minted (`toolInput`, the descriptor `summary`) —
* do not re-serialize the whole args for a list render, and a drill-in that must show everything owes
* itself a TOTAL, bounded traversal (cycle-safe, per-type output forms, throwing getters to a
* placeholder, depth/node/char budgets with a truncation marker — never "full `JSON.stringify` then
* truncate", which does all the work and takes all the throws before the cap). ECHO-ONLY, like
* {@link sourceSessionId}: a warning to a person, never a control input — resume/gate/CAS never read it.
*/
hasBidiControls?: true;
}
/**
* design/80 assistant-scheduler seam #1: project a single PENDING {@link Checkpoint} to its lightweight
* {@link CheckpointSummary}. Shared by every {@link CheckpointStore} impl so the projection is IDENTICAL
* across the in-memory, file, and durable backends (the anti-drift guard) — `severity` always derives from the
* gate's {@link RiskDescriptor} via the single {@link riskSeverity} helper, `spentMicroUsd` always reads
* {@link ResourceLedger.spentMicroUsd}, `rowVerdict` is the row's `judgeCheckpointRow`. Pure; reads no clock/random. The
* summary holds no reference into the row (a display member that is a value of its own is a copy), so editing a summary
* never edits the stored row.
*
* `disclose` receives one sentence for a damage the projection reads past — descriptor axes that are not a plain record, or
* a mark that is not a boolean (the `severity` is then the valid marks' floor, or omitted) — naming the row by checkpoint id
* and session (never its token) and the member by its shape (never its value); it is called synchronously and every listing
* calls it again. A store hands it its own seat. `verdict` is a store's memo of this row's `judgeCheckpointRow` under this
* engine (an in-tree store keeps it by the stored row object, so a replaced row is judged again; an external store by the stored
* blob's sha256 plus the engine build, `CONTRACT_KIT_ENGINE_VERSION`); absent, the row is judged now. The resume never reads it.
*
* TOTAL, as the judge is: a row this projection cannot read (a record it lacks or holds as something else, a member that throws
* when read) is answered, never thrown — as the row's identity alone ({@link CheckpointSummary.rowVerdict}'s unreadable form), with
* a verdict that is not `ok` and one sentence to `disclose`. One damaged row never fails the page that lists it.
*/
export declare function summarizeCheckpoint(cp: Checkpoint, disclose?: (sentence: string) => void, verdict?: CheckpointRowVerdict): CheckpointSummary;
/**
* Whether `summary` is in the unreadable form ({@link CheckpointSummary.rowVerdict}'s note: a row the projection could not read,
* listed by its identity alone): its verdict is not `ok` and every own key it carries is one the unreadable form may carry. A
* projected summary whose verdict is not `ok` and that happens to carry only those members reads `true` as well — that row has no
* other facts to give either. A host that tells the two forms apart asks this, rather than keeping its own list of the members.
*/
export declare function isUnreadableCheckpointSummary(summary: CheckpointSummary): boolean;
/**
* An in-tree store's listing projection with its verdict memo: the verdict a store holds for this stored row object, else
* the row judged now and held. The memo lives as long as the row object the store holds — a `put` (or a replay) holds a new
* object, so a replaced row is judged again; the judge reads no member a store's own transitions rewrite (status, rev, the
* decision and execution records, the steer queue — the requirement table's mutable members).
*/
export declare function summarizeStoredCheckpoint(cp: Checkpoint, memo: WeakMap<Checkpoint, CheckpointRowVerdict>, disclose?: (sentence: string) => void): CheckpointSummary;
/**
* The pluggable durable seam (design/45 §2.1). Symmetric with `ToolResultStore`:
* create-once `put`, `get`, an **atomic CAS `resolve`** (the once-only foundation), and a `reap` for TTL
* expiry. A durable backend (TiDB) makes resume cross-replica; the default in-memory impl is single
* instance / tests only.
*
* **Load-bearing contract (§2.1, service-side report):** `resolve` is the once-only gate. The store guarantees
* *exactly one* `resolve(token, ...)` wins the CAS (pending → resolved); the **runner** must treat
* "won the CAS" as the *sole* trigger to execute the pending action — that is what makes a pending tool
* call run exactly once across retries / double approvals / multiple replicas.
*
* **design/80 §D-D expiry semantic contract (gate.kind-aware reap + `terminalAt` backstop):** the
* reaper-LOOP that calls {@link reap}/{@link expire} is the DEPLOYMENT's (its store impl + loop — OWNED
* service-side); core's D-D job is ONLY to keep writing the durable FIELDS the loop
* reads ({@link Checkpoint.deadline} for an approval gate + the persisted {@link Checkpoint.gate}.kind) and
* to DOCUMENT the contract here so ANY reaper consumer (the service's TiDB loop, or a non-service Pg
* deployment) implements it IDENTICALLY:
* - **FACET A — APPROVAL gates** (`gate.kind` ∈ {`human`, `irreversible_ask`}): the loop's FAST PATH at
* `deadline` is an SLA **resolve-deny** (`resolve(token, {gate:"policy_ask", decision:"deny"}, …)` so the
* suspended run ends cleanly), with a LATER `terminalAt` **abandonment backstop** the loop ALSO honors
* (crash-safe if the SLA timer never fired — then {@link reap}/{@link expire} flips it `expired`).
* - **FACET B — UNATTENDED-TTL gates** (`gate.kind` ∈ {`resource_limit`, `needs_review`, `plan_review`} — the
* resource slice + the review-pause family): `deadline` is an abandonment-TTL → {@link expire}/{@link reap}
* ONLY, **NEVER** a resolve-deny (a resolve-deny on these kinds hits NO `gateMatch` arm → `gate_mismatch`;
* their resume outcome is `resource_limit`/`dry_run_review`/`plan_review` respectively, not `policy_ask`).
* NO core-minted `terminalAt`, NO core reaper, NO change to {@link reap} logic — minting `terminalAt` and
* running the gate.kind-aware loop are the deployment's, by design.
*/
/**
* design/173 §2.3 — the store DURABILITY declaration vocabulary (declaration, never duck-typing —
* the exact posture of {@link CheckpointStore.retention}): `"durable"` promises the rows SURVIVE A
* PROCESS RESTART of the deployment that owns the store's data domain (a durable park can be
* resumed by a later process); `"process-local"` states they die with the process. **This axis
* claims restart survival ONLY — it does NOT claim multi-replica coordination** (whether a SECOND
* concurrent replica can serve the same rows is a separate property of the backend: the file
* backend is single-instance-per-data-dir by design, Pg/TiDB backends coordinate — both honestly
* declare `"durable"` on THIS axis; review fold round 1, finding 2). ABSENT is read FAIL-CLOSED as
* `"process-local"` (the wiring manifest may under-promise durability, never over-promise it); an
* unparseable value is refused loudly (`config.store_durability_invalid`) rather than folded to
* either arm. Adapter contract with a conformance obligation: a backend that persists outside the
* process (file/Pg/TiDB) SHOULD declare `"durable"` — until it does, restart-surviving resume
* capability is reported as absent.
*/
export type StoreDurability = "durable" | "process-local";
/**
* The store ENCODING-FIDELITY declaration vocabulary — the third honest-declaration axis, alongside
* {@link StoreDurability} and {@link CheckpointStore.retention}, and the one that says WHICH VALUES a
* row can hold unchanged.
*
* `"structured-clone"` promises the structured-clone value domain survives a round trip through the
* backend (a `Date` comes back a `Date`, a `Map` a `Map`, `NaN` stays `NaN`); `"json"` states the
* backend serialises through JSON, so the row that comes back after a restart carries the JSON
* PROJECTION of what was filed (`Date` → string, `Map`/`Set` → `{}`, `NaN`/`Infinity` → `null`, `-0`
* → `0`, an `undefined`-valued key gone — a real loss below a row's frame: a tool call's arguments, compared by own-key
* set at the park; none at its top level or its `state`'s, which the engine writes with absences omitted).
*
* Why this has to be declared rather than inferred: the mint decides what a durable approval row may
* carry, and it decides it with `structuredClone` — which is WIDER than a JSON codec. A value can pass
* that check, be filed, degrade on disk, and come back a different value, while the binding hash minted
* over the pre-serialisation value still matches the one the operator echoes (the resume compares the
* persisted string opaquely and never re-hashes). The approval is then accepted for arguments that are
* not the arguments it bound. Only the backend knows its own codec, so only the backend can say.
*
* ABSENT is read FAIL-CLOSED as `"json"` — the narrower domain, the same "may under-promise, never
* over-promise" posture {@link StoreDurability} takes with `"process-local"`: an undeclared backend gets
* a row it can certainly hold, and a backend that can hold more earns the wider domain by saying so. An
* unparseable value is refused loudly (`config.store_fidelity_invalid`) rather than folded to either arm.
*/
export type StoreFidelity = "structured-clone" | "json";
/**
* Resolve a store's declared {@link StoreFidelity} (the read half of the declaration — the exact shape
* `resolveDeclaredFidelity`'s durability twin has): ABSENT → the fail-closed `"json"`, a recognized
* value verbatim, anything else refused loudly. Never duck-types the backend.
*
* Exported at the package root for a host that mints its own checkpoint rows (e.g. a `task_done` wake card): it reads the
* fidelity to stamp at from its store's own declaration instead of writing a constant —
* `put(token, stampCheckpointRequirements(checkpointFrom({ ... }), resolveDeclaredFidelity(store, "checkpointStore")))`.
*/
export declare function resolveDeclaredFidelity(store: {
readonly fidelity?: StoreFidelity;
} | undefined, storeName: string): StoreFidelity;
export interface CheckpointStore {
/**
* Managed-retention declaration (retention.ts), stated by the party that runs the sweep: `"managed"` says this store's
* rows are deleted on schedule by the deployment — an executor runs over them, closing the reap/unpin gap documented on
* {@link reap} (its scheduled expiry DOES release the session pins). `"none"` (or ABSENT — read fail-closed as `"none"`)
* says nothing deletes them on schedule; a deployment with a LOCKED retention policy refuses to start over it.
*/
readonly retention?: RetentionDeclaration;
/**
* design/173 §2.3 — durability declaration (see {@link StoreDurability}): whether checkpoints
* this store accepts survive a process restart. Same "declaration, never duck-typing" posture as
* {@link retention}; the wiring manifest relays it verbatim and reads ABSENT fail-closed as
* `"process-local"`.
*/
readonly durability?: StoreDurability;
/**
* Encoding-fidelity declaration (see {@link StoreFidelity}): which value domain a row keeps INTACT
* through this backend. Same "declaration, never duck-typing" posture as {@link durability}; the park
* mint reads it to decide the width of the snapshot it files, and reads ABSENT fail-closed as
* `"json"`. A backend that serialises through JSON MUST say so (or leave it absent, which says the
* same) — a `"structured-clone"` claim it cannot keep is what lets a row degrade under a binding hash
* that still matches.
*/
readonly fidelity?: StoreFidelity;
/**
* The GRANT-HOLDER declaration ({@link StoreHolderFence}, the one shape the session store declares too): `holder: "writes"` = this
* store judges the holder of every write it is handed that carries one — `put` / `setPendingSteer` / `expire` (`opts.holder`),
* `resolve` (`expect.holder`) and both arms of {@link claimTerminal} (`expect.holder`) — in that write's own atomic step, by the
* deployment's one judge ({@link HolderJudge}). Same "declaration, never duck-typing" posture as the optional axes above
* ({@link durability}, {@link fidelity}): ABSENT reads as "judges no holder", and a run handed a holder over such a store is refused at
* its store seat (`config.invalid_checkpoint_store`) — a holder the store would ignore would fence nothing while the deployment
* believed it fenced. The retired `{ holder: true }` (a promise about `resolve` alone) and every other form are refused at the seat
* ({@link readStoreFence}). A wrapper store forwards this member and the holder of every verb it forwards; a wrapper that drops
* either fences nothing — the store contract kit binds the COMPOSED store to catch exactly that.
*/
readonly fence?: StoreHolderFence;
/** Create-once. Throws {@link CheckpointError} `already_exists` on a token collision (never a silent
* overwrite — a reused token would clobber a live suspension).
* `opts.holder` (the run's grant holder, verbatim): judged first, in the same atomic step as the create — a holder the store's judge
* does not hold current throws `holder.superseded` ({@link holderSupersededError}) with nothing written; no holder ⇒ as before. */
put(token: CheckpointToken, cp: Checkpoint, opts?: CheckpointWriteOptions): Promise<void>;
/** The row filed under `token` as stored, or `null` when none is; a held value that is no row throws `storedCheckpointRowRefusal`'s
* refusal, bytes that do not decode `checkpointRowUnreadable`'s (both: checkpoint-queries.ts); every other row is answered as stored. */
get(token: CheckpointToken): Promise<Checkpoint | null>;
/**
* Atomic CAS: `UPDATE … SET status='resolved' WHERE token=? AND scope=? AND status='pending'`.
* Returns `true` for the single winner (was pending → now resolved), `false` if already resolved/
* expired (`AlreadyResolved` — the caller treats it as a no-op, never re-executes). `scope` is in the
* WHERE for multi-tenant isolation (a wrong-scope resolve must not win).
*
* `outcome` is supplied so a **durable** backend persists it atomically with the status flip (design/45
* v2 resumable-resume hook). **design/80 D-1 (persist-winner):** when the CAS wins, the store ALSO records
* the winning binding as {@link Checkpoint.resolvedOutcome} on the row — so a later {@link reopen} →
* re-resume can be validated against the approved decision (an `env_failed` reopen must replay the same
* winner; design/80 §3 inv #1). A `policy_ask` outcome records the decision bound to its pending tool
* call; the two REVIEW outcomes (`plan_review` / `dry_run_review`) record theirs under a synthetic
* `gate:` marker; `resource_limit` / `wake` / `task_done` bind nothing and record no winner.
*
* **Implementers: derive the winner with {@link winnerFromOutcome} and persist the object WHOLE.** Its
* field set GROWS (`updatedInput`, then `answer`, then `reason` — each additive and optional), and the
* replay guard reads an absent optional field as "this backend never recorded it" so that rows written
* before the field existed still replay. A backend that projects a hand-listed subset of columns is
* therefore indistinguishable from an old row and silently leaves that dimension UNBOUND for every
* decision it ever writes — the replay guard cannot tell the two apart, and there is no capability
* negotiation on this interface to tell it. Round-trip the whole record (opaque JSON is what every
* in-tree backend does) rather than enumerating its keys.
*
* (The crash-recovery semantics of *acting* on a won CAS are runner contract — see
* {@link Runner.resume}; the store only owns the atomic once-only flip + the durable winner.)
*/
resolve(token: CheckpointToken, scope: string, outcome: ResumeOutcome, expect?: ResolveExpectation): Promise<boolean>;
/**
* Inverse of {@link resolve}: CAS `resolved → pending` (`UPDATE … SET status='pending' WHERE token=?
* AND scope=? AND status='resolved'`). Returns the CAS winner (`true` = was resolved → now pending again).
*
* **Compensation for a post-CAS env-restore failure (design/45/49).** `Runner.resumeStream` wins the
* `resolve` CAS *before* the workspace `resumeVM` runs; if that restore then fails (`resume.env_failed`)
* the pending action never executed yet the checkpoint is consumed — without this the suspended work is
* lost to a forced "re-initiate" (fine for a short approval, ruinous for a long unattended task).
* Reopening lets a retry re-resume the SAME work. REQUIRED — the verb is the contract (no declaration stands
* for it; the store seat, {@link resolveCheckpointStore}, refuses a store that does not carry it): a claimed
* resume that ends before its decided action is disposed — a failed restore, a refusal at the leg's prepare, an
* abort, a leg that returns failed — returns the row here, and the engine has no lane for a store that cannot. Safe by
* the `status='resolved'` guard — only the run that consumed the checkpoint (and then failed to restore) can
* reopen it, and only while it is still `resolved`.
*
* **design/80 D-1 (reopen-by-reason):** the `reason` distinguishes the two reopen triggers (both shipped at
* runtask.ts) so re-resume can validate per reason (§3 inv #1): `env_failed` (the action is still valid,
* only infra failed → re-resume MUST replay the persisted {@link Checkpoint.resolvedOutcome} winner) vs
* `tool_unavailable` (P-7: the approved tool vanished, the action may now be invalid → a human re-decides,
* so a FRESH decision is allowed). The store RECORDS the reason on the row as {@link Checkpoint.reopenReason}
* and PRESERVES the persisted winner across the reopen (never clears it).
*
* **A row that carries an execution record is NOT reopenable** (`… AND execution_outcome IS NULL` in the
* WHERE; `checkpointExecutionRecorded` is the shared predicate): the decided action's disposition is on
* file — see {@link CheckpointRow.executionOutcome} — and reopening it would either re-run an action that
* already ran or re-decide one already refused. Answers `false` like every other predicate miss; the
* reasons and the winner are untouched.
*
* **Only the claimer's generation is reopened ({@link ResolveExpectation.rev}, the claim's inverse):** a caller that passes `expect`
* gets the row back only if its live `rev` still equals `expect.rev` — the generation its own won resolve produced (one above the
* one it read, `checkpointClaimRevOf`) — judged in the SAME atomic step as the flip, by the same predicate the resolve's OCC arm
* reads (`checkpointOccMatches`). Any resolve or reopen since then moved the counter, so a delayed or foreign reopen finds a
* generation that is not its claim's and answers `false` with the row untouched (it never un-consumes a newer resumer's claim).
* Omit `expect` (a direct store caller) → no generation precondition, as before. A store that does not judge it reopens whatever
* generation it holds; the kit's reopen case holds every backend to the judgement.
*/
reopen(token: CheckpointToken, scope: string, reason: ReopenReason, expect?: Pick<ResolveExpectation, "rev">): Promise<boolean>;
/**
* Record how the DECIDED action was finally disposed on the resumed leg — the {@link GateOutcome} its
* `tool_end` frame carried (see {@link CheckpointRow.executionOutcome} for what the record means and why
* it is a column of its own beside the immutable decision). REQUIRED, and the verb is the contract: the store seat reads its presence
* ({@link resolveCheckpointStore}, code `config.invalid_checkpoint_store`), no declaration stands for it, and the kit holds every
* backend to what it does (the CAS below, and {@link reopen} refusing a recorded row).
*
* The CAS: `UPDATE … SET execution_outcome=?, execution_at_ms=? WHERE token=? AND scope=? AND
* status='resolved' AND execution_outcome IS NULL`. The answer is a word of the closed
* `ExecutionOutcomeRecordWord` set — `recorded` (the CAS won), `already_recorded` (the row already
* carries an EQUAL record: a retry, idempotent), `not_resolved` (pending/expired: no decision to be the
* outcome of), `absent` (no such row in this scope). A row carrying a DIFFERENT record throws
* `ExecutionOutcomeConflictError` (`checkpoint.execution_outcome_conflict`) — the record is immutable
* and two accounts of one execution are an engine defect, never a store overwrite. Equality is
* structural over the record's JSON (key order and freezing are not part of the value —
* `sameExecutionRecord`); every backend takes its disposition from `executionRecordDisposition`
* (checkpoint-execution-record.ts) and keeps only the commit half itself.
*
* Never touches `status`, `rev`, `resolvedOutcome` or `reopenReason`: the record is a fact about the
* execution, not a transition of the decision. Its one effect on the row's other verbs is that
* {@link reopen} refuses a recorded row.
*/
recordExecutionOutcome(token: CheckpointToken, scope: string, gate: GateOutcome): Promise<ExecutionOutcomeRecordWord>;
/**
* design/80 D-A: park a durable mid-task STEER on a DURABLY-SUSPENDED task's checkpoint. CAS-style update
* `SET state.pendingSteerQueue=? WHERE token=? AND scope=? AND status='pending'`: returns `true` iff the
* checkpoint is still `pending` (a resolved/expired checkpoint can't be steered → `false`, a no-op). Scope
* is in the WHERE for multi-tenant isolation, exactly like {@link resolve}/{@link expire}.
*
* **design/171 §5.3 — this APPENDS to {@link CheckpointState.pendingSteerQueue}; it no longer overwrites a
* single seat.** Two people steering one suspended run used to silently destroy the first instruction,
* with no record that anything was lost. Idempotency moved from last-writer-wins to the `inputId` key:
* re-appending an `inputId` already queued (a service retrying with the message id it already minted)
* is a no-op that still returns `true`. An append whose queue would serialize past
* {@link PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES} throws `steering.queue_full` — bounded fail-loud, never
* by evicting an accepted instruction; there is no entry-count cap.
*
* **An append that adds an entry moves the row's generation** ({@link Checkpoint.rev} + 1, in the same atomic step): the queue is part of what a resume's claim consumes, so a claim that read the row before the append loses its CAS ({@link ResolveExpectation.rev}) and the entry stays on the still-pending row for the next claim. A call that adds nothing (an identical replay) writes nothing and moves nothing; a refused call leaves the row byte-identical, its generation included.
*
* A backend must round-trip the queue field verbatim and must build its new queue with
* {@link appendPendingSteer} so the bounds and the `seq` mint are one implementation rather than one
* per store.
*
* **Trust is FROZEN here** — `steer.trusted` is whatever the SERVICE computed from the verified principal
* at this call (an operator-role check, NOT a client header — the service's job); the core stores it
* VERBATIM and NEVER recomputes it on resume (§3 inv #1).
*
* **Validation (load-bearing, §3 inv #2):** `steer.text` containing a `</system-reminder>` close tag is
* REJECTED with a typed {@link CheckpointError} `steering.invalid_content` (mirroring runtask.ts's trusted-
* steer reject) — a dirty steer NEVER enters {@link CheckpointState}, so the persisted state stays clean
* regardless of `trusted`. (The untrusted RESUME-injection path ALSO sanitizes the text as untrusted data;
* this persist-time reject is the belt that keeps a caller-declared close tag out of the durable record on BOTH
* paths.) Text over {@link MAX_PENDING_STEER_CHARS} is rejected with the same code (HRD-APV-4 — the
* steer is re-delivered into the model context on every resume, so it is capped like every other
* persisted model-facing field on this row; rejected rather than truncated because cutting an
* instruction can invert it). NOT an approval channel: this writes the parked queue and moves the generation, never the status or any decision (§3 inv #4).
*
* `opts.holder` (a leg's own steer, carried verbatim): judged first, in the same atomic step as the append, before the row is
* looked at — a holder the store's judge does not hold current throws `holder.superseded` ({@link holderSupersededError}), the queue
* unchanged; no holder ⇒ as before (a person's steer onto a parked card carries none).
*/
setPendingSteer(token: CheckpointToken, scope: string, steer: PendingSteerInput, opts?: CheckpointWriteOptions): Promise<boolean>;
/**
* CAS-expire a **single** `pending` checkpoint by token: `UPDATE … SET status='expired' WHERE token=?
* AND scope=? AND status='pending'`. Returns the CAS winner (`true` = was pending → now expired; `false`
* = already resolved/expired). The same UPDATE as {@link reap} but keyed by **token**, not by deadline.
*
* **Load-bearing contract (design/51 §2/§4):** `expire` and {@link resolve} race the **same `pending`
* row**, so the store serializes them — exactly one wins. This is what makes {@link TaskStream.destroy}
* a correct *fence-then-reap*: `destroy` calls `expire` FIRST to fence any concurrent `resume` (which
* goes through `resolve`); the paused env is destroyed only once the row is `expired` (this call won, or a loser
* reads it so), so the same checkpoint is **never both reaped and resumed**. `scope` is in the WHERE for multi-tenant isolation, like
* `resolve`/`reap`.
*
* `opts.holder` (an expire a run issues in its own name, carried verbatim): one more precondition of the same CAS — a holder the
* store's judge does not hold current LOSES (`false`, the row untouched; never a throw, so a caller reading the row still sees that it
* was expired by someone else when it was). No holder ⇒ as before (a host's reaper, cancel and cleanup carry none).
*/
expire(token: CheckpointToken, scope: string, opts?: CheckpointWriteOptions): Promise<boolean>;
/**
* design/384 slice 2 / S-25-R1 — the ATOMIC terminal claim: "win the terminal race" and "read the
* truth on a loss" as ONE store operation. OPTIONAL, probed by presence (the `listByScope`
* precedent); the runner's resume chain adopts it when present (the loser triages off `current`
* with zero second read) and keeps the two-step resolve+get path otherwise. This JSDoc is the
* single normative statement of the claim law — `put`'s create-once/read-back three-state and the
* suspend saga's commit discipline are the same single-winner law's PUT variant and cross-reference
* here rather than restate.
*
* The laws:
* 1. **Atomicity** — the win/lose decision and the loser's `current` reading MUST come from the
* same atomic unit (one `UPDATE … RETURNING` / one transaction / one single-threaded map
* operation). A settle is self-sufficient: a caller holding `claimed:false` NEVER needs a
* second read to act.
* 2. **CAS-predicate identity** — `kind:"resolve"`'s win IS {@link resolve}'s win (same WHERE:
* token+scope+pending[+rev]; a win records the winner via {@link winnerFromOutcome} and bumps
* `rev` identically); `kind:"expire"` IS {@link expire}. ONE-MACHINE OBLIGATION: a store that
* provides `claimTerminal` must route all three verbs through one protected write path
* (resolve/expire implemented over claimTerminal, or all three over one shared CAS kernel) —
* two predicates would be a drift window, and this law forbids it.
* 3. **Timeout posture** — no timeout parameter here: transport deadlines belong to the backend,
* wall-clock backstops to the caller. The contract states exactly two halves: a SETTLE carries
* the truth; a REJECT proves NOTHING (the row may already be terminal — the caller must not
* proclaim a terminal state from its own intent; fail-closed projection of "still pending"
* stays legal). A LATE settle is as self-sufficient as a prompt one — an answer arriving after
* the caller's own deadline still carries the true decision, so the caller settles on truth
* with zero follow-up reads.
* 4. **Recovery discipline — truth is comparable, ownership is not.** A bounded retry after a
* reject re-sends the SAME claim (the CAS is idempotent). When the retry answers
* `claimed:false`, `current` tells the caller what the row IS — never WHOSE claim made it so:
* two claimants writing byte-identical outcomes cannot be told apart by content, and
* {@link ResolvedOutcome} carries no claimant identity. Two consumption classes follow:
* IDEMPOTENT consumption (settle on the recorded truth — who wrote it is irrelevant) may use
* `claimed:false` + the recorded decision directly; RESPONSIBILITY-bearing consumption (only
* the winner may execute the pending action — the runner's resume) must NEVER self-attribute
* after ambiguity: treat it as a loss (the `already_resolved` shape, nothing executed) — the
* same law as the existing crash-after-CAS pin ("retry sees resolved and does NOT re-execute"),
* which this claim does not weaken. There is NO replay arm: a burned approval takes the
* existing reopen/re-ask compensation route, and this contract opens no "assume approved and
* replay" door. (A claimant-identity field would be a schema change; not here.) Expire-class
* claims are naturally idempotent (expire-by-me ≡ expire-by-reaper; no attribution needed).
* 5. **A loss reading is a consistent snapshot at the claim's linearization point, not an eternal
* truth** — `resolved` can be reopened back to pending, so "settle is self-sufficient" scopes
* to the disposition of THIS loss (settle on truth / re-validate on OCC / close on absent),
* never to the row's future; a caller needing current state later still `get`s. `current` is a
* projection, not the row (no state / pendingAction payloads).
* 6. **`resolvedOutcome` reads as the row field it is, passed through verbatim** — the persisted
* winner record: written only by decision-bearing resolves ({@link winnerFromOutcome} answers
* `undefined` for resource/wake/task_done), PRESERVED by `reopen`, not cleared by later
* winnerless resolves. In a loss answer it means "the row's last recorded decision winner",
* NOT "the payload of the claim that beat you"; absence means "no decision winner recorded",
* not "the winner had no content". For has-a-human-decided consumption this is exactly the
* needed semantics; "who beat me / with what" is claimant-identity territory this contract
* does not mint.
* 7. **No declaration bit** — presence of the method IS the contract (an implementation
* obligation at the same level as `resolve`'s CAS promise), as it is for the required {@link reopen}:
* the return form itself carries the obligation.
*
* Deployment correspondence (an ask-row store implementing the same law maps its own vocabulary):
* token+scope ↔ the ask id (+ its run binding); pending/resolved/expired ↔ the ask row's
* open/decided/terminal states; intent `resolve(outcome)` ↔ the human-decision verb; intent
* `expire` ↔ the expire/cancel verbs; the `claimed:false → (status, resolvedOutcome)` PAIRED read
* ↔ the decided row's recorded decision (reading the pair as the CURRENT decision is the CALLER's
* discipline here — gate-kind matching — while a single-decision row schema satisfies it
* structurally). Two shape notes carried from that correspondence: a store whose rows have NO
* OCC/rev axis simply never produces the `status:"pending"` loss arm (an honestly absent arm is
* correct — do not fabricate a rev); a store whose domain has NO reopen verb enjoys stronger
* monotonicity than law 5 assumes — consumption written against law 5's weaker snapshot reading
* stays correct there unchanged.
*/
claimTerminal?(token: CheckpointToken, scope: string, intent: TerminalClaimIntent): Promise<TerminalClaimOutcome>;
/**
* CAS-expire `pending` checkpoints in `scope` whose `deadline` has passed (`deadline <= cutoff`):
* `pending → expired`. Returns the count expired (for metrics). Idempotent across replicas (DB
* serializes; only the first wins each row) — no leader election needed (§6).
*
* **Does NOT unpin the sessions of the checkpoints it expires (council finding #2).** A suspend pinned
* its session against idle eviction; reaping the checkpoint here leaves that pin in place. The reaper
* that calls `reap` owns releasing the pin. For a **durable** session store this is a no-op anyway
* (`pin`/`unpin` are no-ops; it never idle-GCs), so reap-without-unpin is harmless — the only store with
* a real pin is the in-memory `TtlSessionStore` (single-instance / tests), where an un-released pin
* keeps an abandoned suspended session in the cache until process exit. v1 leaves the runner without an
* auto-reaper (the service owns the TTL worker); a reaper over the in-memory store should track and
* `unpin` the expired sessions itself if that leak matters for its deployment. This no-unpin posture
* is LOCAL to this live-path `reap`: the managed-retention contract's `expireCheckpoints`
* ({@link import("./retention.js").ManagedRetentionCapability}) deliberately closes the reap/unpin
* split — a retention-terminal row has its pin released BY that method, so pin release stays
* exactly-once per row (each row is terminated by exactly one of the two lanes).
*/
reap(scope: string, cutoff: number): Promise<number>;
/**
* design/80 assistant-scheduler seam #1: list a lightweight {@link CheckpointSummary}
* for EVERY **pending** checkpoint in `scope` (the suspended / awaiting-human tasks — NOT resolved/expired) in
* ONE call, so a supervisor scheduler can enumerate a scope's open suspensions without N+1 `get`s or hauling
* full {@link Checkpoint} payloads. Read-only — it never mutates a row, takes no CAS, and has ZERO effect on
* the once-only resolve. The PENDING predicate is byte-for-byte the {@link resolve} CAS's (`scope === scope &&
* status === 'pending'`), so the list reflects exactly the rows that are still resumable. Order is unspecified
* (the inbox sorts by `severity`/`deadline` itself). An empty scope returns `[]`. Required: every store answers it.
* A row whose summary cannot be read is one row of the answer in its unreadable form ({@link CheckpointSummary.rowVerdict}),
* never a failed page: the rows beside it are listed as they would be without it.
*/
listByScope(scope: string): Promise<CheckpointSummary[]>;
/**
* Deployment seam: the DISTINCT scopes that currently have at least one PENDING checkpoint — the
* enumeration face `listByScope` lacks. A host keeping its own scope registry (e.g. a sidecar file for a
* cross-scope inbox) can rebuild it from the data itself when the registry is lost/corrupt, instead of the
* enumeration silently going empty and pending approvals turning invisible. Scoped to PENDING deliberately:
* it matches `listByScope`'s visible surface, so `listScopes() × listByScope()` is exactly the full inbox,
* and a member the summary does not project is read with `get(token)` on the listed token — the composition
* a deployment's approval queue is, rather than a query of its own over the store's rows.
* **OPTIONAL** (unlike the required {@link listByScope}); the in-memory and file first-party impls provide it.
*/
listScopes?(): Promise<string[]>;
/** The PENDING rows of every scope past their deadline (or age backstop), one facet per call ({@link CheckpointOverdueQuery}; read by
* `readCheckpointOverdueQuery`, keyset-paged, bounded). OPTIONAL, probed by presence; both first-party stores provide it. */
listOverdue?(query: CheckpointOverdueQuery): Promise<CheckpointPage<CheckpointSummary, CheckpointOverdueCursor>>;
/** The rows of ONE session in any status ({@link CheckpointSessionQuery}; read by `readCheckpointSessionQuery`, keyset-paged,
* bounded; a damaged row of the session answers `unreadable`, never skipped — a row with no string session id belongs to no session and is left out, disclosed; the file replay drops a row with a non-string token, scope or status, disclosed there). The query's `axis` says which session of a row it names: its own, or its run's (`checkpointRunSessionOf`). OPTIONAL, probed by presence; both first-party stores provide it. A store that offers it and cannot answer the run axis refuses `axis: "run"` (`config.invalid_argument`) — it never answers the row-session page in its place. */
listBySession?(query: CheckpointSessionQuery): Promise<CheckpointPage<CheckpointRowRead, CheckpointSessionCursor>>;
/** Delete the checkpoint rows of one session that exist when the call starts, in any status, when the guard admits it
* ({@link CheckpointDeleteGuard}); answers the count. Present exactly when the store can judge the guard (a session head read). */
deleteSessionCheckpoints?(sessionId: string, guard: CheckpointDeleteGuard): Promise<number>;
/**
* The operator's delete of the checkpoint rows of one session whose head cannot be read: the rows that exist when the call starts,
* in any status, deleted exactly when the session head read is refused `corrupt_session` (a readable head or no head answers 0 and
* deletes nothing; any other fault of the read rejects and deletes nothing). Never an owner's request and never called by an automatic
* path; placement is not read. Runs before the session store's `deleteUnreadable` of the same id, which removes the head it judged.
* A session id that is not a non-empty string is refused (`config.invalid_argument`). Present exactly when `deleteSessionCheckpoints` is.
*/
deleteUnreadableSessionCheckpoints?(sessionId: string): Promise<number>;
/**
* The checkpoint seat's identity re-key — REQUIRED (an identity migration has nothing else to call: only the engine can
* recompute a row's stamps, so no outside writer can move a row). A one-step seat ({@link import("./identity-rekey.js").ONE_STEP_REKEY_MODES}):
* `plan` counts, `leave` re-files; the input is read by `readIdentityRekeyInput` before anything else (a `TypeError`, nothing
* read). Each overload binds the step to its answer arm. The run's store seat does not read it — only a migration calls it.
*
* @contract checkpoint.rekey_identity — `rekeyIdentity({ fromPrincipal, toPrincipal, scopes, mode })` re-files, in place, every row on which the mapping
* changes a member's value: `principal` and each `state.inheritedGate.ancestorRules[].principal` equal to `fromPrincipal` become `toPrincipal`; `scope`,
* `state.legScope` and `durableApproval.scope` equal to a pair's `fromScope` become that pair's `toScope`; the partition — the recorded `isolationScope`,
* else the row's principal — is a value the scope pair whose source it is moves and the person moving never does (`rekeyOwnerIdentity`), recorded by the
* mint's own rule (only where it differs from the re-filed principal): a row that recorded none and whose principal moves without a pair for it records
* the partition it keeps. Every other member travels as it stands on the row at the write. The row's verdict decides only whether the row is touched: a
* row this engine judges `lacking` is left as it is and counted by `plan` as `conflicting`; `plan` also counts, as `unpairedScopeRows`, the re-filed rows
* whose principal moves while no scope pair names their partition's value. The row's stamps follow their own judge: stamps that match the row before the
* write are recomputed by the mint's stamp, stamps that do not are left as they are, and a row below the stamped format gains none and keeps its version.
* Each row is decided and written within the row's own write serialization, on the row as it stands there, with `rev` one above that row's. A backend
* that keeps columns writes them from `checkpointIndexFacts` of the row it writes, and writes each member it holds in a column into the stored payload
* only as the stored payload already held it, so a read of the row answers every such member as it did before. `leave` answers the rows it re-filed;
* tokens are unique, so no row can stand in another's way and there is no `conflict` answer; a `leave` cut short is completed by running it again.
*/
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "plan";
}): Promise<IdentityRekeyPlan>;
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "leave";
}): Promise<RekeyDone>;
}
/**
* The SINGLE resolution of "which CheckpointStore does this run use" (ruled 2026-08-04; re-homed
* from prepare-task with the design/173 wiring manifest so the static self-check half shares it
* without a runtime cycle). The spec seat is three-valued — a store wins, `undefined` falls through
* to the deployment's `RunnerDeps.checkpointStore`, and the explicit word `"disabled"` means this run
* has NO store at all (see `TaskSpec.checkpointStore`: the per-run off switch for the durable
* machine, so a machine-started run cannot mint a checkpoint nobody will ever resolve).
*
* The off switch is a WORD, not `null`, on purpose: `??` treats `null` exactly like `undefined`, so
* the old null sentinel silently fell through a bare coalesce to the very deployment store the
* caller asked not to have — re-arming every suspend leg while the run looked perfectly normal right
* up until it parked forever — and every read of the pair had to remember a special `=== null` test.
* A string is never nullish, so the ordinary coalesce is the whole rule. The retired spelling is
* REFUSED loudly here (the one read every site goes through) rather than read as either value: a
* caller still writing `null` is told the word to write, at the first prepare, instead of being
* handed a store it asked not to have or a silent off switch it did not spell.
*/
export declare function resolveCheckpointStore(spec: {
checkpointStore?: CheckpointStore | "disabled";
}, deps: {
checkpointStore?: CheckpointStore;
}): CheckpointStore | undefined;
/** The ONE refusal of a store seat whose {@link CheckpointStore} lacks a required member (the {@link CheckpointStore.recordExecutionOutcome}
* verb, the {@link CheckpointStore.reopen} verb) — every missing one named, with the seat and the store's constructor when it
* has one — or `undefined` when the store carries them all. Same door, same code, as the retired-`null` refusal below: a configuration
* the run cannot honour is refused at the first read, never carried. */
export declare function checkpointStoreIncomplete(seat: "TaskSpec.checkpointStore" | "RunnerDeps.checkpointStore", store: object): (Error & {
code: "config.invalid_checkpoint_store";
}) | undefined;
/** The ONE refusal of the retired `checkpointStore: null` spelling (the resolver and the workflow baseline overlay both throw it). */
export declare function retiredCheckpointStoreNull(): Error & {
code: "config.invalid_checkpoint_store";
};
/**
* design/80 D-1 (persist-winner): derive the durable {@link ResolvedOutcome} winner from a resume
* `outcome`, or `undefined` when the outcome binds to no pending action. A `policy_ask` resume names a
* specific tool call (`boundCallId`) + decision; since RB-64 the REVIEW gates (`plan_review` /
* `dry_run_review`) record their decision under a `gate:` sentinel too — the env_failed replay guard can
* only compare what is recorded here. Only `resource_limit` / `task_done` bind nothing and record no
* winner. Shared by every {@link CheckpointStore} impl so the persisted winner is identical across the
* in-memory and durable backends.
*/
export declare function winnerFromOutcome(outcome: ResumeOutcome): ResolvedOutcome | undefined;
/**
* design/80 D-A: the persist-time validation every {@link CheckpointStore.setPendingSteer} impl runs so the
* reject is IDENTICAL across the in-memory and durable backends. A `steer.text` carrying a `</system-reminder>`
* close tag would escape the model-facing `<system-reminder>` wrapper a trusted steer rides on resume — reject
* fail-closed (`steering.invalid_content`) so a dirty steer NEVER enters {@link CheckpointState} (§3 inv #2).
* Applied for BOTH `trusted` values: the durable record must be clean on either path (the untrusted resume
* path ALSO sanitizes as untrusted data, but the close tag must never reach the persisted state at all).
* Returns a copy built from the FROZEN field set ({@link PENDING_STEER_FROZEN_FIELDS} minus the
* store-minted `seq`), so no extra caller field leaks into the row — and, since design/171 §6.3, an
* unknown key is a loud rejection rather than a silent drop: a producer one release ahead of this worker
* must learn that its new field would not survive the parked leg.
*/
export declare function validatePendingSteer(steer: PendingSteerInput): Omit<PendingSteerEntry, "seq">;
/** design/171 §6.1 — the `actor` id/issuer bound. Attribution labels ride the durable row and the model
* context, so they are capped like every other persisted model-facing string on this row. */
export declare const MAX_ACTOR_FIELD_CHARS = 256;
/** design/171 §6.3 — bound on the caller-supplied correlation id (a service's own message id). */
export declare const MAX_STEER_INPUT_ID_CHARS = 128;
/** design/171 §6.1 — the frozen field set of an {@link ActorAssertion} (same fail-loud posture as the
* entry's own set: an unknown key means a producer's provenance field would vanish silently). */
export declare const ACTOR_ASSERTION_FROZEN_FIELDS: readonly ["id", "hostAsserted", "issuer"];
/**
* design/171 §5.3 — THE single read point for a checkpoint's parked steers, in delivery (`seq`) order.
* Every consumer — the resume drain, the wake's nothing-to-deliver guard, a serving layer — goes through
* here, so no site can grow its own idea of what "the parked steer" is.
*
* A row that still carries the RETIRED pre-queue single seat is refused here rather than read
* (`retiredSteerSeatRefusal`, checkpoint-row-verdict.ts, thrown). A resume never reaches this refusal: the row's judge
* refused the row before the claim, with the same refusal.
*/
export declare function readPendingSteerQueue(state: Pick<CheckpointState, "pendingSteerQueue">): PendingSteerEntry[];
/**
* The parked queue's ONE identity judgment (the append below and the wake entrance read it): the held entry
* when `entry` repeats it identically (the replay), `undefined` for a new `inputId`, else
* `steering.duplicate_input_id` naming the facets that differ — the key alone is no proof of a replay.
*/
export declare function judgeParkedSteerRepeat(queue: readonly PendingSteerEntry[], entry: Omit<PendingSteerEntry, "seq">): PendingSteerEntry | undefined;
/**
* design/171 §5.3/§6.3 — THE append, shared by every backend so the bounds and the ordering are one
* implementation rather than one per store.
*
* Returns the NEW queue (the caller persists it); throws `steering.queue_full` when the queue would
* serialize past the byte budget (the only capacity bound). Re-appending an entry whose `inputId` is already queued is a NO-OP returning the queue
* unchanged — that is what keeps `setPendingSteer` retry-safe now that it appends instead of overwriting.
*/
export declare function appendPendingSteer(state: Pick<CheckpointState, "pendingSteerQueue">, entry: Omit<PendingSteerEntry, "seq">): PendingSteerEntry[];
/**
* REF-A4 — THE row half of every guarded checkpoint transition's CAS predicate, shared by every backend:
* the row must EXIST, its `scope` must match (multi-tenant isolation, §2.1 — a wrong-scope caller never
* wins), and it must currently be in `status`. `resolve` requires `"pending"`, `reopen` requires
* `"resolved"` (the inverse gate), `setPendingSteer`/`expire` require `"pending"`.
*
* PURE: it decides nothing about persistence. Each backend keeps its own commit half — the in-memory one
* flips fields in place, the file one appends+fsyncs the event BEFORE the flip (RB-150: commit ordering is
* that backend's own correctness core and must never be absorbed into a shared abstraction).
*/
export declare function checkpointRowMatches(cp: Checkpoint | undefined, scope: string, status: Checkpoint["status"]): cp is Checkpoint;
/** Fault-injection mode for {@link InMemoryCheckpointStore.testInjectFault} (council #5). One-shot. */
export type CheckpointFaultMode =
/** `resolve` commits the CAS (status → resolved) then throws — simulates a crash *after* the commit
* but before the caller is acked, so a retry must see `resolved` and NOT re-execute (idempotency). */
"resolve-after-commit"
/** `resolve` throws *before* the CAS — simulates a crash before the commit; the row stays `pending`
* so a retry can still win it. */
| "resolve-before-commit"
/** design/384 slice 2 — `claimTerminal` wins its claim (the commit lands) then throws before the
* caller is acked: the claim-law recovery scenario (law 3/4 — a reject proves nothing; the retry's
* loss answer carries the truth and a responsibility-bearing consumer must NOT self-attribute). */
| "claim-after-commit"
/** design/384 slice 2 — `claimTerminal` throws *before* its CAS: the row is untouched (still
* pending), so a retry can still win the same claim. */
| "claim-before-commit";
/**
* Default in-process {@link CheckpointStore}. Single-instance / tests only — it does NOT survive a
* restart or span replicas, so it cannot deliver the cross-process guarantee a durable backend does.
* Single-threaded JS already serializes `resolve`, so the CAS is trivially atomic here;
* {@link testInjectFault} simulates the crash-recovery races a real backend must survive.
*/
export declare class InMemoryCheckpointStore implements CheckpointStore {
/** Managed-retention declaration (retention.ts) — the `retention` option (default `"none"`, a third word refused), stated by
* the party that runs the sweep. In-memory rows die with the process, which is not a schedule. */
readonly retention: RetentionDeclaration;
/** design/173 §2.3 — honest declaration: in-memory rows die with the process. */
readonly durability: "process-local";
/** Honest declaration on the fidelity axis: `put`/`get` are `structuredClone`, so a row keeps the
* whole structured-clone domain — a `Date` filed here is a `Date` when it comes back. */
readonly fidelity: "structured-clone";
/** `{ holder: "writes" }`, declared exactly when the store was built with a `holderIsCurrent` judge ({@link CheckpointStore.fence}):
* the judge is then asked on every write that carries a holder. */
readonly fence?: StoreHolderFence;
private cps;
/** The listing's memo of each stored row object's verdict: a `put` stores a new object, so a replaced row is judged again. */
private readonly rowVerdicts;
private fault;
private readonly disclose;
private readonly holderIsCurrent;
readonly deleteSessionCheckpoints?: (sessionId: string, guard: CheckpointDeleteGuard) => Promise<number>;
readonly deleteUnreadableSessionCheckpoints?: (sessionId: string) => Promise<number>;
/** `disclose` is the listing projections' own seat ({@link summarizeCheckpoint}'s and the listing faces'): this store has no
* path, so it forwards each sentence for a row read past a damage, called synchronously by the listing that read it.
* `sessionHeadOf` (a session store's `headOf`) is what {@link CheckpointStore.deleteSessionCheckpoints} judges its guard by, and what
* {@link CheckpointStore.deleteUnreadableSessionCheckpoints} judges unreadability by; `holderIsCurrent` ({@link HolderJudge}), a resolve's `expect.holder`. */
constructor(options?: {
disclose?: (sentence: string) => void;
sessionHeadOf?: (sessionId: string) => Promise<{
readonly owner: string | null;
} | undefined>;
holderIsCurrent?: HolderJudge;
retention?: RetentionDeclaration;
});
put(token: CheckpointToken, cp: Checkpoint, opts?: CheckpointWriteOptions): Promise<void>;
get(token: CheckpointToken): Promise<Checkpoint | null>;
/** The loser's single-round-trip reading (claim law 1): what the row IS, in its own vocabulary —
* or `absent` for a missing row AND a wrong-scope row alike (the isolation rule: cross-scope truth
* in a loss answer would be a read bypass of the scope WHERE). Cloned projection, never a live ref. */
protected claimLossFrom(cp: Checkpoint | undefined, scope: string): TerminalClaimOutcome;
/**
* The ONE protected write core for the terminal-resolve claim — `resolve` and
* `claimTerminal({kind:"resolve"})` both run exactly this (claim law 2's one-machine obligation:
* one predicate, one commit, no drift window). Single-threaded JS makes the check + flip atomic; a
* durable backend folds the same predicate into its CAS WHERE clause.
*
* ORDER (design/384 slice 2, healing the pre-existing resolve shape): the winner is derived and
* CLONED — the point where an uncloneable `updatedInput` says so — BEFORE any field is written, and
* the commit is then one uninterrupted write group (status+rev+winner+reopenReason). The old order
* cloned AFTER the status/rev flip, so an uncloneable winner threw with the row already resolved
* and NO winner recorded; now the same throw leaves the row byte-identical (still pending) — the
* claim REJECTS (a reject proves nothing, law 3) instead of half-committing.
*/
protected claimResolveCore(token: CheckpointToken, scope: string, outcome: ResumeOutcome, expect?: ResolveExpectation): TerminalClaimOutcome;
/** The one protected write core for the terminal-expire claim — `expire` and
* `claimTerminal({kind:"expire"})` both run exactly this (claim law 2, same as the resolve core). */
protected claimExpireCore(token: CheckpointToken, scope: string, holder?: string): TerminalClaimOutcome;
resolve(token: CheckpointToken, scope: string, outcome: ResumeOutcome, expect?: ResolveExpectation): Promise<boolean>;
/** design/384 slice 2 — the atomic terminal claim (the interface JSDoc is the law's single
* normative statement). Implemented OVER the same protected cores `resolve`/`expire` run, which is
* the one-machine obligation discharged rather than restated. ONE fault plane with the one
* machine: a fault armed under the `resolve-*` names fires on the claim route of the SAME CAS too
* (`kind:"resolve"` only — expire never consumed resolve faults), so a crash simulation pinned
* against the two-step verb keeps firing byte-identically when the runner adopts the claim form.
*
* INHERITANCE OBLIGATION (a subclass provides `claimTerminal` whether it means to or not): a
* subclass that overrides `resolve`/`expire` to wrap the CAS (audit hooks, fault injection,
* interleave fixtures) must override THIS method consistently. Overriding the `protected` cores
* (`claimResolveCore`/`claimExpireCore`) instead covers every COMMIT on every route — the cores
* are the one write core all three verbs share — but NOT every ATTEMPT: `resolve`/`expire`
* evaluate the shared row predicate themselves and return `false` without entering a core when
* the row is not pending (missing, another scope, already terminal), while this claim route
* enters the core unconditionally and takes its loss reading from it. A core override therefore
* sees every winning claim and every OCC loss, but a row-predicate loss only when it arrived via
* the claim route; a hook that must record EVERY attempt, including those losses, on EVERY route
* wraps the three public verbs consistently. The same applies to a DELEGATING WRAPPER (Proxy / hand-built object)
* that forwards `claimTerminal` while hooking only `resolve`: forwarding IS providing, and the
* claim route is then the one that actually runs. A resolve-only wrap goes dark the moment a
* consumer prefers the claim route (the runner's resume does), which is a one-machine-law
* violation the SUBCLASS created — the base class cannot route through the public verbs
* instead, because an `await` between the CAS and the loss reading would break the law-1
* atomic unit this method exists to provide. (A wrapper that OMITS the member opts out
* cleanly: the consumer's presence probe then keeps the two-step path, hooks intact.) */
claimTerminal(token: CheckpointToken, scope: string, intent: TerminalClaimIntent): Promise<TerminalClaimOutcome>;
recordExecutionOutcome(token: CheckpointToken, scope: string, gate: GateOutcome): Promise<ExecutionOutcomeRecordWord>;
reopen(token: CheckpointToken, scope: string, reason: ReopenReason, expect?: Pick<ResolveExpectation, "rev">): Promise<boolean>;
setPendingSteer(token: CheckpointToken, scope: string, steer: PendingSteerInput, opts?: CheckpointWriteOptions): Promise<boolean>;
expire(token: CheckpointToken, scope: string, opts?: CheckpointWriteOptions): Promise<boolean>;
reap(scope: string, cutoff: number): Promise<number>;
listByScope(scope: string): Promise<CheckpointSummary[]>;
listScopes(): Promise<string[]>;
listOverdue(query: CheckpointOverdueQuery): Promise<CheckpointPage<CheckpointSummary, CheckpointOverdueCursor>>;
listBySession(query: CheckpointSessionQuery): Promise<CheckpointPage<CheckpointRowRead, CheckpointSessionCursor>>;
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "plan";
}): Promise<IdentityRekeyPlan>;
rekeyIdentity(input: IdentityRekeyInput & {
readonly mode: "leave";
}): Promise<RekeyDone>;
/** Arm a one-shot fault on the next `resolve` (council #5: makes crash-recovery unit-testable). */
testInjectFault(mode: CheckpointFaultMode | null): void;
/** Test/inspection helper: number of stored checkpoints. */
get size(): number;
}