@sema-agent/core
Version:
Stateless, task-oriented AI agent core
314 lines (313 loc) • 22.7 kB
TypeScript
import type { CorruptReadInfo } from "./corrupt-read-sink.js";
import type { CorruptBodyForm } from "../../core/store-contracts/read-back-shape-contract.js";
/**
* design/157 A9 — the SHARED substrate under the three snapshot+ledger file stores
* ({@link import("./background-agent-store.js").FileBackgroundAgentStore},
* {@link import("./checkpoint-store.js").FileCheckpointStore},
* {@link import("./workflow-run-store.js").FileWorkflowRunStore}).
*
* Each of them carried its own copy of the SAME three mechanisms: a per-directory refcounted
* authority table, the snapshot+ledger replay/commit skeleton, and `compact()`'s
* close → rewrite → reopen swap. What stays in the stores is what genuinely differs — the ledger
* EVENT model (`applyEvent`) and the domain predicates (CAS / reap / query projections). The stores
* COMPOSE this (they hold a {@link LedgerCore}); nothing here is inherited or subclassed.
*
* ── CLASS-FIX LEDGER ────────────────────────────────────────────────────────────────────────────
* Every entry below was first fixed on ONE file and then had to be re-fixed on the siblings, some of
* them twice. They now live here once, and the old addresses are named so the考据 is not lost with
* the code that carried it:
*
* · **RB-55 / RB-59 / RB-134 — one authority per DIRECTORY, not per instance.** Two stores over one
* directory each replayed a PRIVATE view, so two concurrent same-rev CASes BOTH won: a double
* claim (background-agent, RB-55), a double-won run update (workflow-run, RB-59 — the 1.408.0
* sweep covered the agent store and not this one, whose cross-instance test only exercised `put`),
* and a human approval consumed twice (checkpoint, RB-134, in the file whose own header calls
* itself "THE LOAD-BEARING file store"). Now: {@link SharedLedgerTable}.
* · **RB-144 — the table KEY is `canonicalStoreKey` (realpath + case fold).** Three stores were
* still keying on a lexical `resolve()` while two of them cited the mailbox as the precedent they
* copied. Now one call site, in {@link SharedLedgerTable.acquire}.
* · **RB-145 — `close()` is IDEMPOTENT per INSTANCE; the refcount belongs to the DIRECTORY.** A
* second `close()` on the same object used to decrement again and tear the shared log out from
* under a live sibling — `log_closed` on its every later write. The per-instance latch stays in
* each store (it is per-object state); the refcount, the identity-checked eviction and the fd
* teardown are {@link LedgerCore.release}.
* · **RB-149 / RB-167 — the compaction swap must be `closeForSwap()`, never `close()`.** `close()`
* means "finished", so a failed rewrite left the log permanently unusable — one transient I/O
* fault bricking every instance on that directory. The mailbox's `finally { new AppendLog(path) }`
* compensation was the closest of the four and still wrong twice: it does not cover an unwritable
* FILE (the reopen throws too), and its reopen error REPLACES the fault that caused the swap. The
* answer is AppendLog's lazy reopen — {@link LedgerCore.compact}.
* · **(2026-08-22, cross-process defect probe) — one authority per directory needs one WRITER per
* directory, and that half was never enforced.** RB-55/59/134 closed the IN-PROCESS shape (two
* instances, two private replays, two winners); two OS PROCESSES over one directory reproduced it
* verbatim (a human approval and its refusal each reported as the winner) — and worse, the one that
* never loaded the other's rows ERASED them at its next {@link LedgerCore.compact} (the snapshot is
* rewritten from the in-memory map, and the live ledger is then truncated). The class docs all
* credited a fence they did not hold: `root/LOCK` belongs to `FileStorageBackend`, which never
* constructs the workflow-run store at all and which a directly-constructed store (all three are root
* exports) never goes through. So the fence now lives WITH the authority: {@link LedgerCore.bootstrap}
* takes `dir/LOCK` ({@link acquireStoreDirLock}) and the last {@link LedgerCore.release} drops it —
* exclusive across processes, refcount-joined in-process, exactly like the authority it guards.
* · **RB-150 / RB-167 — compaction is HOUSEKEEPING.** It runs after the operation is durable AND
* applied, so its failure must never be reported as the operation's failure: a committed
* once-only CAS surfaced as "this did not happen" is the worst possible direction (the caller
* retries, hits the new rev, and fails again — one success reported as two failures). The swallow
* is safe ONLY because of the lazy reopen above — {@link LedgerCore.commit}.
* · **A damaged line is never folded past.** The fold used to disclose a line that is not one of the
* ledger's records and SKIP it; the fold is last-writer-wins, so a skipped line that was a row's newest
* event served the row's previous version as its current one — a completed run read as running, an
* expired or decided approval card read as pending and decided again (its tool executed a second
* time), a reaped row back. Compaction then rewrote that stale fold as the truth and erased the line.
* Now every line is judged as the writer's commit order allows ({@link replayLedger}): a record, an
* append that never returned, or damage — and damage refuses the replay by name
* ({@link FileLedgerDamagedError}), with one operator verb that sets the damage's reach aside. A line
* is text before it is JSON (a byte that is not UTF-8 used to decode into another, valid token), and
* a whole row is a record only under its own key; the write door asks the replay's own judgement, so
* no store writes a line its next open would refuse.
*
* DELIBERATELY NOT FOLDED IN: `mailbox-store.ts` (refcount is per-BOX with a per-instance dedup, and
* its compaction rewrites the LIVE log as a replay-equivalent event stream instead of a separate
* snapshot) and `workflow-journal-store.ts` (one ledger per RUN, no snapshot, no row map). Their
* tables are the same SHAPE, not the same MECHANISM; both keep their own, with a pointer to this
* ledger for the shared half of the history. What they DO share is the judgement of a line —
* record / append that never returned / damage — `judgeJsonlFile` in `fs-atomic.ts` (through
* `readJsonlRecords`): the journal refuses a load on damage as this fold does; the mailbox still
* skips it (KNOWN-LIMITS KL-4482-c).
*/
/** The paths one ledger authority owns. `dir` is also what the authority is keyed on. */
export interface LedgerPaths {
readonly dir: string;
/** Disclosure seat of the replay, told BEFORE the replay answers: each damaged line (`kind: "record"`, its line and form) and then
* the refusal itself (`kind: "file"`, the {@link FileLedgerDamagedError} message) — the replay then throws; or, on a ledger whose
* last segment is an append that never returned, that the tail was read as not having happened (`kind: "file"`; the store's append
* log cuts it as it opens). Already swallow-guarded by the store that wired it. Only the FIRST instance over a directory replays,
* so only its seat can fire: a joiner reads the authority that instance built, which is the same fact its refcount records. */
readonly onCorruptRead?: (info: CorruptReadInfo) => void;
/** Scratch dir for {@link atomicWriteFile} (same filesystem as the targets → rename is atomic). */
readonly tmpDir: string;
readonly ledgerPath: string;
readonly snapshotPath: string;
}
/** The per-store half: how a SNAPSHOT row is keyed, and how one LEDGER event folds into the map. */
export interface LedgerModel<Row, Ev> {
/** What this ledger IS, in an operator's words ("checkpoint ledger") — the noun the directory-fence
* refusal names, so the message points at the store that is actually in use rather than at a path. */
label: string;
keyOf(row: Row): string;
apply(rows: Map<string, Row>, ev: Ev): void;
/**
* `@contract store.read_back_shape_judged` floor: is this parsed body one of MY rows / MY events at
* all? Judged on the DISCRIMINANT only — the key a row is filed under, the tag an event is folded by —
* because what to do with a discriminant this binary does not KNOW is the model's own business (the
* checkpoint ledger refuses the whole replay for a kind from a newer worker, deliberately). A body
* that carries no discriminant carries no such choice: it is damage, and the replay discloses it and
* refuses ({@link replayLedger}). Required rather than optional, so a fourth ledger store cannot inherit the silence by
* omission — before this floor existed, `{"note":"x"}` in an agent ledger filed a row under the key
* `undefined` and the next enumeration read members off it.
*/
judgeRow(x: unknown): boolean;
judgeEvent(x: unknown): boolean;
/** The row key one event addresses. */
eventKey(ev: Ev): string;
/** What `ev` leaves its row as when it settles the row WHOLE, so that nothing an earlier line said about that row survives it: the
* row it files (whose own key is the one the event addresses, or the line is not one of this ledger's — see {@link filesForeignRow}),
* `null` for its removal, `undefined` when it moves only part of a row an earlier line holds. What lets the fold say which rows a
* damaged line can have moved: only those no settling event re-established after it. */
settles(ev: Ev): Row | null | undefined;
/** The row's name in an operator's report. Never a secret: a checkpoint's token is a capability, so it is named otherwise. */
nameOf(row: Row): string;
}
/** One line of a snapshot+ledger pair that is not one of the ledger's records and cannot be an append that never returned. */
export interface LedgerDamagedLine {
/** Which half of the pair: the compacted base, or the live ledger. */
readonly file: "snapshot" | "ledger";
readonly path: string;
/** 1-based physical line. */
readonly line: number;
readonly form: CorruptBodyForm;
/** What the line is, in a disclosure's words. */
readonly what: string;
}
/**
* The refusal of a snapshot+ledger pair that holds damage (`code` `store.ledger_damaged`). Thrown where the ledger is opened — a store's
* constructor (and so `FileStorageBackend`'s), and the read-only {@link import("./checkpoint-store.js").readCheckpointLedger} — never at a
* request: it answers an operator, so it names the files. The way out is {@link import("./ledger-damage.js").setAsideLedgerDamage}, which
* the message names with its arguments.
*/
export declare class FileLedgerDamagedError extends Error {
/** The ledger's directory (`<root>/<ledger>`). */
readonly dir: string;
/** Every damaged line, snapshot lines first, each in file order. */
readonly damaged: readonly LedgerDamagedLine[];
/** Rows present in the fold whose newest state may have been on a damaged ledger line (none re-established them after it). */
readonly rowsInReach: number;
/** Snapshot rows lost outright: one per damaged snapshot line (a snapshot line is one whole row). */
readonly snapshotRowsLost: number;
readonly name = "FileLedgerDamagedError";
readonly code: "store.ledger_damaged";
constructor(message: string,
/** The ledger's directory (`<root>/<ledger>`). */
dir: string,
/** Every damaged line, snapshot lines first, each in file order. */
damaged: readonly LedgerDamagedLine[],
/** Rows present in the fold whose newest state may have been on a damaged ledger line (none re-established them after it). */
rowsInReach: number,
/** Snapshot rows lost outright: one per damaged snapshot line (a snapshot line is one whole row). */
snapshotRowsLost: number);
}
/** Everything one read of a pair establishes, before anything is decided on it. */
export interface LedgerFold<Row> {
readonly rows: Map<string, Row>;
/** Ledger events folded over the snapshot. */
readonly events: number;
readonly damaged: readonly LedgerDamagedLine[];
/** Keys of the present rows a damaged LEDGER line can have moved: every row no settling event re-established after the last
* damaged ledger line (a row from the snapshot counts as established before every ledger line). Empty when the ledger has none. */
readonly reach: readonly string[];
/** The live ledger's last segment when it is an append that never returned. */
readonly uncommittedTail?: {
readonly line: number;
readonly bytes: number;
};
}
/**
* The ONE fold of a snapshot+ledger pair into its rows: the snapshot (the compacted base) row by row, then the live ledger's events in
* order (last-writer-wins, `model.apply`), every line judged by {@link judgeJsonlFile} as its writer allows — the snapshot is published
* whole (so any line in it that is not a row is damage, its unterminated end included), the ledger is appended (so its unparseable
* unterminated end is an append that never returned: commit order is durable append first, in-memory flip after, and an append is ONE
* write of `json + "\n"` rolled back on failure, so no writer leaves a half line WITH its newline). A READ — it takes no writer fence,
* opens no append handle and creates nothing (a missing file reads as empty). It folds past damage only to say what the damage reaches;
* {@link replayLedger} is what refuses on it.
*/
export declare function foldLedger<Row, Ev>(paths: Pick<LedgerPaths, "snapshotPath" | "ledgerPath">, model: LedgerModel<Row, Ev>): LedgerFold<Row>;
/**
* The fold every reader of a pair runs ({@link foldLedger}), and what it does with what it finds: a pair holding damage is REFUSED
* ({@link FileLedgerDamagedError}) after each damaged line and the refusal are told to the seat — never folded past, because the fold is
* last-writer-wins and a line it cannot read may be a row's newest; an uncommitted tail is told once and read as not having happened.
* Both the authority's own bootstrap ({@link LedgerCore.bootstrap}, which takes the fence first) and a reader that must not contend for
* the directory ({@link readLedgerSettled}) run it: a reader never carries a second copy of the fold.
*/
export declare function replayLedger<Row, Ev>(paths: Pick<LedgerPaths, "snapshotPath" | "ledgerPath" | "onCorruptRead">, model: LedgerModel<Row, Ev>): {
rows: Map<string, Row>;
events: number;
};
/** Rewrite a pair from `rows`: the snapshot atomically, then the live ledger atomically emptied. The one serialization of a pair, shared by
* compaction and by the damage set-aside, so a pair rewritten either way reads back the same. */
export declare function writeLedgerPair<Row>(paths: Pick<LedgerPaths, "tmpDir" | "snapshotPath" | "ledgerPath">, rows: Iterable<Row>, beforeLedger?: () => void): void;
/**
* Where one ledger family lives under a data root and how its lines fold — the single statement of its file names, read by the store
* that opens it and by the operator verb that sets its damage aside.
*/
export interface LedgerSpec<Row, Ev> {
/** The directory under the data root, which is also the name the operator verb takes. */
readonly name: string;
readonly ledgerFile: string;
readonly snapshotFile: string;
readonly model: LedgerModel<Row, Ev>;
readonly table: SharedLedgerTable<Row, Ev>;
}
/** The paths of `spec`'s pair under `root` (`tmpDir` is the root's shared scratch directory). */
export declare function ledgerPathsOf(root: string, spec: Pick<LedgerSpec<unknown, unknown>, "name" | "ledgerFile" | "snapshotFile">): Omit<LedgerPaths, "onCorruptRead">;
/**
* {@link replayLedger} for a reader that takes NO writer fence, beside a writer that may be compacting. The pair is read snapshot-first, and
* compaction rewrites the snapshot and THEN empties the ledger, so a read that saw the old snapshot and the emptied ledger would miss every
* row that lives only in the new snapshot — a clean-looking state that never existed. Such a read is recognisable by the snapshot having
* changed version by the time the ledger was read, and is discarded and redone, at most {@link SETTLED_READ_ATTEMPTS} times; a snapshot that
* will not hold still yields `settled: false` — no reading at all — never the last read. (A compaction that has replaced the snapshot but not
* yet the ledger is a state a crashed writer leaves too, and the authority's own bootstrap replays exactly that pair.) Appends move nothing
* here: a ledger read ends at a record boundary, so the events it holds are a prefix of the writer's. A pair holding damage throws
* {@link FileLedgerDamagedError}, exactly as the store's replay refuses it.
*/
export declare function readLedgerSettled<Row, Ev>(paths: Pick<LedgerPaths, "snapshotPath" | "ledgerPath" | "onCorruptRead">, model: LedgerModel<Row, Ev>): {
settled: true;
rows: Map<string, Row>;
events: number;
} | {
settled: false;
};
/** `read` of a pair taken with no writer fence, bracketed by the snapshot's version (see {@link readLedgerSettled}): its answer once the
* snapshot held still across it, or `undefined` after {@link SETTLED_READ_ATTEMPTS} reads that each saw it replaced. */
export declare function readSettled<T>(snapshotPath: string, read: () => T): T | undefined;
/**
* One directory's authority: the replayed row map, the per-key async mutex, the append log and the
* event counter. Created and owned by {@link SharedLedgerTable}; every store instance over the
* directory holds a reference to the SAME object.
*/
export declare class LedgerCore<Row, Ev> {
private readonly key;
private readonly paths;
private readonly model;
private readonly table;
/** The authoritative replayed state — domain queries read it directly. */
readonly rows: Map<string, Row>;
/** How many store instances hold this authority (RB-145: it belongs to the directory). */
refs: number;
private readonly locks;
private events;
private handle;
/** This directory's cross-process writer fence, held for as long as the authority exists. */
private fence;
/** Set when the last holder left: this object is no longer the directory's authority (see compact). */
private released;
constructor(key: string, paths: LedgerPaths, model: LedgerModel<Row, Ev>, table: Map<string, LedgerCore<Row, Ev>>);
/**
* Rebuild the authority: take the directory's cross-process writer fence, then the snapshot (the
* compacted base), then the live ledger's events in order (last-writer-wins), then open the append
* handle. Only the FIRST instance over the directory runs it.
*
* The fence comes FIRST because everything after it assumes what the fence establishes: the replayed
* map is treated as THE authority for the directory (writes are decided against memory, and
* compaction rewrites the on-disk state FROM memory). Replaying first and locking after would be a
* window in which a second process's view is already stale.
*/
bootstrap(): void;
/**
* Serialize an op behind any in-flight op on the same key — the in-process per-key async mutex (the
* SAME `Map<key, Promise>` chain shape as `TtlSessionStore.pending`). Each call appends a new tail;
* the next caller awaits THIS op before running. A prior op's rejection never blocks the chain (we
* await it `.catch`-guarded). The entry is pruned once it is the settled tail with nothing queued.
*/
withLock<T>(key: string, fn: () => Promise<T> | T): Promise<T>;
/**
* Commit one ledger event: fsync'd append FIRST, in-memory flip AFTER — so a crash can never leave
* memory and disk disagreeing. Then the best-effort housekeeping compaction (RB-150/RB-167).
*/
commit(ev: Ev, fsync: boolean, compactEvery: number): void;
/**
* Rewrite the snapshot from the authoritative map (atomic) and truncate the live ledger. After
* this a replay reads the whole state from the snapshot alone — the round-trip is identical.
*
* REFUSED once this authority has been RELEASED. Compaction is the one operation that does not touch
* the append fd (it rewrites whole files), so a store object kept alive past its `close()` could still
* run it — rewriting the directory from a map that stopped being the authority, over rows a SUCCESSOR
* (here or in another process, holding the fence this core gave back) has since written. That is the
* same erasure the directory fence exists to prevent, arriving through a stale reference instead of a
* second process, so it is refused at the same door rather than trusted to caller discipline.
*/
compact(): void;
/** Every deletion batch ends here so the deleted rows' earlier events leave the disk (a batch's own deletes commit with no
* housekeeping compaction): with any event pending the directory is compacted now, once per call, and a failure throws (bytes
* still on disk = not deleted). The repeat of the call compacts again. */
settleErasure(): void;
/** Drop one instance's share. The LAST holder evicts the authority — identity-checked, so a stale
* holder can never revoke a REBUILT entry — retires it (see {@link compact}) and closes the append fd. */
release(): void;
/** Test/inspection: events appended since the last compaction. */
get pendingEvents(): number;
private get log();
}
/**
* The module-level authority table one store family keeps: ONE entry per canonical directory, with
* eviction (RB-134 — a table without invalidation is RB-73's mistake again: after a `close()` the
* next store over that root would join a table whose log was already closed and every write would
* throw `log_closed`, instead of replaying the on-disk truth into a fresh authority).
*/
export declare class SharedLedgerTable<Row, Ev> {
private readonly model;
private readonly live;
constructor(model: LedgerModel<Row, Ev>);
/** Whether a store in this process holds the authority over `dir` now. */
isLive(dir: string): boolean;
/** Join the live authority for this directory, or create + replay a fresh one. */
acquire(paths: LedgerPaths): LedgerCore<Row, Ev>;
}