UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

242 lines (241 loc) • 19.9 kB
import type { Session, SessionCreateOptions, SessionForkOptions, SessionHead, SessionMetadata, SessionPlacementRecord, SessionRepo, SessionRepoRowCells, SessionRow, SessionRowExpectation, SessionRowRead, SessionTreeEntry } from "../../internal/harness.js"; import { type PlacedSessionRow } from "../../core/session.js"; import { type CorruptReadInfo } from "./corrupt-read-sink.js"; import { type HolderJudge, type StoreHolderFence } from "../../core/checkpoint-generation.js"; /** `<root>/sessions` for a resolved data root — shared by {@link FileSessionRepo} and the admission probe. */ export declare function sessionsDirOf(root: string): string; /** By-id placement header read shared by {@link FileSessionRepo.placementOf} and `FileDataRootAdmission.isPlaced`. */ export declare function readRowPlacement(sessionsDir: string, sessionId: unknown): SessionPlacementRecord | undefined; export interface FileSessionRepoOptions { /** * Disclosure sink for a durable read this repo treats as ABSENT (ruled 2026-08-03). Same name and * same `{path, reason}` shape as the sibling file stores' seat — "unreadable read as missing" and * "corrupt read as missing" are one failure grammar, so they get one seat name. * * Fires for: an unreadable sessions DIRECTORY (the listing degrades to "no sessions"), a session log * whose header could not be read during a listing (skipped from the result — a listing reads headers, * it never replays a log; a PLACED row whose owner cell alone is unreadable is not skipped — the placed listing lists it — and is * disclosed as that), and each corrupt interior JSONL record dropped on replay plus that replay's * tally (turns missing from an otherwise healthy session). * * Never fires on plain ENOENT / `not_found` — that is honest absence, and the torn TAIL stays silent * too (dying mid-write is the append log's documented crash-recovery shape, not corruption). * Swallow-guarded: a throwing sink cannot re-introduce the fault the fail-open avoids. * * `sessionId` rides every disclosure about ONE session — its log's skipped records and tally, and its log * skipped from a listing — naming the session the repo was reading (on a listing, the id its file name * spells); a disclosure about the sessions directory itself carries none. */ onCorruptRead?: (info: CorruptReadInfo & { sessionId?: string; }) => void; /** * Who holds the rows' occupant cells ({@link SessionRepoRowCells}). Absent / `"engine"`: this repo — a row's header records its * `incarnation` (and a fork's `forkedFromIncarnation`) and every read hands them out. `"host"`: the host's own store — a content repo: * no header this repo writes holds either cell, no read hands either out (a header an engine-mode write laid down is read without * them, and a cell there that names nobody is not disclosed), the shared authority over a file is judged by the file alone, and a * conditional write by the owner and the log. The host's session store then puts the occupant on the metadata its sessions answer * and on its head read; `TtlSessionStore` refuses a repo of this mode. */ rowCells?: SessionRepoRowCells; /** * The deployment's grant judge ({@link HolderJudge}): every append and leaf move carrying a holder is judged by it first, in the * write's own synchronous step; with it the repo declares `fence = { holder: "writes" }`. The judge belongs to the shared authority * over a session file, not to this repo: a second repo over the same file built with another judge (or with one beside none) is * refused when it joins (`config.invalid_session_store`), naming both — a deployment whose judge is built after its stores hands * every store one trampoline function. */ holderIsCurrent?: HolderJudge; } export declare class FileSessionRepo implements SessionRepo { private readonly dir; private readonly tmpDir; private readonly onCorruptRead; /** RB-437 — the shared authorities THIS repo has joined, weakly (canonical key → the joined storage). * `dispose()` walks it and releases each holder share; the weak value is what makes the identity * check on the way out possible without pinning a storage the table itself only holds weakly. */ private readonly joined; /** This repo's "closed" latch ({@link HolderLatch}): set by {@link dispose}, handed the backend's when a backend built the repo. Once * closed, a write verb that begins is refused `log_closed` before it touches anything, no row is handed out ({@link refuseRowAfterDispose}), * and a session handed out earlier refuses its writes ({@link handedOut}). */ private readonly latch; /** The view this repo hands out of each shared authority it joined ({@link viewOf}), by the authority. */ private readonly views; /** {@link FileSessionRepoOptions.rowCells}, read once. */ readonly rowCells: SessionRepoRowCells; /** `{ holder: "writes" }`, declared exactly when the repo was built with a `holderIsCurrent` judge. */ readonly fence?: StoreHolderFence; private readonly holderIsCurrent; /** `<root>/sessions`, absolute: the directory this repo writes its transcripts into ({@link SessionRepo.transcriptDirectory}). */ readonly transcriptDirectory: string; constructor(root: string, options?: FileSessionRepoOptions); /** The one delivery point for {@link FileSessionRepoOptions.onCorruptRead}'s whole-file level; `sessionId` when the file is one session's log. */ private disclose; private pathFor; /** * Read + torn-tail-recover a session file into (meta, entries). Three answers: no file → `not_found`; a * file whose first record is not a meta header → `corrupt_session`, even when every other record is intact * (every write path here lays the header down first and the header alone carries `createdAt` / fork / * placement / owner, so the file is not a session this store wrote, or its header line is damaged); * otherwise the session, each skipped record disclosed, and `loss` = what the replay dropped (absent = nothing). */ private read; /** * The row's cells from its FIRST record — the one header every write path lays down before any entry; a later meta record is * never read as the header. Each occupant cell goes through the one incarnation decoding (an unknown occupant, said here when the * cell is there but names nobody) and the owner cell through its decoding (a cell that is neither an owner nor anonymous refuses * the row). `skipped` words the corrupt-header refusal's reading of the records around it, where the caller has one. */ private headerOf; /** The header's cells but its owner — what a reader of the row's lane, lineage and occupant needs, each cell through its decoder. */ private cellsOf; /** * The row's header record, where the log has one: its FIRST record, which must be the meta header every write path lays down. A log whose * first record is anything else is no row this store wrote — `corrupt_session`, said once here for every reader of the row — and so is one * whose placement cell is no placement tuple ({@link readPlacementCell}): the placement is the cell that says which lane the row lives * in, so every reader of the row, of any other cell, goes through its judge. The other cells are each read by their own reader * ({@link headerOf} for the whole header, `placementOf` for the placement tuple alone): a reader of one cell does not answer for the others. * The header is read as this repo holds a row ({@link heldRowCells}): every reader of a cell reads it here, so in `"host"` mode no reader * sees an occupant cell an engine-mode write left behind. */ private metaLineOf; /** * The row's head in one read, without replaying the log: ONE descriptor on the session file, its first record for the owner and * occupant cells, and walking back from its end to the last entry record for the leaf. The three come from one inode — a file * replaced (fork / import) or removed (delete) while this reads is still the inode this descriptor opened — so they answer for one * row generation. The leaf is what a replay computes (the leaf after the last entry the whole-file read keeps, judged by the same * per-line rule, a torn tail dropped alike): the log is the only carrier, so no state exists in which the log holds an entry the * head does not see. A leaf entry naming an id the log does not hold is not checked here (a replay refuses that log on open). */ headOf(sessionId: string): Promise<SessionHead | undefined>; /** {@link headOf}'s one read, synchronously — what a conditional delete judges its expectation against in the step that removes the row. */ private headNow; /** The row in one read of its file (one inode): the header's cells, the head they and the replayed log give, and the log. */ readRow(sessionId: string): Promise<SessionRowRead | undefined>; /** {@link readRow}'s one read, synchronously — what a conditional import judges its expectation against in the step that writes. A * file whose header cannot be read rejects (`corrupt_session`): it is a row whose cells nobody can name. */ private rowNow; /** * The row's {@link SessionRow} — its header cells and the newest write it holds, the log's modification time (every write to a row * is an append to its log; the placed listing's age reads the same time) — in one read of the header, never a replay of the log. * `undefined` = no row; a row whose header cannot be read rejects (`corrupt_session`) — except a PLACED row whose only unreadable cell * is the owner's, which is {@link OwnerlessPlacedRow}: a listing asks where a row lives and how old it is, not who owns it. */ private rowOf; /** The one descriptor a by-id read of the row takes: its size and modification time and its header decoded whole, from one inode (a * file replaced or removed while this reads is still the inode this descriptor opened); `undefined` = no file. A reader of one cell * alone takes {@link atFirstRecord}, which this is built on. */ private atRow; /** The descriptor under every by-id header read: the file's size and modification time and its first record, undecoded — the bytes * each cell's reader decodes. One inode, bounded by the lines before the first record, never by the log; `undefined` = no file. */ private atFirstRecord; /** * A disposed repo hands out no row: {@link open} reads the row and is refused, no log bound. The refusal is `log_closed`, as for a view * held across the dispose; a holder that drops such a closed view and resolves the id again (`TtlSessionStore` does) lands here. Every * write verb ({@link create}, {@link fork}, {@link importEntries}, {@link recordOwner}, {@link delete}, {@link deleteUnreadable}, * {@link touch}) is refused by the latch on entry, a new row and a row that is not there alike. */ private refuseRowAfterDispose; /** * The judge belongs to the authority over a path ({@link joinHolderJudge}): a repo bringing another one is refused before it holds a * share, before it evicts a live authority it reads as stale (a repo of another `rowCells` reads another occupant off the same file), * and before it lays a row down or replaces one under the id — checked before anything is written. */ private assertJudgeJoins; /** The session this repo hands out over a (possibly shared) authority: a session over this repo's view of it ({@link viewOf}). */ private handedOut; /** * This repo's one view of a shared authority — the `getStorage()` of every session it hands out over it (two opens through this repo * answer the same object; another repo's view of the same authority is its own, the authority's leaf, entries and log shared either * way). A facade built from {@link HANDED_SESSION_VIEW} alone, with no prototype: a read member is forwarded as it is, a write member * asks this repo's latch first and is refused `log_closed` once the repo is closed (whoever else still holds the authority), the view * test answers false once it is closed (a cache holding the session resolves the id again, through this repo). No member answers the * authority itself. */ private viewOf; private storage; /** * RB-437 — release every shared authority this repo joined (LAST holder ⇒ evict + close the append fd). * * This is the lifecycle-tied half of the eviction rule the four file-REPLACING operations already * cover: after it, a NEW repo/backend over the same root replays each session from disk instead of * serving this process's pre-dispose in-memory leaf, and a Session handle held across the teardown * is refused with `code=log_closed` rather than writing onto a data root the process has released. * * Idempotent; safe to call on a repo that never opened anything. A repo whose authority was replaced * meanwhile (delete/fork/import/create-over-absent) releases NOTHING for that key — the identity check * means a stale holder can never revoke the rebuilt entry. * * From here on the repo neither hands out nor changes a row ({@link refuseRowAfterDispose}): a view the release closed is * not built again through it. */ dispose(): Promise<void>; create(options?: SessionCreateOptions): Promise<Session>; open(metadata: SessionMetadata): Promise<Session>; /** Record activity on the row now: its log's modification time — the one time a listing reads, which every append moves too — is * set to now, the log's bytes untouched. A missing file is nothing to record; any other fault rejects (`storage`, the fault its cause — * an unsafe id string included). An id that is not a string is refused by the path guard's own error, unwrapped: the sentence below * spells only a string, never a value that is read to be spelled. */ touch(sessionId: string): Promise<void>; /** Every ordinary row with the newest write its log holds ({@link rowOf}): one header read per session file, no replay — what a * listing costs grows with the number of sessions, never with their history. Placed rows are the placed listing's. */ list(): Promise<SessionRow[]>; /** * Every row of the sessions directory, each read by {@link rowOf}. The listing degrades to "no sessions" so a * browse face never throws — but "I could not read the directory" and "there are none" are different facts, and only the sink can * tell them apart (ENOENT is honest absence: the constructor creates the directory, so it was removed underneath us). A session * whose header cannot be read is skipped and disclosed — it exists and is missing from the listing — while a file that vanished * between the directory read and its own is honest absence. A placed row whose owner alone is unreadable is neither skipped nor * silent: it is kept (the placed listing lists it) and disclosed, once per listing, in the same sentence whichever listing reads it. */ private rows; /** * Subagent transcript persistence — the PLACED partition's own enumeration (the joint reap's * partition-leg input; `TtlSessionStore` re-exposes it verbatim). Age (`olderThanMs`) is judged on * the session FILE's mtime — the transcript's last append, the time the host listing reads too * (mtime is also the CC orphan-adoption window's basis, so the age reads agree). * Rows missing either `(scope, handle)` join half return the honest `tupleIncomplete` variant * (consumers fail closed on it — never age-reaped, see the SessionStore contract). */ listPlaced(kind: "subagent", opts?: { olderThanMs?: number; scope?: string; }): Promise<PlacedSessionRow[]>; /** Cheap placement probe for one id (the TtlSessionStore's cold-cache release consults it so the * placed real-deletion obligation holds after a restart), answered from the row's header record alone — never a replay of its log — * and from the placement cell alone: a row whose owner cell cannot be read still says whether it is placed (the readers of the owner * refuse that row; this probe is not one of them). `undefined` = missing file OR unplaced; a log with no header record rejects. */ placementOf(sessionId: string): Promise<SessionPlacementRecord | undefined>; delete(metadata: SessionMetadata, expect?: SessionRowExpectation): Promise<void>; /** {@link SessionRepo.deleteUnreadable}: the head read and the removal are one synchronous step (no await between them, so no write of * this process lands in between; another process is kept off the root by its boot lock) — a row that reads in this step, or no row, * is never removed. */ deleteUnreadable(sessionId: string): Promise<boolean>; /** The one removal tail of every deletion here: the shared authority evicted, then the file removed — a failure loud. */ private removeRow; fork(sourceMetadata: SessionMetadata, options?: SessionForkOptions & SessionCreateOptions): Promise<Session>; /** 2c session-sync (the FILE half): the FULL oldest-first log for export. The file backend * has NO F3 floor — `read` returns EVERY persisted entry (`id`/`parentId` verbatim) — so this is the complete * log, BYPASSing any bounded tail (matches `InMemorySessionRepo.exportEntries`). Missing file → not_found. */ exportEntries(sessionId: string): Promise<SessionTreeEntry[]>; /** 2c session-sync: import a verbatim log into `sessionId`. The single fail-closed invariant gate runs * FIRST ({@link validateEntriesForImport}); a new row's header records `owner`, an existing row's is laid down again whole and must already * be `owner`'s (`importRowCells`), and the row must be the one `options.expect` names (`sessionRowMatches`) — the row read, both * judgements and the write with no await between; the head answered is the one the write lays down. Writes the WHOLE file * (meta + entries) atomically via tmp→fsync→rename — the rename is the commit point, so a crash leaves either nothing or an * orphan temp, never a partially-imported session. The importer's existing session is REPLACED (the * orchestrator's importSession owns the already-exists policy, same as InMemory's overwrite). */ importEntries(sessionId: string, owner: string | undefined, entries: SessionTreeEntry[], options?: { preserveActorAssertions?: boolean; expect?: SessionRowExpectation; }): Promise<SessionHead>; /** * {@link SessionRepo.recordOwner}: inside the import's writer boundary — the row read whole, judged ({@link recordedOwnerCells}) and the * file laid down again with only its header line changed (tmp→fsync→rename; the occupant, placement and lineage cells as they were, every * byte after the header as the file held it), with no await between. A live authority that is a view of the row just read is not evicted: it binds a * new append log to the replacing file (which repairs a torn tail, as every open of a log does) and answers the recorded owner ({@link FileSessionStorage.adoptRecordedRow}), so a session handed * out before the write keeps writing to the row; one that is not a view of it is evicted as an import evicts it. A disposed repo * changes no row. */ recordOwner(sessionId: string, owner: string, expect: SessionRowExpectation): Promise<SessionHead | undefined>; }