import { parseExactJson } from './exact-json.ts'; import { worldNow } from './world-clock.ts'; // Twin serve layer (the twins architecture notes, increment 1): answer vendor-shaped // READS from the local event-sourced state — the "local twin" read path. An app // or agent points at this instead of the real vendor; it responds from local // state with the real service unreachable. // // There is ONE twin, not a set of "modes". Pulling reality, writing locally, and // forking are operations on the same substrate (events + local actions + the // projection over them), not exclusive modes — see the architecture doc, "a twin // is a repo". The only serve-time policy here is `readOnly`: a twin accepts local // writes (as actions) unless you start it read-only (a pure mirror of pulled // reality). Forking is a separate data operation (fork.ts), never a serve mode. import { AsyncLocalStorage } from 'node:async_hooks'; import { serveHttp, setServeDecorator, WORLD_BOOT_PATH, type HttpHandler } from './serve-http.ts'; import { performAtHead, performsAtHeadNow } from './head.ts'; import { withHeaders } from './with-headers.ts'; import { createHash } from 'node:crypto'; import { dirname, join } from 'node:path'; import type { SubjectFields } from './hash.ts'; import { hashFieldValue } from './hash.ts'; import { appendActionIfAbsent, appendActionOccurrence, appendActionOccurrences, decideAndAppendAction, projectResources } from './actions.ts'; import { readSubject } from './log.ts'; import type { ActionProjection, TwinAction, TwinActionPrecondition } from './actions.ts'; import { observeWorldPaths, worldPaths } from './storage.ts'; import { getActiveWorldStore } from './world-store.ts'; import { getActiveBlobStore } from './blob-store.ts'; import { parseTraceparent } from './trace-context.ts'; // ── the request journal: the INSPECT half of the read path ───────────────────────────────────── // `actions.jsonl` records MUTATIONS only, so a twin's READS are invisible to `volter world log` // — an empty-catalog GET that 404s leaves no trace, and "did the app even ask?" is unanswerable. // The journal is the minimal honest answer: a per-twin `requests.jsonl` beside `actions.jsonl`, one // line per served HTTP request, kept unless switched off (VOLTER_TWIN_REQUEST_JOURNAL=0). It is an // audit trail, so nothing in it is ever deleted: at ~1 MB the live file closes into the next numbered // segment (`requests.jsonl.1`, `.2`, … oldest first) and a fresh one starts. An append that fails is // said on stderr and counted per journal (`twinRequestJournalFailures`), never silent. `volter world log // --requests` merges the live lines. // // WHAT A LINE CARRIES. `{at, method, path, status}` — the shape — plus, when the request presented // one, the CREDENTIAL SHAPE: which header/query-param NAMES carried a credential-looking value, // each with a truncated sha256 FINGERPRINT of the value. Never the value, never the rest of the // query string, never a body. That is what makes the journal answer the question a twin exists to // answer and could not: *which credential arrived, in which header?* Two different fingerprints // under `dd-api-key` and `dd-application-key` say "two distinct keys arrived, in their own named // headers"; the same fingerprint on two rows says "the same value came back"; a missing name says // the caller sent nothing. Reading a fingerprint back to its secret is not possible — it is // sha256, truncated — so the file stays safe to paste into an issue. // // A query string carries tokens: the journal names its credential PARAMS and fingerprints them, // and records `path` without its query. // // A fingerprint is not a vault: it is sha256 of the value, so a LOW-entropy credential (`"test"`) // is guessable from its fingerprint by anyone who guesses the value first. It is exactly the right // strength for its job — telling two credentials apart, and recognising one across requests. // // WHERE IT IS WIRED. Not per-pack. Every vendor pack mounts its own `Bun.serve({fetch})` inside a // `createTwinServer({port, root, readOnly})` factory — there is no shared middleware, but // there IS a shared CONSTRUCTOR, so `installTwinRequestJournal()` (below, called once at module // load) wraps `Bun.serve` and journals every twin's fetch handler. The pack writes no journaling // line at all. // Measured coverage: 66 of the 67 pack HTTP servers journal with zero pack-side code. The one that // does not is STRUCTURAL, not missed — `smtp` is a raw-TCP `Bun.listen` mail listener with no HTTP // surface. Anything that mounts an HTTP twin through `Bun.serve` is covered by // construction; anything that does not is a second transport and would need its own seam. export type TwinCredentialShape = { /** header name (lowercased) or query-param name the credential arrived under. */ name: string; /** where it sat on the request. */ in: 'header' | 'query'; /** the auth SCHEME when the value carried one (`Bearer`, `Basic`, `AWS4-HMAC-SHA256`). A scheme * is not a secret, and it is what distinguishes "a bearer token arrived" from "a named vendor * header arrived" — the exact confusion this journal was added to end. */ scheme?: string; /** `sha256:<16 hex>` of the value (of the credential part when a scheme was present). Stable * across processes and runs, so equal fingerprints mean equal values; non-reversible. */ fp?: string; /** the name arrived with an EMPTY value — the "the SDK sent the header but no key" case. */ empty?: true; }; /** The header a World puts on a request it forwards to a twin: who made it (`key:`, `person:`, `token`, * `token:read`). The World replaces any a caller sent; the serve seam records it in the twin's request journal and * removes it before the twin's handler. A twin reached on its own port, not through a World, records what it was sent. */ export const CALLER_HEADER = 'x-volter-caller'; /** The caller as it travels in CALLER_HEADER: percent-encoded, since a key's name is a person's words (`preview pr-8 · * org token ci`) and a header carries bytes only. `callerFromHeader` reads it back; a value it cannot decode stands. */ export const callerForHeader = (caller: string): string => encodeURIComponent(caller); export const callerFromHeader = (value: string): string => { try { return decodeURIComponent(value); } catch { return value; } }; export type TwinRequestJournalEntry = { at?: string; method: string; path: string; status: number; /** the serve's wall time in milliseconds (layer 8: a world's response-time report) */ ms?: number; /** credential-looking headers/query params that arrived, named + fingerprinted, never quoted. */ credentials?: TwinCredentialShape[]; /** who made it, as the World named its caller (CALLER_HEADER: `key:`, `person:`, `token`); absent for a * request that did not come through a World */ caller?: string; /** the request's trace-id and parent-id (its `traceparent`). The World mints the parent-id of every request it * forwards, and the request's log entries carry it, so an entry is joined to its caller by `span`, which no caller * chooses (a trace-id is the caller's and spans requests) */ trace?: string; span?: string; /** `request`: written BEFORE the request is served (an audit device's request entry, so a request whose * audit cannot be written is refused); its outcome is the entry without a phase written after. */ phase?: 'request'; /** what the World's scenario did to a request that wrote nothing (a fault that landed on it, a lag that withheld * subjects from it), which the twin's log never holds (scenario-consume.ts noteFault) */ scenario?: Array>; }; /** The journal's closed segments, oldest first: `requests.jsonl.` beside the live file. */ function journalSegments(path: string): string[] { const base = path.slice(path.lastIndexOf('/') + 1); return getActiveWorldStore().list(dirname(path)) .map((name) => (name.startsWith(`${base}.`) ? Number(name.slice(base.length + 1)) : NaN)) .filter((n) => Number.isInteger(n) && n > 0) .sort((a, b) => a - b) .map((n) => `${path}.${n}`); } /** The journal read back: every entry kept for a service, oldest first (an empty list when the journal is switched off or empty). * With `since` (epoch ms), segments that ended before it are not read. */ export function readTwinRequestJournal(service: string, root?: string, options: { since?: number } = {}): TwinRequestJournalEntry[] { const path = twinRequestJournalPath(service, root); const parse = (file: string): TwinRequestJournalEntry[] => { const text = getActiveWorldStore().read(file); if (!text) return []; const rows: TwinRequestJournalEntry[] = []; for (const line of text.split('\n')) { if (!line) continue; try { rows.push(parseExactJson(line) as TwinRequestJournalEntry); } catch { /* a torn line */ } } return rows; }; const kept: TwinRequestJournalEntry[][] = [parse(path)]; // newest first, stopping at the first segment that ended before `since` for (const file of journalSegments(path).reverse()) { const rows = parse(file); const last = rows[rows.length - 1]?.at; if (options.since !== undefined && last && Date.parse(last) < options.since) break; kept.unshift(rows); } return kept.flat(); } /** Lines not kept, per journal: keyed by the journal's own path, so a process serving many Worlds * (a host; an isolate holding several) answers for each World alone. */ const journalFailures = new Map(); /** Journal lines this process failed to keep, since it started, for one service's journal under `root` * (a World's request report sums its own twins and links). */ export function twinRequestJournalFailures(service: string, root?: string): number { try { return journalFailures.get(twinRequestJournalPath(service, root)) ?? 0; } catch { return 0; } } /** Where a reader of a journal stopped: the newest closed segment it had seen and the bytes of the live file it read. */ export type TwinRequestJournalCursor = { segment: number; offset: number }; /** The journal's lines after `cursor` (all of them without one), and the cursor to read on from. A rotation closes * the live file into the next segment as it stood, so a reader that stopped in the live file goes on in that * segment at its offset, then any later segments, and the next read takes the live file from its start; a live file shorter than where * the reader stopped (read between a rotation's two writes) is read again from its start, its lines repeated rather * than lost. Only whole lines are read (a line being appended is read next time). Without a cursor, the newest * `segments` closed segments are read (all of them when omitted), then the live file. */ export function readTwinRequestJournalFrom(service: string, root: string | undefined, cursor: TwinRequestJournalCursor | null, options: { segments?: number } = {}): { entries: TwinRequestJournalEntry[]; cursor: TwinRequestJournalCursor } { const path = twinRequestJournalPath(service, root); const store = getActiveWorldStore(); const segments = journalSegments(path).map((file) => Number(file.slice(path.length + 1))); const newest = segments[segments.length - 1] ?? 0; const entries: TwinRequestJournalEntry[] = []; const take = (file: string, start: number, whole: boolean): number => { const text = store.readRange ? store.readRange(file, start) : ((t) => (t === null ? null : Buffer.from(t, 'utf8').subarray(start).toString('utf8')))(store.read(file)); if (!text) return start; const end = whole ? text.length : text.lastIndexOf('\n') + 1; for (const line of text.slice(0, end).split('\n')) { if (!line) continue; try { entries.push(parseExactJson(line) as TwinRequestJournalEntry); } catch { /* a torn line */ } } return start + Buffer.byteLength(text.slice(0, end), 'utf8'); }; if (cursor === null) { for (const n of options.segments === undefined ? segments : segments.slice(-options.segments)) take(`${path}.${n}`, 0, true); return { entries, cursor: { segment: newest, offset: take(path, 0, false) } }; } if (newest === cursor.segment) { const from = (store.stat(path)?.size ?? 0) < cursor.offset ? 0 : cursor.offset; return { entries, cursor: { segment: newest, offset: take(path, from, false) } }; } for (const n of segments) if (n > cursor.segment) take(`${path}.${n}`, n === cursor.segment + 1 ? cursor.offset : 0, true); // the live file is read next time, from its start: read now, it may be the one the rotation has not emptied yet, // and an offset into it would land inside the new one return { entries, cursor: { segment: newest, offset: 0 } }; } /** ~1 MB per segment: tens of thousands of entries (a shape line is ~80 bytes), and a report over a * recent period reads only the segments that reach into it. */ const REQUEST_JOURNAL_MAX_BYTES = 1_000_000; /** * Does this header/param NAME look like it carries a credential? Deliberately a generic word * predicate, never a vendor table: the kernel must not learn that Datadog calls its keys * `DD-API-KEY` or that Postmark calls its tokens `X-Postmark-Server-Token`. Both fall out of * `key`/`token` as name segments, and so does every vendor that has not been written yet. */ const CREDENTIAL_NAME = /(?:^|[-_.])(?:auth|authorization|token|jwt|key|apikey|secret|credential|credentials|signature|sig|password|passwd|pwd|session|sessionid|cookie|access[-_]?token|refresh[-_]?token)(?:[-_.]|$)/i; /** Auth schemes recognised in a value even when the NAME says nothing (`Bearer …` in `x-custom`). */ const CREDENTIAL_SCHEME = /^(Bearer|Basic|Digest|Token|Negotiate|NTLM|OAuth|Signature|Hawk|AWS4-HMAC-SHA256|SharedKey|SharedKeyLite|GoogleLogin)\s+(\S[\s\S]*)$/i; /** Non-reversible, stable fingerprint. 64 bits of sha256 — enough that two distinct credentials * never collide in a journal, far too little to walk back to a real key. */ export function credentialFingerprint(value: string): string { return `sha256:${createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16)}`; } function credentialShapeFor(name: string, value: string, where: 'header' | 'query'): TwinCredentialShape | undefined { const scheme = CREDENTIAL_SCHEME.exec(value); if (!scheme && !CREDENTIAL_NAME.test(name)) return undefined; const lower = name.toLowerCase(); if (value === '') return { name: lower, in: where, empty: true }; if (scheme) return { name: lower, in: where, scheme: scheme[1]!, fp: credentialFingerprint(scheme[2]!) }; return { name: lower, in: where, fp: credentialFingerprint(value) }; } /** * The credential SHAPE of one request: every credential-looking header and query param, named and * fingerprinted, sorted for stable diffing. Values never leave this function. */ export function twinRequestCredentials(headers: Headers | Record, url?: string | URL): TwinCredentialShape[] { const shapes: TwinCredentialShape[] = []; const seen = new Set(); const add = (name: string, value: string, where: 'header' | 'query') => { const shape = credentialShapeFor(name, value, where); if (!shape) return; const key = `${shape.in}:${shape.name}`; if (seen.has(key)) return; seen.add(key); shapes.push(shape); }; try { if (typeof (headers as Headers).forEach === 'function') { (headers as Headers).forEach((value, name) => add(name, value, 'header')); } else { for (const [name, value] of Object.entries(headers as Record)) add(name, String(value), 'header'); } } catch { /* a malformed header bag must not fail a serve */ } try { if (url !== undefined) { const search = typeof url === 'string' ? new URL(url, 'http://twin.invalid').search : url.search; for (const [name, value] of new URLSearchParams(search)) add(name, value, 'query'); } } catch { /* an unparseable URL must not fail a serve */ } return shapes.sort((a, b) => (a.in === b.in ? a.name.localeCompare(b.name) : a.in.localeCompare(b.in))); } /** The audit is kept unless it is switched off (VOLTER_TWIN_REQUEST_JOURNAL=0): no audit is the * setting someone chooses, never the default. */ export function twinRequestJournalEnabled(env: Record = process.env): boolean { return env.VOLTER_TWIN_REQUEST_JOURNAL !== '0'; } /** Where a service's request journal lives: beside its `actions.jsonl`. */ export function twinRequestJournalPath(service: string, root?: string): string { return join(dirname(worldPaths(service, root).events), 'requests.jsonl'); } /** * Append one request to the journal — a no-op only when VOLTER_TWIN_REQUEST_JOURNAL=0. Never throws; * answers whether the line was kept (true when the journal is switched off: no audit was chosen), so a * caller that must not act unaudited (a link) can refuse. */ export function journalTwinRequest(service: string, entry: TwinRequestJournalEntry, root?: string): boolean { if (!twinRequestJournalEnabled()) return true; const line = JSON.stringify({ // the World's record: stamped on the World's clock, as every record the World writes (architecture); its `ms` alone is // the machine's elapsed time at: entry.at ?? worldNow(), ...(entry.phase ? { phase: entry.phase } : {}), ...(entry.caller ? { caller: entry.caller.slice(0, 120) } : {}), ...(entry.trace && /^[0-9a-f]{32}$/.test(entry.trace) ? { trace: entry.trace } : {}), ...(entry.span && /^[0-9a-f]{16}$/.test(entry.span) ? { span: entry.span } : {}), method: entry.method.toUpperCase(), path: entry.path.split('?')[0], // the query STRING never lands; its credential params do, named + fingerprinted status: entry.status, ...(typeof entry.ms === 'number' ? { ms: entry.ms } : {}), ...(entry.credentials?.length ? { credentials: entry.credentials } : {}), ...(entry.scenario?.length ? { scenario: entry.scenario } : {}), }); let path: string | undefined; try { const store = getActiveWorldStore(); path = twinRequestJournalPath(service, root); store.mkdir(dirname(path)); if ((store.stat(path)?.size ?? 0) >= REQUEST_JOURNAL_MAX_BYTES) { // the live file closes into the next segment; no segment is ever overwritten or removed (a crash between // the two writes leaves the live lines in both: repeated in the next segment, never lost) const next = Number(journalSegments(path).pop()?.slice(path.length + 1) ?? 0) + 1; store.writeAtomic(`${path}.${next}`, store.read(path) ?? ''); store.write(path, ''); } store.append(path, `${line}\n`); return true; } catch (error) { const key = path ?? `${root ?? ''}/${service}`; journalFailures.set(key, (journalFailures.get(key) ?? 0) + 1); console.error(`[request-journal] ${service}: a line was not kept: ${(error as Error).message}`); return false; } } // ── how a wrapped `Bun.serve` learns which twin it is ────────────────────────────────────────── // `Bun.serve({port, fetch})` carries neither the vendor id nor the state root — both live in the // factory's closure. They are recoverable without touching a single pack, because handling a // request makes the pack call the kernel, and every kernel state path funnels through // `worldPaths(service, root)` (storage.ts). Observing the FIRST such call a server makes is the // twin naming itself: `deepgram` under `/tmp/world/data/deepgram`. It is cached per server, so only // the first request pays for it. A server whose first request touches no state falls back to the // call site (a catalog checkout or `@volter/twin-`) and the process's `--root` // argument, which is how the world runtime launches every twin. export const TWIN_JOURNAL_IDENTITY = Symbol.for('volter.twin.requestJournal.identity'); const JOURNAL_SHIM_INSTALLED = Symbol.for('volter.twin.requestJournal.installed'); export type TwinJournalIdentity = { service: string; root?: string }; /** One capture slot per in-flight request, so two twins co-located in ONE process (the shared * host) can never read each other's identity off a racing sibling's first request. * * LAZY ON PURPOSE: kernel modules ride into browser bundles (kernel imports are free of side effects), and a module-scope * `new AsyncLocalStorage()` survives tree-shaking into a client, where `node:async_hooks` does not resolve and `new` * throws at bundle evaluation. Nothing in this module may run at module scope. */ type JournalSlot = { identity?: TwinJournalIdentity; scenario?: Array> }; let identityCapture: AsyncLocalStorage | undefined; function identitySlot(): AsyncLocalStorage { identityCapture ??= new AsyncLocalStorage(); return identityCapture; } /** Note on the journal line of the request being served what the World's scenario did to it; a request served outside * the journal (switched off, or in-process) keeps no note. */ export function noteTwinRequest(note: Record): void { const slot = identityCapture?.getStore(); if (slot) (slot.scenario ??= []).push(note); } function observeIdentityFromWorldPaths(): void { observeWorldPaths((service, root) => { const slot = identityCapture?.getStore(); if (!slot || slot.identity !== undefined) return; slot.identity = root === undefined ? { service } : { service, root }; }); } /** The `--root DIR` a twin was launched with (the world runtime's spawn contract), if any. */ function rootFromArgv(argv: readonly string[] = process.argv): string | undefined { const index = argv.indexOf('--root'); const value = index >= 0 ? argv[index + 1] : undefined; return value && !value.startsWith('--') ? value : undefined; } /** The vendor a `Bun.serve` call site belongs to, from its module path. Infra packages are not * vendors, so they are skipped: whoever called THEM is the twin. */ const INFRA_PACKAGES = new Set(['world-runtime', 'world-host']); export function vendorFromStack(stack: string | undefined): string | undefined { if (!stack) return undefined; const pattern = /(?:twin-packs-p[23][\\/]|@volter[\\/]twin-)([A-Za-z0-9_-]+)/g; for (const match of stack.matchAll(pattern)) { const name = match[1]!; if (!INFRA_PACKAGES.has(name)) return name; } return undefined; } /** * Wrap `Bun.serve` so EVERY twin's HTTP surface journals, with no per-pack line. Idempotent * (a `Symbol.for` marker survives a second copy of this module) and a strict pass-through when * VOLTER_TWIN_REQUEST_JOURNAL=0. Called once at module load, below; exported so a test can assert it. * * A pack that knows its own identity may declare it by putting `{service, root}` on the serve * options under `TWIN_JOURNAL_IDENTITY` (a symbol key Bun's option reader ignores). Nothing in * the estate needs to: `createTwinServer` is the only caller, because it is the one server whose * service is an argument rather than a fact about the pack. */ export function installTwinRequestJournal(): boolean { // a browser bundle carrying the kernel: nothing to wrap, nothing to touch if (typeof window !== 'undefined' || typeof document !== 'undefined') return false; const bun = (globalThis as { Bun?: { serve?: unknown } }).Bun; const original = bun && typeof bun.serve === 'function' ? bun.serve as (...args: unknown[]) => { port?: number } : undefined; if (original && (original as unknown as Record)[JOURNAL_SHIM_INSTALLED]) return true; // Registered HERE, not at module scope, for the same reason the capture slot is lazy: a // module-scope registration is a side effect that survives tree-shaking into the client. observeIdentityFromWorldPaths(); // every server made through the seam (serve-http.ts) journals — on Node this is the only wrap setServeDecorator((options) => journalingFetch(options as unknown as Record & { fetch: (...a: unknown[]) => unknown }, vendorFromStack(new Error().stack)) as HttpHandler); if (!original) return false; // Node: no global to wrap; the seam carries the journal const wrapped = function serve(this: unknown, options: unknown, ...rest: unknown[]) { const config = options as (Record & { fetch?: (...a: unknown[]) => unknown }) | undefined; if (!config || typeof config.fetch !== 'function') return original.apply(this, [options, ...rest]); // Captured HERE, at the `Bun.serve` call, because this is the only moment the pack's own // module is on the stack — by the time a request is served, Bun is the caller. const callSiteVendor = (config[TWIN_JOURNAL_IDENTITY] as TwinJournalIdentity | undefined) ? undefined : vendorFromStack(new Error().stack); return original.apply(this, [{ ...config, fetch: journalingFetch(config as Record & { fetch: (...a: unknown[]) => unknown }, callSiteVendor) }, ...rest]); }; Object.defineProperty(wrapped, JOURNAL_SHIM_INSTALLED, { value: true }); (bun as { serve: unknown }).serve = wrapped; return true; } /** The journaling form of a server's fetch handler: identity resolved once per SERVER (declared * under TWIN_JOURNAL_IDENTITY, else observed from the first state-touching request, else the * call-site vendor + `--root`), every request journaled with its method, path and status. */ function journalingFetch(config: Record & { fetch: (...a: unknown[]) => unknown }, callSiteVendor: string | undefined): (request: Request, server?: unknown) => unknown { if (config.twinRequestJournal === false) return config.fetch; { const declared = config[TWIN_JOURNAL_IDENTITY] as TwinJournalIdentity | undefined; // Resolved once per SERVER, not per request: a twin's identity is a constant of the server. let identity: TwinJournalIdentity | undefined = declared; const inner = config.fetch as (this: unknown, request: Request, server: unknown) => unknown; const journaling = async function (this: unknown, request: Request, server: unknown) { // who made it is read here and goes no further: no twin's handler (a tunnel's, a proxy's) hands it on const sent = request.headers.get(CALLER_HEADER); const caller = sent === null ? undefined : callerFromHeader(sent); if (caller !== undefined) { const headers = new Headers(request.headers); headers.delete(CALLER_HEADER); request = withHeaders(request, headers); } // The World's own boot probe (serve-http.ts, WORLD_BOOT_PATH) is not the app's traffic: never journaled. if (!twinRequestJournalEnabled() || new URL(request.url).pathname === WORLD_BOOT_PATH) return inner.call(this, request, server); const slot: JournalSlot = {}; let status = 500; const startedAt = performance.now(); try { const response = (await identitySlot().run(slot, () => inner.call(this, request, server))) as Response | undefined; if (response instanceof Response) status = response.status; else if (response === undefined) { status = 101; return response; } // accepted WebSocket upgrade return response; } finally { // Only an OBSERVED identity is cached: it is the twin's own words. A fallback is // per-request, so the first request that touches state upgrades every later one instead // of locking a guessed root in for the life of the server. identity ??= slot.identity; const resolved = identity ?? fallbackIdentity(callSiteVendor); if (resolved) { const url = new URL(request.url); const parent = parseTraceparent(request.headers.get('traceparent')); journalTwinRequest(resolved.service, { method: request.method, path: url.pathname, status, ms: Math.round(performance.now() - startedAt), credentials: twinRequestCredentials(request.headers, url), ...(caller ? { caller } : {}), ...(parent ? { trace: parent.traceId, span: parent.parentId } : {}), ...(slot.scenario ? { scenario: slot.scenario } : {}), }, resolved.root); } } }; return journaling; } } /** Identity for a server whose first request touched no state: the vendor that owns the calling * module, plus the `--root` the world runtime launched this twin with. */ function fallbackIdentity(callSiteVendor: string | undefined): TwinJournalIdentity | undefined { const service = process.env.VOLTER_TWIN_JOURNAL_SERVICE || callSiteVendor; if (!service || !/^[A-Za-z0-9_-]+$/.test(service)) return undefined; const root = rootFromArgv(); return root === undefined ? { service } : { service, root }; } // One call, at module load. `@volter/world-core`'s entrypoint re-exports this module, and every pack // that serves imports the kernel, so wrapping here is what makes the journal a property of the // PRODUCT rather than of the four packs that once remembered to call it. // // It is a no-op wherever `Bun.serve` is absent, which is what keeps it safe in a browser bundle: // off-Bun it returns before touching `node:async_hooks`, `process.argv`, or the storage hook. installTwinRequestJournal(); // A subject rendered as a vendor resource: its folded current fields + identity. export type TwinResource = { id: string; type: string; updatedAt: string } & Record; // The twin's current view = the OBSERVED mirror (events.jsonl) with the local // ACTION log (actions.jsonl) projected over it. Observed facts and local // actions are kept separate; this is the single projected read model. export function twinResources(service: string, root?: string): TwinResource[] { return projectResources(service, root); } // Result of a local twin write — it is an ACTION, not an egress/real write. export type TwinWriteResult = { status: 'performed' | 'replayed'; actionId: string; /** the id the vendor minted when the head performed the write */ externalId?: string; /** what the vendor answered when the head performed the write, as the adapter returned it */ vendorData?: unknown }; export type TwinWriteInput = { operation: string; provider?: string; subjectType: string; subjectId: string; fields: SubjectFields; input?: Record; projection?: ActionProjection; occurredAt?: string; actor?: { kind: 'agent' | 'human' | 'bot' | 'system'; id?: string }; preconditions?: TwinActionPrecondition[]; correlationId?: string; uniqueness?: string; /** AT-MOST-ONCE, opt in. A local vendor write is an OCCURRENCE by default: two calls are two * actions, even byte-identical in the same instant. Pass a caller-supplied key when a re-issue * of the SAME request must collapse onto the first. Without a key the kernel cannot tell a retry * from a repeat, and guessing from content is what silently dropped writes. * * SCOPE: the key dedupes * on (service, operation, subjectId, key). It therefore helps only when the CALLER supplies the * subject id. A create whose id the twin mints gets a fresh id per call and is NOT deduped by * this — which is the commonest shape a vendor's own idempotency header covers — so a pack * modelling such a header for creates keeps doing it itself, by request signature and stored * response (the payments pack in this catalog does). Reuse of a key with a DIFFERENT payload * raises a conflict, which the generic twin server answers as a 400. */ idempotencyKey?: string; /** The EXACT identity of an action being re-materialized, when the caller already has one — * replay reproducing a source changeset's actions into a target world. Distinct from * `idempotencyKey`, which is a REQUEST key the kernel derives an id from: this IS the id, so a * replayed action keeps the identity it had in the source world. Implies at-most-once, because * identity equality is what at-most-once means. Not for packs. */ actionId?: string; }; export type AtomicTwinWriteDecision = | { kind: 'skip'; value: T } | { kind: 'write'; value: T; write: TwinWriteInput }; /** The largest string a write's recorded request keeps in the log itself. */ const INPUT_INLINE_MAX = 64 * 1024; /** * A write's recorded request, with each string longer than INPUT_INLINE_MAX (an attached file's base64: an npm * publish's tarball) kept once as a content-addressed blob under the service's state and named in its place as * `{ $blob, bytes }`. The request stays whole and deterministic, and a body several writes record is kept once, never * copied into the log (docs/contributing/architecture.md, "The log keeps a large request once"). `recordedInput` reads * it back whole. */ async function offloadInput(service: string, input: unknown, root: string | undefined): Promise { if (typeof input === 'string') { if (input.length <= INPUT_INLINE_MAX) return input; // hashed as it is (UTF-8), and encoded only when its blob is new: each write of a request records the same body const key = join(worldPaths(service, root).dir, 'inputs', createHash('sha256').update(input, 'utf8').digest('hex')); const blobs = getActiveBlobStore(); if (!(await blobs.exists(key))) await blobs.put(key, Buffer.from(input, 'utf8')); return { $blob: key, bytes: Buffer.byteLength(input, 'utf8') }; } if (Array.isArray(input)) return Promise.all(input.map((v) => offloadInput(service, v, root))); if (input && typeof input === 'object') { const out: Record = {}; for (const [k, v] of Object.entries(input)) out[k] = await offloadInput(service, v, root); return out; } return input; } /** A recorded request as it was sent: each string the log keeps as a blob, read back. */ export async function recordedInput(input: unknown): Promise { if (Array.isArray(input)) return Promise.all(input.map(recordedInput)); if (input && typeof input === 'object') { const ref = input as { $blob?: unknown; bytes?: unknown }; if (typeof ref.$blob === 'string' && typeof ref.bytes === 'number' && Object.keys(input).length === 2) { const bytes = await getActiveBlobStore().get(ref.$blob); return bytes ? new TextDecoder().decode(bytes) : undefined; } const out: Record = {}; for (const [k, v] of Object.entries(input)) out[k] = await recordedInput(v); return out; } return input; } function actionForTwinWrite(service: string, write: TwinWriteInput): TwinAction { const occurredAt = write.occurredAt ?? new Date().toISOString(); // Idempotency: dedup a RE-ISSUED IDENTICAL write only. The key includes a hash of the write // CONTENT, not just the timestamp. `undefined` keys are omitted by canonicalJson, preserving // every pre-input/projection action id for existing packs. const contentHash = hashFieldValue({ operation: write.operation, subjectId: write.subjectId, fields: write.fields, input: write.input, projection: write.projection }); // Replay carries the source action’s exact identity, including an occurrence ordinal for a repeated write. const actionId = write.actionId ?? (write.idempotencyKey ? `twin:${service}:${write.operation}:${write.subjectId}:idem:${write.idempotencyKey}` : `twin:${service}:${write.operation}:${write.subjectId}:${occurredAt}:${contentHash}${write.uniqueness ? `:${write.uniqueness}` : ''}`); return { id: actionId, service, op: 'set', operation: write.operation, subject: { type: write.subjectType, id: write.subjectId }, occurredAt, ...(write.actor ? { actor: write.actor } : {}), ...(write.preconditions?.length ? { preconditions: write.preconditions } : {}), ...(write.correlationId ? { correlationId: write.correlationId } : {}), ...(write.idempotencyKey ? { idempotencyKey: write.idempotencyKey } : {}), ...(write.input ? { input: write.input } : {}), fields: write.fields, ...(write.projection ? { projection: write.projection } : {}), }; } /** * Decide a state-dependent local write and append it under the same cross-process action lock. * Use this when acceptance or the new fields depend on current projected state; a caller-side * read followed by `applyTwinWrite` is not atomic across processes. */ export async function applyTwinWriteAtomic( service: string, prepare: (resources: readonly TwinResource[]) => AtomicTwinWriteDecision, root?: string, /** A type index when the decision and its preconditions need only that type, read inside the state lock. */ read?: () => TwinResource[], ): Promise<{ value: T; result?: TwinWriteResult }> { // Same ruling as applyTwinWrite: a local write is an OCCURRENCE unless the caller supplied // identity. The mode rides on the decision because only the callback knows which write it chose. const committed = decideAndAppendAction(service, (resources) => { const decision = prepare(resources); if (decision.kind === 'skip') return { kind: 'skip', value: decision.value }; return { kind: 'append', value: decision.value, action: actionForTwinWrite(service, decision.write), identity: decision.write.idempotencyKey || decision.write.actionId ? 'caller' : 'occurrence', }; }, root, read); // as applyTwinWrite: a seed's write is the placeholder's default data, never performed const head = committed.action && committed.appended && !committed.placeholder ? await performAtHead(service, committed.action, root) : { performed: false }; return { value: committed.value, ...(committed.action ? { result: { status: committed.appended ? 'performed' : 'replayed', actionId: committed.action.id, ...(head.externalId ? { externalId: head.externalId } : {}) } } : {}), }; } // Resolve a read request against the twin's resources. Returns the matched // resource(s) + an HTTP-ish status, deterministically from state. // GET / -> { service, mode, resourceTypes, count } // GET / -> list of resources of that type // GET // -> one resource (id may be url-encoded) export function resolveTwinRead( service: string, pathname: string, opts: { root?: string } = {}, ): { status: number; body: unknown } { const resources = twinResources(service, opts.root); const parts = pathname.replace(/^\/+|\/+$/g, '').split('/').filter(Boolean); if (parts.length === 0) { const types = [...new Set(resources.map((r) => r.type))].sort(); return { status: 200, body: { service, resourceTypes: types, count: resources.length } }; } const type = parts[0]!; const ofType = resources.filter((r) => r.type === type); if (parts.length === 1) { return { status: 200, body: { type, count: ofType.length, items: ofType } }; } const id = decodeURIComponent(parts.slice(1).join('/')); const found = ofType.find((r) => r.id === id); if (!found) return { status: 404, body: { error: 'not_found', type, id } }; return { status: 200, body: found }; } // Simulator/fork-mode write: the twin ACCEPTS a write as a LOCAL ACTION appended // to the action log — NOT an observed event and NOT an egress/real write. // State is the mirror with this action projected over it, so a subsequent read // returns the change. The observed event log is untouched; the real service is // provably untouched (no network I/O, no egress). Pushing the action to the real // vendor is a separate, explicit step that records egress + confirms the action. export async function applyTwinWrite( service: string, write: TwinWriteInput, root?: string, ): Promise<{ result: TwinWriteResult; resource: TwinResource }> { const action = actionForTwinWrite(service, write.input === undefined ? write : { ...write, input: await offloadInput(service, write.input, root) as TwinWriteInput['input'] }); // A LOCAL VENDOR WRITE IS AN OCCURRENCE. Two calls are two actions, even byte-identical in the // same instant, and the ordinal in the action id says which occurrence this is: identity derived // from content and instant would drop a write returning a subject to a value it held before, under // a pinned world clock where every write in a world shares one instant. See // docs/contributing/architecture.md, "The state kernel", "A local write is an occurrence". // // AT-MOST-ONCE is opt in, by KEY: `idempotencyKey` makes the id a function of the caller's own // request identity, so a re-issue collapses onto the first and answers `replayed`. Content can // never decide this — it cannot separate the same request delivered twice from the same change // made twice. // // `uniqueness` (a billable AI completion that must ledger every call) is honoured, and with // occurrence semantics it is redundant rather than wrong. // // correlationId (D3): a caller-supplied request-scoped id lands on the action row; the appenders // generate one when omitted, so it's never missing. const committed = write.idempotencyKey || write.actionId ? appendActionIfAbsent(action, root) : appendActionOccurrence(action, root); // The COMMITTED action's id, not the one computed before the lock: an occurrence past the first // carries an ordinal, and a caller told the base id would be naming an action that is not there. const { appended, action: landed } = committed; // THE HEAD (head.ts): a twin whose root says `auto` performs the entry now, before the app is // answered; the vendor's id, when it minted one, is the id the answer carries. // a write landed as the placeholder's default data (a seed) is a pull, never a commit: the head is not asked const head = appended && !committed.placeholder ? await performAtHead(service, landed, root) : { performed: false }; const answerId = head.externalId ?? write.subjectId; const result: TwinWriteResult = { status: appended ? 'performed' : 'replayed', actionId: landed.id, ...(head.externalId ? { externalId: head.externalId } : {}), ...(head.data !== undefined ? { vendorData: head.data } : {}) }; // THE WRITTEN RESOURCE, read when a caller asks for it. Projecting the whole tree after every write to answer it // made each write O(tree) and a batch of N writes O(N x tree), whether or not the caller used the answer (a Timestream // seed of a member's wearable history stalled its twin for minutes). Resolved by (type, id): an id alone is ambiguous // when two resource TYPES share it. let resolved: TwinResource | undefined; return { result, get resource(): TwinResource { return resolved ??= readSubject(service, write.subjectType, answerId, root) ?? ({ id: answerId, type: write.subjectType, updatedAt: landed.occurredAt, ...write.fields } as TwinResource); }, }; } /** * Several local writes of one service, landed as `applyTwinWrite` lands each called in turn — the same actions, ids and * order — under one lock and one append (actions.ts `appendActionOccurrences`). Writes that need the one-at-a-time * path take it: a caller's identity (`idempotencyKey`/`actionId`), preconditions, or a head that performs each entry as * it lands. An input is offloaded once per distinct value, as each write's own offload would name it. */ export async function applyTwinWrites( service: string, writes: readonly TwinWriteInput[], root?: string, ): Promise> { if (writes.length <= 1 || performsAtHeadNow(service, root) || writes.some((write) => write.idempotencyKey || write.actionId || write.preconditions?.length)) { const out: Array<{ result: TwinWriteResult; resource: TwinResource }> = []; for (const write of writes) out.push(await applyTwinWrite(service, write, root)); return out; } // Each distinct input offloaded once: `offloadInput` is content-addressed (a string's blob is named by its // SHA-256), so the result is the one each write's own offload would give, and a command's writes, which share one // recorded request, hash and look up its blob once instead of once per write. const offloaded = new Map(); for (const write of writes) if (write.input !== undefined && !offloaded.has(write.input)) offloaded.set(write.input, await offloadInput(service, write.input, root)); const committed = appendActionOccurrences(writes.map((write) => actionForTwinWrite(service, write.input === undefined ? write : { ...write, input: offloaded.get(write.input) as TwinWriteInput['input'] })), root); const out: Array<{ result: TwinWriteResult; resource: TwinResource }> = []; for (const [index, { appended, action: landed, placeholder }] of committed.entries()) { const write = writes[index]!; // the head does not perform here (`performsAtHeadNow` was false): this marks the request's deferred group as written if (appended && !placeholder) await performAtHead(service, landed, root); const answerId = write.subjectId; let resolved: TwinResource | undefined; out.push({ result: { status: appended ? 'performed' : 'replayed', actionId: landed.id }, get resource(): TwinResource { return resolved ??= readSubject(service, write.subjectType, answerId, root) ?? ({ id: answerId, type: write.subjectType, updatedAt: landed.occurredAt, ...write.fields } as TwinResource); }, }); } return out; } export async function createTwinServer(options: { service: string; root?: string; port?: number; readOnly?: boolean }): Promise<{ port: number; stop: () => void }> { const readOnly = options.readOnly ?? false; const serveOptions = { port: options.port ?? 0, idleTimeout: 60, async fetch(request: Request) { const url = new URL(request.url); const json = (status: number, body: unknown) => new Response(JSON.stringify(body, null, 2), { status, headers: { 'content-type': 'application/json' } }); if (request.method === 'GET') { // Re-read per request so a concurrently-syncing twin serves fresh state. const { status, body } = resolveTwinRead(options.service, url.pathname, { root: options.root }); return json(status, body); } // Writes are accepted as local actions unless this twin was started read-only. if (readOnly) return json(405, { error: 'read_only', hint: 'this twin was started read-only; omit readOnly to accept writes' }); const parts = url.pathname.replace(/^\/+|\/+$/g, '').split('/').filter(Boolean); if (parts.length < 2) return json(400, { error: 'write_needs_type_and_id', hint: 'POST // with a JSON body of fields' }); let fields: SubjectFields; try { fields = (await request.json()) as SubjectFields; } catch { return json(400, { error: 'invalid_json_body' }); } // AT-MOST-ONCE OVER HTTP, the way vendors spell it. A local write is an occurrence, so an // identical repeat POST is a second action and answers 201. A caller that means "the same request again" sends // `Idempotency-Key`, exactly as Stripe and others define it, and gets 200 `replayed`. Without // this the `replayed` arm below was unreachable on the kernel's own write endpoint. const idempotencyKey = request.headers.get('idempotency-key') ?? undefined; let committed: Awaited>; try { committed = await applyTwinWrite(options.service, { operation: `${request.method.toLowerCase()}.${parts[0]}`, subjectType: parts[0]!, subjectId: decodeURIComponent(parts.slice(1).join('/')), fields, actor: { kind: 'agent' }, ...(idempotencyKey ? { idempotencyKey } : {}), }, options.root); } catch (e) { // Reusing an idempotency key with a different payload is a caller error; other failures propagate. if (idempotencyKey && e instanceof Error && e.message.startsWith('Conflicting duplicate twin action')) { return json(400, { error: 'idempotency_error', message: `Keys for idempotent requests can only be used with the same parameters they were first used with. Try using a key other than '${idempotencyKey}' if you meant to execute a different request.` }); } throw e; } const { result, resource } = committed; return json(result.status === 'replayed' ? 200 : 201, { status: result.status, resource }); }, }; // This generic server's twin is an ARGUMENT, not a fact about a pack, so it NAMES ITSELF for the // request journal rather than being recognised from its call site. Every vendor pack is journaled // without declaring anything (installTwinRequestJournal, above); this is the lone declaration. Object.defineProperty(serveOptions, TWIN_JOURNAL_IDENTITY, { value: { service: options.service, ...(options.root !== undefined ? { root: options.root } : {}) }, enumerable: true, }); const server = await serveHttp(serveOptions); return { port: server.port, stop: () => { void server.stop(true); } }; }