import { parseExactJson } from './exact-json.ts'; import { dirname, isAbsolute, join, resolve } from 'node:path'; import { withStateLock } from './ancestry.ts'; import { getActiveWorldStore, storageLockScope, worldStateFile, type WorldLockOptions } from './world-store.ts'; import type { WorldPaths } from './types.ts'; /** The project root a World's state lives under, resolved (worldPaths's `root`, without claiming a journal identity). */ export function projectRoot(root?: string): string { return resolve(root || process.env.PROJECT_ROOT || process.cwd()); } /** * Name of the per-project state directory holding world data * (`//world/...`). Defaults to `.volter`; hosts that need a * different directory set VOLTER_STATE_DIR. Every path in this package must * go through worldStateRoot — never the literal. */ export function stateDirName(): string { const name = process.env.VOLTER_STATE_DIR || '.volter'; if (isAbsolute(name) || name.split(/[\\/]/).includes('..')) throw new Error('VOLTER_STATE_DIR must be a relative directory without .. segments'); return name; } export function worldStateRoot(root?: string): string { return join(projectRoot(root), stateDirName(), 'world'); } function assertServiceName(service: string): string { if (!/^[A-Za-z0-9_-]+$/.test(service)) { throw new Error(`Invalid world service name: ${service}`); } return service; } /** * IDENTITY SEAM for the request journal (serve.ts). `worldPaths` is the single funnel every * state read/write in every pack goes through, so it is also the one place a twin says, in its * own words, WHO it is (`service`) and WHERE its state lives (`root`) — the two things an HTTP * layer that only sees `Bun.serve({fetch})` cannot know. serve.ts installs an observer here so * the journal it writes lands beside that twin's `actions.jsonl` instead of guessing a root. * Nothing else may use this: it is a one-slot observability hook, never a control seam. */ let worldPathsObserver: ((service: string, root: string | undefined) => void) | undefined; /** Install the observer; the one it replaces is returned (a test puts it back). */ export function observeWorldPaths(observer: ((service: string, root: string | undefined) => void) | undefined): ((service: string, root: string | undefined) => void) | undefined { const previous = worldPathsObserver; worldPathsObserver = observer; return previous; } /** While > 0, a read of ANOTHER pack's store is in progress (`projectOwnerResources`): that is not the request's twin * saying who it is, so it claims no journal identity. */ let identityQuiet = 0; /** Run `fn` without its worldPaths calls reaching the identity observer. */ export function withoutIdentityClaim(fn: () => T): T { identityQuiet++; try { return fn(); } finally { identityQuiet--; } } export function worldPaths(service: string, root?: string): WorldPaths { const safeService = assertServiceName(service); if (identityQuiet === 0) worldPathsObserver?.(safeService, root); const resolvedRoot = projectRoot(root); const dir = join(worldStateRoot(root), safeService); return { root: resolvedRoot, service: safeService, dir, events: join(dir, 'events.jsonl'), resources: join(dir, 'resources'), }; } /** * THE WORLD'S DATA DIRECTORY, as the World runtime hands it to every service it starts. Each twin of a World runs on * its own root, `/` (world-runtime's startService and startColocatedServices), so one twin's * `.volter/world/` is not another's; `ownerStoreRoots` finds a store across them. */ export const WORLD_DATA_ENV = 'VOLTER_WORLD_DATA'; /** Does `root` hold `service`'s store: its log or its branch record (what a write or a fork leaves; a read leaves * neither)? The paths are built without worldPaths, so a probe claims no journal identity. */ function holdsStore(service: string, root: string): boolean { const dir = join(worldStateRoot(root), service); const store = getActiveWorldStore(); return ['events.jsonl', 'actions.jsonl', 'branch.json'].some((file) => store.exists(join(dir, file))); } /** * The roots that hold the store of `owner` (ANOTHER pack's, read by contract: architecture A3), for a twin on `root`: * - `[root]` when `root` itself holds that store (both packs on one root: `volter world serve`, a test, a pack serving * several services on its root, as aws does); * - else, when `root` is one of a World's service roots (a directory directly under the World's data directory), every * other service root there that holds it (usually one; two when the World runs the owning pack twice); * - else `[]`: nothing is issued yet, or the twin runs outside a World. * Only a declared cross-pack read resolves through here (`projectOwnerResources`); a pack's reads of its OWN store never * leave its root, so a fresh twin never reads a sibling that happens to run the same pack. Not memoized: it is a few * stats per service root, and a store that appears after the first read (the owner's first write) must be found. */ export function ownerStoreRoots(owner: string, root?: string): string[] { const safeOwner = assertServiceName(owner); const own = projectRoot(root); if (holdsStore(safeOwner, own)) return [own]; const data = worldStateFile('data'); if (!data || dirname(own) !== resolve(data)) return []; return getActiveWorldStore().list(dirname(own)) .map((name) => join(dirname(own), name)) .filter((candidate) => candidate !== own && holdsStore(safeOwner, candidate)) .sort(); } /** Read + parse a whole-file JSON sidecar, citing the path on a parse failure. Callers own * existence semantics — this parses a file that is expected to exist; guard with existsSync * first when absence is allowed. */ export function readJsonFile(path: string): T { try { const raw = getActiveWorldStore().read(path); if (raw === null) throw new Error('no such file'); return parseExactJson(raw) as T; } catch (error) { throw new Error(`${path}: invalid JSON: ${(error as Error).message}`); } } /** * Append `data` to `path`. When VOLTER_DURABLE=1, `fsyncSync` the file after the write so * the appended record survives an OS crash / power loss — not just a process crash. * * Default (VOLTER_DURABLE unset) is OFF: `appendFileSync` is a completed write syscall, so a * *process* crash after it returns still leaves the record on the log (the OS owns the page * cache). The window this leaves open is a **kernel-panic / power loss** between the write * landing in the page cache and the fs flushing it to stable storage — a torn or lost tail * record. That crash window matters more once real pulled staging data lives in these files * (purpose 2), so hosts that need durability opt in with VOLTER_DURABLE=1 at the cost of an * fsync per append. See docs/contributing/architecture.md D1. */ export function appendDurable(path: string, data: string): void { getActiveWorldStore().append(path, data); } /** * Opt-in structured stderr logging for the audit trail: * one line per action-log append and per push-ledger row, so "who reviewed the change * that caused this real write" is mechanically greppable from a single log stream via * `correlationId`. Off by default — mirrors the VOLTER_DURABLE opt-in policy above: no * always-on I/O, never on the default path. Set VOLTER_TWIN_LOG=1 to enable. */ export function twinLog(kind: string, details: Record): void { if (process.env.VOLTER_TWIN_LOG !== '1') return; console.error(`[twin:${kind}]`, JSON.stringify(details)); } /** Run `fn` holding an exclusive cross-process lock, via the active store. On the fs * store this is the reclaimable file lock the event log uses; on an in-memory, * single-instance store it is a synchronous pass-through. Used to make read-then-append * critical sections atomic. Public so world-runtime can guard concurrent `upWorld` * claims of one instance dir with the SAME lock semantics the event log uses. */ export function withFileLock(lockPath: string, fn: () => T, options: WorldLockOptions = {}): T { return withStateLock(lockPath, fn, storageLockScope(options)); } /** Exported so other modules that share a service's events log (e.g. egress.ts) * can serialize their own critical sections on the SAME lock, instead of * inventing a second, uncoordinated lockfile. */ export function eventsLockPath(paths: WorldPaths): string { return join(paths.dir, 'events.jsonl.lock'); } /** * Serializes mutations that can change a service's projected state, regardless of whether the * durable row lands in events.jsonl or actions.jsonl. The per-log locks still protect their own * append/dedupe mechanics; this outer lock makes a projection-based decision linearizable against * connector observations as well as local actions. */ export function projectionLockPath(paths: WorldPaths): string { return join(paths.dir, 'projection.lock'); }