UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

554 lines (553 loc) • 40.7 kB
import { type LockHolder, type LockRemedy, type StoreLockName } from "./lock-reading.js"; export { processFingerprint, isProcessLive, type ProcessFingerprint } from "../../core/process-identity.js"; import type { CorruptBodyForm } from "../../core/store-contracts/read-back-shape-contract.js"; import type { CorruptRecordRead, CorruptReplayTally } from "./corrupt-read-sink.js"; /** * Validate an engine-minted id (sessionId / tool-result ref) before using it as a path component. These are * `uuidv7` / an encoded tool-result ref — already filename-safe — but a strict guard is cheap * defense-in-depth: reject `.`/`..`/empty/separators so nothing can traverse out of the store dir. * * A component is a STRING: anything else (an object, an array, a number, `null`, a `String` wrapper) is refused with the same * sentence a bad string gets, saying the value's kind and never what it holds, and is never read — no `toString` runs. What * comes back is the very string that was checked, so a caller that builds the path from the answer reads one value, not two. */ export declare function sanitizePathComponent(raw: string): string; /** * Map a model-influenced memory `scope` to a safe directory name (CC `sanitizePath` parity). Replace every * non-alphanumeric run with `-`; if the result is over 200 chars, append a short content hash so two long * scopes can't collide. The ORIGINAL scope is the partition key the engine passes — this only affects the * on-disk dir name, never the stored data. Never `path.join` a raw scope. A scope is a STRING: any other value is refused, by its kind and * unread, as {@link sanitizePathComponent} refuses one. A scope holding an unpaired surrogate is refused too ({@link assertWellFormedKey}, * `config.invalid_argument`): its digest is the one of its U+FFFD spelling, another scope's directory. U+FFFD itself names its own. */ export declare function sanitizeScope(scope: string): string; /** A caller's key (`what` names the parameter) that holds an unpaired surrogate is refused, `config.invalid_argument`, before a store names * anything by it: the one judge is `holdsUnpairedSurrogate`, the refusal never repeats the value. A value that is not a string is not read * here (no `toString` runs): the caller's own string check refuses it as before. */ export declare function assertWellFormedKey(key: string, what: string): void; /** {@link sanitizeScope}'s directory name by the formula alone, unjudged: for a name a store already holds and only re-derives — a tracked * set's recorded scope, a run's part removed by its own id, a row a running adoption quarantines — which an earlier release admitted. */ export declare function scopeLabelOf(scope: string): string; /** Resolve the data root (CC `getClaudeConfigHomeDir` analog): the one spelling ({@link dataRootSpelling}: `$AGENT_DATA_DIR ?? * ~/.ai-agent`, NFC), canonicalized once the dir exists. It asks the root's one walk first (`walkedDataRoot`, the walk * `dataRootLocation` answers): a value the walk refuses is refused here with the walk's code and nothing is made. A walked value is * made as it always was (the spelling, recursively, 0o700 for each directory made) and its physical path answered — the same answer * as `dataRootLocation`. `anchor` places a relative root under another directory than this process's (refused * `config.invalid_argument` when it is not a non-empty absolute path, or given with no root; see `walkedDataRoot`). */ export declare function resolveDataRoot(explicit?: string, anchor?: string): string; /** * Atomically CREATE `target` carrying `content` — it appears in ONE step already fully written, no empty/partial * window. Fixes the create-then-write race: a reader/pruner can see a half-written * file, and a crash mid-write leaves a zero-byte target a retry would silently keep. Writes a temp in `target`'s * OWN dir (same FS → `link` is atomic) + fsync, then `linkSync`-publishes it; throws `EEXIST` if `target` exists. */ export declare function writeThenLink(target: string, content: string | Uint8Array): void; /** Ensure a directory exists with 0o700 perms (idempotent). */ export declare function ensureDir(dir: string): void; /** * The 5-step atomic whole-file replace (§2.1). Skipping any of steps 3/5/6 is the classic corruption bug: * 1. open a temp under `root/tmp/` (same FS → rename is atomic), * 2. write the bytes, * 3. fsync the DATA (else ext4 "zero-length file after crash"), * 4. close → rename(tmp, target) (atomic intra-FS namespace swap), * 5. fsync the containing DIRECTORY (persists the rename itself). * On any failure the temp is unlinked so a crashed write leaves no scratch behind. */ export declare function atomicWriteFile(tmpDir: string, target: string, bytes: string | Uint8Array): void; /** * Read a JSONL file and return every COMPLETE, parseable record — the universal torn-tail recovery (§2.2): * - the last segment, when no `\n` ends it, is judged as every line is (`@contract store.read_back_shape_judged`): * an object is served, an unparseable remnant is a crash's partial write and is discarded, * - any interior line that fails `JSON.parse` is skipped (never throws — `listRemoteAgentMetadata` * parity), so a single corrupt interior line never poisons the whole replay. * A missing file → `[]`. This is why JSONL beats one big JSON blob: a torn tail can never corrupt the store. * * SHAPE (`@contract store.read_back_shape_judged`): parseability is not the judgement. Every store on this * format writes ONE JSON OBJECT per line, so a line parsing to a number, string, boolean, `null` or array * takes the road a torn line takes — disclosed and skipped — because it is the same fact: these bytes are * not what this store wrote. `judge` (optional) is the consuming store's own floor on an object ("does it * carry my members at all?"); a record it rejects is skipped as `missing-required` on the same road, so * the count below covers every skip. * * `onCorrupt` (optional): one `record` disclosure per skipped record, then — iff any was skipped — one * `replay` tally. The unparseable unterminated tail stays out of both by design: dying mid-write is the * crash shape this format exists to absorb. An unterminated tail that parses to a non-object is not that * shape (no prefix of an object parses to one), so it is disclosed like any other foreign line. The callback * is invoked as given — a seat that must not throw swallow-guards on ITS side. */ export declare function readJsonlRecords<T>(path: string, onCorrupt?: (info: CorruptRecordRead | CorruptReplayTally) => void, judge?: JsonlRecordJudge): T[]; /** * How a JSONL file came to hold its bytes — which decides what its unterminated last segment can be. * · `appended`: a live append log ({@link AppendLog}). A record is ONE write of `json + "\n"`, rolled back when it fails, and it is * acknowledged only after it is on disk; so an unparseable unterminated last segment is an append that never returned — the state * before it is the true one, and the next open cuts the bytes. * · `whole`: published in one step ({@link atomicWriteFile}: temp, fsync, rename). It has no append in flight, so the same bytes are * damage like any other line that is not a record. */ export type JsonlWritten = "appended" | "whole"; /** One line of a JSONL file, as {@link judgeJsonlBytes} and {@link judgeJsonlFile} read it. `line` is 1-based and physical. */ export type JsonlFileLine<T> = { readonly verdict: "record"; readonly record: T; readonly line: number; } | { readonly verdict: "damage"; readonly line: number; readonly form: CorruptBodyForm; readonly what: string; } /** An `appended` file's unparseable unterminated last segment: an append that never returned (`bytes` = its UTF-8 length). */ | { readonly verdict: "uncommitted-tail"; readonly line: number; readonly bytes: number; } /** An empty line before the file's end. It carries no record — and no writer of these files leaves one, so where a reader cannot * afford a record's bytes erased under its newline, it is damage (the snapshot+ledger fold); {@link readJsonlRecords} passes it. */ | { readonly verdict: "blank"; readonly line: number; }; /** * THE judgement of a JSONL file's bytes, line by line: every line is a record, damage, an empty line, or — only as the unterminated last * segment of an `appended` file — an uncommitted tail ({@link JsonlWritten}). Nothing is disclosed or dropped here; the reader that called * it decides what each verdict does ({@link readJsonlRecords} skips damage and says so; the snapshot+ledger fold refuses on it). Empty * bytes hold no line; the empty segment after a final newline is the file's end, not a line. * * `written` is the caller's statement of how the file got its bytes (`"appended"` or `"whole"`). Refuses (`config.invalid_argument`) any * `bytes` that is not a genuine `Uint8Array` (a `Buffer` is one) or any `written` other than `"appended"` or `"whole"`. Copies the input * bytes once at entry into a dedicated unpooled `ArrayBuffer` through the intrinsic typed-array machinery so subclass accessors, shared * Buffer pools, and mid-scan mutations by `judge` cannot alter or leak the judgement. `endsOnBoundary` is `true` when the bytes are empty * or end with a newline byte (`0x0a`), `false` otherwise. */ export declare function judgeJsonlBytes<T>(bytes: Uint8Array, written: JsonlWritten, judge?: JsonlRecordJudge): { readonly lines: JsonlFileLine<T>[]; readonly endsOnBoundary: boolean; }; /** * Read a JSONL file (a missing file holds no bytes) and return its line-by-line judgement through {@link judgeJsonlBytes}. */ export declare function judgeJsonlFile<T>(path: string, written: JsonlWritten, judge?: JsonlRecordJudge): JsonlFileLine<T>[]; /** A consuming store's floor on a parsed JSONL object: `accepts` = one of its records; `what` names a * rejected one in the disclosure's words. */ export interface JsonlRecordJudge { accepts(record: object): boolean; what: string; } /** * The FIRST record of an open JSONL file of `size` bytes — the record {@link readJsonlRecords} would return first — read forward one * block at a time and stopping there: a read bounded by the lines before it, never by the file. Skipped lines are not disclosed (the * whole-file read discloses them); `undefined` = the file holds no record. */ export declare function firstJsonlRecord(fd: number, size: number, judge?: JsonlRecordJudge): object | undefined; /** * The LAST record of an open JSONL file of `size` bytes that `pick` accepts — the last such record {@link readJsonlRecords} would * return — found by walking back from the end one block at a time: a read bounded by the lines after it, never by the file. The * unterminated last segment is judged as the whole-file read judges it. Skipped lines are not disclosed; `undefined` = none. */ export declare function lastJsonlRecord(fd: number, size: number, pick: (record: object) => boolean, judge?: JsonlRecordJudge): object | undefined; /** * RB-144: THE canonical key for "one authority per physical location". Every file backend keeps a * module-level table so that N instances over one directory collapse into one CAS authority; getting the * KEY wrong reopens the defect the table exists to close, which this repo paid for four times (mailbox, * session store, then the agent/run/task-list stores still keying on a lexical `resolve()`). Point fixes * kept missing siblings, so the rule lives in ONE place they all call. * * Two normalizations, each for a demonstrated failure: * - PHYSICAL PATH — a symlinked data dir (`/var` → `/private/var` on macOS, a bind-mount, a linked * `~/.ai-agent`) otherwise yields two authorities for one directory, and both writers win the CAS. * - CASE FOLD — on a case-insensitive filesystem `Foo/` and `foo/` are the same directory. The mint * answers with the on-disk spelling, which folds the two only where the entry EXISTS; the fold here * also covers a not-yet-created tail, and folding a PATH would name a different directory on a * case-SENSITIVE volume (see the cc task-list store's lock target, which must not fold) — so it stays * at this call site, which keys, rather than inside the mint, which answers about paths. * * The key is used ONLY for table lookup — never for I/O, so the on-disk name stays verbatim. A path that * does not exist yet resolves through its deepest existing ancestor; a path with no resolvable ancestor at * all keys on its lexical form (a store must not fail to construct because canonicalization is unavailable). */ export declare function canonicalStoreKey(p: string): string; /** * An append-only JSONL log, bound for its whole life to ONE file. One record = one `JSON.stringify(...) + "\n"` written whole (never * split across records → the only torn line possible is a crash tail, which {@link readJsonlRecords} drops). `fsync` is opt-in per * append (the checkpoint commit point ALWAYS fsyncs; session/memory cadence is the caller's `fsyncEvery`). * * Descriptors: a log holds one only while it is among the most recently written logs of this module * (`setAppendLogDescriptorBudget`); past the budget the least recently written one parks, and its next write opens the file again. A * holder keeps the log, never a descriptor, so a store needs no bound of its own. Any open of the file store that meets the process's * descriptor limit makes the logs yield theirs before it gives up. * * The file: every append — descriptor held or reopened — first checks that the path still names the file this log left * ({@link isFileAtPath}); when it does not, the append is refused (`log_file_replaced`) and nothing at the path changes. The check is * three facts, and only these: the same inode, a length not shorter than where this log last left the file, and the last bytes this * log left there (at most 64) still in place. So bytes appended after them by someone else pass (a whole line is kept, a crash's half * line is cut by the tail repair), and an in-place rewrite that keeps the length and those last bytes is not seen. Where a record * ended is read off the file's length after the write, so another writer's bytes landing next to it are found again, not assumed * away. A holder that replaces the file has two ways that are never refused: {@link closeForSwap} around the replacement (the next * write binds to whatever the path names then), or {@link close} the log and build a new one after it (a new log binds to the file * it opens). */ export declare class AppendLog { private fd; /** * RB-167 (2026-07-26): distinguishes "closed because the holder is done with it" from "closed for a * compaction swap". Only the first is permanent. * * Every store that compacts does close → rewrite → reopen, and the rewrite can fail (EACCES, ENOSPC, a * read-only mount, an immutable flag). The stores handled that in three different and individually * insufficient ways: three of them left the log CLOSED FOREVER, so one transient I/O error turned into * `log_closed` on every later write — and because these logs are now SHARED per directory, that bricks * every instance on it, not just the one that compacted. The fourth reopened in a `finally`, which only * covers the failure shapes where reopening still works and, worse, replaces the original error with the * reopen's own when it does not. * * The reopen therefore belongs here, lazily: a swap-closed log reopens on its next write, so a fault that * has cleared simply resolves itself, a fault that has not surfaces at the write (with its own error, the * original having already propagated from the compaction), and `close()` keeps meaning exactly what * RB-99 made it mean. */ private disposed; private readonly path; /** * RB-438 — the file size as of the end of THIS log's last successful append (or of the last time it * observed the file at a record boundary). `-1` = unknown, re-establish on the next append. * * It is the cheap arbiter for "did the file change under us since we last left it whole": equal ⇒ * nothing to check, different ⇒ read the last byte and repair if it is not a newline. See * {@link repairTail}. */ private boundary; /** The file this log is bound to: its device and inode when the log opened it. `undefined` = not bound (before the first open, and * after {@link closeForSwap} until the next write opens whatever the path names then). */ private binding; /** The last bytes before {@link boundary} (at most {@link APPEND_LOG_WITNESS_BYTES}), as this log last left them: what tells a file * this log left from one that took its inode number (an inode is reused once the file is gone and no descriptor holds it) or was * rewritten in place. `undefined` whenever `boundary` is unknown. */ private witness; /** Parks this log: what the pool calls when the budget needs its descriptor. */ private readonly parker; constructor(path: string); /** * Hold a descriptor on the file this log is bound to, or refuse. Synchronous and calls no foreign code: nothing can run between the * check and the write that follows it in this process. * · Held: the path must still name the file this log left ({@link leftHere}), checked by `stat` and through the held descriptor. * · Parked: the path is opened WITHOUT creating, and the new descriptor must be that file; a refusal closes it again. * · Not bound: the path is opened (created if absent, "a+" = O_RDWR|O_APPEND: writes still go to EOF atomically, and the descriptor * can be read for the tail and the witness) and the log binds to what it opened. * Before opening, the least recently written OTHER log parks if the budget is reached; an open that meets the process's descriptor * limit yields, as every open of the file store does (`takeYielding`). A failure that is no answer about the file is thrown as it * is ({@link isFileAtPath}). */ private takeDescriptor; /** The held half of the one judgment ({@link isFileAtPath}): `stat` the path, judge it through the held descriptor. */ private heldIsHere; /** The parked half of the one judgment ({@link isFileAtPath}): open the path WITHOUT creating and judge the new descriptor. Answers * that descriptor when it is the file this log left, `undefined` when it is not (closed again); any other failure is thrown. */ private openIfHere; /** * Whether `fd`, open on a file whose `stat` is `st`, is the file this log left: a regular file with the inode it is bound to (a * directory put at the path can take a removed file's inode number — measured on Linux), at least as long as where this log last * left it at a record boundary, with the bytes it left before that boundary still in place. With the boundary unknown only the * inode is judged. */ private leftHere; /** Record that the file stands at a record boundary of `size` bytes (`-1` = unknown), with the witness read from the file. */ private settleAt; /** After `buf` was written whole: where it ended is what the file's length says, never what it should be. When the length is the * boundary plus `buf`, the record went right at the boundary — move past it, the witness from the bytes just written. Any other * length means someone else's bytes landed between this log's check and its write, or after it: where this record ends is not * known, so the boundary stays the last one this log knows (its bytes are still in place before it — an append moves nothing * earlier), and the next append's tail repair finds the end from the file. */ private settleAfterWrite; /** Whether the file's last byte (of `size`) is a newline — `false` when it cannot be read. */ private endsOnNewline; /** The pool needs this log's descriptor: close it and keep the binding, the boundary and the witness for the next write. */ private park; private sizeOrUnknown; /** * RB-438 (2026-07-31, hardening probe R2) — re-establish the last-complete-record boundary before a write. * * The open-time tail repair (constructor and the RB-167 lazy reopen) only ever ran at OPEN time, and * the RB-66 loop below only repairs a SHORT write — not a `writeSync` that THROWS mid-loop (ENOSPC/EDQUOT/ * EIO after a partial `write(2)`, the classic full-volume shape) and not the `n <= 0` guard. Both leave * `written` bytes on disk with no terminating newline while the fd and this object stay live, and every * caller retries through the SAME AppendLog (`FileSessionStorage.appendEntry` throws before `recordEntry`, * so the in-memory leaf is unchanged and the CAS retry appends again). The retry's record was then GLUED * onto the remnant, so replay dropped BOTH — after that second append had returned and fsync'd. Measured: * records [1,2,3] + a torn remnant + appends 5,6 replayed as [1,2,3,6]. * * Cost on the healthy path is ONE `fstat` per append (the sizes match and we return); the tail read only * happens when the file actually moved off a boundary, and it reads the last segment, not the file. A * legitimate concurrent appender (another process under the boot-lock handoff) leaves the file * newline-terminated, so it is adopted, not truncated; a whole record it left without its newline is kept * and ended, and only a partial one is cut. */ private repairTail; /** * Append one record (`json + "\n"`). `fsync:true` makes the record durable before return. * * RB-66 (2026-07-25, red probe): `writeSync(fd, string)` issues ONE write(2) and may SHORT-WRITE — the * same defect class this file's own `writeThenLink` already documents and fixed ("silently SHORT-WRITES * "), never propagated to this shared primitive. A short write here leaves a torn * line with no trailing newline, so the NEXT append concatenates onto it and replay drops BOTH records. * Loop until every byte lands (write(2) returns how many it took) — the O_APPEND atomicity per call is * unchanged, and a genuine I/O error still throws. * * A write that fails leaves no bytes of its own: the file is cut back to where the write began, so a caller * that retries the record writes it once — a record that failed is never also half-present. * * The record is serialized FIRST, before the descriptor is touched: serializing can run the record's own code (`toJSON`, getters), * which may write to this or another log, close this one, or make the budget park it. From taking the descriptor to the last byte * written nothing outside this file runs, so no descriptor is closed or reused under the write; a serializer that throws leaves * the disk as it was. */ append(record: unknown, fsync: boolean): void; /** * Cut the file back to `startedAt` after a write that threw, provided the bytes past it are exactly this * write's own (`written` of them): a peer that appended after us owns what follows, and its bytes are not * ours to cut. Best effort — the error the caller must see is the write's, so a rollback that cannot run * answers false and the next append's tail repair judges what is left. */ private rollBackFailedWrite; close(): void; /** Whether the path names the file this log left: the inode it is bound to, at least as long as this log last left it, with the last * bytes it left there (at most 64) still in place — the one judgment every append makes, whether this log holds a descriptor now or * not. A path that names no file (nothing there, a directory) is not; nor a file removed or replaced, cut shorter, or whose last bytes * from this log were overwritten; bytes others appended after them do not count against it, and an in-place rewrite that keeps both * the length and those bytes is not seen. A closed log answers no, as does one not bound to any file yet (after {@link * closeForSwap}). A failure that is no answer about the file — the process out of descriptors with no other log to yield one, a * permission, an I/O error — is thrown as it is, never read as "not the file": the caller retries, nothing is evicted. */ isFileAtPath(): boolean; /** * RB-167 — release the descriptor AND the binding for a SWAP: the holder is about to replace the file (a compaction), or has re-read * a file another writer replaced. The next write opens whatever the path names then (creating it if absent) and binds to that. * * Callers must use this rather than `close()` around a rewrite: `close()` means "this log is finished", * and a store that used it for a swap and then failed to rewrite left the log permanently unusable — * one transient I/O error becoming a permanent brick, shared by every instance on that directory. */ closeForSwap(): void; private releaseFd; } /** Bytes read per positioned read while a file's tail is walked back to its last newline. */ export declare const JSONL_TAIL_READ_BLOCK: number; /** * The longest last segment (in BYTES) a repair station will judge: V8's maximum string length in UTF-16 code units * (Node's `buffer.constants.MAX_STRING_LENGTH`). A segment of N bytes decodes to at most N code units, so one within * the bound can never make `toString` throw. One past it MAY still decode (multi-byte text has fewer units than * bytes) but is left unjudged either way: telling would mean reading and decoding up to three times the bound. */ export declare const JSONL_TAIL_SEGMENT_LIMIT: number; /** A file's last segment (the bytes after its last `\n`, or the whole file when it holds none) — or the fact that it is * too long to judge. `start` is the segment's offset; a file that ends on a newline has an empty segment at `size`. */ export type JsonlTailSegment = { unjudgeable: false; start: number; bytes: Buffer; } | { unjudgeable: true; }; /** * The last segment of an open file of `size` bytes, found by walking back from the end one block at a time to the * last newline: a read is bounded by the segment's length, never by the file's. The one reader of "what is the tail" * for every repair station; whether the segment is a record is {@link jsonlFormOf}'s to say. */ export declare function readTailSegment(fd: number, size: number, limit?: number): JsonlTailSegment; /** Why a {@link BootLock}/{@link acquireStoreDirLock} acquisition was refused, as a branchable code. */ export type FileStoreLockErrorCode = /** A LIVE process (this one or another) already holds the directory. Steady state: it ends when that * process ends. */ "store.dir_in_use" /** Another process is mid-RECLAIM of a lock left by a crashed owner. Transient by construction — the * claimant either finishes (and then owns the directory) or dies (and its gate is pruned in turn), so * the honest advice here is "retry", NOT the "stop the other process" that `dir_in_use` earns. */ | "store.dir_claiming" /** The lock cannot be read (bytes that are no lock record, a record a later engine wrote, a member of the wrong type), or * is buried under nested reclaim gates from repeated crashes. Never pruned blindly; the remedies name what to remove. */ | "store.lock_unreadable" /** THIS process held the lock and has lost it: its process anchor is no longer the pipe it opened (a descriptor closed under * it, a worker thread ended), so another process may already be taking the directory over. Every change the file store makes * under that lock throws this (the write throat in `descriptor-seat.ts`: whole-file writes, appends, moves, links, removals, * directories, stamps — matched by physical path); the process should exit and be started again. */ | "store.lock_lost"; /** * The structured refusal of a file-store directory fence. Carried as a class (not a bare `Error`) so a host can branch on * {@link code}, on {@link holder} (a live holder, proven, against one that cannot be checked from here) and on {@link remedies} * (the advice as data, so a host words it in its own terms) instead of reading the message. */ export declare class FileStoreLockError extends Error { readonly code: FileStoreLockErrorCode; /** The lock file whose acquisition was refused. */ readonly lockPath: string; readonly name = "FileStoreLockError"; /** Who holds the lock, as the one lock reading judged it (see {@link LockHolder}). Not an own property when nobody was read. */ readonly holder?: LockHolder; /** What a person can do about it — the advice in {@link message} is generated from these. */ readonly remedies: readonly LockRemedy[]; constructor(code: FileStoreLockErrorCode, message: string, /** The lock file whose acquisition was refused. */ lockPath: string, /** Who holds the lock, as the refusal read it — `undefined` when it read nobody (a lost publish race, a retry cap, nested reclaim gates, a lost lock). */ holder?: LockHolder, /** What a person can do (empty when nothing but waiting for, or stopping, the holder helps). */ remedies?: readonly LockRemedy[]); } /** A store's own words for a lock refusal: the same refusal — its code, holder and remedies — said again in `message`, against * `lockPath`. */ export declare function rewordedLockRefusal(err: FileStoreLockError, message: string, lockPath: string): FileStoreLockError; /** * The coarse boot guard (§2.4): an `O_EXCL` owner file (`root/LOCK` for the whole data dir; one per store * ledger directory via {@link acquireStoreDirLock}) that forbids two processes sharing it. A second * instance fails fast ("another instance owns this data dir"). A STALE lock (the process that WROTE it is * gone — see {@link isProcessLive}, which is not the same question as "is that pid free") is pruned and * re-acquired — `proper-lockfile`/CC `concurrentSessions` parity. * * This is the family's ONE lock MECHANISM (the per-operation CAS stays in-process: one event loop + a * per-token async mutex, so there is NO per-operation flock). A holder of one of these fences guarantees * the in-process model's premise — a single writer to the directory — actually holds. Cross-process * CORRECT concurrency (many writers at once) is still the Pg/TiDB backend's job, by design: this fence * refuses the second writer, it does not coordinate it. */ export declare class BootLock { private readonly lockPath; private readonly reclaimUnjudgedAfterMs?; private held; /** The verdict of the ONE release this holding gets, replayed to any later caller (see {@link release}). */ private spentVerdict; /** This holding's share of the process anchor in the lock's directory (a fence on a platform that makes one). */ private anchorHold; /** The bytes this object last published at its path — what "this lock is ours" means (never a pid number alone). */ private published; private kind; /** * The directory fence `name` in `dir` — the lock that keeps a second process out of the directory while it is open. The only * way to take a fence: its name comes from the one table of lock names the listing reads too, and it carries the anchor. */ static fence(dir: string, name: StoreLockName): BootLock; /** * A GATE held for one operation at `lockPath` (a reclaim, a claim's removal): not a fence — no anchor, not listed. * @param reclaimUnjudgedAfterMs reclaim a gate whose holder cannot be JUDGED from here (another host or pid namespace, no * comparable start time, a process table that refused the question) once its file has stood longer than this, by the same gated * reclaim as a dead holder's: a gate is held for an instant, so one standing that long has a holder that stopped, and refusing * it for good would refuse what it guards for good. Absent, such a gate is refused for as long as it stands. */ constructor(lockPath: string, reclaimUnjudgedAfterMs?: number | undefined); /** Whether the lock file has stood longer than `reclaimUnjudgedAfterMs` (never, without that bound). */ private outlivedUnjudgedBound; /** Acquire the lock or throw. Reclaims a lock whose recorded OWNER is gone (see below). */ acquire(): void; /** * @param depth how many stale reclaim gates deep we already are (see the gate below). Bounded so a * pathological chain demands an operator instead of recursing without end. */ private acquireWithin; /** Publish our lock, or say out loud that a fresh contender got there first. */ private publishOrLoseRace; /** Take back a lock THIS process published and could not remove on release (never someone else's). */ private pruneOwnAbandoned; /** The refusal of a lock someone holds (or that cannot be read), said once for every lock this class takes: the one clause, * against the lock's own path, and the reading it rests on. */ private refusal; private writeLock; /** * Key for the {@link abandonedLocks} registry: the RESOLVED path, deliberately NOT case-folded. Folding * (as the store-table key does) would alias `/data/foo/LOCK` and `/data/Foo/LOCK` — two genuinely * different files on a case-sensitive filesystem — and this registry authorizes a DELETE. Missing an * entry costs a loud refusal; a false hit costs someone else's lock. */ private get abandonKey(); /** * Read the lock as one of three ANSWERS, never as one "undefined" that means all of them: absent (nobody * holds it), a named owner, or unreadable. Collapsing the last two is what let a release that could not * even READ the file report the lock as gone — after which the bookkeeping was dropped while the file * still named this process, and the directory was refused for the rest of the process's life. */ private inspectLock; /** * Release the lock (only if we hold it), ONCE. Best-effort; never throws. * * @returns whether the lock is now GONE — removed, or provably somebody else's. A `false` means the file * is still there and this process cannot prove it is not the owner of record, which the caller must not * treat as released: every later acquisition would read a live owner (us) and refuse a directory nobody is * using. The path is remembered as ABANDONED so a later acquisition in this process can take it back * rather than refuse a directory nobody is using — a lock carrying our own pid can only be ours * ({@link pruneOwnAbandoned} removes and republishes it; {@link resumeAbandoned} re-arms a holder over * the file as it stands). * * ONE-SHOT, and that is load-bearing. This object stops being a holder the moment it is ASKED to release * — before the filesystem is touched — and a second call REPEATS the first verdict instead of acting on * it again. A lock file names its publishing PROCESS, so two BootLocks over one path in this process are * byte-identical on disk: after a FAILED release the path can legitimately be re-published (a later acquisition here * finishing our cleanup), and a stale object that "removed its own lock" a second time would be deleting * the SUCCESSOR's fence while both sides believed they held the directory — the double-writer this whole * mechanism exists to refuse, minted from bookkeeping instead of from a race. So a second release answers * the first question again and touches nothing. */ release(): boolean; /** * The filesystem half of {@link release}: remove the lock while the file still names US, and report what * the directory looks like AFTERWARDS (never what we intended). * * "Still names us" is a READ, and `unlink` cannot be made conditional on content — so, exactly as in * {@link resumeAbandoned}, an external removal landing between the two lets this delete a file that is no * longer the one we read. That is the advisory-pid-file mechanism's exposure, identical for every holder * and every moment of a holding, not something this ordering introduces; the re-inspection below is why * the ANSWER stays honest even then. */ private removeOwnLock; /** Remember this path as left behind by this holding, with the bytes it published (see {@link abandonedLocks}). */ private noteAbandoned; /** * Resume holding a lock THIS process published and could not remove on release — the state a zero-ref * entry in {@link acquireStoreDirLock}'s table is in, and the only way a joiner may ride that entry. * * Pure INSPECTION of the disk: it publishes nothing and removes nothing. The claim is honoured only * when the file still there is the one we left (our own pid) AND no publish on this path has spent the * abandoned note since — any successful publish (ours, or a reclaim) makes some OTHER object the holder, * and re-arming here would put two holders on one path, exactly what one-shot {@link release} closes. A * `false` says the bookkeeping can no longer be trusted and the caller must go back to the disk: the * file may have been cleared (an operator, a tmp cleaner) and the directory since taken by another * OS process. * * A successful resume SPENDS the note, for the same reason a successful publish does: the note is what * authorizes {@link pruneOwnAbandoned} to DELETE this file, and while somebody holds the path that * authorization must not exist — a second acquisition here is a genuine conflict that has to be refused * by name, not a leftover to be cleaned up over a live holder. A later failed release writes it again. * * What a `true` establishes, exactly: the file was the one we left AT THE MOMENT WE LOOKED. It is not an * atomic handoff and cannot be — this fence is an advisory pid FILE, so nothing stops an operator (or a * tmp cleaner) from removing it the instant after any check, here or hours into an ordinary holding, and * a foreign process publishing over the gap. That exposure belongs to the mechanism and is the same for * a fence nobody ever released; what this check removes is the far wider window in which the removal * already happened and the table would have kept vouching for it anyway. The branch where the file is * ALREADY gone is not re-armed here at all: it falls through to a real acquisition, whose `O_EXCL` * publish is the atomic test-and-set, and a foreign owner there is refused by name. */ resumeAbandoned(): boolean; } /** One holder's share of a directory fence. Releasing is idempotent and only the LAST share unlinks. */ export interface StoreDirLockLease { /** The lock file this share is counted against (inspection/tests). */ readonly lockPath: string; /** Drop this share. The lock file survives until every share over the directory is released. */ release(): void; } /** * Take (or JOIN) the cross-process writer fence for one store directory. * * The file family's premise everywhere is "one writer per data directory"; before this, the ONLY thing * enforcing it was the `root/LOCK` a `FileStorageBackend` takes — which a store constructed directly * (every one of them is a root export) never sees, and which never covered a store the backend does not * construct at all. A second OS process then replayed a PRIVATE view of the same ledger: both sides win * a once-only CAS, and the one that never loaded the other's rows ERASES them at its next compaction. * So the fence belongs to the directory that holds the authority, taken by whoever opens it. * * Semantics: exclusive across PROCESSES (a live foreign owner ⇒ {@link FileStoreLockError} naming the * pid; a dead owner's lock is pruned as stale), refcount-JOINED inside this process (siblings over one * directory share the fence, and the last {@link StoreDirLockLease.release} unlinks it). `dir` must * already exist (the caller's `ensureDir`), since the fence lives inside it. */ export declare function acquireStoreDirLock(dir: string, opts: { label: string; fileName?: StoreLockName; }): StoreDirLockLease;