// THE HEAD — where a write is applied (docs/concepts/the-model.md). // // Every write is an entry first. Then the twin's head says what happens to it: no root, or a root // under `gated`/`hold`, and the entry waits (simulated); a root under `auto`, and the entry is // PERFORMED NOW, in the process that serves the twin, before the app is answered — checks, then the // pack's perform adapter over the kernel executor with the credential opened from its seal, then // the landed copy with the receipt. The push door and `volter world deploy` perform through the // same `performEntries`; there is no hook and no phase ledger. The receipt on the entry is the // record: a `deployed` copy is never performed again, a `failed` one is retried. import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { basename, dirname, isAbsolute, join, resolve } from 'node:path'; import { confirmAction, currentCorrelationId, isTwinBookkeeping, resolveSubjectId, revertAction, type TwinAction } from './actions.ts'; import { keySealer, type CredentialPayload, type SealedCredential, type Sealer } from './credential.ts'; import { buildRemoteExecute, validateRemoteOrigin, type CredentialCustody } from './executor.ts'; import { getPack } from './packRegistry.ts'; import type { RemoteExecute, RemoteExecuteResponse } from './remote-execute.ts'; import { aliasesFrom, branchEntries, parentEntries, readTree, type Entry, type Receipt } from './log.ts'; import { resolveReferences } from './references.ts'; import { authStrategyFor, NO_SECRETS_CHECK, readRoot, runChecks, stateSystemFor, type Check, type DeployPolicy, type RootConfig, type StateSystemAdapters } from './state-system.ts'; import { stateDirName, worldPaths } from './storage.ts'; import { worldNow } from './world-clock.ts'; import { getActiveWorldStore } from './world-store.ts'; // ── the pack's perform adapter ────────────────────────────────────────────────────────────── /** What a perform answers: the id the vendor minted (the local id when it kept ours), its URL, and * the vendor's answer as fields for the landed copy. */ export type PushOutcome = { externalId: string; url?: string; data?: Record; /** the successful vendor response for the caller, distinct from the resource fields stored in data */ response?: RemoteExecuteResponse; /** the group's entry the id is for, when it is not the group's first (a cascade writes children first) */ actionId?: string; /** the group's other entries the answer named an id for (a resource's `companions`) */ also?: Array<{ actionId: string; externalId: string; data?: Record }>; /** the group's entries the vendor refused while it took the rest (a git push to a root without `atomic`, each ref its * own outcome: ADR 0031); each settles refused with its reason */ refused?: Array<{ actionId: string; reason: string }>; }; /** What a perform is handed beside the executor: a resolver from a local id to the vendor's (an * entry authored against `twin-1` crosses against `REAL-42` once that subject's landing adopted it). */ /** `credential`: the sealed credential's keyed fingerprint (credential.ts — an HMAC under the sealing key, or the * vault's transit hmac at a pinned key version, * never the secret and no offline oracle for it), so a pack keys its budget ledger per real credential: * every World and branch performing with one vendor key then shares that key's one allowance. */ export type PerformContext = { resolve: (type: string, localId: string) => string; service?: string; root?: string; credential?: string; localGroup?: TwinAction[] }; /** One request's entries (a group: they share its `correlationId`), performed as the one call that made them. */ export type PerformAction = (execute: RemoteExecute, group: TwinAction[], ctx: PerformContext) => Promise; export function performContext(service: string, root?: string, credential?: string): PerformContext { return { resolve: (type, localId) => resolveSubjectId(service, type, localId, root), service, ...(root !== undefined ? { root } : {}), ...(credential !== undefined ? { credential } : {}) }; } /** The keyed fingerprint of the root's sealed credential, or undefined when none is sealed. */ function rootCredentialFingerprint(root: BoundRoot): string | undefined { const sealed = getActiveWorldStore().read(root.credential); if (sealed === null) return undefined; const fingerprint = (JSON.parse(sealed) as SealedCredential).fingerprint; return typeof fingerprint === 'string' && fingerprint !== '' ? fingerprint : undefined; } // ── the user's key and the sealed credential ──────────────────────────────────────────────── /** The user's key-encryption key: `$XDG_CONFIG_HOME/volter/kek` (created on first use). */ export function userKekPath(): string { const base = process.env.XDG_CONFIG_HOME && process.env.XDG_CONFIG_HOME !== '' ? process.env.XDG_CONFIG_HOME : join(homedir(), '.config'); return join(base, 'volter', 'kek'); } export function userKek(): string { const path = userKekPath(); if (existsSync(path)) return readFileSync(path, 'utf8').trim(); mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); const key = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64'); writeFileSync(path, `${key}\n`, { mode: 0o600 }); chmodSync(path, 0o600); return key; } /** Where the key that wraps every sealed credential comes from. A local World uses the user's key * file (`userKek`); a hosted World's host supplies its deployment's secret once at start. */ let sealingKeySource: (() => string) | null = null; export function setSealingKeySource(source: (() => string) | null): void { sealingKeySource = source; } export function sealingKey(): string { return sealingKeySource ? sealingKeySource() : userKek(); } /** What seals and opens this process's credentials: the host's sealer (a vault's transit engine, company decision * 0034), else a key sealer over `sealingKey()`. */ let hostSealer: Sealer | null = null; export function setSealer(sealer: Sealer | null): void { hostSealer = sealer; } export function currentSealer(): Sealer { return hostSealer ?? keySealer(sealingKey); } /** The destination a credential is bound to (SealedBody.bound): the origin it is sent to, and only that. */ export function destinationOf(url: string): string { return `origin=${new URL(url).origin}`; } /** * Open the credential sealed at `path`, under the current sealer, for `bound` (destinationOf the place it is about to * be sent; omitted where it is sent nowhere, a webhook's signing secret). A record bound elsewhere, or bound nowhere, * refuses. A record the host's vault did not seal (`v: 1`) is sealed again by the vault (decision 0034), keeping its * binding, placedAt and fingerprint (its identity, as a rotation keeps them). The rewrite lands only over the record that was read; if another came meanwhile, that one is opened instead, * so a credential replaced while this one moved is never handed out. */ export async function openSealedAt(path: string, slot: string, bound?: string): Promise { return (await openSealedRecord(path, slot, bound))?.payload ?? null; } /** Whether this host seals through a vault (setSealer): what a record under the host's key is moved to. */ export function sealsThroughVault(): boolean { return hostSealer !== null; } /** openSealedAt, with the exact record it answers from: the text it read, or the text its own move wrote. A rotation * lands only over that text (rootCustody), so it never mistakes another record for the one it opened. */ export async function openSealedRecord(path: string, slot: string, bound?: string, again = true): Promise<{ payload: CredentialPayload; text: string } | null> { const store = getActiveWorldStore(); const text = store.read(path); if (text === null) return null; const sealed = JSON.parse(text) as SealedCredential; const payload = await currentSealer().open(sealed, slot, bound); const move = hostSealer !== null && sealed.v === 1; let wrote: string | null = null; if (move) { try { const resealed = await currentSealer().seal(payload, sealed.placedAt, slot, sealed.bound); // read and write are synchronous, so nothing comes between this check and the write if (store.read(path) === text) { const moved = `${JSON.stringify({ ...resealed, fingerprint: sealed.fingerprint, ...(sealed.rotatedAt ? { rotatedAt: sealed.rotatedAt } : {}) }, null, 2)}\n`; store.write(path, moved, { secret: true }); wrote = moved; } } catch (error) { // the credential opened: a rewrite that fails (the vault down, a token expired) waits for the next open console.warn(`[credential] ${slot}: not moved to the vault yet (${(error as Error).message})`); } } const answeredFrom = wrote ?? text; if (store.read(path) !== answeredFrom) return again ? openSealedRecord(path, slot, bound, false) : null; return { payload, text: answeredFrom }; } /** A root as a world materializes it: the config plus the path of the sealed credential. */ export type BoundRoot = RootConfig & { credential: string }; /** Open the credential a root names, under the current sealer, for the root's own origin. */ export async function openRootCredential(root: BoundRoot, vendor: string = vendorOf(root)): Promise { return (await openRootRecord(root, vendor)).payload; } async function openRootRecord(root: BoundRoot, vendor: string): Promise<{ payload: CredentialPayload; text: string }> { const opened = await openSealedRecord(root.credential, vendor, destinationOf(root.url)); if (opened === null) throw new Error(`no credential sealed for ${vendor} — \`printf '' | volter twin ${vendor} credential\``); return opened; } /** Seal a credential the vendor rotated (an `exchange` with `rotate`) where the root's was, under the same key, slot and * binding. It is the same credential: its placedAt and fingerprint stay (a pack's budget keys its ledger by the * fingerprint, and a new one per grant would start the ledger over), and rotatedAt says when. `source` is the record * the rotation began from: if another credential was set meanwhile, the rotation is dropped, never written over it. */ export async function resealRootCredential(root: BoundRoot, payload: CredentialPayload, vendor: string = vendorOf(root), source?: string | null): Promise { const store = getActiveWorldStore(); const held = store.read(root.credential); if (source !== undefined && held !== source) throw new Error(`the ${vendor} credential was set again while it rotated: the rotation is dropped`); const before = held === null ? null : (JSON.parse(held) as SealedCredential); const now = new Date().toISOString(); const sealed = await currentSealer().seal(payload, before?.placedAt ?? now, vendor, destinationOf(root.url)); // read and write are synchronous: nothing comes between this check and the write if (store.read(root.credential) !== held) throw new Error(`the ${vendor} credential was set again while it rotated: the rotation is dropped`); store.write(root.credential, `${JSON.stringify({ ...sealed, ...(before ? { fingerprint: before.fingerprint } : {}), rotatedAt: now }, null, 2)}\n`, { secret: true }); store.remove(unsealedMarkerOf(root)); } /** Beside a root's credential, the record of a rotation its seal failed to keep (`rootCustody`'s `unsealed`). */ export function unsealedMarkerOf(root: BoundRoot): string { return root.credential.replace(/\.json$/, '.unsealed.json'); } /** The root's custody for an exchange that rotates: the credential as sealed now, and the seal of a rotated one, which * lands only over the record that was opened. */ export function rootCustody(root: BoundRoot, vendor: string = vendorOf(root)): CredentialCustody { // the credential's identity: its path and its fingerprint, which a rotation keeps and a user's re-seal of another // credential changes, so a token exchanged for one account never answers for the next const store = getActiveWorldStore(); const held = store.read(root.credential); const fingerprint = held === null ? '' : String((JSON.parse(held) as SealedCredential).fingerprint ?? ''); let source: string | null = null; return { key: `${root.credential}#${fingerprint}`, open: async () => { // the exact record this exchange began from: the text the open read, or the text its own move wrote const opened = await openRootRecord(root, vendor); source = opened.text; return opened.payload; }, seal: (credential) => resealRootCredential(root, credential, vendor, source), // the vendor already spent the sealed secret: until a seal lands, the root renews only inside the process holding the // new one, so the World keeps a record a person or `doctor` can read after that process ends unsealed: (field, cause) => store.write(unsealedMarkerOf(root), `${JSON.stringify({ vendor, field, at: new Date().toISOString(), cause: cause.slice(0, 300) }, null, 2)}\n`), }; } /** The vendor a root belongs to: its credential is sealed under the vendor's name. */ export function vendorOf(root: BoundRoot): string { return basename(root.credential, '.json'); } /** The world a root belongs to: the credential sits at `/.volter/credentials/.json`. */ export function worldRootOf(root: BoundRoot): string { return resolve(dirname(root.credential), '..', '..'); } // ── the world's checks ────────────────────────────────────────────────────────────────────── /** The checks a world runs before any entry is performed: the shipped no-secrets check, then every * file under `.volter/checks/` exporting `{ name, run }`. */ export async function loadChecks(worldRoot: string): Promise { const dir = join(resolve(worldRoot), stateDirName(), 'checks'); const out: Check[] = [NO_SECRETS_CHECK]; for (const file of getActiveWorldStore().list(dir).filter((f) => /\.(ts|js|mjs)$/.test(f)).sort()) out.push(await checkLoader(join(dir, file), file.replace(/\.(ts|js|mjs)$/, ''))); return out; } /** How a check file becomes a Check. Locally the file is imported; a hosted World's host supplies a * loader that runs the check in an isolate of its own, with no network and nothing of the World's. */ export type CheckLoader = (path: string, name: string) => Promise; const importCheck: CheckLoader = async (path, name) => { // Node's ESM loader takes an absolute path only as a file URL (on Windows `C:\…` reads as the scheme `c:`); Bun takes either const mod = (await import(isAbsolute(path) ? fileUrlOf(path) : path)) as { check?: Check; default?: Check }; const check = mod.check ?? mod.default; if (!check || typeof check.run !== 'function') throw new Error(`${path} must export a check { name, run }`); return { name: check.name ?? name, run: check.run }; }; /** An absolute path's file URL, built here: `node:url` is not in the browser bundles that also reach this module. */ const fileUrlOf = (path: string): string => { // a long path (`\\?\C:\…`) is the drive path it names; a UNC path (`\\server\share\…`) puts the server in the URL's host const long = /^\\\\\?\\(?:UNC\\)?/i.exec(path); const unc = /^\\\\\?\\UNC\\/i.test(path) || (!long && /^\\\\[^\\?]/.test(path)); const rest = (long ? path.slice(long[0].length) : unc ? path.slice(2) : path).replace(/\\/g, '/'); const encoded = rest.split('/').map((seg) => encodeURIComponent(seg).replace(/%3A/g, ':')).join('/'); return unc ? `file://${encoded}` : `file://${rest.startsWith('/') ? '' : '/'}${encoded}`; }; let checkLoader: CheckLoader = importCheck; export function setCheckLoader(loader: CheckLoader | null): void { checkLoader = loader ?? importCheck; } /** One check file through the host's loader: what placing a check validates with. */ export function loadCheck(path: string, name: string): Promise { return checkLoader(path, name); } // ── the head ──────────────────────────────────────────────────────────────────────────────── export type Head = { kind: 'simulated' } | { kind: 'real'; deploy: DeployPolicy; root: BoundRoot }; /** The root a state service under `root` is bound to — its own root.json, else a sibling state's * (slack records under `chat`; the root was written under `slack`). */ export function boundRoot(service: string, root?: string): BoundRoot | null { const own = readRoot(service, root) as BoundRoot | null; if (own?.credential) return own; const stateRoot = dirname(worldPaths(service, root).dir); const store = getActiveWorldStore(); const states = store.list(stateRoot).filter((name) => store.stat(join(stateRoot, name))?.isDirectory); for (const state of states) { if (state === service) continue; const r = readRoot(state, root) as BoundRoot | null; if (r?.credential) return r; } return null; } /** What this twin's head does with a write. */ export function headOf(service: string, root?: string): Head { const bound = boundRoot(service, root); return bound ? { kind: 'real', deploy: bound.deploy, root: bound } : { kind: 'simulated' }; } /** A check refused the write: the entry is in the log as refused; the pack answers in the vendor's error shape. */ export class RefusedWriteError extends Error { constructor(readonly check: string, readonly reason: string, readonly actionId: string) { super(`${check}: ${reason}`); this.name = 'RefusedWriteError'; } } /** The head could not be bound for a write that needed it (no credential sealed, no adapter registered, * no root): a server-side fault, answered as one. */ export class HeadError extends Error { constructor(message: string) { super(message); this.name = 'HeadError'; } } /** A selected live request can retry after the earlier write finishes; its local group must roll back. */ class DeploymentOrderError extends HeadError {} /** The vendor refused or failed the write: the entry is in the log as failed, with the vendor's words. */ export class VendorWriteError extends Error { constructor(message: string, readonly actionId: string) { super(message); this.name = 'VendorWriteError'; } } export type DeployReport = { /** entries performed by this call */ pushed: number; deployed: Array<{ actionId: string; externalId?: string; at: string; /** what the vendor answered, as the adapter returned it */ data?: unknown; response?: RemoteExecuteResponse }>; /** the first refusal; nothing after it was attempted */ refused?: { actionId: string; check: string; reason: string }; /** the first failure, with the vendor's words; nothing after it was attempted */ failed?: { actionId: string; error: string }; /** a group the vendor took in part: its entries it refused, each with its reason; nothing after it was attempted */ partial?: Array<{ actionId: string; reason: string }>; /** entries after the refusal or failure, not attempted */ skipped: string[]; /** entries whose landed copy already said `deployed` — not performed again */ replayed: string[]; /** entries the World's own doors made (a door, a screen, the gap, the clock, a seed): never offered to the vendor */ worldOnly: string[]; }; /** The receipt a branch entry's latest landed copy carries, if any. */ function receiptsByEntry(parent: Entry[]): Map { const out = new Map(); for (const e of parent) if (e.landsId && e.receipt) out.set(e.landsId, e.receipt); return out; } /** Whether an entry records a call of the vendor's surface (an operation or a GraphQL mutation): what a perform can send * again (the real-system adapters, "What the derived core records with a write"). */ function surfaceWrite(e: { input?: Record }): boolean { // a push to a World repository is the vendor's too: a deploy sends it as a git push (derived-core.ts pushedInput) return typeof e.input?.operationId === 'string' || (e.input?.graphql !== undefined && e.input.graphql !== null) || (e.input?.git !== undefined && e.input.git !== null); } /** The branch entries a root twin still has to settle: `set` rows, not reverted, whose landed copy is absent or says * `failed`/`skipped` (a `deployed` or `refused` copy settles the entry), split into what is offered to the vendor (a * surface write or a git push on a subject the vendor can have) and what is the World's own: a write a door, a screen, the gap, the * clock or a seed made, and any write on a subject only the World's own writes made. */ export function settlingEntries(service: string, root?: string): { offered: TwinAction[]; worldOnly: TwinAction[] } { const parent = parentEntries(service, root); const receipts = receiptsByEntry(parent); const branch = branchEntries(service, root); const reverted = new Set(branch.filter((e) => e.op === 'revert' && e.revertsActionId).map((e) => e.revertsActionId!)); const live = branch.filter((e) => e.op === 'set' && !reverted.has(e.id) && !isTwinBookkeeping(e as TwinAction)) as TwinAction[]; // a subject some surface write made (or the vendor holds: the parent log knows it) is the vendor's; one only the // World's own writes made is not, and nothing written to it is sent const key = (e: TwinAction): string => `${e.subject.type}\u0000${e.subject.id}`; const first = new Map(); for (const e of live) if (!first.has(key(e))) first.set(key(e), e); const vendors = new Set([...[...first].filter(([, e]) => surfaceWrite(e)).map(([k]) => k), ...(parent as Array).filter((e) => !e.landsId).map(key)]); const pending = live.filter((e) => { const r = receipts.get(e.id); return r === undefined || r.status === 'failed' || r.status === 'skipped'; }); return { offered: pending.filter((e) => surfaceWrite(e) && vendors.has(key(e))), worldOnly: pending.filter((e) => !surfaceWrite(e) || !vendors.has(key(e))), }; } /** The entries a root twin offers the vendor (settlingEntries' `offered`). */ export function deployableEntries(service: string, root?: string): TwinAction[] { return settlingEntries(service, root).offered; } /** Entries in groups of the request that made them (their `correlationId`), each group in log order. */ function groupsOf(entries: TwinAction[]): TwinAction[][] { const groups = new Map(); for (const e of entries) { const k = e.correlationId ?? e.id; groups.set(k, [...(groups.get(k) ?? []), e]); } return [...groups.values()]; } const queues = new Map>(); // one performer per twin: wire writes perform in append order /** * PERFORM this twin's deployable entries against its root, in order, checks in front of every one, * stopping at the first refusal or failure. Each outcome lands as the entry's copy with its receipt * on the parent log. `actionIds` narrows to a changeset's (or one write's) entries. */ export async function performEntries(opts: { service: string; root?: string; actionIds?: string[]; at?: string; checks?: Check[]; adapters?: StateSystemAdapters; execute?: RemoteExecute; }): Promise { const key = `${opts.root ?? ''}::${opts.service}`; const prior = queues.get(key) ?? Promise.resolve(); const run = prior.then(() => performNow(opts), () => performNow(opts)); queues.set(key, run.catch(() => undefined)); return run; } /** The root a perform runs against: the sealed one, or — when the caller brings its own executor (a library holding * the person's token in its own process) — the twin's root.json with no credential sealed at all. */ function performRoot(service: string, root: string | undefined, callerExecute: boolean): { sealed: BoundRoot | null; vendor: string } { const head = headOf(service, root); if (head.kind === 'real') return { sealed: head.root, vendor: vendorOf(head.root) }; const unsealed = callerExecute ? readRoot(service, root) : null; if (!unsealed) throw new Error(`the ${service} twin has no root — nothing to perform against`); return { sealed: null, vendor: service }; } async function performNow(opts: Parameters[0]): Promise { const { service, root } = opts; const bound = performRoot(service, root, opts.execute !== undefined); const vendor = bound.vendor; const adapters = opts.adapters ?? stateSystemFor(vendor) ?? stateSystemFor(service); if (!adapters?.perform) throw new Error(`the ${vendor} twin has no perform adapter — a pack names one in its descriptor and registers itself (registerPack)`); const settling = settlingEntries(service, root); const selected = opts.actionIds === undefined ? undefined : new Set(opts.actionIds); const pick = (list: TwinAction[]): TwinAction[] => selected === undefined ? list : list.filter((action) => selected.has(action.id)); // Classify the World's own writes before enforcing vendor order, using the same rules as settlement below. const parent = parentEntries(service, root); const taken = new Set(); const refusedIds = new Set(); for (const e of parent) { if (e.receipt?.status === 'deployed') taken.add(e.aliasOf ?? e.subject.id); else if (e.receipt?.status === 'refused') refusedIds.add(e.subject.id); } for (const id of taken) refusedIds.delete(id); const named = (action: TwinAction): string[] => { const out: string[] = []; const walk = (v: unknown): void => { if (typeof v === 'string') out.push(v); else if (v && typeof v === 'object') for (const x of Object.values(v)) walk(x); }; const i = (action.input ?? {}) as Record; walk(i.path); walk(i.query); walk(i.body); return out; }; const ownWrite = (group: TwinAction[], refused: Set): { reason: string; refusedSubject: boolean } | undefined => { const unsent = adapters.unsent?.(group[0]!.input as Record | undefined); if (unsent) return { reason: unsent, refusedSubject: false }; return named(group[0]!).some((v) => refused.has(v)) ? { reason: 'names a subject the vendor refused: the World\'s alone', refusedSubject: true } : undefined; }; const classifiedOwn = new Map(); if (selected !== undefined) { const orderingRefused = new Set(refusedIds); const offered = groupsOf(settling.offered).filter((group) => { const own = ownWrite(group, orderingRefused); if (!own) return true; for (const action of group) classifiedOwn.set(action.id, own); if (own.refusedSubject) for (const action of group) orderingRefused.add(action.subject.id); return false; }).flat(); const last = offered.reduce((index, action, at) => selected.has(action.id) ? at : index, -1); const earlier = offered.slice(0, last + 1).find((action) => !selected.has(action.id)); if (earlier) throw new DeploymentOrderError(`the ${service} twin has an earlier undeployed entry (${earlier.operation ?? earlier.subject.type}, ${earlier.id}); deploy its changeset first. Selected deployment cannot skip earlier writes on the same vendor.`); } // the caller's executor, or the one built over the sealed credential; an unsealed root has no other const execute = opts.execute ?? buildRemoteExecute(validateRemoteOrigin(bound.sealed!.url, { allowInsecureLoopback: true }), await openRootCredential(bound.sealed!, vendor), authStrategyFor(vendor), getPack(vendor)?.hosts, { custody: rootCustody(bound.sealed!, vendor), vendor }); // an unsealed root's World is where its state resolves (the root given, PROJECT_ROOT, or the working directory) const checks = opts.checks ?? (await loadChecks(bound.sealed ? worldRootOf(bound.sealed) : worldPaths(service, root).root)); const report: DeployReport = { pushed: 0, deployed: [], skipped: [], replayed: [], worldOnly: pick(settling.worldOnly).map((e) => e.id) }; if (opts.actionIds) { const settled = receiptsByEntry(parentEntries(service, root)); for (const id of opts.actionIds) if (settled.get(id)?.status === 'deployed') report.replayed.push(id); } const settle = (action: TwinAction, at: string, receipt: Partial, fields: Record = action.fields ?? {}, vendorSubjectId?: string): void => { confirmAction({ service, actionId: action.id, subject: action.subject, fields, occurredAt: at, ...(vendorSubjectId ? { vendorSubjectId } : {}), receipt, ...(root !== undefined ? { root } : {}) }); }; // the subjects the vendor refused and never took: a request naming one is the World's alone, never sent (the // real-system adapters, "Perform" 3), settled as it landed here let stopped = false; for (const group of groupsOf(pick(settling.offered))) { if (stopped) { report.skipped.push(...group.map((a) => a.id)); continue; } const own = classifiedOwn.get(group[0]!.id) ?? ownWrite(group, refusedIds); if (own) { const at = opts.at ?? worldNow(); for (const action of group) { settle(action, at, { status: 'landed', reason: own.reason }); if (own.refusedSubject) refusedIds.add(action.subject.id); } report.worldOnly.push(...group.map((a) => a.id)); continue; } const at = opts.at ?? worldNow(); // checks in front of every entry: one refused refuses the group, which is one call let verdict: Awaited> = null; for (const action of group) { verdict = await runChecks(checks, action, readTree(service, root)); if (verdict) break; } if (verdict) { for (const action of group) settle(action, at, { status: 'refused', reason: `${verdict.name}: ${verdict.reason}` }); report.refused = { actionId: group[0]!.id, check: verdict.name, reason: verdict.reason }; stopped = true; continue; } // a declared reference to an adopted id is resolved before the pack sees the entry: the vendor is // asked about #7, never the local #3 (docs/contributing/architecture.md#alias-aware-lookup-at-the-request-boundary) const aliases = aliasesFrom(parentEntries(service, root)); const resolved = group.map((action) => { const fields = resolveReferences(service, action.subject.type, action.fields ?? {}, aliases); return fields === action.fields ? action : { ...action, fields }; }); try { const outcome = await adapters.perform(execute, resolved, { ...performContext(service, root, bound.sealed ? rootCredentialFingerprint(bound.sealed) : undefined), localGroup: group }); // the vendor's answer, when the adapter returned one as fields, is what the primary entry's landed copy holds const answered = outcome.data !== null && typeof outcome.data === 'object' && !Array.isArray(outcome.data) ? (outcome.data as Record) : {}; const primary = resolved.find((a) => a.id === outcome.actionId) ?? resolved[0]!; const also = new Map((outcome.also ?? []).map((a) => [a.actionId, a])); const refusedHere = new Map((outcome.refused ?? []).map((r) => [r.actionId, r.reason])); for (const action of resolved) { const refusal = refusedHere.get(action.id); if (refusal !== undefined) { settle(action, at, { status: 'refused', reason: refusal }); refusedIds.add(action.subject.id); continue; } const answeredId = action === primary ? outcome.externalId : also.get(action.id)?.externalId; const externalId = answeredId || aliases.get(`${action.subject.type}:${action.subject.id}`); settle(action, at, { status: 'deployed', ...(action === primary && outcome.url ? { url: outcome.url } : {}) }, { ...action.fields, ...(action === primary ? answered : also.get(action.id)?.data ?? {}) }, externalId || undefined); const data = action === primary ? outcome.data : also.get(action.id)?.data; report.pushed += 1; report.deployed.push({ actionId: action.id, at, ...(externalId ? { externalId } : {}), ...(data !== undefined ? { data } : {}), ...(action === primary && outcome.response ? { response: outcome.response } : {}) }); } if (refusedHere.size) { report.partial = [...refusedHere].map(([actionId, reason]) => ({ actionId, reason })); stopped = true; } } catch (error) { // a write the vendor refuses (a 4xx: it can never be sent as it is) settles the group refused, as a check's // refusal does, so the next deploy moves on to the group after it; anything else failed and stays offered if (error instanceof RefusedWriteError) { for (const action of group) { settle(action, at, { status: 'refused', reason: error.message }); refusedIds.add(action.subject.id); } report.refused = { actionId: group[0]!.id, check: error.check, reason: error.reason }; stopped = true; continue; } const message = error instanceof Error ? error.message : String(error); for (const action of group) settle(action, at, { status: 'failed', reason: message }); report.failed = { actionId: group[0]!.id, error: message }; stopped = true; } } return report; } /** * The write path's second half (serve.ts): a write just appended to a twin whose head is real and * `auto` is performed now. Returns the vendor's id when it minted one, so the answer carries it. * Raises `RefusedWriteError` / `VendorWriteError` for the pack to answer in the vendor's shape. */ /** Whether `performAtHead` would perform an entry now (a twin whose root says `auto`, outside a pack fetch's deferred * group): a caller appending several writes at once appends them one at a time then, each performed before the next. */ export function performsAtHeadNow(service: string, root?: string): boolean { const request = currentCorrelationId(); if (request !== undefined && deferred.has(request)) return false; const head = headOf(service, root); return head.kind === 'real' && head.deploy === 'auto'; } export async function performAtHead(service: string, action: Pick, root?: string): Promise<{ performed: boolean; externalId?: string; data?: unknown }> { // a pack fetch performs its request's entries as one group after the handler (performRequestGroup) const request = currentCorrelationId(); const mark = request !== undefined ? deferred.get(request) : undefined; if (mark) { mark.appended = true; return { performed: false }; } const head = headOf(service, root); if (head.kind !== 'real' || head.deploy !== 'auto') return { performed: false }; let report: DeployReport; try { report = await performEntries({ service, actionIds: [action.id], ...(root !== undefined ? { root } : {}) }); } catch (error) { if (error instanceof DeploymentOrderError) { revertAction({ service, actionId: action.id, occurredAt: worldNow(), ...(root !== undefined ? { root } : {}) }); throw new VendorWriteError(`An earlier ${service} write is still pending; this request was rolled back before reaching the vendor. Retry after that write finishes.`, action.id); } throw error instanceof HeadError ? error : new HeadError(error instanceof Error ? error.message : String(error)); } // under live use an entry the vendor did not take does not stay in the tree: the app was told no, the // world says no — a revert lands (the receipt stays on the original, so the log shows what happened) const undone = report.refused?.actionId === action.id || report.failed?.actionId === action.id; if (undone) revertAction({ service, actionId: action.id, occurredAt: worldNow(), ...(root !== undefined ? { root } : {}) }); if (report.refused?.actionId === action.id) throw new RefusedWriteError(report.refused.check, report.refused.reason, action.id); if (report.failed?.actionId === action.id) throw new VendorWriteError(report.failed.error, action.id); const done = report.deployed.find((d) => d.actionId === action.id); return { performed: done !== undefined, ...(done?.externalId ? { externalId: done.externalId } : {}), ...(done?.data !== undefined ? { data: done.data } : {}) }; } /** The requests a pack fetch is answering, whose entries it performs as one group when the handler returns, and * whether each has appended any. */ const deferred = new Map(); /** Run a pack fetch's handling of one request with its writes' perform deferred to the group (`performRequestGroup`): * its answer, and whether it appended (a request that wrote nothing has no group, and consults no head). */ export async function deferPerform(request: string, fn: () => Promise): Promise<{ value: T; appended: boolean }> { const mark = { appended: false }; deferred.set(request, mark); try { return { value: await fn(), appended: mark.appended }; } finally { deferred.delete(request); } } /** Under `auto`, perform the entries one request made as one call (the real-system adapters, "Perform"): the ids the * vendor gave them by local id, or the vendor's refusal or failure, the request's entries reverted as performAtHead * reverts one. Nothing when the head is not real and auto, or the request wrote nothing the vendor is offered. */ export async function performRequestGroup(service: string, request: string, root?: string): Promise<{ ids: Map; response?: RemoteExecuteResponse; refused?: Array<{ actionId: string; reason: string }> } | RefusedWriteError | VendorWriteError> { const head = headOf(service, root); const ids = new Map(); if (head.kind !== 'real' || head.deploy !== 'auto') return { ids }; const group = deployableEntries(service, root).filter((e) => e.correlationId === request); if (!group.length) return { ids }; let report: DeployReport; try { report = await performEntries({ service, actionIds: group.map((e) => e.id), ...(root !== undefined ? { root } : {}) }); } catch (error) { if (error instanceof DeploymentOrderError) { revertRequest(service, request, group, root); return new VendorWriteError(`An earlier ${service} write is still pending; this request was rolled back before reaching the vendor. Retry after that write finishes.`, group[0]!.id); } throw error instanceof HeadError ? error : new HeadError(error instanceof Error ? error.message : String(error)); } if (report.refused || report.failed) { revertRequest(service, request, group, root); return report.refused ? new RefusedWriteError(report.refused.check, report.refused.reason, report.refused.actionId) : new VendorWriteError(report.failed!.error, report.failed!.actionId); } if (report.partial) revertRequest(service, request, group.filter((e) => report.partial!.some((r) => r.actionId === e.id)), root); for (const d of report.deployed) { const e = group.find((g) => g.id === d.actionId); if (e && d.externalId && d.externalId !== e.subject.id) ids.set(e.subject.id, d.externalId); } const response = report.deployed.find((entry) => entry.response)?.response; return { ids, ...(response ? { response } : {}), ...(report.partial ? { refused: report.partial } : {}) }; } /** Revert what a request's refused entries made, latest first. An entry that is a declared push a screen recorded * (`input.git`, ADR 0031) owns the request's writes after it up to the next such push, its push's effects (the * reactions and vendor moves the pack runs on it), which go with it; any other refused entry goes alone, as the group * it is in. */ function revertRequest(service: string, request: string, refused: TwinAction[], root?: string): void { const pushed = (e: { input?: Record }): boolean => e.input?.git !== undefined && e.input.git !== null; const undo = new Set(); if (refused.some(pushed)) { const made = (branchEntries(service, root) as TwinAction[]).filter((e) => e.correlationId === request && e.op === 'set'); for (const r of refused) { if (!pushed(r)) { undo.add(r.id); continue; } const at = made.findIndex((e) => e.id === r.id); if (at < 0) { undo.add(r.id); continue; } undo.add(r.id); for (const e of made.slice(at + 1)) { if (pushed(e)) break; undo.add(e.id); } } } else for (const r of refused) undo.add(r.id); for (const e of branchEntries(service, root).filter((x) => undo.has(x.id)).reverse()) revertAction({ service, actionId: e.id, occurredAt: worldNow(), ...(root !== undefined ? { root } : {}) }); } /** Wrap a pack's fetch: a `RefusedWriteError` or `VendorWriteError` the head raised becomes the * vendor's own error body (the pack's `shape`), so an app under live use sees what the vendor * would have said. Anything else propagates. */ export function answerVendorErrors(fetch: (request: Request) => Promise, shape: (error: RefusedWriteError | VendorWriteError) => Response): (request: Request) => Promise { return async (request: Request): Promise => { try { return await fetch(request); } catch (error) { if (error instanceof RefusedWriteError || error instanceof VendorWriteError) return shape(error); // a head that could not be bound is a server error, answered as one (never a runtime's fallback // page); anything else the twin threw propagates as it always did if (error instanceof HeadError) return Response.json({ error: error.message }, { status: 500 }); throw error; } }; }