import { parseExactJson } from './exact-json.ts'; // Transaction/action log: observed facts and local transaction commits are separate. // // The observed-event log (`events.jsonl`) holds only what was observed upstream // (connector pulls) or confirmed after a push. Local simulator/fork writes do NOT // go there — they are transaction commits in `actions.jsonl`, projected OVER the // observed mirror to produce the twin's current state. Undo is a `revert` commit; // a push that succeeds appends a `confirm` commit mapping the local transaction // to the observed event it produced, which SUPPRESSES the local projection (the // fact is now carried by the observed log, so it must not be double-counted). // // Projection = observed mirror, then apply each `set` transaction in order, // skipping any transaction that was reverted or confirmed. import { canonicalStatePath, withHistoryLock } from './ancestry.ts'; import { AsyncLocalStorage } from 'node:async_hooks'; import { randomUUID } from 'node:crypto'; import { dirname, join } from 'node:path'; import { canonicalJson, subjectKey } from './hash.ts'; import type { SubjectFields } from './hash.ts'; import { appendDurable, eventsLockPath, ownerStoreRoots, projectionLockPath, twinLog, withFileLock, withoutIdentityClaim, worldPaths } from './storage.ts'; import { landAsPlaceholder, placeholderPullActive } from './placeholder-remote.ts'; import { aliasesFrom, appendToBranchLog, dropCheckpoint, landedCopy, landedIds, parentEntries, readTree, treeStamp, type Receipt } from './log.ts'; import { inVendorMove, refuseReadOnlyWrite } from './request-scope.ts'; import { getActiveWorldStore, storageLockScope, type WorldLockOptions } from './world-store.ts'; import { currentTraceparent, traceparentForDelivery } from './trace-context.ts'; import type { TwinResource } from './serve.ts'; export type TwinActionOp = 'set' | 'revert'; export type TwinActionPreconditionOp = 'exists' | 'not_exists' | 'eq' | 'neq' | 'version_eq'; export type TwinActionPrecondition = { subject: { type: string; id: string }; field: string; op: TwinActionPreconditionOp; value?: unknown; }; export type TwinActionRevertSpec = { strategy: 'inverse' | 'suppress' | 'compensating-action'; operation?: string; fields?: SubjectFields; }; // Multi-resource transaction projection (the twins architecture notes → "Local // Transaction Commit Packet"). The flat single-subject `fields` overlay is the // common shorthand; `projection` is the richer form for a transaction that // atomically touches MORE THAN ONE resource (e.g. create a PR + a review), deletes // a resource, or emits a delivery (webhook/notification) the twin should fire. export type ProjectedResource = { type: string; id: string; fields: SubjectFields }; export type ProjectedResourcePatch = { type: string; id: string; fields: SubjectFields }; export type ProjectedResourceRef = { type: string; id: string }; export type ProjectedDelivery = { kind: 'webhook' | 'event' | 'notification'; target: string; payload: Record }; export type ActionProjection = { creates?: ProjectedResource[]; updates?: ProjectedResourcePatch[]; deletes?: ProjectedResourceRef[]; emits?: ProjectedDelivery[]; }; export type TwinAction = { id: string; service: string; op: TwinActionOp; subject: { type: string; id: string }; occurredAt: string; actor?: { kind: 'agent' | 'human' | 'bot' | 'system'; id?: string }; /** Optional vendor operation name, e.g. `issue.update` or `message.send`. */ operation?: string; /** The caller's own request key, when it asked for at-most-once. Provenance, AND the marker that * makes replay identity ignore `occurredAt`: the whole point of a request key is that a retry * arriving at a different millisecond is the SAME request, so comparing the two bodies must not * fail on the timestamp. Without this, a caller that did not pin `occurredAt` got a thrown * "Conflicting duplicate twin action" — a 500 where it had asked for idempotence. */ idempotencyKey?: string; /** Raw operation input (provenance); not projected — `fields`/`projection` carry the state change. */ input?: Record; /** Preconditions are evaluated against the current projected twin state before append. */ preconditions?: TwinActionPrecondition[]; // op 'set': the local field changes to overlay on `subject` (single-resource shorthand). fields?: SubjectFields; // op 'set': the richer multi-resource transaction projection (optional; composes with `fields`). projection?: ActionProjection; // op 'revert': the prior action id being undone. revertsActionId?: string; /** A pending row a snapshot import planted (contract "A snapshot import never plants a push"): * still local state the projection serves, never awaiting push until released on purpose. */ quarantined?: { at: string; by: string }; /** Optional machine-readable hint for how a UI/pack should construct a revert. */ revert?: TwinActionRevertSpec; /** * Request-scoped correlation id (D3 — the purpose-3 audit trail: "who reviewed the * change that caused this real write"). Always present on an appended action — * appendAction/appendActionIfAbsent generate one when the caller doesn't supply it — * and threaded through to the push-ledger row(s) a push against this action produces * (see pushLedger.ts), so an action row and its push-ledger row(s) join on this id * alone, with no dependence on actionId/pushId naming conventions. */ correlationId?: string; /** The W3C `traceparent` of the request that caused this action, when it carried a valid one * (trace-context.ts). Authoring metadata like correlationId: excluded from replay identity. */ traceparent?: string; /** * The action's MERGE BASE against the remote (runtime contract R14, non-fast-forward * rule): per touched subject, the observed mirror's remote ref (shadow.ts remoteRefs) * at authoring time — null when the mirror had never seen the subject. Stamped by the * appenders on every `set` action; pushTransaction compares these refs again at push * time and REFUSES when any has moved (someone else changed the remote), demanding * fetch + reconcile. Authoring metadata like correlationId: excluded from replay * identity, so an identical retry converges on the first commit's (older, safer) basis. */ }; export type TwinTransactionCommit = TwinAction; export type TwinTransactionCommitOp = TwinActionOp; export type TwinTransactionPrecondition = TwinActionPrecondition; export type TwinTransactionRevertSpec = TwinActionRevertSpec; export class TwinActionPreconditionError extends Error { constructor(readonly actionId: string, readonly failed: TwinActionPrecondition) { super(`Twin transaction precondition failed for ${actionId}: ${failed.subject.type}:${failed.subject.id}.${failed.field} ${failed.op}`); this.name = 'TwinActionPreconditionError'; } } function actionsPath(service: string, root?: string): string { return join(dirname(worldPaths(service, root).events), 'actions.jsonl'); } // Canonical, as the history lock's path is (ancestry.ts withHistoryLock), so a take inside it is seen as nested in the same // directory whatever the path it was asked by (/var or /private/var). The file is the same one, so a take by another // process through the other spelling still excludes this one. const actionsLock = (service: string, root?: string): string => join(canonicalStatePath(worldPaths(service, root).dir), 'actions.jsonl.lock'); const projectionLock = (service: string, root?: string): string => { const paths = worldPaths(service, root); return projectionLockPath({ ...paths, dir: canonicalStatePath(paths.dir) }); }; /** Every appended action carries a correlationId — generate one when the caller * hasn't supplied it, so downstream joins (push ledger, logs) always have an id * to key on (D3). Preserves a caller-supplied id (e.g. propagated from an HTTP * request id) so a whole call chain can share one. */ function withCorrelationId(action: TwinAction): TwinAction { // The wire's request id (the addressed service stamps every response with one and threads it // into the handler's async context) is the correlation when the caller supplies none — the // join from a request on the wire to the action rows it caused, with no pack involved. const correlated = action.correlationId ? action : { ...action, correlationId: currentCorrelationId() ?? randomUUID() }; // the request's W3C trace context (trace-context.ts) is stamped the same way, from the handler's async context. What the // vendor makes on its own while a request is served (its actor is the system's, or a vendor move) is a span of its own // in that trace, so it is never joined to the request's caller (served-world's timeline), who did not make it const vendors = action.actor?.kind === 'system' || inVendorMove(); const traceparent = correlated.traceparent === undefined ? (vendors ? traceparentForDelivery() : currentTraceparent()) : undefined; return traceparent ? { ...correlated, traceparent } : correlated; } /** Subjects a `set` action touches: its own subject, every projection resource, and every * precondition subject — a precondition established the action's validity against that * subject's state, so remote movement there is drift for this action too. */ export function touchedSubjects(action: TwinAction): Array<{ type: string; id: string }> { const out = new Map(); out.set(subjectKey(action.subject), action.subject); for (const r of [ ...(action.projection?.creates ?? []), ...(action.projection?.updates ?? []), ...(action.projection?.deletes ?? []), ]) out.set(subjectKey(r), { type: r.type, id: r.id }); for (const p of action.preconditions ?? []) out.set(subjectKey(p.subject), p.subject); return [...out.values()]; } // THE LOG'S IDS, MEMOIZED per store and per log file, as a read's tree is (log.ts): named by the file's size and // mtime. An append's ordinal asks only which ids are taken, and answering it by re-reading and re-parsing the whole log // made every append O(log) and a seed of N records O(N^2) (a 7,479-reading Timestream seed stalled its twin for // minutes). The appender, holding the lock, adds its own id and re-keys; any other writer's append changes the key and // the next caller reads afresh. type IdMemo = { key: string; ids: Set }; const idMemos = new WeakMap>(); function logKey(path: string): string { const s = getActiveWorldStore().stat(path); return s ? `${s.size}:${s.mtimeMs}` : '-'; } function idMemoSlot(): Map { const store = getActiveWorldStore(); let memos = idMemos.get(store); if (!memos) { memos = new Map(); idMemos.set(store, memos); } return memos; } function actionIds(service: string, root?: string): ReadonlySet { const path = actionsPath(service, root); const memos = idMemoSlot(); const key = logKey(path); const held = memos.get(path); if (held && held.key === key) return held.ids; const ids = new Set(listActions(service, root).map((a) => a.id)); memos.set(path, { key, ids }); return ids; } /** A service's projection lock, under its history lock: one directory's locks are taken history, projection, * actions, events, in that order (architecture, the history lock). */ function withProjection(service: string, root: string | undefined, fn: () => T, options: WorldLockOptions = {}): T { const scope = storageLockScope(options); return withHistoryLock(worldPaths(service, root).dir, () => withFileLock(projectionLock(service, root), fn, scope), scope); } function appendActionRaw(action: TwinAction, root?: string): void { appendActionsRaw([action], root); } /** One service's actions appended as ONE store append, in order: the same lines `appendActionRaw` writes one at a time. */ function appendActionsRaw(actions: readonly TwinAction[], root?: string): void { if (!actions.length) return; const service = actions[0]!.service; const path = actionsPath(service, root); // No mkdir: every append is made holding the projection lock (withProjection), whose file is in this same directory // and was made there by the take. const memos = idMemoSlot(); const held = memos.get(path); const current = held !== undefined && held.key === logKey(path); const data = actions.map((action) => `${JSON.stringify(action)}\n`).join(''); // the log is the branch log a read's tree is folded from: the append extends that memo too (log.ts appendToBranchLog) const after = withHistoryLock(worldPaths(service, root).dir, () => appendToBranchLog(service, root, data, () => appendDurable(path, data)), { operation: 'action append' }); if (current) { for (const action of actions) held.ids.add(action.id); held.key = after ?? logKey(path); } else memos.delete(path); for (const action of actions) { twinLog('action.append', { service: action.service, id: action.id, op: action.op, correlationId: action.correlationId }); appendObserver?.(action, root); } } /** ONE observer of appended entries (state-system.ts: the runtime's `deploy: auto` hook). Called * under the append locks, so it must only schedule work, never do it. */ let appendObserver: ((action: TwinAction, root: string | undefined) => void) | undefined; export function observeAppends(observer: ((action: TwinAction, root: string | undefined) => void) | undefined): void { appendObserver = observer; } /** The placeholder remote (contract section of that name): while a service's placeholder-pull * window is open, a `set` write is a pull, not a commit — it lands as the placeholder's entries and no * action row exists. Returns the action the caller hands back (its id names what landed). */ function landIfPlaceholderPull(action: TwinAction, root?: string): TwinAction | null { if (action.op !== 'set' || !placeholderPullActive(action.service, root)) return null; const { entries } = landAsPlaceholder(action, root); twinLog('action.placeholder', { service: action.service, id: action.id, op: action.op, entries: entries.length }); return { ...action, id: entries.at(-1)?.id ?? action.id }; } function replayBody(action: TwinAction): string { const { correlationId: _correlationId, traceparent: _traceparent, ...stampedBody } = action; // A confirmation is content-addressed by the observed event ids. Its timestamp is observation // metadata. Two reconcilers confirming the same bytes at different wall-clock // instants must therefore converge on the first durable confirmation rather than conflict. // A KEYED write is the same request however long the retry took, so its timestamp is observation // metadata too — exactly as a confirmation's is. Comparing it would turn the retry the key was // asked for into a hard conflict. const body = stampedBody.idempotencyKey !== undefined ? (({ occurredAt: _occurredAt, ...rest }) => rest)(stampedBody) : stampedBody; return canonicalJson(body); } function existingExactAction(action: TwinAction, root?: string): TwinAction | undefined { const existing = listActions(action.service, root).find((candidate) => candidate.id === action.id); if (!existing) return undefined; if (replayBody(existing) !== replayBody(action)) { throw new Error(`Conflicting duplicate twin action: ${action.service}/${action.id}`); } return existing; } /** The request-scoped correlation id (D3): for the duration of one handler call, the id a pack fetch mints for the * request (a caller's `x-twins-request-id` is recorded with each write as provenance, never as the group), or, under * the kernel fetch adapter, the wire's `x-twins-request-id`; read by appendAction as the default. */ // created on first use, never at import: a browser bundle carrying the kernel carries this module and has // no AsyncLocalStorage (see serve.ts identitySlot) let correlationStore: AsyncLocalStorage | undefined; const correlationScope = (): AsyncLocalStorage => (correlationStore ??= new AsyncLocalStorage()); export function runWithCorrelationId(id: string, fn: () => T): T { return correlationScope().run(id, fn); } export function currentCorrelationId(): string | undefined { return correlationScope().getStore(); } export function appendAction(action: TwinAction, root?: string): TwinAction { refuseReadOnlyWrite(action.service); // a read-only request writes nothing (request-scope.ts) // Evaluate and append under the service projection and actions locks. A precondition is a // compare-and-set, not an advisory validation: checking outside either lock would let another // writer invalidate it before this action lands. The shadow basis is stamped under the same // lock so the recorded merge base is the mirror the preconditions were checked against. return withProjection(action.service, root, () => withFileLock(actionsLock(action.service, root), () => { const stamped = withCorrelationId(action); assertPreconditions(stamped, root); const placeholder = landIfPlaceholderPull(stamped, root); if (placeholder) return placeholder; appendActionRaw(stamped, root); return stamped; }, { operation: 'action append' }), { operation: 'action append' }); } /** Append `action` only if no exact action with the same id already exists — the whole * replay/precondition/append decision runs under the service projection + actions locks, so it's * atomic across processes (two concurrent identical writes converge to ONE action; distinct * writes both land). A reused id with different content fails loudly. */ export function appendActionIfAbsent(action: TwinAction, root?: string): { action: TwinAction; appended: boolean; placeholder?: true } { refuseReadOnlyWrite(action.service); return withProjection(action.service, root, () => withFileLock(actionsLock(action.service, root), () => { const identified = withCorrelationId(action); // An exact retry is already committed. Resolve it before re-evaluating author-time // preconditions against the state that first commit intentionally changed — and // before paying the basis stamp's event-log read (the replayed path stays cheap). const existing = existingExactAction(identified, root); if (existing) return { action: existing, appended: false }; const stamped = identified; assertPreconditions(stamped, root); const placeholder = landIfPlaceholderPull(stamped, root); if (placeholder) return { action: placeholder, appended: true, placeholder: true }; appendActionRaw(stamped, root); return { action: stamped, appended: true }; }, { operation: 'action append' }), { operation: 'action append' }); } /** * Append `build(n)` as an OCCURRENCE: the nth time this exact write has been made. * * A local vendor write is an occurrence, not a replay — two calls are two actions, even * byte-identical in the same instant (docs/contributing/architecture.md, "The state kernel", * "A local write is an occurrence"). `appendActionIfAbsent` cannot express that: its identity is content, and * content provably cannot separate "the same request delivered twice" from "the same change made * twice". So a caller wanting at-most-once passes an explicit key and uses that function; a caller * recording what actually happened uses this one. * * The ordinal keeps every EXISTING action id byte-identical: occurrence 0 is `build(0)`'s own id, * and only a genuine repeat becomes `#1`, `#2`. It is derived under the same projection + * actions locks as the append, so two processes racing take different ordinals rather than * colliding, and it is deterministic — replaying one sequence of writes onto a fresh root yields * the same ordinals, which is what serve-path determinism requires. */ export function appendActionOccurrence(base: TwinAction, root?: string): { action: TwinAction; appended: boolean; placeholder?: true } { refuseReadOnlyWrite(base.service); return withProjection(base.service, root, () => withFileLock(actionsLock(base.service, root), () => { const stamped = occurrenceOf(base, actionIds(base.service, root)); assertPreconditions(stamped, root); const placeholder = landIfPlaceholderPull(stamped, root); if (placeholder) return { action: placeholder, appended: true, placeholder: true }; appendActionRaw(stamped, root); return { action: stamped, appended: true }; }, { operation: 'action append' }), { operation: 'action append' }); } /** * Append several writes of ONE service as occurrences, in order, under one projection + actions lock and as one store * append: each lands with the id, ordinal and correlation `appendActionOccurrence` would give it called once per write * in the same order (a write's ordinal counts the batch's earlier writes as taken). Preconditions are checked against * the state the earlier ones made, which only the one-at-a-time path sees. While a placeholder pull is open a write * lands as the placeholder's entries, as `appendActionOccurrence`'s does. */ export function appendActionOccurrences(bases: readonly TwinAction[], root?: string): Array<{ action: TwinAction; appended: boolean; placeholder?: true }> { if (!bases.length) return []; const service = bases[0]!.service; if (bases.some((base) => base.service !== service)) throw new Error(`appendActionOccurrences: one service per batch, got ${[...new Set(bases.map((base) => base.service))].join(', ')}`); if (bases.some((base) => base.preconditions?.length)) throw new Error('appendActionOccurrences: a write with preconditions is appended alone'); refuseReadOnlyWrite(service); return withProjection(service, root, () => withFileLock(actionsLock(service, root), () => { const logged = actionIds(service, root); const batch = new Set(); const taken = { has: (id: string) => batch.has(id) || logged.has(id) }; const landed: Array<{ action: TwinAction; appended: boolean; placeholder?: true }> = []; let unwritten: TwinAction[] = []; for (const base of bases) { const stamped = occurrenceOf(base, taken); const placeholder = landIfPlaceholderPull(stamped, root); if (placeholder) { // no action row: its id is not taken, as it is not in the log the one-at-a-time path reads // the lines before it are written first, so the log and the pull keep the writes' order appendActionsRaw(unwritten, root); unwritten = []; landed.push({ action: placeholder, appended: true, placeholder: true }); continue; } batch.add(stamped.id); unwritten.push(stamped); landed.push({ action: stamped, appended: true }); } appendActionsRaw(unwritten, root); return landed; }, { operation: 'action append' }), { operation: 'action append' }); } /** The occurrence rule, shared by both appenders that use it — the ordinal AND the merge base. * Pure over (base, the log as it stands): the caller holds the lock. */ function occurrenceOf(base: TwinAction, taken: Pick, 'has'>): TwinAction { { let ordinal = 0; while (taken.has(occurrenceId(base.id, ordinal))) ordinal += 1; // an occurrence past the first is its own entry: the tree it changes is read at the head, and a // Push onto a moved parent is refused by position, not by a basis stamped here. return withCorrelationId({ ...base, id: occurrenceId(base.id, ordinal) }); } } /** Occurrence 0 IS the base id — so nothing that exists today changes shape. The appender owns * this math; a caller passing an already-ordinalled id would stack them (`…#1#1`). */ export function occurrenceId(base: string, ordinal: number): string { return ordinal === 0 ? base : `${base}#${ordinal}`; } export type AtomicActionDecision = | { kind: 'skip'; value: T } | { kind: 'append'; action: TwinAction; value: T; /** `'occurrence'` (default) appends every call, with the ordinal and the first occurrence's * merge base. `'caller'` is at-most-once on the caller's own identity — what an * `idempotencyKey` or `actionId` means. It rides on the DECISION rather than on the * function's arguments because only the callback knows which write it chose. */ identity?: 'occurrence' | 'caller'; }; /** * Evaluate current projected state and optionally append one action under ONE service projection * transaction (the shared projection lock plus the action-log lock). This is the narrow * state-dependent seam for vendor operations whose acceptance and resulting fields depend on the * latest observed + local projection (for example, immutable version publish). * * The callback must remain synchronous and side-effect free: it computes a decision from the * supplied snapshot. Durable state changes only through the returned action, which this helper * appends before releasing the lock. */ export function decideAndAppendAction( service: string, decide: (resources: TwinResource[]) => AtomicActionDecision, root?: string, /** A narrower indexed snapshot, read under the same lock; it must cover every decision and precondition. */ read: () => TwinResource[] = () => projectResources(service, root), ): { value: T; action?: TwinAction; appended: boolean; placeholder?: true } { return withProjection(service, root, () => withFileLock(actionsLock(service, root), () => { const resources = read(); const decision = decide(resources); if (decision.kind === 'skip') return { value: decision.value, appended: false }; refuseReadOnlyWrite(service); // a decision to write is the write a read-only request may not make if (decision.action.service !== service) { throw new Error(`Atomic action service mismatch: expected ${service}, got ${decision.action.service}`); } const identified = withCorrelationId(decision.action); // This seam was left on content-dedupe when the occurrence ruling first landed, and 21 packs // write through it — so they kept losing a write that returned a subject to a value it held // one instant earlier, which is the whole defect. if (decision.identity === 'caller') { const existing = existingExactAction(identified, root); if (existing) return { value: decision.value, action: existing, appended: false }; const stamped = identified; assertPreconditionsAgainst(stamped, resources); const placeholder = landIfPlaceholderPull(stamped, root); if (placeholder) return { value: decision.value, action: placeholder, appended: true, placeholder: true }; appendActionRaw(stamped, root); return { value: decision.value, action: stamped, appended: true }; } const stamped = occurrenceOf(decision.action, actionIds(service, root)); assertPreconditionsAgainst(stamped, resources); const placeholder = landIfPlaceholderPull(stamped, root); if (placeholder) return { value: decision.value, action: placeholder, appended: true, placeholder: true }; appendActionRaw(stamped, root); return { value: decision.value, action: stamped, appended: true }; }, { operation: 'action decision' }), { operation: 'action decision' }); } export function appendTransactionCommit(commit: TwinTransactionCommit, root?: string): TwinTransactionCommit { return appendAction(commit, root); } export function listActions(service: string, root?: string): TwinAction[] { const path = actionsPath(service, root); return getActiveWorldStore() .readLines(path) .filter((line) => line.trim()) .map((line) => parseExactJson(line) as TwinAction); } function projectedField(resource: TwinResource | undefined, field: string): unknown { if (!resource) return undefined; return resource[field]; } /** The kernel's ONE deterministic check: does `actual` satisfy the precondition expression? * Shared by write-time preconditions (here), plan conflict detection (plan.ts) and changeset * verifiers (changeset.ts) — one evaluator, so a check means the same thing everywhere. */ export function checkPrecondition(precondition: TwinActionPrecondition, actual: unknown): boolean { switch (precondition.op) { case 'exists': return actual !== undefined; case 'not_exists': return actual === undefined; case 'eq': case 'version_eq': return Object.is(actual, precondition.value); case 'neq': return !Object.is(actual, precondition.value); default: return false; } } /** Look a precondition subject's field up in projected resources (undefined = no resource or * no field — exactly what `exists`/`not_exists` distinguish). */ export function projectedPreconditionValue(precondition: TwinActionPrecondition, resources: TwinResource[]): unknown { const resource = resources.find((r) => r.type === precondition.subject.type && r.id === precondition.subject.id); return projectedField(resource, precondition.field); } function assertPreconditionsAgainst(action: TwinAction, resources: TwinResource[]): void { if (!action.preconditions?.length) return; for (const precondition of action.preconditions) { const actual = projectedPreconditionValue(precondition, resources); if (!checkPrecondition(precondition, actual)) throw new TwinActionPreconditionError(action.id, precondition); } } function assertPreconditions(action: TwinAction, root?: string): void { // Most writes carry none: projecting (and cloning) the whole tree to check nothing cost every append O(tree). if (!action.preconditions?.length) return; assertPreconditionsAgainst(action, projectResources(action.service, root)); } /** * Project the action log over the observed mirror → current twin resources. * `set` actions overlay fields (creating subjects that don't exist in the mirror); * reverted and confirmed actions are skipped (confirmed facts come from the * observed log instead, so they are not projected twice). */ /** THE TREE (log.ts): what a read sees — the nearest checkpoint plus the entries since; the parent's * entries, then this branch's, skipping any the parent already holds. `until` folds only the * branch entries BEFORE that id — the state a write saw at its own append (the rebase's * evaluation point). */ export function projectResources(service: string, root?: string, opts: { until?: string } = {}): TwinResource[] { return readTree(service, root, opts); } /** A read of another pack's store that cannot choose: the subject it looks for (or, with none named, the store itself) * is held by more than one service of the World. A reader answers it as the vendor answers a credential it cannot * resolve; it is never a server error. */ export class OwnerStoreAmbiguousError extends Error { constructor(owner: string, roots: string[], subject?: { type: string; id: string }) { super(`${subject ? `${subject.type} ${subject.id} of ` : ''}${owner}'s store is held by more than one service of this World (${roots.join(', ')}); a cross-pack read cannot choose between them`); this.name = 'OwnerStoreAmbiguousError'; } } /** One owner store as a cross-pack reader sees it: its rows (frozen, shared by every read until the store changes) and * an index by `type:id`. Memoized per (owner, root) on the store's `treeStamp`, so a reader resolving a token on every * request folds and copies the owner's tree only when the owner has written since. */ type OwnerIndex = { stamp: string; rows: readonly TwinResource[]; byKey: Map }; const ownerIndexes = new Map(); function ownerIndex(owner: string, root: string): OwnerIndex { const key = `${owner}\0${root}`; const stamp = treeStamp(owner, root); const held = ownerIndexes.get(key); if (held && held.stamp === stamp) return held; const rows = readTree(owner, root).map((r) => Object.freeze(r)); const index: OwnerIndex = { stamp, rows: Object.freeze(rows), byKey: new Map(rows.map((r) => [`${r.type}:${r.id}`, r])) }; ownerIndexes.set(key, index); return index; } /** * ANOTHER pack's rows, read by contract (architecture A3: one vendor's store split across two packs, googleoauth's tokens * read by webrisk; the reader's manifest declares the pair, `ownerReads`): the * owner's tree, from wherever the World keeps the owner's store (`ownerStoreRoots`). Read only: the rows are frozen and * shared. It claims no journal identity (the twin answering is the reader). * * With `subject`, the store that holds that subject (the token a request presents): `[]` when none does, and * `OwnerStoreAmbiguousError` only when more than one does, so a second service running the owning pack never breaks a * lookup of what only one of them issued. Without it, the one store there is, and `OwnerStoreAmbiguousError` when the * World holds two. */ export function projectOwnerResources(owner: string, root?: string, subject?: { type: string; id: string }): readonly TwinResource[] { return withoutIdentityClaim(() => { const roots = ownerStoreRoots(owner, root); if (!subject) { if (roots.length > 1) throw new OwnerStoreAmbiguousError(owner, roots); return roots[0] ? ownerIndex(owner, roots[0]).rows : []; } const key = `${subject.type}:${subject.id}`; const holding = roots.filter((r) => ownerIndex(owner, r).byKey.has(key)); if (holding.length > 1) throw new OwnerStoreAmbiguousError(owner, holding, subject); return holding[0] ? ownerIndex(owner, holding[0]).rows : []; }); } /** The local → vendor id aliases the landed copies carry: a read by the id a caller was handed before * its write was performed resolves to the row the vendor now owns. */ export function subjectAliases(service: string, root?: string): Map { const out = new Map(); for (const [from, to] of aliasesFrom(parentEntries(service, root))) out.set(from, to); return out; } /** Resolve a subject id through the aliases: the vendor's id when a confirm rebound it, else the id itself. */ export function resolveSubjectId(service: string, type: string, id: string, root?: string): string { return subjectAliases(service, root).get(`${type}:${id}`) ?? id; } /** * Confirm a local action after it was pushed to the real vendor: record the * confirmed fields as an OBSERVED event (origin 'external' — it's now real) and * append a `confirm` action mapping the local action → that observed event id. * Projection then drops the local action (the fact lives in the observed log), so * the change is counted exactly once. Returns the observed event id. */ export function confirmAction(opts: { service: string; actionId: string; subject: { type: string; id: string }; fields: SubjectFields; /** Additional observed resources landed by the same compound action, under the same lock. */ additionalObservations?: Array<{ subject: { type: string; id: string }; fields: SubjectFields }>; /** The subject id the VENDOR minted for this write (the push outcome's externalId). When it * differs from the local id, the landed copy carries the vendor's id and `aliasOf` names the * local one, so a read by either id finds the row. */ vendorSubjectId?: string; /** the receipt on the landed copy; `deployed` when omitted (the push performed it) */ receipt?: Partial; occurredAt: string; root?: string; }): { observedEventId: string; observedEventIds: string[] } { refuseReadOnlyWrite(opts.service); // LANDING (log.ts): the entry is copied to the parent log with its receipt — no confirm row, no // suppression; the fold skips a branch entry the parent holds. const paths = worldPaths(opts.service, opts.root); const base = listActions(opts.service, opts.root).find((a) => a.id === opts.actionId) ?? ({ id: opts.actionId, service: opts.service, op: 'set', subject: opts.subject, occurredAt: opts.occurredAt } as TwinAction); const receipt: Receipt = { status: 'deployed', at: opts.occurredAt, ...(opts.vendorSubjectId ? { externalId: opts.vendorSubjectId } : {}), ...(opts.receipt ?? {}) }; const copies = [ ...(opts.additionalObservations ?? []).map((o) => landedCopy(base, receipt, { subject: o.subject, fields: o.fields })), landedCopy(base, receipt, { subject: opts.subject, fields: opts.fields, ...(opts.vendorSubjectId ? { vendorSubjectId: opts.vendorSubjectId } : {}) }), ]; withProjection(opts.service, opts.root, () => { withFileLock(eventsLockPath(paths), () => { const held = landedIds(parentEntries(opts.service, opts.root)); for (const copy of copies) if (!held.has(copy.id)) appendDurable(paths.events, `${JSON.stringify(copy)}\n`); }, { operation: 'action confirmation' }); dropCheckpoint(opts.service, opts.root); }, { operation: 'action confirmation' }); const observedEventIds = copies.map((c) => c.id); return { observedEventId: observedEventIds.at(-1)!, observedEventIds }; } export type RevertOutcome = | { status: 'reverted'; revertId: string } | { status: 'already-reverted' } | { status: 'confirmed' } | { status: 'not-found' } | { status: 'not-revertable'; op: TwinActionOp }; /** * Revert one pending `set` action — decision AND append under the service projection + * actions locks, so a concurrent writer (a connector confirming the same action from * another process) cannot land between the check and the revert: the whole read-decide- * append is ONE critical section. Idempotent: a repeat answers 'already-reverted'. * Only `set` rows are revertable — reverting a revert or a confirm is a category error. */ export function revertAction(opts: { service: string; actionId: string; occurredAt: string; root?: string }): RevertOutcome { refuseReadOnlyWrite(opts.service); return withProjection(opts.service, opts.root, () => withFileLock(actionsLock(opts.service, opts.root), (): RevertOutcome => { const all = listActions(opts.service, opts.root); const target = all.find((a) => a.id === opts.actionId); if (target === undefined) return { status: 'not-found' }; if (target.op !== 'set') return { status: 'not-revertable', op: target.op }; // landed and taken by the vendor: not revertable; a landed copy the vendor refused or failed is const landedCopy = parentEntries(opts.service, opts.root).find((e) => e.id === opts.actionId || e.landsId === opts.actionId); if (landedCopy && landedCopy.receipt?.status !== 'refused' && landedCopy.receipt?.status !== 'failed') return { status: 'confirmed' }; if (all.some((a) => a.op === 'revert' && a.revertsActionId === opts.actionId)) return { status: 'already-reverted' }; const revert: TwinAction = withCorrelationId({ id: `revert:${opts.actionId}`, service: opts.service, op: 'revert', subject: target.subject, occurredAt: opts.occurredAt, revertsActionId: opts.actionId, }); appendActionRaw(revert, opts.root); return { status: 'reverted', revertId: revert.id }; }, { operation: 'action revert' }), { operation: 'action revert' }); } /** The LOCAL OVERLAY: pending actions (set, not reverted, not yet confirmed) — the divergence * from the mirror, what a twin's projection folds over the observed state. A QUARANTINED row * (contract "A snapshot import never plants a push") is still local state and stays here; it * leaves only the PUSHABLE suffix below. */ export function pendingActions(service: string, root?: string): TwinAction[] { const actions = listActions(service, root); const reverted = new Set(actions.filter((a) => a.op === 'revert').map((a) => a.revertsActionId)); const landed = landedIds(parentEntries(service, root)); return actions.filter((a) => a.op === 'set' && !reverted.has(a.id) && !landed.has(a.id)); } /** A twin's OWN bookkeeping in its action log — a subject type beginning with `_` (stripe's * `_idempotency` store, for one): part of the overlay the twin serves from, never a change the * app made. It is not pushed or deployed. It is not in the log a user reads, a diff or a changeset either, except the * World's people (`isWorldPerson`). */ export function isTwinBookkeeping(action: Pick): boolean { return action.subject.type.startsWith('_'); } /** A person a twin's pages sign in (`_person`, people.ts): bookkeeping to the kernel, and the one bookkeeping the log * a user reads, the diff and every changeset carry, so an account replayed into another World signs in there. A * replay writes its committed row (the email, the password's hash and what the sign-up keeps), never the sign-up. * ADR 0025. */ export function isWorldPerson(action: Pick): boolean { return action.subject.type === '_person'; } /** Whether an action is in the World's history as a user reads it, diffs it and cuts changesets from it. */ export function inWorldHistory(action: Pick): boolean { return !isTwinBookkeeping(action) || isWorldPerson(action); } /** The PUSHABLE suffix — `log origin..HEAD` as the push arm, the pending door, plans and the * unpushed count read it: the overlay minus quarantined rows (an import is a copy, not a * decision; releasing a quarantined row is an explicit act, never a scheduler's) and minus the * twin's own bookkeeping. */ export function pushablePendingActions(service: string, root?: string): TwinAction[] { return pendingActions(service, root).filter((a) => a.quarantined === undefined && !isTwinBookkeeping(a)); }