import { resolveReferences } from './references.ts'; import { withHistoryLocks } from './ancestry.ts'; import { captureHistory, captureParentHistory, historyChanges, historyEntries, historyPrefix, readHistoryView, type HistoryReference } from './history.ts'; import { worldPaths } from './storage.ts'; // The changeset primitive — "commit" for operational reality (docs/concepts/the-model.md, v0). // // Everything upstream of it already exists: worlds are the working copy, forks are branches, // and each twin's `actions.jsonl` (actions.ts) is the history. What was missing is the object // in between: a NAMED, BOUNDED, REPLAYABLE slice of that history — and the `diff` that shows a // human what a session actually did before anything becomes real. // // Three objects, in dependency order: // // MARKER a cross-service BASE POSITION — per-ledger `{count, lastActionId}` pairs captured // at one instant. Not a global sequence number: a world has N independent append-only // ledgers with no shared clock, so the only honest "where we were" is the tuple of // per-ledger positions. `lastActionId` is what makes it VERIFIABLE — a ledger that was // rewritten, purged, or rebuilt under a marker fails loudly at diff time instead of // silently reporting the wrong delta. // // DELTA every action appended after the marker, across every ledger, ordered by // `occurredAt` with stable ledger/row ties (a timeline, not cross-vendor causality), grouped by vendor // for rendering. // // CHANGESET a delta frozen into a content-addressed object: `{id, world, base, actions, // approvals, applied}` + `contentHash`. The hash covers the IMMUTABLE body only // (id/world/base/actions), so a later approval or push receipt appended to the object // cannot invalidate the hash the approval bound to — the point of content-addressing. // // REPLAY is the CI primitive. It feeds recorded actions back through `applyTwinWrite` — the // KERNEL write path, not HTTP — into another world's twins. // // Replay is idempotent because it SAYS SO, not because content happens to hash the same. A local // vendor write is an OCCURRENCE — two calls are two actions, even byte-identical in the same // instant (BRIEFS/TWIN-RUNTIME-CONTRACT.md, "Local writes: occurrence or replay?") — so feeding // back the same content would make a re-replay DOUBLE-APPLY. Instead replay passes the source action's own id as // `actionId`, which is at-most-once on an identity it genuinely holds: a replayed world's action // ids equal the source's, and replaying twice is `appended: false` end to end. The uniqueness seam // (billable occurrences that must not collapse) still survives, recovered from the source id and // passed through verbatim. // // On top of replay sits the OPERATIONAL-PR CONTRACT: VERIFIERS — deterministic checks // against post-replay projected state, each one the kernel's own precondition expression // evaluated by the kernel's own evaluator (`checkPrecondition`) — whose results are recorded on // the object as `verification`; APPROVALS, each bound to the body hash at signing (drift // refuses, loudly); and READINESS — recomputed from the object every time, never trusted off a // stored boolean. Verification and approvals are ABOUT-the-body metadata: they live on the // object but outside `contentHash`, exactly so recording them cannot invalidate the hash they // bound to. The verifier SET, by contrast, is authored content and is hashed (when non-empty), // so an approval binds to what will be checked as well as what was done. This contract is // consumer-agnostic by design: anything that can render a diff, run a replay and record a // signature can implement review on top of it. // // This module is deliberately WORLD-IGNORANT: it takes ledger references (a state service + // the control root that holds it) and never learns what a world is. `volter world` supplies // discovery and the CLI verbs; the state-level logic lives here, beside the ledgers it reads. import { createHash } from 'node:crypto'; import { aliasesFrom, ownParentEntries, readTreeMapsAt, wholeLog, type Entry } from './log.ts'; import { appendActionIfAbsent, checkPrecondition, listActions, projectedPreconditionValue, projectResources, inWorldHistory, isWorldPerson } from './actions.ts'; import type { TwinActionRevertSpec } from './actions.ts'; import type { TwinAction, TwinActionPrecondition, TwinActionPreconditionOp } from './actions.ts'; import { canonicalJson, diffSubjectFields, hashFieldValue, type FieldChange } from './hash.ts'; import { applyTwinWrite } from './serve.ts'; import type { TwinResource } from './serve.ts'; /** One twin's action ledger, addressed the way the control plane addresses state: * `worldPaths(stateService, controlRoot)`. `service` is the caller's label for it (in a world: * the world service id); `stateService` is the control-plane service whose ledger this is. * They differ whenever a twin records under a different state name than its world service id. */ export type LedgerRef = { /** the vendor/twin as the operator names it — what `diff` groups by and `replay` matches on */ service: string; /** the control-plane state service whose `actions.jsonl` this is (often === service) */ stateService: string; /** control root such that `worldPaths(stateService, controlRoot)` resolves the ledger */ controlRoot: string; }; /** One ledger's recorded position inside a marker. `count` is the row count at capture; * `lastActionId` is the verification anchor (see the marker note above). */ export type LedgerPosition = { service: string; stateService: string; count: number; lastActionId: string | null; /** the twin's history view and its position in it: what a branch at this mark starts from (ADR 0036 §5) */ view?: string; position?: number; }; export const MARKER_KIND = 'volter.world.marker.v1'; export const CHANGESET_KIND = 'volter.world.changeset.v1'; /** The base position a diff or changeset is taken against. */ export type WorldMarker = { kind: typeof MARKER_KIND; id: string; world: string; createdAt: string; /** Every ledger that existed at capture time. A ledger absent here is treated as position 0 * (a twin that recorded its first action AFTER the mark contributes its whole ledger). */ ledgers: LedgerPosition[]; /** the World clock's instant at the mark, or null when it ran on the machine's time (a run's position, ADR 0036 §5) */ clock?: string | null; /** whether the machine's fault door took the app's disk with the mark */ disk?: boolean; }; /** The id reserved for the synthetic "everything this world has ever recorded" base. */ export const WORLD_BOOT_MARKER_ID = 'world-boot'; /** An action inside a delta/changeset, bound to the twin whose ledger recorded it. The raw * `TwinAction` is kept verbatim (provenance); `service`/`stateService` are the binding replay * needs to route it into the right twin of another world. */ export type ChangesetAction = { service: string; stateService: string; action: TwinAction; }; /** Per-vendor rollup of a delta, in first-occurrence order — the shape `diff` renders. */ export type VendorSummary = { service: string; count: number; operations: Array<{ operation: string; count: number; subjectIds: string[] }>; }; export type LedgerDelta = { world: string; base: WorldMarker; /** every action after `base`, across every ledger, ordered by `occurredAt` */ actions: ChangesetAction[]; vendors: VendorSummary[]; total: number; /** Presentation only, outside changeset bodies: fields immediately before and after each write. */ fieldChanges?: Record>; }; export const fieldDiffKey = (service: string, stateService: string, id: string): string => JSON.stringify([service, stateService, id]); /** A verifier: one deterministic check against post-replay projected state — the CI assertion * of the operational PR (docs/concepts/the-model.md). The `assert` is the kernel's ONE check * expression (`TwinActionPrecondition`: subject/field/op/value, evaluated by * `checkPrecondition`), the same shape write-time preconditions and plan conflicts already * use — a verifier is that check pointed at a replay target instead of the authoring world. */ export type ChangesetVerifier = { /** caller-chosen handle, unique within the changeset (results key on it) */ id: string; /** the world service (twin) whose post-replay state the assert reads */ service: string; assert: TwinActionPrecondition; }; /** One verifier's outcome against a replay target. `assert` is repeated verbatim so the result * is readable on its own; `actual` is what the projected state held (omitted when undefined — * which is itself what `exists`/`not_exists` distinguish). */ export type ChangesetVerifierResult = { id: string; service: string; assert: TwinActionPrecondition; passed: boolean; actual?: unknown; }; /** The recorded outcome of `changeset verify` — ABOUT-the-body metadata, like approvals: it * lives on the object but is outside `contentHash`, and each verify REPLACES the previous * record (the provenance fields say exactly which run this is). */ export type ChangesetVerification = { at: string; /** where the replay landed — a world name, or 'ephemeral' for a throwaway target */ into: string; /** the body hash at verification time; a later body edit makes this visibly stale */ contentHash: string; /** sha256 over the post-replay projected state of every replay target — two verifies that * produced the same world state produce the same digest (the determinism receipt) */ worldDigest: string; passed: boolean; results: ChangesetVerifierResult[]; /** the world's checks (state-system.ts) that refused an entry — CI on deployment, run at verify */ refusals?: Array<{ actionId: string; service: string; check: string; reason: string }>; }; /** One signature: who approved, when, against exactly which body hash. The hash-at-signing is * the point — an approval is meaningless without the bytes it bound to. */ export type ChangesetApproval = { principal: string; at: string; contentHash: string; note?: string; }; export type Changeset = { kind: typeof CHANGESET_KIND; id: string; name: string; /** the world it was authored in */ world: string; /** the marker id it forked from */ base: string; createdAt: string; actions: ChangesetAction[]; /** deterministic checks that must pass on replay — part of the hashed body when present, * so an approval also binds to WHAT was checked, not just what was done */ verifiers: ChangesetVerifier[]; /** latest verify run (replaced, never accumulated) — outside the hash, like approvals */ verification: ChangesetVerification | null; /** who signed, against `contentHash` */ approvals: ChangesetApproval[]; /** The governed push's outcome: receipts and, on a partial apply, the compensation report; null until applied. */ applied: ChangesetApplication | null; /** The human summary rendered deterministically from `actions` * at authoring (`narrateActions`). Outside the hash — it is DERIVED from the hashed actions, so * an approval already binds to it — and re-rendered on every read: a hand-edited narration no * longer equals its re-render, and the object is neither approvable nor applicable until * re-authored. */ narration?: string; /** The author's own words for the changeset (git's commit message) — what `volter changeset -m` * records. Outside the hash, like the narration; a reviewer reads both. */ message?: string; /** Who cut it, as the World names a caller (`key:`, `key: for:`, `person:`, `machine`, `person`, * `token`); the command on this machine records its signed-in person, and is absent when no one is signed in there. * Outside the hash, as approvals are (docs/contributing/architecture.md, "Who acted is recorded"). */ cutBy?: string; /** The person accountable for it: the cutting grant's person, else the pusher's person when it lands in a shared World * with none. Outside the hash. */ owner?: string; /** Who pushed it into the World that keeps this copy, a caller as `cutBy` names one. Outside the hash. */ pushedBy?: string; /** Set by `rebaseChangeset`: the hash this object was rebased from, and when. Outside the hash. */ rebasedFrom?: { contentHash: string; at: string }; /** Where the parent log stood when this was cut, per state service (its entry count): * a rebase reads the parent's entries since here to name what moved under the changeset. Outside * the hash (metadata of the cut, not of the change). */ cut?: Record; /** sha256 over the canonical JSON of `{id, world, base, actions}` (+ `verifiers` when any) */ contentHash: string; }; /** Names that address a file on disk (markers, changesets): no separators, no traversal. */ const SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; export function assertSafeChangesetName(name: string, what = 'changeset'): string { if (!SAFE_NAME.test(name)) { throw new Error(`Invalid ${what} name: ${JSON.stringify(name)} (letters, digits, '.', '_' and '-' only, starting with a letter or digit)`); } return name; } // ── markers ──────────────────────────────────────────────────────────────────────────────────── /** The "everything ever recorded in this world" base: zero ledgers, so every ledger diffs from * position 0. Used when a world has no marks yet — `diff` must still answer, not refuse. */ export function worldBootMarker(world: string, createdAt: string): WorldMarker { return { kind: MARKER_KIND, id: WORLD_BOOT_MARKER_ID, world, createdAt, ledgers: [] }; } /** Capture the current position of every ledger — the cross-service base marker. */ export function captureMarker(opts: { id: string; world: string; ledgers: LedgerRef[]; createdAt?: string; clock?: string | null; disk?: boolean }): WorldMarker { const ledgers = opts.ledgers.map((ledger) => { const rows = listActions(ledger.stateService, ledger.controlRoot); const { view, position } = captureHistory(ledger.stateService, ledger.controlRoot); return { service: ledger.service, stateService: ledger.stateService, count: rows.length, lastActionId: rows.length ? rows[rows.length - 1]!.id : null, view, position, } satisfies LedgerPosition; }); return { kind: MARKER_KIND, id: opts.id, world: opts.world, createdAt: opts.createdAt ?? new Date().toISOString(), ledgers, ...(opts.clock !== undefined ? { clock: opts.clock } : {}), ...(opts.disk ? { disk: true } : {}) }; } function positionKey(service: string, stateService: string): string { return `${service}\u0000${stateService}`; } /** A marker taken in world A says nothing about world B's ledgers — comparing them would * produce a confident, wrong delta. Refuse. */ export function assertMarkerBelongsTo(marker: WorldMarker, world: string): void { if (marker.world !== world) { throw new Error(`Marker "${marker.id}" was captured in world "${marker.world}", not "${world}" — a base marker only means something in the world it came from`); } } // ── diff ─────────────────────────────────────────────────────────────────────────────────────── /** * Every action appended after `base`, across `ledgers`, in `occurredAt` order. * * A ledger is verified against its recorded position before any of it is reported: fewer rows * than the marker counted, or a different action id at that position, means the ledger was * rewritten and the marker no longer addresses anything real. That is a * loud error — quietly re-basing on a rewritten ledger is how a diff lies. */ export function diffLedgers(opts: { world: string; ledgers: LedgerRef[]; base: WorldMarker; /** each write's field changes, for a caller that shows them (default) */ fields?: boolean; /** with the records each twin's root observed since the base (a refresh's, an ingest's): a window's evidence (architecture, "Replicating an issue") */ observed?: boolean }): LedgerDelta { assertMarkerBelongsTo(opts.base, opts.world); const positions = new Map(opts.base.ledgers.map((p) => [positionKey(p.service, p.stateService), p])); type Ordered = { entry: ChangesetAction; ledgerIndex: number; rowIndex: number }; const ordered: Ordered[] = []; const seen = new Set(); opts.ledgers.forEach((ledger, ledgerIndex) => { const key = positionKey(ledger.service, ledger.stateService); seen.add(key); const position = positions.get(key); const rows: TwinAction[] = listActions(ledger.stateService, ledger.controlRoot); const from = position?.count ?? 0; if (opts.observed) { // the root's log as the base's history view held it: what was observed after it is the vendor's, in its order const parent = ownParentEntries(ledger.stateService, ledger.controlRoot); const held = position?.view ? readHistoryView(worldPaths(ledger.stateService, ledger.controlRoot).dir, position.view).layout.parent : 0; if (parent.length < held) throw new Error(`Ledger ${ledger.service}/${ledger.stateService}'s root log has ${parent.length} entries but marker "${opts.base.id}" recorded ${held} — the root's log was rewritten or purged since the mark`); const pulled = parent.slice(held).filter((e) => e.operation === 'observed'); pulled.forEach((action, offset) => ordered.push({ entry: { service: ledger.service, stateService: ledger.stateService, action: action as TwinAction }, ledgerIndex, rowIndex: offset - pulled.length })); } if (position && from > 0) { if (rows.length < from) { throw new Error(`Ledger ${ledger.service}/${ledger.stateService} has ${rows.length} action(s) but marker "${opts.base.id}" recorded ${from} — the ledger was rewritten or purged since the mark`); } const anchor = rows[from - 1]!; if (anchor.id !== position.lastActionId) { throw new Error(`Ledger ${ledger.service}/${ledger.stateService} no longer matches marker "${opts.base.id}": expected action "${position.lastActionId}" at position ${from}, found "${anchor.id}" — the ledger was rewritten since the mark`); } } rows.slice(from).forEach((action, offset) => { if (!inWorldHistory(action)) return; // the twin's own store, never a change the app made (a person is the World's: ADR 0025) ordered.push({ entry: { service: ledger.service, stateService: ledger.stateService, action }, ledgerIndex, rowIndex: from + offset }); }); }); // A ledger the marker recorded that has since vanished entirely is the same corruption as a // short ledger — the marker's anchor is unverifiable, so the delta cannot be trusted. for (const position of opts.base.ledgers) { if (position.count > 0 && !seen.has(positionKey(position.service, position.stateService))) { throw new Error(`Ledger ${position.service}/${position.stateService} recorded by marker "${opts.base.id}" (${position.count} action(s)) no longer exists in world "${opts.world}" — the ledger was rewritten or purged since the mark`); } } ordered.sort((a, b) => { const at = a.entry.action.occurredAt ?? ''; const bt = b.entry.action.occurredAt ?? ''; if (at !== bt) return at < bt ? -1 : 1; // ties keep discovery order (ledger, then row) — the same stable rule `tail` uses if (a.ledgerIndex !== b.ledgerIndex) return a.ledgerIndex - b.ledgerIndex; return a.rowIndex - b.rowIndex; }); const actions = ordered.map((o) => o.entry); return { world: opts.world, base: opts.base, actions, vendors: summarizeByVendor(actions), total: actions.length, ...(opts.fields === false ? {} : { fieldChanges: describeActionFields(opts.ledgers, actions) }) }; } /** Read each write's pre-state through the authoritative kernel projection. No UI history fold. */ export function describeActionFields(ledgers: LedgerRef[], actions: ChangesetAction[]): NonNullable { const fieldChanges: NonNullable = {}; for (const ledger of ledgers) { const entries = wholeLog(ledger.stateService, ledger.controlRoot); // An observation is atomic: its internal positions cannot be projected. Compare its // writes with the state at the start of that batch, through the same kernel reader. const positions = new Map(); let batchStart = 0; entries.forEach((e, i) => { if (!e.batch || e.batch !== entries[i - 1]?.batch) batchStart = i; if (!positions.has(e.id)) positions.set(e.id, e.batch ? batchStart : i); }); const mine = actions.filter(a => a.service === ledger.service && a.stateService === ledger.stateService && a.action.fields && positions.has(a.action.id)); // every write's pre-state from one capture of this twin's history (a capture per write read the whole log each time) const trees = mine.length ? readTreeMapsAt(ledger.stateService, ledger.controlRoot, mine.map(a => positions.get(a.action.id)!)) : new Map(); for (const { action, service, stateService } of mine) { if (!action.fields) continue; const subject = trees.get(positions.get(action.id)!)?.get(`${action.subject.type}:${action.subject.id}`); const fields = subject?.fields ?? {}; const changes = diffSubjectFields({ subject: action.subject, fields, fieldHashes: Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, hashFieldValue(v)])), latestEventId: '', updatedAt: '', }, action.fields); // a person's password hash is shown as set, never its value (ADR 0025) if (isWorldPerson(action) && changes.password_sha256) changes.password_sha256 = { before: changes.password_sha256.before === undefined ? undefined : '(set)', after: '(set)' }; fieldChanges[fieldDiffKey(service, stateService, action.id)] = changes; } } return fieldChanges; } /** Group a delta by vendor, then by operation — both in FIRST-OCCURRENCE order, so the rollup * reads in the same causal order as the actions themselves. */ export function summarizeByVendor(actions: ChangesetAction[]): VendorSummary[] { const vendors = new Map(); for (const { service, action } of actions) { let vendor = vendors.get(service); if (!vendor) { vendor = { service, count: 0, operations: [] }; vendors.set(service, vendor); } vendor.count += 1; const name = action.operation ?? action.op ?? '?'; let operation = vendor.operations.find((o) => o.operation === name); if (!operation) { operation = { operation: name, count: 0, subjectIds: [] }; vendor.operations.push(operation); } operation.count += 1; operation.subjectIds.push(action.subject?.id ?? '?'); } return [...vendors.values()]; } // ── the changeset object ─────────────────────────────────────────────────────────────────────── /** What `changesetContentHash` needs to see — the immutable fields, with `verifiers` and `cut` optional. */ export type ChangesetHashable = Pick & Partial>; /** The IMMUTABLE body a `contentHash` covers. `approvals`/`verification`/`applied`/`createdAt` * are excluded on purpose: an approval or a verify run must not invalidate the hash it bound * to — content-addressing is about the actions, not the object's lifecycle. `verifiers` ARE * in the body (when any exist): they are authored content, and an approval must bind to what * will be checked, not just what was done. An empty verifier set is omitted: absent and empty hash identically. */ function changesetBody(changeset: ChangesetHashable): Record { const body: Record = { id: changeset.id, world: changeset.world, base: changeset.base, actions: changeset.actions }; if (changeset.verifiers?.length) body.verifiers = changeset.verifiers; // the cut is part of what an approval binds to: a rebase moves it, and with it the hash — a rebase is a re-review if (changeset.cut && Object.keys(changeset.cut).length) body.cut = changeset.cut; return body; } export function changesetContentHash(changeset: ChangesetHashable): string { return `sha256:${createHash('sha256').update(canonicalJson(changesetBody(changeset))).digest('hex')}`; } const PRECONDITION_OPS: readonly TwinActionPreconditionOp[] = ['exists', 'not_exists', 'eq', 'neq', 'version_eq']; /** A verifier that cannot be evaluated deterministically is refused at authoring time, not * discovered at verify time. */ export function assertValidVerifiers(verifiers: ChangesetVerifier[]): ChangesetVerifier[] { const seen = new Set(); for (const verifier of verifiers) { if (!verifier.id?.trim()) throw new Error('Invalid verifier: every verifier needs an id'); if (seen.has(verifier.id)) throw new Error(`Invalid verifier: duplicate id "${verifier.id}"`); seen.add(verifier.id); if (!verifier.service?.trim()) throw new Error(`Invalid verifier "${verifier.id}": missing service (the twin whose state it checks)`); const assert = verifier.assert; if (!assert?.subject?.type || !assert.subject.id || !assert.field) { throw new Error(`Invalid verifier "${verifier.id}": assert needs subject {type, id} and a field`); } if (!PRECONDITION_OPS.includes(assert.op)) { throw new Error(`Invalid verifier "${verifier.id}": unknown op ${JSON.stringify(assert.op)} (want ${PRECONDITION_OPS.join('|')})`); } if ((assert.op === 'eq' || assert.op === 'neq' || assert.op === 'version_eq') && assert.value === undefined) { throw new Error(`Invalid verifier "${verifier.id}": op "${assert.op}" needs a value`); } } return verifiers; } /** Freeze a delta into a named, content-addressed changeset. */ export function buildChangeset(opts: { name: string; world: string; base: string; actions: ChangesetAction[]; verifiers?: ChangesetVerifier[]; createdAt?: string; message?: string; cut?: Record; cutBy?: string; owner?: string }): Changeset { assertSafeChangesetName(opts.name); const verifiers = assertValidVerifiers(opts.verifiers ?? []); const core = { id: `chg_${opts.name}`, world: opts.world, base: opts.base, actions: opts.actions, verifiers, ...(opts.cut === undefined ? {} : { cut: opts.cut }) }; return { kind: CHANGESET_KIND, ...core, name: opts.name, createdAt: opts.createdAt ?? new Date().toISOString(), verification: null, approvals: [], applied: null, narration: narrateActions(opts.actions), ...(opts.message === undefined ? {} : { message: opts.message }), ...(opts.cutBy === undefined ? {} : { cutBy: opts.cutBy }), ...(opts.owner === undefined ? {} : { owner: opts.owner }), contentHash: changesetContentHash(core), }; } /** Recompute and compare — a changeset whose bytes were edited after authoring is not the * object anyone approved. Callers render this as a warning or a hard failure as suits. */ export function changesetHashMatches(changeset: Changeset): boolean { return changeset.contentHash === changesetContentHash(changeset); } // ── replay ───────────────────────────────────────────────────────────────────────────────────── export type ReplayTarget = { /** the changeset service this target satisfies */ service: string; /** the state service to write into (may differ from the source's) */ stateService: string; controlRoot: string; }; export type ReplayActionResult = { service: string; sourceActionId: string; /** the action id in the TARGET ledger — identical to `sourceActionId` whenever the target * state service matches the source's, which is what makes replay verifiable */ actionId: string; /** 'write' = through `applyTwinWrite` (the kernel write path); 'append' = recorded verbatim */ via: 'write' | 'append'; status: 'performed' | 'replayed'; }; export type ReplayReport = { changeset: string; contentHash: string; /** the authoring world */ world: string; into: string; total: number; performed: number; replayed: number; services: string[]; actions: ReplayActionResult[]; }; /** * Recover the `uniqueness` value `applyTwinWrite` folded into an action id, or report that the * id is not twin-write-shaped at all (a hand-written or pack-appended action). * * The id format is `twin:::::[:]` * and both `operation` and `subjectId` may themselves contain ':', so the id cannot be split * field-wise. A repeated write additionally carries an occurrence ordinal (`…#1`), stripped below. Instead the deterministic prefix is REBUILT from the action's own recorded parts — * if it matches, whatever follows is exactly the uniqueness seam. Getting this right is what * keeps billable occurrences (two identical AI completions in one millisecond) from collapsing * into one action on replay. */ export function twinWriteShape(action: TwinAction): { uniqueness?: string } | null { if (action.op !== 'set' || !action.operation || !action.fields) return null; const hash = hashFieldValue({ operation: action.operation, subjectId: action.subject.id, fields: action.fields }); const prefix = `twin:${action.service}:${action.operation}:${action.subject.id}:${action.occurredAt}:${hash}`; // A REPEAT carries an occurrence ordinal (`…#1`). Strip it before matching, or every repeated // write falls out of the write path and replays through the `append` fallback — which is // reserved for actions the write path cannot EXPRESS, and which the report labels accordingly. // The ruling makes repeats ordinary, so without this the first changeset containing one flips a // replay assertion that has nothing to do with it. The ordinal is digits after a trailing '#', // and a content hash is hex, so this cannot eat a real id's tail. const id = action.id.replace(/#\d+$/, ''); if (id === prefix) return {}; if (id.startsWith(`${prefix}:`)) return { uniqueness: id.slice(prefix.length + 1) }; return null; } /** * Replay a changeset's actions, in order, into `targets`. * * Two paths, and the split is about EXPRESSIVENESS, not preference: * - `write` — the default and the point: back through `applyTwinWrite`, the same kernel entry * an SDK call lands on. The target re-derives the action id from content, so it matches the * source id and a second replay is a total no-op. * - `append` — the honest fallback for actions the write path cannot express: multi-resource * `projection` transactions (applyTwinWrite carries only flat `fields`, so routing them * through it would silently DROP the creates/deletes/emits) and `revert`/`confirm` * bookkeeping rows. These are appended verbatim under `appendActionIfAbsent`, which is * id-keyed — so they are idempotent on re-replay too. * * `preconditions` are deliberately NOT replayed. They were evaluated against the authoring * world's state at author time; re-evaluating them against a different base would fail replays * that are perfectly valid recordings. Verifying a changeset against a target's state is the * verifiers' job, not a silent side effect of replay. Dropping them cannot change any action * id — preconditions are not part of the content hash. */ export async function replayChangeset( changeset: Changeset, opts: { into: string; targets: ReplayTarget[]; available?: string[] }, ): Promise { const byService = new Map(opts.targets.map((t) => [t.service, t])); const needed = [...new Set(changeset.actions.map((a) => a.service))]; const missing = needed.filter((service) => !byService.has(service)); if (missing.length) { const have = opts.available ?? opts.targets.map((t) => t.service); throw new Error(`Cannot replay changeset "${changeset.name}" into world "${opts.into}": it touches ${missing.length === 1 ? 'a twin' : 'twins'} that world does not have — ${missing.join(', ')} (world "${opts.into}" has: ${have.length ? have.join(', ') : 'no services'})`); } const results: ReplayActionResult[] = []; for (const entry of changeset.actions) { const target = byService.get(entry.service)!; const action = entry.action; const shape = action.projection ? null : twinWriteShape(action); if (shape) { const { result } = await applyTwinWrite( target.stateService, { operation: action.operation!, subjectType: action.subject.type, subjectId: action.subject.id, fields: action.fields!, occurredAt: action.occurredAt, ...(action.actor ? { actor: action.actor } : {}), ...(action.correlationId ? { correlationId: action.correlationId } : {}), ...(shape.uniqueness === undefined ? {} : { uniqueness: shape.uniqueness }), // AT MOST ONCE, AND THE SOURCE'S IDENTITY. Replay re-materializes an action that // already has an id, and the target must keep it — a replayed world's action ids equal // the source's, which the CI primitive pins. Local vendor writes are occurrences by // default and never collapse on content (a write returning a value to what it was one // instant earlier is still a write); replay is the caller that // genuinely wants dedupe and is the one that can say so honestly, because it holds the // identity. See the runtime contract, "Local writes: occurrence or replay?". actionId: action.id, }, target.controlRoot, ); results.push({ service: entry.service, sourceActionId: action.id, actionId: result.actionId, via: 'write', status: result.status }); continue; } // Drop preconditions (evaluated in the source world) AND the source world's shadowBasis // (refs into the SOURCE's event log — meaningless against the target's mirror; carrying // it verbatim would poison the target's non-fast-forward check, R14). The appender // re-stamps against the target; replay identity excludes the basis, so re-stamping // cannot conflict with a prior copy. const { preconditions: _dropped, ...rest } = action; const { appended } = appendActionIfAbsent({ ...rest, service: target.stateService }, target.controlRoot); results.push({ service: entry.service, sourceActionId: action.id, actionId: action.id, via: 'append', status: appended ? 'performed' : 'replayed' }); } return { changeset: changeset.name, contentHash: changeset.contentHash, world: changeset.world, into: opts.into, total: results.length, performed: results.filter((r) => r.status === 'performed').length, replayed: results.filter((r) => r.status === 'replayed').length, services: needed, actions: results, }; } // ── verify / approve / status — the operational-PR contract ──────────────────────────────────── /** * Run a changeset's verifiers against post-replay state. Deterministic on purpose: each assert * reads the target's PROJECTED state (`projectResources` — the same projection the kernel's * preconditions and plan conflicts read) and is evaluated by `checkPrecondition` — the same * evaluator, so a verifier means exactly what a precondition means. The `worldDigest` is a * receipt over everything the verifiers could have seen: two runs that produced the same * post-replay state produce the same digest. * * `targets` are the same references replay wrote through — a verifier is only honest against * the ledgers the replay actually landed in. A verifier naming a service with no target is a * loud error (there is nothing real to check it against), never a silent pass. */ export function runChangesetVerifiers( changeset: Changeset, targets: ReplayTarget[], opts: { at: string; into: string }, ): ChangesetVerification { const resourcesByService = new Map(); const digestInput: Array<{ service: string; stateService: string; resources: unknown }> = []; for (const target of [...targets].sort((a, b) => (a.service === b.service ? (a.stateService < b.stateService ? -1 : 1) : a.service < b.service ? -1 : 1))) { const resources = projectResources(target.stateService, target.controlRoot); // one world service may record under several state services (aws → s3 + dynamodb): // its verifiers see the union resourcesByService.set(target.service, [...(resourcesByService.get(target.service) ?? []), ...resources]); digestInput.push({ service: target.service, stateService: target.stateService, resources }); } const results: ChangesetVerifierResult[] = changeset.verifiers.map((verifier) => { const resources = resourcesByService.get(verifier.service); if (!resources) { const have = [...resourcesByService.keys()].sort(); throw new Error(`Verifier "${verifier.id}" checks twin "${verifier.service}" but the replay target has no such twin (targets: ${have.join(', ') || 'none'})`); } const { assert } = verifier; const actual = projectedPreconditionValue(assert, resources); const passed = checkPrecondition(assert, actual); return { id: verifier.id, service: verifier.service, assert, passed, ...(actual === undefined ? {} : { actual }) }; }); return { at: opts.at, into: opts.into, contentHash: changesetContentHash(changeset), worldDigest: `sha256:${createHash('sha256').update(canonicalJson(digestInput)).digest('hex')}`, passed: results.every((result) => result.passed), results, }; } /** Record `verification` on the object — REPLACING any prior run (the provenance fields carry * which run this is), never touching the hash the body is addressed by. */ export function withVerification(changeset: Changeset, verification: ChangesetVerification): Changeset { return { ...changeset, verification }; } /** * Append an approval bound to the changeset's CURRENT body hash. Refuses when the stored * `contentHash` no longer matches the body: an object whose bytes moved after authoring is not * the object anyone reviewed, and signing it would launder the drift. Loud, never silent. */ export function approveChangeset( changeset: Changeset, opts: { principal: string; at?: string; note?: string }, ): { changeset: Changeset; approval: ChangesetApproval } { if (!opts.principal?.trim()) throw new Error('Approval requires a principal (--as )'); const bodyHash = changesetContentHash(changeset); if (changeset.contentHash !== bodyHash) { throw new Error(`Refusing to approve changeset "${changeset.name}": its stored contentHash (${changeset.contentHash}) does not match its body (${bodyHash}) — the object drifted after authoring, and an approval must bind to exactly what was reviewed`); } if (narrationDrift(changeset)) throw new Error(`Refusing to approve changeset "${changeset.name}": its narration no longer describes its actions — a hand-edited summary cannot be signed; re-author it`); const approval: ChangesetApproval = { principal: opts.principal.trim(), at: opts.at ?? new Date().toISOString(), contentHash: bodyHash, ...(opts.note ? { note: opts.note } : {}), }; return { changeset: { ...changeset, approvals: [...changeset.approvals, approval] }, approval }; } /** Everything `changeset status` reports — recomputed from the object, never trusted off * stored booleans (the same rule `planRequiresApproval` follows). */ export type ChangesetReadiness = { name: string; world: string; contentHash: string; /** stored hash matches the body */ hashOk: boolean; /** the different people whose approvals bind to the current hash, and how many this World requires */ approvers: number; required: number; /** a verification exists, binds to the current hash, and every verifier passed */ verified: boolean; verification: ChangesetVerification | null; /** every approval on the object */ approvals: number; /** approvals whose hash-at-signing is the current body hash — the only ones that count */ bindingApprovals: number; ready: boolean; /** empty exactly when ready */ reasons: string[]; }; /** Ready to apply: hashed as authored, verified against its current contents, and approved for them by `rules.approvals` * different people (the World's changeset rules; one when it names none). */ /** Whom an approval counts for: the person a key acts for (`key: for:`), else the principal itself. */ export function approverOf(principal: string): string { const at = principal.indexOf(' for:'); return principal.startsWith('key:') && at > 0 ? principal.slice(at + ' for:'.length) : principal; } export function changesetReadiness(changeset: Changeset, rules: { approvals?: number } = {}): ChangesetReadiness { const bodyHash = changesetContentHash(changeset); const hashOk = changeset.contentHash === bodyHash; const verification = changeset.verification; const binding = changeset.approvals.filter((approval) => approval.contentHash === changeset.contentHash); const reasons: string[] = []; if (!hashOk) reasons.push(`contentHash mismatch: stored ${changeset.contentHash}, body hashes to ${bodyHash} — the object was edited after authoring`); const drift = narrationDrift(changeset); if (drift) reasons.push('narration drifted from the actions — the summary a reviewer reads no longer describes what would be done; re-author'); if (!verification) { reasons.push('never verified — run `changeset verify`'); } else if (verification.contentHash !== changeset.contentHash) { reasons.push(`verification is stale: it ran against ${verification.contentHash} — re-run \`changeset verify\``); } else if (!verification.passed) { const failed = verification.results.filter((result) => !result.passed); reasons.push(`verification FAILED: ${failed.map((result) => result.id).join(', ')} (${failed.length} of ${verification.results.length})`); } const required = rules.approvals ?? 1; // different people: a key's approval (`key: for:`) is its person's, so a person and their agent are one const approvers = new Set(binding.map((approval) => approverOf(approval.principal))).size; if (approvers < required) { reasons.push(binding.length === 0 ? (changeset.approvals.length ? 'no approval binds to the current body hash' : 'no approvals — run `changeset approve --as `') : `${approvers} of the ${required} approvals this World requires`); } const verified = Boolean(hashOk && verification && verification.contentHash === changeset.contentHash && verification.passed); return { name: changeset.name, world: changeset.world, contentHash: changeset.contentHash, hashOk, approvers, required, verified, verification, approvals: changeset.approvals.length, bindingApprovals: binding.length, ready: reasons.length === 0, reasons, }; } // ── v2: governed push — apply ─────────────────────────────────────────────────────────────── // /** The object with its application recorded — `applied` is outside the hash. */ export function withApplication(changeset: Changeset, application: ChangesetApplication): Changeset { return { ...changeset, applied: application }; } // ── v4: the checkable narration ──────────────────────────────────────────────────────────── // // The narration is what a reviewer READS; the actions are what would be DONE. They are the same // thing only if the narration is a pure function of the actions — so it is: rendered here at // authoring, inside the hash, and re-rendered on every read. A narration that no longer equals // its re-render (a hand edit, a stale copy) makes the object not-ready: neither approvable nor // applicable until re-authored. Deterministic by construction — causal order, full subject // lists, the field names each write sets, no clock, no elision. function narrateFields(action: TwinAction): string { const names = Object.keys(action.fields ?? {}).sort(); if (names.length === 0) return ''; return ` setting ${names.join(', ')}`; } /** One deterministic paragraph per twin, one sentence per operation, in first-occurrence order. */ export function narrateActions(actions: ChangesetAction[]): string { if (actions.length === 0) return 'Does nothing: the changeset carries no actions.'; const paragraphs: string[] = []; for (const vendor of summarizeByVendor(actions)) { const sentences = vendor.operations.map((operation) => { const rows = actions.filter((entry) => entry.service === vendor.service && (entry.action.operation ?? entry.action.op ?? '?') === operation.operation); const fieldSets = [...new Set(rows.map((entry) => narrateFields(entry.action)))]; const fields = fieldSets.length === 1 ? fieldSets[0]! : ''; return `${operation.count} × ${operation.operation} on ${rows.map((entry) => `${entry.action.subject.type}:${entry.action.subject.id}`).join(', ')}${fields}.`; }); paragraphs.push(`${vendor.service}: ${sentences.join(' ')}`); } return paragraphs.join('\n'); } /** The recorded narration against its re-render — null when they agree or when the object carries none. */ export function narrationDrift(changeset: Pick & Partial>): { recorded: string; expected: string } | null { if (changeset.narration === undefined) return null; const expected = narrateActions(changeset.actions); return expected === changeset.narration ? null : { recorded: changeset.narration, expected }; } // ── rebase onto a moved mirror ───────────────────────────────────────────────────────────── // // Every `set` action carries its merge base (`shadowBasis`: the remote ref of each subject it // touches, stamped at append) and push refuses on drift against it. A changeset authored before // the mirror moved is therefore unapplicable after a fetch. `rebaseChangeset` is the merge: per action, the current refs of its subjects are read in the // authoring world; an unmoved basis is carried; a moved basis has the action's preconditions // re-evaluated against the world's current projected state — pass: re-stamped and carried; // fail: a CONFLICT by subject, field, expected and actual, and the object is not rewritten. A // moved basis with no precondition is carried re-stamped and reported `rebased-blind`. The // rebased object keeps id, name, base and every action id; its hash moves (the actions moved), // so approvals drop and the verification is stale — a rebase is a re-review. export type ApplyReceipt = { actionId: string; service: string; stateService: string; status: 'confirmed' | 'replayed' | 'failed' | 'skipped'; pushId?: string; externalId?: string; url?: string; error?: string; }; export type CompensationEntry = { service: string; actionId: string; subject: { type: string; id: string }; externalId?: string; /** the action's own revert spec when it carries one, else the inverse on the vendor id */ revert: TwinActionRevertSpec | { strategy: 'inverse' }; }; /** How a push went: the receipts origin answered, recorded on the changeset object. */ export type ChangesetApplication = { at: string; contentHash: string; /** The destination the push went to. */ destination: { url: string; namespace: string }; outcome: 'applied' | 'partial' | 'refused'; forced?: boolean; refusal?: string[]; receipts: ApplyReceipt[]; compensation: CompensationEntry[]; }; export type RebaseTarget = { service: string; stateService: string; controlRoot: string }; export type RebaseActionResult = { actionId: string; service: string; status: 'unchanged' | 'rebased' | 'rebased-blind' | 'conflict'; moved?: Record; conflicts?: Array<{ subject: { type: string; id: string }; field: string; op: string; expected?: unknown; actual: unknown }>; }; export type RebaseReport = { changeset: string; from: string; to: string | null; at: string; outcome: 'unchanged' | 'rebased' | 'conflict'; actions: RebaseActionResult[] }; export function rebaseChangeset(changeset: Changeset, opts: { targets: RebaseTarget[]; at?: string }): { changeset: Changeset; report: RebaseReport } { return withHistoryLocks(opts.targets.map((t) => worldPaths(t.stateService, t.controlRoot).dir), () => rebaseChangesetLocked(changeset, opts), { operation: 'branch-pointer adjustment' }); } function rebaseChangesetLocked(changeset: Changeset, opts: { targets: RebaseTarget[]; at?: string }): { changeset: Changeset; report: RebaseReport } { const at = opts.at ?? new Date().toISOString(); const targetFor = new Map(opts.targets.map((t) => [t.service, t])); // what the parent did since the cut, per service — the entries past the cut position. // A set action conflicts where the parent set the same field of the same subject to something // else; a subject the parent touched otherwise is rebased; the rest is unchanged. const sinceCut = new Map(); const aliases = new Map>(); for (const t of opts.targets) { const cut = changeset.cut?.[t.service] ?? changeset.cut?.[t.stateService]; if (!cut) continue; const directory = worldPaths(t.stateService, t.controlRoot).dir; const current = captureParentHistory(t.stateService, t.controlRoot); aliases.set(t.service, aliasesFrom(historyEntries(readHistoryView(directory, current.view)))); sinceCut.set(t.service, historyChanges(t.stateService, historyPrefix(readHistoryView(directory, cut.view), cut.position), readHistoryView(directory, current.view))); } const stable = (v: unknown): string => JSON.stringify(v) ?? 'undefined'; // a field both sides set to an INSTANT is when each wrote, not what: never a conflict const instant = (v: unknown): boolean => typeof v === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d/.test(v) && Number.isFinite(Date.parse(v)); const missing = [...new Set(changeset.actions.map((e) => e.service))].filter((s) => !targetFor.has(s)); if (missing.length) throw new Error(`Cannot rebase changeset "${changeset.name}": no target for ${missing.join(', ')}`); const results: RebaseActionResult[] = []; const actions: ChangesetAction[] = []; for (const entry of changeset.actions) { const target = targetFor.get(entry.service)!; const action = entry.action; const since = sinceCut.get(entry.service); if (action.op === 'set' && since !== undefined) { const mine = resolveReferences(target.stateService, action.subject.type, action.fields ?? {}, aliases.get(entry.service) ?? new Map()); const touching = since.filter((e) => e.op === 'set' && e.subject.type === action.subject.type && (e.subject.id === action.subject.id || e.aliasOf === action.subject.id)); const conflicts: NonNullable = []; for (const e of touching) if (e.fields?.deleted === true && mine.deleted !== true) conflicts.push({ subject: action.subject, field: 'deleted', op: 'exists', expected: true, actual: false }); for (const e of touching) for (const [field, value] of Object.entries(e.fields ?? {})) if (field in mine && stable(mine[field]) !== stable(value) && !(instant(value) && instant(mine[field]))) conflicts.push({ subject: action.subject, field, op: 'set', expected: mine[field], actual: value }); if (conflicts.length) { actions.push(entry); results.push({ actionId: action.id, service: entry.service, status: 'conflict', conflicts }); continue; } if (touching.length) { actions.push(entry); results.push({ actionId: action.id, service: entry.service, status: 'rebased' }); continue; } } actions.push(entry); results.push({ actionId: action.id, service: entry.service, status: 'unchanged' }); } const conflict = results.some((r) => r.status === 'conflict'); const movedAny = results.some((r) => r.status === 'rebased' || r.status === 'rebased-blind'); if (conflict || !movedAny) { return { changeset, report: { changeset: changeset.name, from: changeset.contentHash, to: null, at, outcome: conflict ? 'conflict' : 'unchanged', actions: results } }; } // the cut moves to where the parent stands now: the hash moves with it const cut = Object.fromEntries(opts.targets.map((t) => [t.service, captureParentHistory(t.stateService, t.controlRoot)])); const core = { id: changeset.id, world: changeset.world, base: changeset.base, actions, verifiers: changeset.verifiers, cut }; const rebased: Changeset = { ...changeset, ...core, ...(changeset.narration === undefined ? {} : { narration: narrateActions(actions) }), contentHash: changesetContentHash(core), approvals: [], verification: null, rebasedFrom: { contentHash: changeset.contentHash, at } }; return { changeset: rebased, report: { changeset: changeset.name, from: changeset.contentHash, to: rebased.contentHash, at, outcome: 'rebased', actions: results } }; }