/** Metadata a caller needs about a stored path. `isDirectory` distinguishes a JSON * sidecar from a per-service subdirectory; `size`+`mtimeMs` * drive the append-dedupe index's cache-validity check in storage.ts. */ export type WorldStat = { size: number; mtimeMs: number; isDirectory: boolean; isSymbolicLink?: boolean; }; /** Diagnostic context only; it does not change lock acquisition or stale-owner policy. */ export type WorldLockOptions = { retainLiveOwner?: boolean; operation?: string; caller?: string; }; /** * Capture at the outermost lock helper, then carry the same caller through nested helpers. * LIMIT THE CAPTURE TO THE FRAMES READ: V8's third frame supplies the caller, * while new Error().stack normally collects up to Error.stackTraceLimit frames (ten by default). * The limit is lowered to three only for Error's own writable numeric data property above three, and restored * only when lowered. Absent, accessor, non-writable and lower limits receive no writes. Existing constructor * and user stack-formatter failure paths remain; this diagnostic optimization changes no lock ownership rule. */ export declare function storageLockScope(options?: WorldLockOptions): WorldLockOptions & { operation: string; caller: string; }; /** * The synchronous persistence seam. Every path is an ABSOLUTE key the caller already * computed (via `worldPaths`/`worldStateRoot`); the store treats it as an opaque key, * so a single active store partitions cleanly by `root` (the root is embedded in the * key) and no per-root wiring is needed. */ export interface WorldStore { /** Whole-file read; `null` when the path does not exist. */ read(path: string): string | null; /** File content split on `\n` (blank lines and the trailing empty included, so a * caller can report 1-based row numbers); `[]` when the path does not exist. */ readLines(path: string): string[]; /** Raw append of exactly `data` (the caller owns any trailing newline). On the fs * backend this is the VOLTER_DURABLE-aware durable append. Does NOT create parents — * call `mkdir` first, matching the historical `appendDurable` contract. */ append(path: string, data: string): void; /** Non-atomic whole-file write, creating parent dirs. Matches the plain * `writeFileSync` sidecar writers (cursors, refs, leases, plans, fork-meta). `secret` makes the * file owner-only (0600 in a 0700 directory) where the backend has permissions. */ write(path: string, data: string, options?: { secret?: boolean; }): void; /** Atomic whole-file write (write-temp-then-rename on fs), creating parent dirs. * Used where a reader must never observe a half-written document (state.json). `secret` makes * the file owner-only where the backend has permissions. */ writeAtomic(path: string, data: string, options?: { secret?: boolean; }): void; /** Does the path exist? */ exists(path: string): boolean; /** Recursively remove the path (force; a missing path is not an error). */ remove(path: string): void; /** Ensure a directory (and parents) exists. A no-op on backends with implicit dirs. */ mkdir(dirPath: string): void; /** Immediate child names of a directory; `[]` when it does not exist. */ list(dirPath: string): string[]; /** Metadata for a path, or `null` when it does not exist. */ stat(path: string): WorldStat | null; /** The file from byte `start` to its end, decoded as UTF-8 (`start` must fall on a character boundary: a line's * start in a log); `null` when the path does not exist. Optional: a reader of an append-only log uses it to read * only what was appended, and reads the whole file on a store without it. */ readRange?(path: string, start: number): string | null; /** Resolve filesystem aliases for durable ownership; absent on opaque-key stores. */ canonicalPath?(path: string): string; /** `read`, for a small file every operation needs and few change (a branch's pointer, the World's clock): the text * kept from the last read while the path's own facts stand, so an unchanged file costs one check and no read. * Optional: a store without it is read. */ readKept?(path: string): string | null; /** The facts of the generation kept beside a tree's files in `dirPath` (TREE_FILES): one string that differs after * any write of one of them through a store, by this process or another; `null` where the directory has none yet, * which says nothing. Optional: a store without it is asked for each file's own facts. */ generation?(dirPath: string): string | null; /** The generation in `dirPath` now, when exactly one write of a tree's file through a store has moved it since * `before` (a generation this store answered for it); `null` when it cannot say so. A writer that read `before` just * ahead of its own write, holding the directory's history lock, learns that its write was the only one (log.ts * appendToBranchLog). Optional, beside `generation`. */ generationAfterOwnWrite?(dirPath: string, before: string): string | null; /** Run `fn` holding an exclusive lock on `lockPath`, releasing it afterwards. The fs * backend uses the historical cross-process reclaimable file lock; an in-memory, * single-instance backend is a synchronous pass-through. */ withLock(lockPath: string, fn: () => T, options?: WorldLockOptions): T; /** Where this store's World keeps each piece of its own state (worldStateFile): set on a store that is a World of its * own (every `MemoryWorldStore`, so an in-memory walk inside a World reads nothing of the World around it); absent on * the process's own World's store (`FsWorldStore`), whose locations are the ones the runtime gave the process. */ readonly world?: WorldOwnState; } /** A World's own state that the kernel reads, each piece by name (architecture, "A World's own state is located through * the active World"): its clock, its seed identity, its scenario and facts, its completeness record, its instance record * and its data directory. */ export type WorldStateName = 'clock' | 'seed' | 'scenario' | 'facts' | 'completeness' | 'instance' | 'data'; export type WorldOwnState = { [name in WorldStateName]?: string; }; /** The variable each piece is named by in a process the runtime starts for its World (runtime.ts sets them all). */ export declare const WORLD_STATE_ENV: Readonly>; /** Where the active World keeps `name`, or undefined where it keeps none: the active store's own World's location where * the store is a World of its own (never the process's environment, which names another World's files), else the * process's own World's, from `env` (the process's environment unless a caller holds its World's env). */ export declare function worldStateFile(name: WorldStateName, env?: Record | undefined): string | undefined; /** The files a service's tree is folded from, by name in its state directory (log.ts: the parent log, the branch log, * the branch's pointer), and the generation a store keeps beside them. */ export declare const TREE_FILES: { readonly parent: "events.jsonl"; readonly branch: "actions.jsonl"; readonly pointer: "branch.json"; }; export declare const TREE_GENERATION = "tree.generation"; /** * A WORLD'S CARRIED LOCKS, REMOVED AT ITS OPEN. A World booted over retained state may carry lock files * whose takers have ended. An unreadable holder record is reclaimable under the ownership rules below. * * A file is carried only when all of these hold: it is a world-core lock or its reclaim record (`*.lock`, * `*.lock.recovery`) in a service's state directory (`///world`, never a yarn.lock or any * project file); its text is empty or a holder record's beginning (`{"pid"`) that does not parse; and its file time is * before `before`, the start of this boot's claim. A restore sets the time before the claim; a taker that is live now * (a CLI's changeset rebase, a branch World keeping this one as its parent's storage, a two-call taker between its * create and its record) made its file after it. Each removal is still a reclaimer's: a lock's under its `.recovery`, * taken with its record (createRecorded), a held `.recovery` skipped; the file read again, renamed aside, the aside copy * read again and linked back where it now holds a record (EEXIST there is the path taken since, left to its holder). * A record that parses is kept, under its rules (a dead holder's, our own pid's, the 60 s age, which a restore resets: * not this rule's). Answers the paths removed. */ export declare function removeCarriedLocks(roots: readonly string[], options: { stateDir: string; before: number; }): string[]; /** Name a bookkeeping phase within an existing acquisition; never acquire another lock. */ export declare function withStorageLockOperation(path: string, operation: string, fn: () => T): T; /** The filesystem store: durable append, atomic replacement and reclaimable cross-process locks. */ export declare class FsWorldStore implements WorldStore { read(path: string): string | null; /** * A small file's text, kept while its own facts stand. THE GUARANTEE: the key is the path's own lstat (device, * inode, size, modification and change times); this process's own writes through the store drop what is kept at * once; another process's write is seen when any of those facts moves. That is the guarantee a tree's stamp * already rests on for its logs (their size and modification time), with the inode and change time added: a * replaced file (writeAtomic) is another inode, a file written in place has another time. What it cannot see is a * rewrite to the same size on the same or a reused inode within one tick of the file system's clock, with no check * between; the logs' stamp has the same limit. A link is read through, and not kept. * A text read after a write that came between the lstat and the read is kept under the OLDER key, so the next * check finds the facts moved and reads again: what is kept is never newer than its key, and never served past it. */ private readonly kept; readKept(path: string): string | null; /** * A TREE'S GENERATION: one file beside a tree's three files, a byte longer after every write of any of them, so a * reader that has the tree's stamp asks ONE question to know it still stands (log.ts treeFacts), where it asked * three, two of them of files a World with no parent does not have. * * WHAT MAKES IT SOUND. A writer appends a byte BEFORE its write and another AFTER it; a reader takes the * generation's facts BEFORE it reads the files' own. The file only grows, so its size never repeats on one inode, * and a replaced or removed file is another inode or none. So for any write W and any reader that kept a stamp S * under generation G: if W's first byte is after G was read, the kept G is behind and S is not served; if it is * before, then either W itself was before S's own reads (S holds it), or W's second byte is after G was read, and * again G is behind. An append is one call the system orders among all writers: each byte is one append of its * own, whole or not at all, on a POSIX filesystem and in a tab's one kernel (browser-substrate * packages/node/src/kernel-virtual-filesystem.ts appendFileSync, an O_APPEND open and writeAll, which sends a write * of at most DATA_BYTES as one SYS_write request the kernel serves whole; or, by a file step, its table's own * O_APPEND open and write of the one byte, filesystem.ts appendFileBytes). The proof rests on that; log.ts * appendToBranchLog's (`generationAfterOwnWrite`: one write is exactly two bytes) as well. * * WHERE THAT STOPS. (1) A writer that dies between its write and its second byte, with a reader's whole check * between its first byte and its write: that reader keeps the older stamp until the next write of the tree. (2) A * writer of these files that does not come through a store of this version (another package's, a copy made over a * live directory by another program): the generation does not move. A directory made or removed whole has no * generation or another's, which serves nothing kept. (3) A stamp that names files outside its own directory (a * World with a parent: its view and its ancestors' logs) is never kept under a generation (log.ts). */ generation(dirPath: string): string | null; /** One write is `moved` twice, a byte each: the same file, those two bytes longer. */ generationAfterOwnWrite(dirPath: string, before: string): string | null; /** One more byte on the generation beside `path`, where `path` is one of a tree's files. A directory that is not * there has no reader to tell: the write that makes it is followed by the byte that makes its generation. */ private moved; /** A write of `path`, with the generation beside it moved before and after where it is one of a tree's files. */ private writing; readLines(path: string): string[]; readRange(path: string, start: number): string | null; append(path: string, data: string): void; write(path: string, data: string, options?: { secret?: boolean; }): void; writeAtomic(path: string, data: string, options?: { secret?: boolean; }): void; exists(path: string): boolean; remove(path: string): void; mkdir(dirPath: string): void; list(dirPath: string): string[]; /** The real path of each path already resolved: a state directory's does not move under a running process, and * every history lock asked for it again. A path that does not exist yet is not kept. */ private readonly canonical; canonicalPath(path: string): string; stat(path: string): WorldStat | null; /** Run `fn` holding an exclusive cross-process file lock. The lockfile records * identity, operation, caller and any nested wait; a contender that finds a stale lock (dead pid or age > * LOCK_STALE_MS) reclaims it by atomically renaming it aside — so a crashed holder * can't wedge the world forever. Reclaim is race-safe: only the process that wins * the rename clears the stale inode, and the exclusive `wx` create still decides the * winner. (Moved verbatim from storage.ts `withFileLock`.) */ withLock(lockPath: string, fn: () => T, options?: WorldLockOptions): T; } /** * An in-memory store. Files are entries in a `Map`; directories are * synthesized from the key set (a path is a directory when it is a strict prefix of a * file key). `withLock` is a synchronous pass-through — a single in-process instance has * no concurrent writers to serialize, so the read-then-append critical sections the * kernel guards are already atomic under the single-threaded event loop. * * This is the portability proof: point the active store here and the entire kernel — and * the clerk twin on top of it — runs with the filesystem untouched. */ export declare class MemoryWorldStore implements WorldStore { /** A memory store is a World of its own: its state is where `world` says, and what it does not name it has none of * (worldStateFile never falls back to the process's environment for it). The object is the World's: a walk that plays * a scenario names it here. */ readonly world: WorldOwnState; constructor(world?: WorldOwnState); /** path → content, and path → version stamp driving `stat().mtimeMs`. */ private readonly files; private readonly versions; /** path → UTF-8 byte size, kept as content changes so `stat` never re-encodes a growing log. */ private readonly sizes; /** The stamp of this store's most recent mutation (0 = never mutated). A serverless * entry snapshots this before running the sync kernel and flushes ONLY when it moved — * read-only requests (the common case) then skip the durable write entirely. */ private lastMutation; mutationStamp(): number; /** Paths whose content changed strictly after `stamp` — the DELTA-FLUSH primitive * for a serverless entry: it records `mutationStamp()` at hydration, * runs the sync kernel, then persists ONLY these paths (plus removals, which the caller * detects by diffing its hydrated path set against `entries()` — a removed path has no * version to report). O(paths) scan, O(delta) write. */ changedSince(stamp: number): string[]; private bump; read(path: string): string | null; readLines(path: string): string[]; append(path: string, data: string): void; write(path: string, data: string): void; writeAtomic(path: string, data: string): void; exists(path: string): boolean; remove(path: string): void; mkdir(_dirPath: string): void; list(dirPath: string): string[]; stat(path: string): WorldStat | null; withLock(_lockPath: string, fn: () => T): T; /** Test/inspection helper: a plain snapshot of every stored file. Not part of the * `WorldStore` contract — used by `flushFrom` and by tests asserting no fs was touched. */ entries(): Record; } /** The store the kernel currently persists through: the request's scoped store, else the * module-global one (`FsWorldStore` by default). */ export declare function getActiveWorldStore(): WorldStore; /** Swap the active store. A serverless/DO/test entry sets a `MemoryWorldStore` (or a * backend-backed store) here before running the sync kernel, and restores the previous * one afterwards. Returns the store that was active, so callers can restore it. */ export declare function setActiveWorldStore(store: WorldStore): WorldStore; /** Run `fn` with `store` active, restoring it after a synchronous result or after its promise settles. * * CONCURRENCY: where the runtime has AsyncLocalStorage the scope is per async context, so * unserialized requests for different worlds interleave without bleeding stores. Only a runtime * without it (a browser bundle) falls back to the module-global swap, which is safe only when * store-scoped work is serialized. */ export declare function withWorldStore(store: WorldStore, fn: () => Promise): Promise; export declare function withWorldStore(store: WorldStore, fn: () => T): T; /** A durable, async source of a world snapshot (path → content). */ export interface HydrationSource { load(): Promise>; } /** A durable, async sink for a world snapshot (path → content). */ export interface HydrationSink { save(snapshot: Record): Promise; } /** Fill `store` from an async durable `source` before the sync kernel runs. */ export declare function hydrateInto(store: MemoryWorldStore, source: HydrationSource): Promise; /** Persist `store`'s current contents back to an async durable `sink` after the sync * kernel has run. */ export declare function flushFrom(store: MemoryWorldStore, sink: HydrationSink): Promise;