@sema-agent/core
Version:
Stateless, task-oriented AI agent core
840 lines • 66 kB
TypeScript
import type { SubagentEditedFile, SubagentStep } from "../agents/subagent-steps.js";
import type { SubagentTranscriptTier } from "./wiring-manifest.js";
import type { ExtensionRequester } from "./task-event.js";
import { type MemberOutcome, type MemberRefusals } from "./member-outcome.js";
import { type DamagedRowVerdict, type RowContext } from "./row-shape.js";
/**
* The settled words of a background agent row — its run has ended, and only a deletion or a revival moves the row again: the one
* answer to "is this row's run over", read by every reap, listing, ending and stop path of the engine and of a host. The other two
* lifecycle words, `running` and `parked`, are live: such a row is never reaped and has no ending yet.
*/
export declare const BACKGROUND_AGENT_SETTLED_STATUSES: readonly ["completed", "failed", "killed"];
export type BackgroundAgentSettledStatus = (typeof BACKGROUND_AGENT_SETTLED_STATUSES)[number];
/** The live words of a background agent row, the other half of {@link BACKGROUND_AGENT_STATUSES}: its run has not ended. A write that
* ends a live row (a stop) acts on these two only. The package root exports both halves: a reader asks each half by its own
* predicate, and a word outside the vocabulary answers false to both. */
export declare const BACKGROUND_AGENT_LIVE_STATUSES: readonly ["running", "parked"];
/** A background agent row's lifecycle words (closed; the stored row's `status` is read against it): the two live words, then
* {@link BACKGROUND_AGENT_SETTLED_STATUSES}. */
export declare const BACKGROUND_AGENT_STATUSES: readonly ["running", "parked", "completed", "failed", "killed"];
export type BackgroundAgentStatus = (typeof BACKGROUND_AGENT_STATUSES)[number];
/**
* Whether `status` is one of {@link BACKGROUND_AGENT_SETTLED_STATUSES}. Anything else answers `false` — `running` and `parked`, and
* any value outside {@link BACKGROUND_AGENT_STATUSES} (another word, another case, not a string). Such a value is not a word this
* engine writes, and the row reader refuses a row carrying it (a damaged row, `rowVerdict`). A reader holding one anyway reads it as
* neither half: it does not reap the row, does not read it as ended, and does not write over it as live
* ({@link isBackgroundAgentLiveStatus}).
*/
export declare function isBackgroundAgentSettledStatus(status: unknown): status is BackgroundAgentSettledStatus;
/** Whether `status` is one of {@link BACKGROUND_AGENT_LIVE_STATUSES} — the reading a write that ends a live row is gated on. */
export declare function isBackgroundAgentLiveStatus(status: unknown): status is (typeof BACKGROUND_AGENT_LIVE_STATUSES)[number];
import { type RekeyConflict, type RekeyDone, type RekeyMode, type RekeyPlan, type ScopeRekeyInput } from "./identity-rekey.js";
/** Terminal/live usage rollup persisted on the row (mirror of the task_notification/BCE fields). */
export interface BackgroundAgentUsage {
totalTokens?: number;
toolUses?: number;
durationMs?: number;
tokens?: number;
turns?: number;
costMicroUsd?: number;
}
/**
* One durable background-agent execution row. Field discipline (design/151 §3.1, HIGH-4): revival
* re-hydration data is LOOKUP KEYS ONLY (`agentType`/`model`/`name` — the reference's
* `.meta.json` sidecar shape) — never a serialized spec and never closures; a tier-3 revival rebuilds
* the spec the same way a fresh named-teammate spawn would (roster/agent definition + the reviver's
* deployment assembly).
*/
export interface BackgroundAgentRecord {
/** Row key: the registry handle (`a…` domain), stable across restarts. */
handle: string;
/** Tenant/principal scope — put-time REQUIRED (assertOwnership parity: a row with neither a real
* scope nor an owner would be world-readable through the fallback; the registry writer always has
* both). It is the row's partition key: `update` never rewrites it, and a row changes partition only
* through {@link BackgroundAgentStore.rekeyScope} (an arrival under the new key, then the old key's leave). */
scope: string;
/** task-scoped: the host taskId · session-scoped: the sessionId (registry owner semantics). */
owner: string;
sessionScoped: boolean;
/** The child's store session id — the transcript / resume anchor. Absent at put (the child session
* is minted AFTER registration); bound via a follow-up CAS update. */
sessionId?: string;
/** Spawn-time root linkage — the durable enumeration key for task-scoped rows
* ({@link BackgroundAgentStore.listBySession}) and the restart read leg of the access predicate. */
parentSessionId?: string;
/** the ROOT host session of the delegation tree (fixed point down the internals chain). Its own axis, not the
* parent's: {@link parentSessionId} is the session of the leg that spawned this one, and the two coincide only when
* the spawning leg ran in the root session itself (a cascade rung or a deeper leg spawns under its own session while the
* root stays the host's). The row's delegation depth is {@link spawnDepth}, never read off these two. The recovery-face enumeration anchor: after a
* restart, intermediate spawner sessions are dead ends — "everything under this host session"
* keys on THIS field (listBySession matches it as a second arm), not on an alias walk. */
rootSessionId?: string;
/** The occupant of {@link rootSessionId}'s row (its `SessionMetadata.incarnation`) as the spawning tree held it — the other
* half of the root anchor's address, written beside it by the registration that creates the row. A revival reads it back
* with the anchor, so the frames its subtree escalates to the root are addressed to the occupant the tree was born under
* (delivered while that occupant holds the root, discarded and announced once the id was created again). ABSENT = the
* spawning tree held no occupant for its root, or a row an earlier release wrote: the revived tree's root occupant is
* then unknown. A store returns it as written, absent as absent. */
rootSessionIncarnation?: string;
/** The scope {@link rootSessionId}'s durable box mounts in (the registry scope of the tree's root leg) — the third member of the
* root anchor's address, written beside it with the occupant. A drive of this row on a runner where no leg of the root runs
* writes the completion into that box. ABSENT = a row an earlier release wrote: the root's box is not judged, and such a drive's
* completion keeps the mount's sink. A store returns it as written, absent as absent. */
rootSessionScope?: string;
parentTaskId?: string;
/** The agent's name — the spawner's explicit one, or the one the engine derives from `handle`
* (`engineAgentName`) when the spawn named none. Written by the registration that creates the row, so
* every row core writes carries one; a revival re-reads it verbatim. A host store that reads a row an
* earlier version wrote without one derives it from `handle` with the same function. */
name: string;
agentType?: string;
/** Who started the agent when an extension did: the extension, by its registration name (`$.agent.spawn`). Written once, by the
* registration that creates the row; a revival keeps it (the row's origin, not the waker's). ABSENT = not an extension's spawn
* (the model's own, the host's) — and every row an earlier release wrote: the one reading, with no word for either. A display and
* audit fact only — it decides nothing. */
requestedBy?: ExtensionRequester;
description?: string;
/** Revival lookup key (CC meta-sidecar parity); populated when known, never required. The team
* key is {@link rootSessionId} — one implicit team per session, no column of its own. */
model?: string;
/** design/151 §3.1d (HIGH-3): the WRITING process instance id (random per registry instance). A
* fallback read of a `running` row whose writer is not the reading instance serves an HONEST
* "outcome unknown here" — never a fabricated "running" liveness claim.
* S3 revival ORDER OBLIGATION: a cross-process revival must first CAS this field
* over to the reviving instance's writerId (the claim), THEN register-with-id — a fresh lane's
* first write against a row still carrying the dead process's writerId reads back "foreign" and
* poisons itself by design. Claim-CAS first is the only sequence the adjudication admits. */
writerId: string;
/**
* design/153 §7.2c (r6 H-3) — the monotonic OWNERSHIP GENERATION, bumped by every ownership
* transfer (tier-3 claim, 件3 resume claim finalize, the in-process retained-revive claim). A
* ROLLBACK is itself a transfer, so every rollback shape mints a NEW epoch too — the reconciliation
* sweep's reservation/running rollbacks, the parked-reservation rollback (which additionally syncs
* this process's SURVIVING lane forward so its own later terminal write does not foreignize), and
* the revival-claim compensation. No rollback restores a pre-claim epoch: an orphaned lane's
* authority must never become resumable, and restoring the old generation would let the next claim
* by the SAME writer land on the very (writerId, epoch) pair that lane still holds. What a rollback
* restores is the pre-claim writerId and row shape — that is what makes the row addressable again;
* the fresh generation is what keeps the abandoned lane from speaking for it. The
* durable-lane adopt matches
* `writerId + writerEpoch` BOTH: a stale lane of the SAME writer (pre-transfer snapshot still in
* its chain) reads "foreign" instead of adopting the new rev and replaying its old record — the
* lane-self-clobber ABA the epoch exists to close. Optional: legacy rows (undefined) keep the
* pre-epoch writerId-only adopt semantics unchanged.
*/
writerEpoch?: number;
spawnedAt: number;
updatedAt: number;
settledAt?: number;
/** design/153 §7.1: `"parked"` = durably suspended on a pending checkpoint (neither live nor terminal; what it
* waits on is the checkpoint's gate — a person's approval, or a resource limit such as a scheduler's yield, which
* its owner's next leg continues) — reap-exempt like `running`; cleared to a real state by resume claim, TaskStop
* (checkpoint arbitration first), or the reconciliation sweep (checkpoint expired/missing). */
status: BackgroundAgentStatus;
/** Open enum (task-registry `StopSource` mirror). */
stoppedBy?: string;
/** The cross-channel completion correlation id
* (task-registry `SemaTaskHandle.completionId` mirror). Written alongside `status`/`settledAt` at
* the same durable terminal write that lands them, so a cross-restart read — a host poll or a listing
* ({@link BackgroundAgentRowSummary.completionId}) after the writing process is gone — REPLAYS this exact value.
* A terminal write that has a live handle copies what the handle already minted; a store-side terminal write
* with no live handle (the store-only reconciliation, the stale-running reap) mints it through the same
* fill-once `mintCompletionId` — one minter either way. */
completionId?: string;
/** The row's stop-cycle number: 1 from the registration's first write, and one step past the stored value
* ({@link nextCycleSeq}) in the very write of each claim that opens a cycle — the retained wake's, the tier-3 and
* drain revivals', the parked-resume consume flip's. No other write touches it, so every lane's next cycle reads the
* number the last claim left, and `task_id:status:seq` keys never repeat for one row (across lanes and restarts).
* Absent only on a row an older version wrote before its first settle. */
seq?: number;
/**
* design/153 §7.1 — the checkpoint token this row is parked ON (any gate; `status:"parked"`
* only; park mint writes it, resume claim / terminal settle clears it). The checkpoint token CAS is
* the MASTER arbitration domain (r4 F-05): every parked-row CAS also verifies THIS binding, and the
* row never adjudicates a park outcome on its own. A row CAS that loses after the checkpoint was
* committed is compensated by EXPIRING the checkpoint (no "committed but undiscoverable" orphans).
*/
parkedCheckpointToken?: string;
/** design/153 §7.1 — when the park landed (epoch ms). Observability + reconciliation ordering only. */
parkedAt?: number;
/** design/153 §7.2 — the in-flight resume claim's compensable-ticket id (parked→running CAS writes
* it, a successful attach finalize clears it, a pre-attach failure rolls back BY it). A `running`
* row still carrying BOTH this and `parkedCheckpointToken` past the claim lease is a stale claim —
* the reconciliation sweep rolls it back to `parked`. */
parkClaimId?: string;
summary?: string;
finalOutput?: string;
/** The FULL result (workflow.ts NH-1 shape via {@link BackgroundAgentTaskHandle.resultFull}),
* set only when it differs from `finalOutput` — the restart/durable-fallback poll path needs the same
* pairing the live handle carries, or a process restart loses the very recoverability this field exists
* to preserve. */
finalOutputFull?: string;
/** The child's failure text (registry `handle.error` mirror; the reap-stop sentinel never lands here).
* The stale-running reap flip ALSO writes its attribution here (`??`-guarded) —
* `error` is the field the durable serving face renders (`serveDurableAgentRow`), while `summary`
* has no reader on that face, so an attribution written only to `summary` was invisible: a host
* crash read as a bare `failed` + "(no result text)". */
error?: string;
/** The classification triplet the in-memory handle carries under
* the SAME names (`errorCode`/`errorRetryable`/`errorKind`; see RB-386②/RB-405 G3 on
* {@link import("./task-registry-shared.js").BackgroundAgentTaskHandle}), written to this row at the
* same terminal write that lands `error` — so a cross-restart fallback read
* ({@link import("./task-registry-agent.js").serveDurableAgentRowLane}) can render the identical
* classification clause the live poll does, instead of the row structurally losing it once the
* writing process exits (the residual this field set closes). */
errorCode?: string;
errorRetryable?: boolean;
errorKind?: string;
errorRetryAfterMs?: number;
resultIsPartial?: boolean;
/** How the agent ended (`MemberOutcome`): its ending word and its one refusal record (asks nobody could answer, calls refused, a
* verdict that never landed, a person's halt), written by the terminal settle beside `status` (a refusal leaves the status
* `completed`). Absent on a row whose ending the leg's own settle never reached (a landed stop or reap). A row an earlier engine
* wrote carries none and may carry `refusedAsks` instead — read either through `agentOutcomeOf`, never this member alone. */
outcome?: import("./member-outcome.js").MemberOutcome;
/** Written by engines before rows carried {@link outcome}: the run's asks nobody could answer. Never written now; READ only, by
* `agentOutcomeOf`, so an upgraded process serving an old row still says what its agent did not get done. */
refusedAsks?: import("./task-result.js").RefusedAsk[];
recentSteps?: SubagentStep[];
editedFiles?: SubagentEditedFile[];
usage?: BackgroundAgentUsage;
/** The org scopes the row's most recent leg actually mounted. ABSENT is NOT "unknown ⇒
* unconstrained": the revival reads an absent field as the ZERO verdict (see
* `readDurableOrgAdmission` in memory-admission.ts), so a pre-#22 row and a row whose leg
* mounted no org plane both admit nothing on the org axis. Written by the leg itself once its
* prepare has adjudicated (task-registry `recordBackgroundAgentOrgAdmission`), so every revival
* cycle re-records its own — necessarily narrower — verdict. */
admittedOrgScopes?: string[];
/** The explicit org WRITE grant that verdict carried; `null` = the org write face was read-only.
* Same absent-reads-as-zero rule as {@link admittedOrgScopes} (absent ⇒ `null`). */
admittedOrgWriteScope?: string | null;
/**
* The tighten-only floor the row's child was BORN under: the clamp table's projection of the spec the spawn built for it
* (`clampSeatsOf`, both carriers — the parent's clamps that rode it and the definition's own restrictions), the same shape
* as {@link import("./child-clamp-seats.js").ClampValues}. Written once, by the registration that creates the row
* (`{}` when nothing was clamped), and never rewritten: a revival builds its spec under the table's fold of THIS floor and
* the waking caller's own clamps, so whoever wakes the child can narrow it and nobody can widen it. Same reason as the
* org-admission pair above for why a policy fact rides a lookup-keys-only row: the tier-3 leg rebuilds the spec from the
* WAKER's mount, so without the row nothing of the spawning run's clamps reaches the revived cycle.
* ABSENT is not "no floor": a row that states none (written before rows carried it, or by a store that does not keep the
* member) is not revived — `readClampFloor` reads it as unreadable and both revival doors refuse
* (`revive.policy_floor_unreadable`). A store persists it verbatim: `{}` reads back as `{}`.
*/
policyFloor?: import("./child-clamp-seats.js").ClampValues;
/**
* The agent's own delegation depth at birth, from 1 (a child of the main agent's delegation tool is 1, its child 2, …) — written
* once, by the registration that creates the row, and never rewritten. A revival mounts the agent's delegation tool by THIS depth
* (it may delegate only while it is under the tool's `maxDepth`), never by the depth of the tool that woke it. ABSENT on a row
* an earlier release wrote, or a store that does not keep the member: a legal row, revived without the delegation tool (announced
* once, `delegation.spawn_depth_unknown`). A value that is not a whole number from 1 makes the row unreadable. A store keeps it
* verbatim; an engine that predates it carries it as a member it does not read.
*/
spawnDepth?: number;
/**
* `true` = the agent was born a worker of a run that keeps a member ledger (`TaskSpec.runLedger`), so its spawn handed it no tool
* that starts agent runs. Written once, by the registration that creates the row, and never rewritten. A revival by the host's
* parked-resume drive hands the revived agent no such tool either, whichever leg drives it. ABSENT = not born in such a run, or a
* row an earlier release wrote, or a store that does not keep the member: read as not born in one. Any other value makes the row
* unreadable. A store keeps it verbatim; an engine that predates it carries it as a member it does not read.
*/
bornInLedgerRun?: true;
/** Optimistic-concurrency revision. The writer always CASes with its OWN held rev (design/151
* MED-8): a foreign row (stale leftover / another writer) has an unknown rev, so the CAS loses
* instead of clobbering. Bumped by the store on every successful `update`. */
rev: number;
}
/**
* The terminal payload a REVIVAL must erase from the row it is re-launching, as ONE list.
*
* A revived handle starts a fresh cycle on an existing row: status flips back to `running`, but every
* field describing how the PREVIOUS cycle ended is still sitting there. Left standing, each one
* surfaces the old cycle's answer under the new cycle's status — a stale `finalOutputFull` is served
* in preference to the fresh `finalOutput` by the durable read face, a stale `errorCode`/`errorKind`
* pair renders a "network / retryable" classification on a row that has since completed cleanly, a
* stale `completionId` makes two different completions report one correlation id.
*
* There are TWO revival entry points — the in-process wake and the cross-process tier-3 claim-CAS —
* and they maintained two hand-written copies of this list. The copies drifted: `finalOutputFull` and
* the error triplet were added to one and not the other, and each addition was a separately-found
* defect of the same shape. One list, both callers, so the next field added to the terminal snapshot
* can only be forgotten once.
*
* Every member is optional on {@link BackgroundAgentRecord} (that is what makes them clearable);
* identity, lifecycle, concurrency and GOVERNANCE fields are deliberately absent — a revival
* inherits those. The org-admission freeze (`admittedOrgScopes` / `admittedOrgWriteScope`) and the
* birth floor (`policyFloor`) are in the governance group on purpose: clearing either would hand the
* next cycle a blank slate, which is the widening each exists to prevent.
*/
export declare const REVIVED_ROW_CLEARED_FIELDS: readonly ["settledAt", "stoppedBy", "completionId", "finalOutput", "finalOutputFull", "error", "errorCode", "errorRetryable", "errorKind", "errorRetryAfterMs", "resultIsPartial", "outcome", "refusedAsks", "summary", "recentSteps", "editedFiles", "usage"];
/** Erase {@link REVIVED_ROW_CLEARED_FIELDS} from a record a revival is about to write back. */
export declare function clearRevivedRowTerminalPayload(record: BackgroundAgentRecord): void;
/** The stop-cycle number a wake opens on a row: one past the row's, written by the claim that opens the cycle, in
* that same write (so of two claims on one row only the winner's number exists). The one place it is computed — the
* retained wake, the tier-3 and drain revivals and the parked-resume consume flip all call it; a row with no stored
* row (a store-less registration) passes its registry handle's number, which is that row. */
export declare function nextCycleSeq(row: {
readonly seq?: number;
}): number;
/**
* Whether a deployment's subagent transcript tier DECLARES that a finished agent's transcript outlives the process — the one tier a vanished
* transcript contradicts. `full` makes that promise; `rows` keeps the agent's record but says transcripts follow the session store's fate (a
* transcript gone from a process-local store is what that tier means), and `none` has no row to bind one. The tier is the wiring manifest's
* own word (`WiringManifest.fleet.subagentTranscripts`, derived by `resolveSubagentTranscriptTier`); every site that meets a gone transcript
* hands the tier its mount derived to {@link announceTranscriptIntegrityGapOnce}, which asks this predicate — the one place it is asked.
*/
export declare const declaresTranscriptDurability: (tier: SubagentTranscriptTier) => boolean;
export declare function announceTranscriptIntegrityGapOnce(handle: string, scope: string | undefined, sink: ((handle: string, scope: string | undefined) => void) | undefined, tier: SubagentTranscriptTier): void;
/**
* Content-free projection for list reads (design/151 HIGH-1: `summary`/`finalOutput`/`recentSteps` and friends NEVER ride a list
* — content is get-by-handle only, behind the full predicate). A UNION: a row that reads ({@link BACKGROUND_AGENT_ROW_SHAPE}) is
* listed as {@link ReadableBackgroundAgentRowSummary}; one that does not is still one row of the listing —
* {@link DamagedBackgroundAgentRowSummary}, its handle and its verdict. Only the damaged arm carries `rowVerdict`: narrow with
* `"rowVerdict" in summary` before reading a member.
*/
export type BackgroundAgentRowSummary = ReadableBackgroundAgentRowSummary | DamagedBackgroundAgentRowSummary;
/** A listed row that does not read: its handle and its verdict (the family's code, the member that failed first, its form and
* the fixed engine sentence a `get` of it refuses with). No other member. */
export interface DamagedBackgroundAgentRowSummary {
readonly rowVerdict: DamagedRowVerdict;
readonly handle: string;
}
/** The summary of a row that reads. */
export interface ReadableBackgroundAgentRowSummary {
handle: string;
/** The tenant partition the row lives in ({@link BackgroundAgentRecord.scope}). A per-row follow-up on a summary (`get` / `delete` /
* `updateIf`) addresses the row in this scope: {@link BackgroundAgentStore.listByRoot} answers across scopes, so its caller reads the
* scope off each row instead of supplying one. */
scope: string;
owner: string;
sessionScoped: boolean;
sessionId?: string;
parentSessionId?: string;
rootSessionId?: string;
name: string;
agentType?: string;
requestedBy?: ExtensionRequester;
status: BackgroundAgentRecord["status"];
spawnedAt: number;
updatedAt: number;
settledAt?: number;
usage?: BackgroundAgentUsage;
/** The row's completion identity ({@link BackgroundAgentRecord.completionId}), verbatim — the value the live completion
* frame, the inbox / replay record and the host poll carry for the same completion, so a host that listed the row
* after a restart recognizes the completion it already met on another channel. An identity, not content (it may ride
* a list). Present iff the record carries one — a settled row; absent on a `running` / `parked` row and on a revived
* row until its new cycle settles. */
completionId?: string;
/** What the agent did not get done because something refused it — the refusal record of the row's ending ({@link agentOutcomeOf}`(row).refused`:
* asks nobody could answer, calls a person or something else refused, a verdict that never landed, a person's halt), the same
* record the completion frame, the fleet terminal and the poll carry inside `outcome`. Not content: the refused calls' tool names
* and ids, the closed cause words, the refusal's way-out sentences, bounded as the record is (`REFUSALS_LISTED` per list, the rest
* counted). Present iff the row's ending carries one; `{ unreadable: true }` (beside what did read) when the row's stored ending
* does not read. ABSENT says nothing was stated, never "nothing was refused": a `running` / `parked` row, a row whose ending
* carries no record, and a row an earlier engine wrote without the record (it kept only asks nobody could answer, which do list). */
refused?: MemberRefusals;
}
/** Typed store error so callers branch on `code` (mirrors `WorkflowRunStoreError`). */
export declare class BackgroundAgentStoreError extends Error {
readonly code: "agent_record.already_exists" | typeof BACKGROUND_AGENT_ROW_MALFORMED_CODE;
constructor(code: "agent_record.already_exists" | typeof BACKGROUND_AGENT_ROW_MALFORMED_CODE, message: string);
}
/** The refusal code of a row whose stored body (or a write's candidate) does not read as {@link BACKGROUND_AGENT_ROW_SHAPE}. */
export declare const BACKGROUND_AGENT_ROW_MALFORMED_CODE = "agent_record.row_malformed";
/**
* THE BACKGROUND AGENT ROW'S MEMBER-SHAPE TABLE (`rowShapeReader`, row-shape.ts). `rowKey` is the file ledger's row predicate (a
* string handle and scope: the row's key). `members` is what the readers reach for: the owner and the session anchors (the access
* predicate and the session listing read them), the status word, the stamps, the revision and the writer's generation (the CAS
* compares them and bumps them — a stored revision that is no count is refused, never incremented), the stop-cycle number (the
* one mint steps it — a stored `seq` that is no cycle number is refused, never stepped), the claim and park bindings,
* the display members, and `name` — whose ABSENCE reads as the name the engine derives from the handle (`engineAgentName`; a row
* without a name whose handle derives none does not read). `requestedBy` is read by its own reader (a value it does not read is
* no requester). The write gate also holds a candidate to a non-empty scope (a row without one is world-readable through the
* access fallback). Exit `list-damaged`: a listing answers such a row by its handle, a `get` and every CAS refuse it in
* {@link BACKGROUND_AGENT_ROW_MALFORMED_CODE}, and deletion by its handle goes on.
*/
export declare const BACKGROUND_AGENT_ROW_SHAPE: import("./row-shape.js").RowShapeReader<BackgroundAgentRecord>;
/**
* A stored row as every reader reads it — the row (an absent `name` read as the engine's name for its handle), or the refusal
* ({@link BACKGROUND_AGENT_ROW_MALFORMED_CODE}) of one that does not read, told to `disclose` first. A backend's `get` and every
* CAS's read of the live row go through this; a SQL twin passes its authoritative columns (`handle`, `scope`, `rev`).
*/
export declare function readStoredBackgroundAgent(raw: unknown, ctx: RowContext, disclose?: (sentence: string) => void): BackgroundAgentRecord;
/** A write's candidate — its handle, scope and revision already placed by the backend's rule — held to
* {@link BACKGROUND_AGENT_ROW_SHAPE} and its write-only invariants: the row to store, or the refusal before anything is written. */
export declare function admitBackgroundAgent(candidate: BackgroundAgentRecord, ctx: RowContext): BackgroundAgentRecord;
/**
* design/151 §3.1c — the fallback access predicate (S-1 定谳 class). Mirrors the live registry's
* `canAccess` axes with ONE remaining durable-only addition: a task-scoped row is readable by its
* PARENT SESSION (`parentSessionId` leg) — after a restart the host session is the row's only
* legitimate owner (the spawn-time task ids are dead). The live registry still does not grant the
* parentSessionId leg (an intermediate session must not steer a sibling turn's running child);
* the ROOT arm, however, is now on BOTH faces — RB-236 (2026-07-29) aligned the live `canAccess`
* with this predicate's root-session arm, closing the "running grandchild is not_found to
* the session that owns the tree" window. Durable rows remain the settled/read/revive face.
* Cross-session same-scope reads stay not_found (content-axis ruling).
*
* Scope is FAIL-CLOSED both ways (`undefined` never matches) — records are put with a real scope.
*/
export declare function canAccessAgentRecord(record: Pick<BackgroundAgentRecord, "scope" | "owner" | "sessionScoped" | "parentSessionId" | "rootSessionId" | "rootSessionIncarnation">, access: {
owner?: string;
scope?: string;
sessionId?: string;
rootSessionIncarnation?: string;
}): boolean;
/**
* The pluggable durable ledger seam. Contract notes for implementations (file/pg):
* - `put` is create-once: throw {@link BackgroundAgentStoreError} `already_exists` on a live key —
* never silently overwrite (a leftover row from a dead process must not be clobbered by a
* fresh-minted colliding handle; the writer treats that as a loud no-durability degrade).
* - `update` is a CAS (`WHERE handle=? AND scope=? AND rev=?`): return false on a missing row, a
* scope mismatch (multi-tenant isolation — a wrong-scope update must not win), or a rev mismatch.
* On success bump `rev` by EXACTLY 1 and persist (全景 S3c F-3: the tier-3 claim derives the
* post-claim rev as `expect.rev + 1` for its lane seed and rollback CAS — a larger bump would
* silently downgrade every revival to the adopt-heal slow path and every rollback to the
* staleRunning sweep; both bundled impls bump by 1, the contract follows them).
* - `get`/`listBySession` are RAW row reads keyed by (handle|session, scope) — the full access
* predicate ({@link canAccessAgentRecord}) is applied by the ENGINE consumer (registry fallback),
* roster-store posture: a store implementation never widens visibility, and a deployment must not
* serve raw rows without the predicate.
* - `reap` deletes only what the policy names; a `running` OR `parked` row is deleted by NO policy —
* the `staleRunningMaxAgeMs` arm first CAS-flips a stale `running` to `failed` (host interrupted),
* then it ages out as a terminal row. A `parked` row is FULLY reap-exempt (design/153 §7.1: its
* writer does not heartbeat — the child is durably suspended, silence is its normal state; the
* checkpoint-bound reconciliation sweep, not row age, owns its cleanup). With no options, reap is
* a no-op (retention is always an explicit policy).
* Sizing: a LIVE writer renews its running rows' `updatedAt` every
* `DURABLE_AGENT_HEARTBEAT_MS` (60s — task-registry writer lease), so row age measures SILENCE —
* of the WRITER PROCESS, specifically: a wedged child inside a healthy
* process keeps renewing and never goes stale, by design (in-process supervision owns that case).
* Set `staleRunningMaxAgeMs` ≥ 10× the heartbeat (≥10min). A premature flip still self-heals:
* the live writer's settle reads the row back, adopts the bumped rev (writerId match) and
* re-CASes the real terminal truth over the reaper's guess.
* ⚠️ Row deletion does NOT release the child SESSION (the store cannot reach the session store) —
* the blessed reap path is the registry-side orchestration (design/151 §3.1 MED-7 +
* C-2): it conditionally DELETES the row under its re-verified rev first, and only a WINNING
* delete releases the transcript session (release-first destroyed a live transcript when a
* concurrent revive won the CAS after the release). Calling raw `reap` alone strands transcripts.
* Cross-process caveat: a revive's durable `running` transition rides the async
* lane — between the in-memory revive and its flush, a DIFFERENT process's sweep still holds a
* terminal-looking row whose rev the flush has not yet bumped. In-process sweeps are gated on the
* live handle; cross-process revival (S3) must claim-CAS FIRST (see {@link BackgroundAgentRecord.writerId}).
*/
/** The stale-running reap flip's attribution, written to BOTH `summary` (legacy
* slot, kept for any out-of-repo reader) and `error` (the field {@link canAccessAgentRecord}-gated
* durable serving actually renders). One exported constant so the two store implementations (in-memory
* here, file twin) can never drift apart (RB-74/RB-111 family). Wording carries the reference's three
* facts: what happened (host process gone mid-run), the consequence (in-process state
* lost), and the action (check the worktree/output for partial work before assuming the task landed). */
export declare const STALE_RUNNING_REAP_ATTRIBUTION = "the host process was interrupted while this agent was running \u2014 its in-process state was lost. Check its worktree / output file for partial work before assuming the task landed (stale running row reaped).";
/**
* REF-D18: the `updateIf` CAS predicate — the SINGLE shape the interface method and both the
* In-Memory and File implementations reference (previously each re-declared it inline). Mechanism
* finding this merge closes: a `class X implements Interface` clause does NOT catch a missing
* optional field when the implementing method re-declares its own narrower inline param type (TS
* method-parameter bivariance) — this exact duplicate-signature-drift class already produced a
* shipped double-counting bug in this file's family (RB-74, then RB-87/RB-111 fixed it in one
* implementation and not the other, same release; see the file-store twin's own comment).
*/
export interface BackgroundAgentUpdateIfExpect {
rev: number;
status?: BackgroundAgentRecord["status"];
parkedCheckpointToken?: string | null;
parkClaimId?: string | null;
}
/** REF-D18: `reap`'s retention-policy options — same single-shape rationale as {@link
* BackgroundAgentUpdateIfExpect} above. */
export interface BackgroundAgentReapOptions {
/** Delete terminal rows settled longer ago than this. Absent = this arm is not applied. Must be a
* finite, non-negative number of milliseconds. */
maxAgeMs?: number;
/** Keep at most this many terminal rows, newest first. Absent = this arm is not applied. Must be a
* finite, non-negative whole number — see {@link assertBackgroundAgentReapOptions} for why a
* malformed value here is the dangerous one. */
keep?: number;
/** Flip `running` rows untouched for longer than this to a failed terminal. Absent = not applied.
* Must be a finite, non-negative number of milliseconds. */
staleRunningMaxAgeMs?: number;
}
/** The retention knobs a background-agent `reap` takes (and the durable-agent joint reap beside it). */
export declare const BACKGROUND_AGENT_REAP_KNOBS: readonly ["maxAgeMs", "keep", "staleRunningMaxAgeMs"];
/** knob-hygiene #98 — read a reap policy once and refuse a malformed one before any row is touched. Delegates to the one
* shared reading ({@link receiveRetentionPolicy}) both bundled stores and the sibling mailbox / workflow-run retention
* seams run through, so no implementation can drift from another; the sweep deletes by the copy this returns. */
export declare function receiveBackgroundAgentReapOptions(opts: BackgroundAgentReapOptions | undefined): Readonly<BackgroundAgentReapOptions>;
export interface BackgroundAgentStore {
put(record: BackgroundAgentRecord): Promise<void>;
get(handle: string, scope: string): Promise<BackgroundAgentRecord | null>;
update(handle: string, scope: string, record: BackgroundAgentRecord, expect: {
rev: number;
}): Promise<boolean>;
/**
* design/153 §7.2c (r6 H-3) — the GUARDED CAS the park/claim lanes require: atomic
* `WHERE rev [AND status] [AND parkedCheckpointToken] [AND parkClaimId]`. The plain `update`'s
* rev-only guard is NOT enough there (a rev can move for unrelated reasons between read and
* write while the park-critical fields changed meaning — reservation, rollback and finalize all
* bind to the FIELD state, not just the revision). Same success semantics as `update` (bump rev
* by exactly 1). An `expect` field set to a string matches equality; `null` matches ABSENCE.
* REQUIRED method (BREAKING for store implementers, announced): a silently-ignoring legacy
* implementation would fail OPEN on the exact CAS the approval chain's safety rests on.
*/
updateIf(handle: string, scope: string, record: BackgroundAgentRecord, expect: BackgroundAgentUpdateIfExpect): Promise<boolean>;
/** Rows whose durable session anchor (`sessionScoped ? owner : parentSessionId`) OR root anchor
* (`rootSessionId` — the whole delegation tree under one host session) equals
* `sessionId`, newest-first by `spawnedAt`. Content-free projections (HIGH-1). `opts.status`
* filters one state; `opts.limit` keeps the newest N after the sort. */
listBySession(scope: string, sessionId: string, opts?: {
status?: BackgroundAgentRecord["status"];
limit?: number;
}): Promise<BackgroundAgentRowSummary[]>;
/** ALL of a scope's rows (content-free, newest-first): the joint-reap orchestration's
* enumeration face (`TaskRegistry.reapDurableAgents` — conditional delete first, session release
* only after a winning delete). Deployment-op context, not a model-serving face —
* model-facing reads stay behind {@link canAccessAgentRecord}. */
listByScope(scope: string, opts?: {
status?: BackgroundAgentRecord["status"];
limit?: number;
}): Promise<BackgroundAgentRowSummary[]>;
/** Every row of ONE delegation tree: a row qualifies when its tree root ({@link delegationRootOf}) equals `rootSessionId` — in
* EVERY scope, each summary carrying the scope its row lives in, so a follow-up on a row addresses it there (the session-deletion
* enumeration's face: a host session's children are found by the session, never by a scope the caller would have to guess).
* Content-free, newest-first; `opts` as {@link listBySession}. Deployment-op context, not a model-serving face — it crosses the
* tenant boundary by design, so a deployment that hands a row to a caller applies {@link canAccessAgentRecord} first. A row whose
* root is another session is not listed, even when its parent is `rootSessionId` (a grandchild of an intermediate session belongs
* to its own root's tree). `rootSessionId` is judged by {@link assertDelegationRoot} before any row is read. */
listByRoot(rootSessionId: string, opts?: {
status?: BackgroundAgentRecord["status"];
limit?: number;
}): Promise<BackgroundAgentRowSummary[]>;
/** row-precise removal (the joint-reap deletion arm). Returns false on a miss.
* `expect.rev` makes it CONDITIONAL — a live writer's concurrent revival (heartbeat
* adopt bumps rev) must beat the reaper's stale snapshot, so the joint reap always deletes with
* the rev it just re-verified. One row of a deletion batch: a store that keeps a log of its writes (the file twin) does NOT take
* the row's earlier entries off its medium here — the batch's end does ({@link settleErasure}). The joint reap ends its batch with
* it; a host that deletes rows with this verb itself ends its own batch the same way. */
delete(handle: string, scope: string, expect?: {
rev: number;
}): Promise<boolean>;
/**
* The end of a deletion batch made of {@link delete} calls: every deletion batch ends with one compaction. A store that keeps a
* log of its writes takes the earlier entries of the rows deleted since its last compaction off its medium now — once, however
* many rows the batch deleted; a failure throws (bytes still there are not deleted), and the next call settles them. The store's
* own batch verbs ({@link reap} with a deletion bound, {@link deleteBySession}) end this way inside. OPTIONAL: a store whose
* `delete` leaves nothing of the row on its medium (the in-memory twin) omits it.
*/
settleErasure?(): Promise<void>;
/**
* The session-tree cascade's leg ({@link import("./retention.js").RETENTION_CASCADE}`.backgroundAgentStore`): delete the TERMINAL
* rows of `scope` that {@link listBySession} names for `sessionId` — the rows {@link backgroundAgentSessionRows} selects, each
* re-checked against the live row as it is deleted; a running or parked row is a live reference and stays, and a row that does not
* read is left as stored (its listing told it). Answers the handles it deleted; idempotent (a repeat answers `[]`); a store fault
* throws. A store that keeps a log of its writes takes the deleted rows' earlier entries off its medium before it answers — once
* per call, however many rows it deleted (a failure to do so throws: bytes still there are not deleted, and a repeat settles them).
*/
deleteBySession(scope: string, sessionId: string): Promise<string[]>;
/** Enumerate the scopes that currently hold rows, so a deployment-op
* retention loop can drive {@link TaskRegistry.reapDurableAgents} per scope without external
* bookkeeping (a local backend under multi-tenant use otherwise grows principal-scoped rows
* forever). Optional: a store whose deployment tracks scopes elsewhere (pg: SELECT DISTINCT)
* may omit it. Deployment-op face, never model-serving. */
listScopes?(): Promise<string[]>;
/** Retention sweep for `scope` (explicit policy, see interface notes). Returns rows deleted+flipped. A sweep with a deletion
* bound (`maxAgeMs` / `keep`) is a deletion batch: it ends as {@link settleErasure} does (once per call; a failure throws after
* the rows are deleted, and the next sweep settles them). */
reap(scope: string, now: number, opts?: BackgroundAgentReapOptions): Promise<number>;
/**
* Re-file one isolation scope's rows under another, in the steps {@link import("./identity-rekey.js").REKEY_MODES}
* names (REQUIRED, as every identity seat's re-key member is). The input is read by
* {@link import("./identity-rekey.js").readScopeRekeyInput} before anything is read or written; the step is judged by
* {@link planScopeRekey}. The answer arm is bound to the step, as on the policy seat.
*
* @contract background_agent.rekey_scope — `rekeyScope({ fromScope, toScope, mode })` re-files every row stored under
* `(handle, fromScope)` to `(handle, toScope)`. `arrive` puts a copy carrying `scope: toScope`, `rev + 1` and every other
* field as the store reads the source row (`owner`, writer fields and history are not the axis); a row already at the
* target is this move's arrival only when it is that copy exactly. `leave` deletes each source row whose arrival is in
* place, guarded by the rev it read, and leaves any other source row; `withdraw` deletes each arrival, guarded the same
* way. A target row that is not the arrival makes `arrive` answer `conflict`; nothing is written then. Every row the step
* reads — each row filed under `fromScope` and each target — is read as `get` reads it ({@link readStoredBackgroundAgent}):
* one that does not read refuses the whole step in {@link BACKGROUND_AGENT_ROW_MALFORMED_CODE}, every step, before anything
* is written; every copy passes the write gate ({@link admitBackgroundAgent}) before the first write. Scope values are
* read as the put gate reads them. Revisions follow the store's delete law: a key deleted and filed again may restart lower.
*/
rekeyScope(input: ScopeRekeyInput & {
readonly mode: "plan";
}): Promise<RekeyPlan>;
rekeyScope(input: ScopeRekeyInput & {
readonly mode: "arrive";
}): Promise<RekeyDone | RekeyConflict>;
rekeyScope(input: ScopeRekeyInput & {
readonly mode: "leave" | "withdraw";
}): Promise<RekeyDone>;
}
/** One source row of a scope re-key and the row its target key holds: `arrived` = that row is this move's copy. */
export interface ScopeRekeyMove {
readonly source: BackgroundAgentRecord;
readonly target: BackgroundAgentRecord | null;
readonly arrived: boolean;
}
/**
* The copy `arrive` files for `source` under `toScope`: every member as stored, `rev + 1`, and the partition's value moved wherever
* the row records it — `scope`, and `rootSessionScope` when it names the same partition (the root's box mounts in the scope its
* tree was filed under; a box of another scope stays). No other member carries a partition: the session ids address sessions, the
* org-admission pair names org planes, the policy floor holds clamp values.
*/
export declare function scopeRekeyCopyOf(source: BackgroundAgentRecord, toScope: string): BackgroundAgentRecord;
/**
* THE judge of a scope re-key over one store's rows, both bundled backends' (pure: it reads rows the caller hands it —
* {@link readScopeRekeyPlan} hands it the rows filed under `fromScope`, each as the store reads it). Each is a source; its
* target is the row `targetOf` answers under `toScope`; a target is the arrival exactly when it equals
* {@link scopeRekeyCopyOf} of its source (the handle is minted once and `put` creates once, so no other row can be that
* copy). `fromScope === toScope` moves nothing. Returns the moves (sorted by handle) and the answer the step gives before
* any write — the backend then writes what the moves say.
*/
export declare function planScopeRekey(rows: Iterable<BackgroundAgentRecord>, targetOf: (handle: string) => BackgroundAgentRecord | null, input: ScopeRekeyInput): {
moves: readonly ScopeRekeyMove[];
answer: RekeyPlan | RekeyDone | RekeyConflict;
};
/**
* A scope re-key's plan over a backend's stored rows (`stored`: the store's key → the row as stored; `keyOf`: the store's
* key of `(handle, scope)`, `scope \u0000 handle` in both bundled backends, so the rows filed under `fromScope` are the keys
* that begin `keyOf("", fromScope)` — the partition the store files a row under, whatever its body says). Each such row whose
* key `only` admits, and each target, is read through {@link readStoredBackgroundAgent}: one that does not read throws the
* family's refusal before any plan exists, so the backend writes nothing. Then {@link planScopeRekey} judges the step.
*/
export declare function readScopeRekeyPlan(stored: ReadonlyMap<string, unknown>, keyOf: (handle: string, scope: string) => string, input: ScopeRekeyInput, opts?: {
readonly only?: ReadonlySet<string>;
readonly disclose?: (sentence: string) => void;
}): ReturnType<typeof planScopeRekey>;
/** The writes one scope re-key step makes, from its plan, keyed by `keyOf`: the copies to file (`arrive`, none when the
* answer is a conflict — each already through the write gate, {@link admitBackgroundAgent}, so a refusal comes before the
* first write), the source rows to delete (`leave`) or the arrivals to delete (`withdraw`), each with the rev it was read at. */
export declare function scopeRekeyWritesOf(mode: RekeyMode, plan: ReturnType<typeof planScopeRekey>, toScope: string, keyOf: (handle: string, scope: string) => string): {
puts: readonly {
key: string;
row: BackgroundAgentRecord;
}[];
deletes: readonly {
key: string;
rev: number;
}[];
};
/** What a parked row's approval card is, as the checkpoint store states it. `unreadable` = no read of the store could say. */
export type ParkedCardState = "pending" | "resolved" | "expired" | "missing" | "unreadable";
/** The store seat the card-state reader needs: the body read every store has, and the body-tolerant session listing a store may offer. */
export type ParkedCardStore = Pick<import("./checkpoint-store.js").CheckpointStore, "get"> & Partial<Pick<import("./checkpoint-store.js").CheckpointStore, "listBySession">>;
/**
* THE reader of a parked row's card state — both halves of the reconciliation (this module's store sweep and the registry's live sweep)
* ask it, and nothing else decides what state a card is in. The state is the store's word: the body read answers it when the body
* decodes; when the body does not (the read throws, or the card carries no state word) the store's own body-tolerant listing
* (`listBySession` — a row it cannot read is listed `unreadable` with the status as stored) answers it. A card neither read can speak for is
* `unreadable`, which the sweeps treat as "touch nothing"; it is announced once per (scope, handle) per process, as `delegation.parked_card_unreadable` on the default notice seat — a voided card
* whose body is lost never stops being unreadable, and a sweep that skips it every cadence in silence leaves the row parked for good.
* The announcement names the agent, never the card's token (a resume capability).
*/
export declare function parkedCardState(store: ParkedCardStore, card: {
token: string;
handle: string;
scope: string;
sessionId: string | undefined;
}): Promise<ParkedCardState>;
/**
* design/153 §7.1 (r4 F-03) — the parked-row ↔ checkpoint reconciliation sweep. `parked` rows are
* reap-exempt (their writer does not heartbeat), so WITHOUT this sweep an expired/removed approval
* checkpoint leaves the row parked forever. Deployment-op face (same posture as
* `TaskRegistry.reapDurableAgents`): the deployment calls it on its retention cadence with BOTH
* stores. Two arms, both master-arbitrated by the checkpoint (never by row age):
* 1. parked rows whose checkpoint is EXPIRED or MISSING → CAS to `failed` (honest terminal, error
* names the cause). A `pending` or `resolved` checkpoint leaves the row alone (`resolved` =
* a resume is mid-flight — the claim path owns it).
* 2. stale claims (r4 F-04): `running` rows still carrying BOTH `parkClaimId` and
* `parkedCheckpointToken` past `staleClaimMaxAgeMs` (claimed, then the claimer died before the
* attach finalize) → CAS BACK to `parked` iff the checkpoint is still pending (redeemable
* again); expired/missing → arm-1 shape (failed).
* 3. stranded flip-lost orphans (server cross-probe B1, 2026-07-24): `parked` rows with NO claim
* whose checkpoint is RESOLVED (the consume flip never landed) → `failed` (approval consumed,
* outcome unknown). ⚠️ Arms 2-3 run ONLY when `staleClaimMaxAgeMs` is supplied (review F-5:
* a deployment that never passes it never reaps these shapes), and an in-process caller's own
* handles are excluded — the stranded arm therefore needs an OUT-OF-PROCESS sweep (or a later
* run after the owning process exits) to fire.
* Every write is a rev-CAS — a live writer's concurrent transition wins and the sweep just skips.
*
* SPLIT-BRAIN FENCE (件1): failing a row whose PARKING PROCESS is still alive would
* desynchronize its live handle (poll keeps saying parked, TaskStop mis-reports). An in-process
* deployment therefore calls {@link import("./task-registry.js").TaskRegistry.reconcileParkedAgents}
* (which handles ITS OWN handles live, then delegates here with `excludeWriterId` = its writerId);
* calling this bare is correct only where no engine instance is live for the scope. Residual (multi-
* replica shared store, ANOTHER live instance's rows): same documented posture as RB-38③ — that
* instance's next durable write CAS-fails and poisons its lane loudly rather than silently diverging.
*/
export declare function reconcileParkedAgents(stores: {
agentStore: BackgroundAgentStore;
checkpointStore: ParkedCardStore;
}, scope: string, now: number, opts?: {
staleClaimMaxAgeMs?: number;
excludeWriterId?: string;
excludeHandles?: ReadonlySet<string>;
}): Promise<{
failed: number;
rolledBack: number;
unreadable: number;
}>;
/** A background agent row's ending as every face reads it: the row's own outcome when it is this row's (it reads, and its word
* projects onto the row's status — {@link memberRowStatusOf}), taken in sealed; else the one derived from the row's status words
* (a row an earlier engine wrote, whose refused asks rode their own key; a row whose outcome is an earlier cycle's). A row that has
* not settled (`running`, `parked`) states none, whatever it stores. The one reading of a row — a stored one, or a live registry
* handle's own words — the poll faces, the listings and a host serving rows read it here. A stored record that does not read (the
* outcome, or the old asks key, changed in storage) never makes the row unreadable: the row answers with its refusals `unreadable`
* — never as a row with nothing refused — and the default notice seat is told once per (scope, handle) per process
* (`delegation.agent_row_ending_unreadable`). */
export declare function agentOutcomeOf(row: {
readonly status: string;
} & Pick<BackgroundAgentRecord, "errorCode" | "stoppedBy" | "outcome" | "refusedAsks"> & Partial<Pick<BackgroundAgentRecord, "handle" | "scope">>): MemberOutcome | undefined;
/**
* The root of the delegation tree a row belongs to — the ONE reading of it, for a durable row and a live registry handle alike: the
* row's recorded `rootSessionId`; a row written before that column existed answers with its `parentSessionId` (the fallback for those
* old rows only: such a row's parent is its root when its spawning leg ran in the root session, the common shape then); a session-scoped
* row with neither answers with its `owner` (a session-scoped registration's owner is the session id).
* `undefined` when none of the three is there — such a row is in no tree. Read by {@link BackgroundAgentStore.listByRoot} (through
* {@link queryBackgroundAgents}), by the registry's live tree selection, and by a revival keying its entry pool off the claimed row.
*/
export declare function delegationRootOf(row: {
readonly rootSessionId?: string;
readonly parentSessionId?: string;
readonly sessionScoped?: boolean;
readonly owner?: string;
}): string | undefined;
/**
* THE judge of the root a tree query names ({@link BackgroundAgentStore.listByRoot}, `TaskRegistry.activeDelegationHandlesByRoot`), run
* before any row is read, in every backend: a non-empty string of at most {@link DELEGATION_ROOT_MAX_CHARS} UTF-16 units with no
* control character. Anything else is refused with `config.invalid_argument` — an empty or non-string root would answer "no rows" for
* a question that was never asked, and a deletion that enumerates a session's children by it would then delete none of them.
*/
export declare function assertDelegationRoot(rootSessionId: unknown): asserts rootSessionId is string;
/** What {@link queryBackgroundAgents} keeps besides the partition: one status, and the newest N after the sort. */
interface BackgroundAgentQueryCut {
/** Keep only this status. ABSENT ⇒ every status. */
status?: BackgroundAgentRecord["status"];
/** Keep the newest N, applied AFTER the sort. ABSENT ⇒ no cap. */
limit?: number;
}
/**
* REF-A3 — the query shape `listBySession` (scope + {@link sessionId}), `listByScope` (scope alone) and `listByRoot` (`root` alone) are
* expressed in. Named rather than inline because it crosses a module boundary (the file backend imports it), and every field's
* ABSENCE is a defined "no filter" state rather than a missing value. Exactly one partition: a tenant (`scope`), or one delegation
* tree across tenants (`root`).
*/
export type BackgroundAgentQuery = (BackgroundAgentQueryCut & {
/** Tenant partition key, always in the WHERE — a row in another scope is never visible. */
scope: string;
/**
* Session-anchored enumeration: a row qualifies when its durable anchor
* (`sessionScoped ? owner : parentSessionId`) OR its `rootSessionId` (the whole
* delegation tree under one host session) equals this. ABSENT ⇒ scope-wide enumeration.
*/
sessionId?: string;
root?: never;
}) | (BackgroundAgentQueryCut & {
/** One delegation tree in every scope: a row qualifies when {@link delegationRootOf} equals this (judged by
* {@link assertDelegationRoot} before any row is read). */
root: string;
scope?: never;
sessionId?: never;
});
/**
* REF-A3 — THE query projection for {@link BackgroundAgentStore.listBySession} /
* {@link BackgroundAgentStore.listByScope} / {@link BackgroundAgentStore.listByRoot}: filter → sort newest-first by `spawnedAt` → truncate →
* content-free summary (HIGH-1). Pure (no store state, no I/O): it takes any row iterable, so the
* in-memory backend passes its `Map` values and the file backend passes the shared ledger's. The two
* backends held byte-identical hand copies of this before — the same one-of-two-implementations drift
* hazard RB-60 / RB-74 / RB-87 / RB-111 each landed on, on this very surface.
*
* PUBLIC (a serving layer runs the same filter/sort/truncate the bundled backends do, instead of a
* sixth hand copy). It is a projection over rows the CALLER supplied — it neither reads a store nor
* authorizes anything: the summaries it returns are content-free but still name handles and session
* anchors, so a deployment that hands any of them to an external caller applies
* {@link canAccessAgentRecord} first (the {@link BackgroundAgentStore} interface notes state the same
* obligation for raw rows: a store never widens visibility, and raw rows are not a serving face).
*/
export declare function queryBackgroundAgents(rows: Iterable<BackgroundAgentRecord>, query: BackgroundAgentQuery, disclose?: (sentence: string) => void): BackgroundAgentRowSummary[];
/**
* The rows {@link BackgroundAgentStore.deleteBySession} takes, by handle — every backend's one reading: the rows `listBySession(scope,
* sessionId)` lists ({@link queryBackgroundAgents}) whose record reads and whose status is terminal (not `running`, not `parked`). A
* row that does not read is not taken (its listing told `disclose`). Pure; a backend re-checks each row against this as it deletes it.
* A `sessionId` that is not a non-empty string is refused (`assertDeletionSessionId`) — never read as "every row of the scope".
*/
export declare function backgroundAgentSessionRows(rows: Iterable<BackgroundAgentRecord>, scope: string, sessionId: string, disclose?: (sentence: string) => void): string[];
/** One stored row as a listing answers it: its content-free summary, or — a row that does not read — its handle and verdict
* (told to `disclose`). A SQL twin projects each row it lists through this, its authoritative columns in `ctx`. */
export declare function summarizeStoredBackgroundAgent(raw: unknown, ctx: RowContext, disclose?: (sentence: string) => void): BackgroundAgentRowSummary;
/**
* THE CAS guard of {@link BackgroundAgentStore.update} / {@link BackgroundAgentStore.updateIf}, shared by every backend: the row must
* exist under this scope; the live row is READ before its revision is compared (a row that does not read is refused, told to
* `disclose` — its revision is never compared or bumped); the revision and the field guards must match; the candidate, its handle,
* scope and revision placed by the key, is held to the write gate. Returns the row to persist, `null` when the CAS lost; PURE.
*/
export declare function nextBackgroundAgentOnUpdate(live: BackgroundAgentRecord | undefined, key: string, handle: string, scope: string, record: BackgroundAgentRecord, expect: BackgroundAgentUpdateIfExpect, disclose?: (sentence: string) => void): BackgroundAgentRecord | null;
/** The row a stale-running sweep flips to `failed`, or `undefined` when it does not flip: not a running row of the scope, not
* stale, or a row that does not read (told to `disclose`, and left as stored). Every backend's one reading of arm 1. */
export declare function staleRunningFlip(live: BackgroundAgentRecord | undefined, key: string, scope: string, now: number, staleMs: number, disclose?: (sentence: string) => void): BackgroundAgentRecord | undefined;
/** The form a stale running row flips to — THE one writing of it: `failed`, stopped by the system, the shared attribution on `error`
* and `summary` (each only where the row carries none), settled and updated at `now`, and the completion identity minted
* (fill-once) — a terminal write with no live handle is where that completion is born. PURE: a copy is returned, `live` is not
* touched. It judges nothing: `live` is a row that READS and is running, and that the caller found stale. `rev` is the live
* row's own — the store places the next one (an `update` CAS does; {@link staleRunningFlip} does for the sweep that writes in
* place). A SQL twin whose staleness is a column predicate writes the flip through this instead of a hand copy. */
export declare function staleRunningFlipOf(live: BackgroundAgentRecord, now: number): BackgroundAgentRecord;
/** A terminal-retention candidate: a terminal row of the scope whose stamps read — its key, spawn time and settle (else spawn) time. */
export interface BackgroundAgentReapCandidate {
readonly key: string;
readonly spawnedAt: number;
readonly age: number;
}
/** The rows a terminal-retention sweep may consider, newest first by `spawnedAt` — every backend's one reading of arm 2: a terminal
* status word (`running` and `parked` are exempt), a finite `spawnedAt`, a `settledAt` absent or finite. A row whose status or
* stamps do not read is never reaped by age or count (told to `disclose`). */
export declare function backgroundAgentReapCandidates(rows: Iterable<readonly [string, BackgroundAgentRecord]>, scope: string, disclose?: (sentence: string) => void): BackgroundAgentReapCandidate[];
/**
* In-process reference implementation. NOT default-mounted (divergence ② above) — single-instance
* deployments and tests wire it explicitly; it does not survive a restart, so with THIS store the
* lifecycle flip buys retained transcripts only for the process lifetime (capability presence ≠
* durability — the `SessionStore.fork` doctrine applies verbatim). `structuredClone` on both
* boundaries (no aliasing between the caller's live objects and stored rows).
*/
export declare class InMemoryBackgroundAgentStore implements BackgroundAgentStore {
private rows;
private key;
put(record: BackgroundAgentRecord): Promise<void>;
get(handle: string, scope: string): Promise<BackgroundAgentRecord | null>;
update(handle: string, scope: string, record: BackgroundAgentRecord, expect: {
rev: number;
}): Promise<boolean>;
updateIf(handle: string, scope: string, record: BackgroundAgentRecord, expect: BackgroundAgentUpdateIfExpect): Promise<boolean>;
listBySession(scope: string, sessionId: string, opts?: {
status?: BackgroundAgentRecord["status"];
limit?: number;
}): Promise<BackgroundAgentRowSummary[]>;
listByScope(scope: string, opts?: {
status?: BackgroundAgentRecord["status"];
limit?: number;
}): Promise<BackgroundAgentRowSummary[]>;
listByRoot(rootSessionId: string, opts?: {
status?: BackgroundAgentRecord["status"];
limit?: number;
}): Promise<BackgroundAgentRowSummary[]>;
delete(handle: string, scope: string, expect?: {
rev: number;
}): Promise<boolean>;
deleteBySession(scope: string, sessionId: string): Promise<string[]>;
listScopes(): Promise<string[]>;
rekeyScope(input: ScopeRekeyInput & {
readonly mode: "plan";
}): Promise<RekeyPlan>;
rekeyScope(input: ScopeRekeyInput & {
readonly mode: "arrive";
}): Promise<RekeyDone | RekeyConflict>;
rekeyScope(input: ScopeRekeyInput & {
readonly mode: "leave" | "withdraw";
}): Promise<RekeyDone>;
reap(scope: string, now: number, opts?: BackgroundAgentReapOptions): Promise<number>;
}
export {};