import { parseExactJson } from './exact-json.ts'; // THE LOG (docs/concepts/the-model.md). One kind of entry, one log per // branch, and a branch is a parent plus a position in the parent's log: // // parent log `events.jsonl` what the branch inherited — the origin's history as fetched, the // placeholder's default data, and every entry of this branch that // LANDED on the parent (a push, or a deploy at a root), with its // receipt. Written only by fetch, refresh and landing; never by a // write the app made. // branch log `actions.jsonl` this branch's own entries, in order: every write the app made, // recorded as it was served. Written only by the write path. // branch.json the parent: the placeholder, a base world root at a position, // or a served world's URL. Absent = an unbranched world whose // parent is whatever its parent log holds. // views/.json immutable verified segment ranges and projection layout. // checkpoints/latest.json the tree bound to the exact inherited view: a read is // the checkpoint plus the entries since, never a replay from zero. // // Landing replaces confirm-and-suppress: an entry that lands is COPIED to the parent log with its // receipt (and under the vendor's id when the vendor minted one, `aliasOf` naming the local id), // and the fold skips a branch entry whose id the parent already holds. Nothing is suppressed, // rebound or quarantined by a bookkeeping row; `unpushed` is the branch log minus what the parent // holds. import { captureHistory, historyChanges, historyEntryTime, historyEntries, historyKeptAt, historyLayoutAt, historyLength, historyPrefix, inheritedHistory, inheritedHistoryKey, originHead, readHistoryView, replaceHistoryOrigin, saveHistoryView, validateHistoryOrigin, type HistoryLayout } from './history.ts'; import { dirname, join } from 'node:path'; import { canonicalStatePath, checkParent, commitParentPin, movedStatePaths, pinParent, withAncestryLock, withHistoryLock } from './ancestry.ts'; import { resolveReferences } from './references.ts'; import { hashFieldValue } from './hash.ts'; import type { SubjectFields } from './hash.ts'; import { worldPaths } from './storage.ts'; import { getActiveWorldStore, TREE_FILES } from './world-store.ts'; import type { TwinResource } from './serve.ts'; /** The vendor's answer to one entry, on the entry itself. `landed` = on the parent, waiting; * `deployed` = performed against the vendor; `refused` = a check said no; `failed` = the vendor * said no; `skipped` = after a failure. */ export type Receipt = { status: 'landed' | 'deployed' | 'refused' | 'failed' | 'skipped'; at: string; /** the id the vendor minted, when it differs from the local one */ externalId?: string; url?: string; /** the check that refused, or the vendor's words */ reason?: string; data?: Record; }; export type EntryOp = 'set' | 'revert'; /** One line of a log. `TwinAction` in actions.ts is this type by another name; every field a * write records lives here. */ export type Entry = { /** where the entry came from when not this branch's own write: the placeholder origin (the default data) */ provenance?: 'placeholder'; /** the observation this entry was folded in (a refresh): one id per look; no position falls inside one */ batch?: string; id: string; service: string; op: EntryOp; subject: { type: string; id: string }; occurredAt: string; operation?: string; actor?: { kind: 'agent' | 'human' | 'bot' | 'system'; id?: string }; fields?: SubjectFields; projection?: { creates?: Array<{ type: string; id: string; fields: SubjectFields }>; updates?: Array<{ type: string; id: string; fields: SubjectFields }>; deletes?: Array<{ type: string; id: string }>; emits?: Array<{ kind: 'webhook' | 'event' | 'notification'; target: string; payload: Record }> }; revertsActionId?: string; /** a landed copy: the local entry id this row lands (its subject may carry the vendor's id) */ landsId?: string; /** a landed copy under the vendor's id: the local subject id it stands for */ aliasOf?: string; receipt?: Receipt; /** the W3C traceparent of the request that wrote this entry (trace-context.ts); never part of its identity */ traceparent?: string; [extra: string]: unknown; }; /** A BRANCH IS A POINTER (contract "Just like Neon", 1): its parent — a world at a path, or an origin at * a URL — and the POSITION in the parent's whole log this branch starts from. A path parent is read * through its immutable view, never its mutable current pointer; a URL parent uses a retained * cache view. Only rebase or acknowledged push moves the selected view and position. */ export type BranchMeta = { parent?: { at: string; position: number; view?: string; remoteView?: string; generation?: string; directory?: string; viewDirectory?: string }; branchedAt?: string; origin?: import('./history.ts').HistoryOrigin; fetchedOrigin?: import('./history.ts').HistoryOrigin; previousParents?: Array<{ directory: string; generation: string }>; }; export const CHECKPOINT_EVERY = 100; // Retained checkpoints and process memos are disposable projections, never history. const TREE_PROJECTION_VERSION = 2; export function parentLogPath(service: string, root?: string): string { return worldPaths(service, root).events; } export function branchLogPath(service: string, root?: string): string { return join(dirname(worldPaths(service, root).events), TREE_FILES.branch); } export function branchMetaPath(service: string, root?: string): string { return join(dirname(worldPaths(service, root).events), TREE_FILES.pointer); } /** The fetched cache of a URL parent's whole log — what `fetch` extends and a read folds up to the position. */ export function originLogPath(service: string, root?: string): string { return join(dirname(worldPaths(service, root).events), 'origin.jsonl'); } /** A parent is at a URL when it is not a path on this machine. */ export function isUrlParent(at: string): boolean { return /^[a-z][a-z0-9+.-]*:\/\//i.test(at); } export function checkpointPath(service: string, root?: string): string { return join(dirname(worldPaths(service, root).events), 'checkpoints', 'latest.json'); } // A log only grows by appends, so each store keeps the rows it last parsed per path and parses only what // was appended since: a long walk reads its logs on every request, and re-parsing them made each request's // cost grow with the World's age. Rows are shared between readers and never mutated. On a store that can // read a byte range, only the appended bytes are read: from the start of the last entry parsed, which must // still be that entry (every entry carries its own id), so a log rewritten or replaced is read afresh (an edit in // place that kept the last entry at its byte offset would read as appends; no writer edits a log in place). The // whole file per write, a new string a little longer each time with the last one held, grew a twin's // native memory without bound (a PlanetScale twin: 3.2 GB in a 19-minute walk). type ParsedLog = { rows: unknown[]; lines: number; content?: string; bytes?: number; tail?: string }; const parsedRows = new WeakMap>(); function parseLines(path: string, lines: string[], offset: number, out: T[]): void { for (const [i, line] of lines.entries()) { if (!line.trim()) continue; try { out.push(parseExactJson(line) as T); } catch (error) { throw new Error(`${path}:${offset + i + 1}: invalid JSONL row: ${(error as Error).message}`); } } } /** A log's content from the start of its last non-blank line to its end: what must still stand at that byte offset * for the log to have only grown since. `undefined` when the content does not end a line or holds no entry. */ function tailOf(content: string): string | undefined { if (!content.endsWith('\n')) return undefined; // blank as parseLines reads it: a line that trims to nothing (a CRLF's `\r`, spaces) is no entry let start = content.lastIndexOf('\n', content.length - 2) + 1; while (start > 0 && !content.slice(start, content.indexOf('\n', start)).trim()) start = content.lastIndexOf('\n', start - 2) + 1; if (!content.slice(start, content.indexOf('\n', start)).trim()) return undefined; return content.slice(start); } function readRows(path: string): T[] { const store = getActiveWorldStore(); const cache = parsedRows.get(store) ?? parsedRows.set(store, new Map()).get(store)!; const held = cache.get(path); if (store.readRange && held?.bytes !== undefined && held.tail !== undefined) { const chunk = store.readRange(path, held.bytes - Buffer.byteLength(held.tail)); if (chunk === null) { cache.delete(path); return []; } const appended = chunk.startsWith(held.tail) ? chunk.slice(held.tail.length) : undefined; if (appended === '') return held.rows.slice() as T[]; // only whole appended lines extend the rows; a torn last line is read (and refused) as the whole file reads it if (appended !== undefined && appended.endsWith('\n')) { const rows = held.rows.slice(); const lines = appended.split('\n'); parseLines(path, lines, held.lines, rows); const tail = tailOf(held.tail + appended)!; cache.set(path, { rows, lines: held.lines + lines.length - 1, bytes: held.bytes + Buffer.byteLength(appended), tail }); return rows.slice() as T[]; } } const content = store.read(path); if (content === null) { cache.delete(path); return []; } if (!store.readRange && held?.content !== undefined) { if (held.content === content) return held.rows.slice() as T[]; // an append after a whole row extends the rows already parsed; anything else is parsed afresh if (held.content.endsWith('\n') && content.startsWith(held.content)) { const rows = held.rows.slice(); parseLines(path, content.slice(held.content.length).split('\n'), held.lines, rows); cache.set(path, { content, rows, lines: held.lines + content.slice(held.content.length).split('\n').length - 1 }); return rows.slice() as T[]; } } const rows: T[] = []; const lines = content.split('\n'); parseLines(path, lines, 0, rows); const tail = store.readRange ? tailOf(content) : undefined; cache.set(path, tail !== undefined ? { rows, lines: lines.length - 1, bytes: Buffer.byteLength(content), tail } : { content, rows, lines: lines.length - 1 }); return rows.slice(); } export function readBranchMeta(service: string, root?: string, read?: string | null): BranchMeta | null { // `read`: branch.json's text where the caller has just read it (a tree's stamp reads it once for both uses). const raw = read !== undefined ? read : getActiveWorldStore().read(branchMetaPath(service, root)); if (raw === null) return null; return movedBranchMeta(parseExactJson(raw) as BranchMeta, service, root); } /** Relocate retained references only where the destination holds the same storage generation. */ function movedBranchMeta(meta: BranchMeta, service: string, root?: string): BranchMeta { const own = worldPaths(service, root).dir; const relocation = (directory: string, generation: string | undefined) => { if (generation === undefined) return null; const move = movedStatePaths(directory, own); if (!move) return null; const ancestry = getActiveWorldStore().read(join(move(directory), 'ancestry.json')); return ancestry !== null && (parseExactJson(ancestry) as { generation?: unknown }).generation === generation ? move : null; }; let parent = meta.parent; if (parent) { const directory = parent.directory ?? (!isUrlParent(parent.at) ? worldPaths(service, parent.at).dir : undefined); const move = directory ? relocation(directory, parent.generation) : null; parent = { ...parent, ...(move ? { at: move(parent.at), ...(parent.directory ? { directory: move(parent.directory) } : {}) } : {}), ...(parent.viewDirectory ? { viewDirectory: own } : {}) }; } const origin = (o: BranchMeta['origin']) => { if (!o) return o; const move = relocation(o.directory, o.generation); return move ? { ...o, directory: move(o.directory), at: isUrlParent(o.at) ? o.at : move(o.at) } : o; }; return { ...meta, ...(parent ? { parent } : {}), ...(meta.origin ? { origin: origin(meta.origin) } : {}), ...(meta.fetchedOrigin ? { fetchedOrigin: origin(meta.fetchedOrigin) } : {}), ...(meta.previousParents ? { previousParents: meta.previousParents.map((p) => ({ ...p, directory: relocation(p.directory, p.generation)?.(p.directory) ?? p.directory })) } : {}) }; } export function writeBranchMeta(service: string, meta: BranchMeta, root?: string): void { // Under the branch's own history lock (a capture of its parent's nests inside it, child before ancestor); only the // pin and the pointer's publication take the coordinator. withHistoryLock(worldPaths(service, root).dir, () => { if (meta.parent && (!Number.isInteger(meta.parent.position) || meta.parent.position < 0)) throw new Error('Invalid branch position'); const path = branchMetaPath(service, root); const old = readBranchMeta(service, root); // Tracking can name a different owner from the immediate fork parent. Retain its immutable // view through the existing view dependency mechanism, including empty origin snapshots. for (const origin of [meta.origin, meta.fetchedOrigin]) if (origin) { validateHistoryOrigin(origin); checkParent(origin.directory, origin.generation); const descriptor = historyPrefix(readHistoryView(origin.directory, origin.view), origin.position); saveHistoryView(worldPaths(service, root).dir, { ...descriptor, origin: { ...origin, depth: 0 } }); } const previousParents = [...(old?.previousParents ?? [])]; if (old?.parent?.directory && old.parent.generation) previousParents.push({ directory: old.parent.directory, generation: old.parent.generation }); if (previousParents.length) meta = { ...meta, previousParents: [...new Map(previousParents.map(p => [p.directory, p])).values()] }; let local: { directory: string; view: string; generation?: string } | undefined; if (meta.parent && !isUrlParent(meta.parent.at)) { const directory = canonicalStatePath(worldPaths(service, meta.parent.at).dir); const view = meta.parent.view ?? captureHistory(service, meta.parent.at).view; const viewDirectory = meta.parent.viewDirectory ?? directory; if (meta.parent.viewDirectory && canonicalStatePath(viewDirectory) !== canonicalStatePath(worldPaths(service, root).dir)) throw new Error('Composed history view must belong to this branch'); const descriptor = readHistoryView(viewDirectory, view); historyPrefix(descriptor, meta.parent.position); // the parent the view was captured from: a parent removed or re-created since is refused at the pin local = { directory, view, generation: meta.parent.generation ?? (viewDirectory === directory ? descriptor.owner.generation : undefined) }; } if (meta.parent && isUrlParent(meta.parent.at) && !meta.parent.view) { const head = originHead(service, root); if (head) meta = { ...meta, parent: { ...meta.parent, view: head.view, remoteView: head.remoteView } }; else if (meta.parent.position === 0) { const empty = captureHistory(service, root); meta = { ...meta, parent: { ...meta.parent, view: empty.view } }; } else throw new Error('Origin has no completed immutable history view'); } withAncestryLock(() => { if (local && meta.parent) { const parent = meta.parent; const generation = pinParent(local.directory, path, local.generation); meta = { ...meta, parent: { ...parent, view: local.view, at: canonicalStatePath(parent.at), directory: local.directory, generation } }; } getActiveWorldStore().mkdir(dirname(path)); getActiveWorldStore().writeAtomic(path, `${JSON.stringify(meta, null, 2)}\n`); if (meta.parent?.directory && !isUrlParent(meta.parent.at)) commitParentPin(meta.parent.directory, path); }, { operation: 'pointer publication' }); }, { operation: 'pointer publication' }); } /** This root's own parent-log rows, as entries. */ export function ownParentEntries(service: string, root?: string): Entry[] { return readRows(parentLogPath(service, root)); } /** This root's own branch-log rows. */ export function branchEntries(service: string, root?: string): Entry[] { return readRows(branchLogPath(service, root)); } /** The parent as this branch sees it: the base world's view at the branch position (its parent * log to `parentCount`, its branch log to `branchCount`), then everything this root's own parent * log holds (fetched, refreshed or landed since). An unbranched root is just its own parent log. */ export function parentEntries(service: string, root?: string, _seen?: Set): Entry[] { const view = inheritedHistory(service, root); return [...(view ? historyEntries(view) : []), ...ownParentEntries(service, root)]; } /** The fetched cache of a URL parent's whole log (every entry fetched so far, past the position too). */ export function originEntries(service: string, root?: string): Entry[] { const head = originHead(service, root); return head ? historyEntries(readHistoryView(worldPaths(service, root).dir, head.view)) : readRows(originLogPath(service, root)); } /** Extend the cache with one of the parent's entries; deduplicated by id. */ export function appendOriginEntry(entry: Entry, root?: string): { appended: boolean } { const path = originLogPath(entry.service, root); const store = getActiveWorldStore(); store.mkdir(dirname(path)); return withHistoryLock(worldPaths(entry.service, root).dir, () => store.withLock(`${path}.lock`, () => { if (readRows<{ id?: string }>(path).some((r) => r.id === entry.id)) return { appended: false }; store.append(path, `${JSON.stringify(entry)}\n`); return { appended: true }; }, { operation: 'origin append' }), { operation: 'origin append' }); } /** Ids the parent holds, including the local ids its landed copies stand for. */ export function landedIds(parent: Entry[]): Set { const out = new Set(); for (const e of parent) { out.add(e.id); if (e.landsId) out.add(e.landsId); } return out; } /** The vendor-minted id per local subject: every landed copy that carries `aliasOf`. A local id the * vendor itself holds names the vendor's subject, never the alias: a World that minted a local id * before it had observed the vendor's own subject under that id (its tree was behind) must not fold * the vendor's subject onto the landed one, nor send a caller who addresses the vendor's id there. */ export function aliasesFrom(parent: Entry[]): Map { const vendorHeld = new Set(); for (const e of parent) if (e.batch !== undefined || e.operation === 'observed' || e.provenance === 'placeholder' || (e.landsId !== undefined && e.receipt?.status === 'deployed')) vendorHeld.add(`${e.subject.type}:${e.subject.id}`); const out = new Map(); for (const e of parent) { if (!e.aliasOf || e.aliasOf === e.subject.id) continue; const from = `${e.subject.type}:${e.aliasOf}`; if (!vendorHeld.has(from)) out.set(from, e.subject.id); } return out; } const META = new Set(['id', 'type', 'updatedAt']); export type Subject = { type: string; id: string; updatedAt: string; fields: SubjectFields }; export type Tree = Map; /** Last write per field. `deleted: true` is the tombstone a delete carries; it holds until the subject * is written again (a create under the same address resurrects it — the write need not say so). */ function overlay(tree: Tree, type: string, id: string, fields: SubjectFields, at: string): void { const key = `${type}:${id}`; const existing = tree.get(key) ?? { type, id, updatedAt: at, fields: {} }; const merged: SubjectFields = { ...existing.fields, ...fields }; if (existing.fields.deleted === true && fields.deleted !== true) delete merged.deleted; tree.set(key, { ...existing, updatedAt: at, fields: merged }); } /** One subject read by the same guarded key as a write's answer; restore the vendor's own metadata fields. */ export function heldSubject(service: string, type: string, id: string, root?: string): Subject | undefined { const row = readSubject(service, type, id, root); return row ? { type: row.type, id: row.id, updatedAt: row.updatedAt, fields: ownFields(row) } : undefined; } /** * One local write folded onto its subject as the tree folds its entry (`overlay`): the subject as it was (undefined * for one new to the tree) is copied, never changed. A command's writes staged in `ctx.batch` are read back by * folding them this way, so a read inside the batch sees what the tree will hold once they land (derived-core.ts). */ export function foldLocalWrite(previous: Subject | undefined, type: string, id: string, fields: SubjectFields, at: string): Subject { const key = `${type}:${id}`; const tree: Tree = previous ? new Map([[key, { ...previous, fields: { ...previous.fields } }]]) : new Map(); overlay(tree, type, id, fields, at); return tree.get(key)!; } /** Fold entries onto a tree, in order: `set` overlays its fields and applies its projection; a * reverted entry folds nothing. `skip` names entries the * parent already holds. */ export function foldEntries(tree: Tree, entries: Entry[], skip: Set = new Set()): void { const reverted = new Set(entries.filter((e) => e.op === 'revert' && e.revertsActionId).map((e) => e.revertsActionId!)); for (const e of entries) { if (e.op !== 'set' || reverted.has(e.id) || skip.has(e.id)) continue; // a landed copy the vendor did not take (refused by a check, failed at the vendor) is on the log with // its receipt, and not in the tree: the tree holds what the vendor holds or what is still queued if (e.landsId && (e.receipt?.status === 'refused' || e.receipt?.status === 'failed')) continue; if (e.fields) overlay(tree, e.subject.type, e.subject.id, e.fields, e.occurredAt); if (e.projection) { for (const c of e.projection.creates ?? []) overlay(tree, c.type, c.id, c.fields, e.occurredAt); for (const u of e.projection.updates ?? []) overlay(tree, u.type, u.id, u.fields, e.occurredAt); for (const d of e.projection.deletes ?? []) tree.delete(`${d.type}:${d.id}`); } } } /** Fold aliases: whatever still sits under a local id (a later local update against the id the * caller holds) folds onto the vendor's row. */ export function foldAliases(tree: Tree, aliases: Map, service?: string, only?: Set): void { for (const [fromKey, toId] of aliases) { const stray = tree.get(fromKey); if (!stray) continue; overlay(tree, stray.type, toId, stray.fields, stray.updatedAt); tree.delete(fromKey); } // declared references follow the adoption (docs/contributing/architecture.md#alias-aware-lookup-at-the-request-boundary), whatever order the entries folded in if (service !== undefined && aliases.size > 0) { // `only`: an extension's touched subjects, the only ones an earlier fold has not already resolved for (const s of only ? [...only].map((k) => tree.get(k)).filter((held): held is Subject => held !== undefined) : tree.values()) { const resolved = resolveReferences(service, s.type, s.fields, aliases); if (resolved !== s.fields) s.fields = resolved; } } } /** The tree as resources: `id`, `type` and `updatedAt` are the SUBJECT's. A resource whose own fields * carry a different `id`, `type` or `updatedAt` (a Jira issue has a key and a numeric id; a Stripe * price has a `type` of its own) keeps them BESIDE the row, on a non-enumerable property: a spread, * `Object.entries`, JSON and a conformance sweep never see them, so a pack that serves the row as it * stands serves exactly the vendor's fields it wrote; `ownFields` restores them for a pack that wants * the vendor's own values in the vendor's positions. */ const OWN = Symbol.for('volter.resource.own'); export function treeResources(tree: Tree): TwinResource[] { return [...tree.values()].map((s) => { const out: Record = { id: s.id, type: s.type, updatedAt: s.updatedAt }; const own: Record = {}; for (const [k, v] of Object.entries(s.fields)) { if (!META.has(k)) out[k] = v; else if (v !== undefined) own[k] = v; } if (Object.keys(own).length) Object.defineProperty(out, OWN, { value: own, enumerable: false }); return out as TwinResource; }); } /** A copy of a resource a reader may change: its fields, and the vendor's own id/type/updatedAt it keeps beside them. */ export function copyResource(r: TwinResource): TwinResource { const out = { ...r }; const own = (r as unknown as Record)[OWN]; if (own !== undefined) Object.defineProperty(out, OWN, { value: own, enumerable: false }); return out; } /** A resource's own fields, the vendor's way: the subject's address stripped, its own `id`/`type`/`updatedAt` restored when it had them. */ export function ownFields(r: TwinResource): Record { const { id: _id, type: _type, updatedAt: _at, ...rest } = r; const own = ((r as unknown as Record)[OWN] ?? {}) as { id?: unknown; type?: unknown; updatedAt?: unknown }; // restored first: a vendor's object leads with its id, and a reader's grep may count on the order const out = { ...(own.id !== undefined ? { id: own.id } : {}), ...(own.type !== undefined ? { type: own.type } : {}), ...rest, ...(own.updatedAt !== undefined ? { updatedAt: own.updatedAt } : {}) }; // the own record rides along unseen, so an own view taken of an own view is the same view (never one that drops them) if ((r as unknown as Record)[OWN] !== undefined) Object.defineProperty(out, OWN, { value: own, enumerable: false }); return out; } /** `facts`, when present, is the parent and branch logs' size and version with branch.json at the cut * (parentKeyOf/statKey): a cold read whose facts match trusts the cut without re-hashing the logs. */ type Checkpoint = { parentDigest: string; branchDigest: string; branchCount: number; subjects: Subject[]; facts?: string }; export function dropCheckpoint(service: string, root?: string): void { getActiveWorldStore().remove(checkpointPath(service, root)); } /** Preserve each ancestor's observed-then-local overlay, including landed IDs and aliases. */ export function foldHistory(entries: Entry[], layout: HistoryLayout, service?: string): Tree { const baseCount = layout.base ? historyLength(layout.base) : 0; const tree: Tree = layout.base ? foldHistory(entries.slice(0, baseCount), layout.base, service) : new Map(); const parent = entries.slice(0, baseCount + layout.parent); const inheritedIds = landedIds(parent.slice(0, baseCount)); const ownParent = parent.slice(baseCount); // A local acknowledgement is provenance for an inherited write, not a newer write. // Reapplying it would overwrite later upstream fields (including vendor counters). // Deployment outcomes remain observations and must still fold their returned fields. const acknowledged = new Set([...inheritedIds, ...ownParent.filter(e => e.landsId && e.receipt?.status === 'landed' && inheritedIds.has(e.landsId)).map(e => e.id)]); foldEntries(tree, ownParent, acknowledged); foldEntries(tree, entries.slice(baseCount + layout.parent, baseCount + layout.parent + layout.branch), landedIds(parent)); foldAliases(tree, aliasesFrom(parent), service); return tree; } /** * One subject of the current tree as a resource, by its type and id: the resource `projectResources(...).find` gives * for the same type and id, read by the subject's key without cloning or projecting the rest of the tree. Every subject is * held under `${type}:${id}` (overlay is the only setter, and an alias re-keys through it), so the key is the * subject. A write’s answer reads its subject directly without projecting the rest of the tree. */ export function readSubject(service: string, type: string, id: string, root?: string): TwinResource | undefined { const key = `${type}:${id}`; const held = currentTree(service, root).tree.get(key); // a type or id holding ':' can share a key with another (type, id): only the subject itself is it if (!held || held.type !== type || held.id !== id) return undefined; return treeResources(new Map([[key, { ...held, fields: { ...held.fields } }]]))[0]; } export function readTree(service: string, root?: string, opts: { until?: string; at?: number; view?: string } = {}): TwinResource[] { return treeResources(readTreeMap(service, root, opts)); } /** * The twin's resources as they stood at a past instant of the World: the same fold as the current tree (inherited * history, this root's parent log, its branch log, in their layout), over the entries that had occurred by `instant` * (an entry's receipt time where it landed, else its occurrence; an observation kept whole), as a branch cut there * would hold them. It saves no view and writes nothing: a read may ask it (a scenario's `lag`, derived-core.ts). */ export function readTreeAsOf(service: string, instant: string, root?: string): TwinResource[] { const stamp = Date.parse(instant); if (!Number.isFinite(stamp)) throw new Error(`Invalid history instant ${instant}`); return withHistoryLock(worldPaths(service, root).dir, () => { const inherited = inheritedHistory(service, root); const own = ownParentEntries(service, root); const branch = branchEntries(service, root); const layout: HistoryLayout = { ...(inherited ? { base: inherited.layout } : {}), parent: own.length, branch: branch.length }; const kept = historyKeptAt([...(inherited ? historyEntries(inherited) : []), ...own, ...branch], layout, stamp); return treeResources(foldHistory(kept.entries, kept.layout, service)); }, { operation: 'tree fold' }); } /** The upstream view for observation diffing, without this root's local overlay. Inherited * history keeps its own layout: an ancestor's local writes are part of our pinned base. */ export function readParentTreeMap(service: string, root?: string): Tree { return withHistoryLock(worldPaths(service, root).dir, () => { const inherited = inheritedHistory(service, root); const own = ownParentEntries(service, root); return foldHistory([...(inherited ? historyEntries(inherited) : []), ...own], { ...(inherited ? { base: inherited.layout } : {}), parent: own.length, branch: 0, }, service); }, { operation: 'tree fold' }); } // A READ'S TREE, MEMOIZED per store and per process or isolate. What a read folds is named by cheap // facts: the parent log's size and version with branch.json (whose parent names an immutable history // view and a position), and the branch log's size and version (WorldStore.stat: every append or // rewrite by any writer changes them). While they stand, the fold is the same, and a hit hands out a // clone, as the checkpoint path does. When only the branch log grew by appends (the common write), the // memoized tree is extended in place with just the new entries (the memo's subjects are never handed // out: every read gets a clone), and the extension records which subjects it touched, so a pack's own // projection of the tree can follow a write without refolding (`treeChangesSince`). Anything else is the // full read below. Without it every read re-parsed and re-hashed the World's whole log to validate its // checkpoint (a 6448-event Jira World: seconds per request). /** One extension of a memo: the subjects it touched, and those it put at the tree's end (a subject new to the tree, * or deleted and made again), in the order they now stand there. */ type TreeStep = { from: string; to: string; keys: Set; appended: string[] }; type TreeMemo = { parentKey: string; branchKey: string; branchCount: number; lastBranchId: string | null; landed: Set; aliases: Map; tree: Tree; steps: TreeStep[] }; const treeMemos = new WeakMap>(); /** How many extensions a memo remembers the touched subjects of; a projection further behind refolds. */ const TREE_STEPS_KEPT = 64; function statKey(path: string): string { const s = getActiveWorldStore().stat(path); return s ? `${s.size}:${s.mtimeMs}` : '-'; } /** What a service's PARENT side at `root` is folded from (its parent log, branch.json and inherited history), as one * string: while it stands, its aliases and landed ids are the same, whatever the branch's own log does. */ export function parentStamp(service: string, root?: string): string { return treeFacts(service, root).parentKey; } function parentKeyOf(service: string, root?: string): string { return parentFacts(service, root).key; } /** The parent side's key, and whether it names a file outside the tree's own directory (an inherited view). */ function parentFacts(service: string, root?: string): { key: string; inherits: boolean } { // branch.json is small and every stamp needs it: kept while its own facts stand (world-store.ts readKept), so an // unchanged pointer costs one check. Its text is still in the key, so a changed pointer still moves the stamp. const store = getActiveWorldStore(), pointer = branchMetaPath(service, root); const meta = store.readKept ? store.readKept(pointer) : store.read(pointer); const inherited = inheritedHistoryKey(service, root, meta); return { key: `${TREE_PROJECTION_VERSION}|${statKey(parentLogPath(service, root))}|${meta ?? ''}|${inherited}`, inherits: inherited !== '' }; } // ONE QUESTION PER STAMP, WHERE THE STORE KEEPS A GENERATION (world-store.ts FsWorldStore.generation, which states // what makes it sound and where that stops). A stamp was three questions of the file system, on every operation of // every twin: the parent log, the pointer and the branch log, the first two of files a World with no parent does not // have. The facts are kept under the generation read BEFORE them, and served while the generation still reads the // same. Never kept: where the directory has no generation yet (nothing has been written there by a store that keeps // one), and where the parent side names files of other directories (an inherited view: its ancestors' writes move no // generation here). Both are asked in full, as before. type TreeFacts = { parentKey: string; branchKey: string }; const keptFacts = new WeakMap>(); function treeFacts(service: string, root?: string): TreeFacts { const store = getActiveWorldStore(); const branchLog = branchLogPath(service, root); if (!store.generation) return { parentKey: parentKeyOf(service, root), branchKey: statKey(branchLog) }; const directory = dirname(branchLog); const generation = store.generation(directory); let kept = keptFacts.get(store); if (!kept) { kept = new Map(); keptFacts.set(store, kept); } const held = kept.get(directory); if (generation !== null && held?.generation === generation) return held; const parent = parentFacts(service, root); const facts = { parentKey: parent.key, branchKey: statKey(branchLog) }; if (generation !== null && !parent.inherits) kept.set(directory, { ...facts, generation }); else kept.delete(directory); return facts; } /** What a service's tree (and every subject's history) at `root` is folded from, as one string: while it * stands, nothing was written. A pack that projects the tree into its own state memoizes on it. */ export function treeStamp(service: string, root?: string): string { const facts = treeFacts(service, root); return `${facts.parentKey}#${facts.branchKey}`; } const cloneTree = (tree: Tree): Tree => new Map([...tree].map(([k, s]) => [k, { ...s, fields: { ...s.fields } }])); const memoStamp = (m: TreeMemo): string => `${m.parentKey}#${m.branchKey}`; /** The subject keys entries write (as foldEntries folds them), and the vendor rows an alias moves a local one onto. */ function touchedKeys(entries: Entry[], aliases: Map): Set { const keys = new Set(); for (const e of entries) { if (e.fields) keys.add(`${e.subject.type}:${e.subject.id}`); for (const c of e.projection?.creates ?? []) keys.add(`${c.type}:${c.id}`); for (const u of e.projection?.updates ?? []) keys.add(`${u.type}:${u.id}`); for (const d of e.projection?.deletes ?? []) keys.add(`${d.type}:${d.id}`); } for (const key of [...keys]) { const to = aliases.get(key); if (to !== undefined) keys.add(`${key.slice(0, key.indexOf(':'))}:${to}`); } return keys; } /** The keys `fold` inserts into `tree` (a Map puts an inserted key at its end, so a key deleted and set again moves * there too), in the order they then stand, each once. */ function insertionsDuring(tree: Tree, fold: () => void): string[] { const order = new Map(); const own = tree as Tree & { set: Tree['set'] }; own.set = (key, value) => { if (!tree.has(key)) { order.delete(key); order.set(key, true); } return Map.prototype.set.call(tree, key, value) as Tree; }; try { fold(); } finally { delete (own as { set?: unknown }).set; } return [...order.keys()].filter((k) => tree.has(k)); } export function readTreeMap(service: string, root?: string, opts: { until?: string; at?: number; view?: string } = {}): Tree { if (opts.until !== undefined || opts.at !== undefined || opts.view !== undefined) return readTreeMapFull(service, root, opts); const read = currentTree(service, root); return read.memo ? cloneTree(read.tree) : read.tree; } /** The current tree: the memo's own (never to be handed out) when the memo holds it, else a fresh fold. */ function currentTree(service: string, root?: string): { tree: Tree; memo?: TreeMemo } { const store = getActiveWorldStore(); let memos = treeMemos.get(store); if (!memos) { memos = new Map(); treeMemos.set(store, memos); } const slot = `${service}\u0000${root ?? ''}`; // A hit needs no lock: a memo is only ever stored from a fold made under the history lock, and while the // facts still match that fold, nothing was written since. A writer mid-batch has moved them. const unlocked = memos.get(slot); if (unlocked) { const facts = treeFacts(service, root); if (unlocked.parentKey === facts.parentKey && unlocked.branchKey === facts.branchKey) return { tree: unlocked.tree, memo: unlocked }; } return withHistoryLock(worldPaths(service, root).dir, () => { const parentKey = parentKeyOf(service, root); const branchKey = statKey(branchLogPath(service, root)); const held = memos.get(slot); if (held && held.parentKey === parentKey && held.branchKey === branchKey) return { tree: held.tree, memo: held }; const branch = branchEntries(service, root); const last = (entries: Entry[]): string | null => (entries.length ? entries[entries.length - 1]!.id : null); if (held && held.parentKey === parentKey && branch.length >= held.branchCount && (held.branchCount === 0 ? held.lastBranchId === null : branch[held.branchCount - 1]?.id === held.lastBranchId) && !branch.slice(held.branchCount).some((e) => e.op === 'revert')) { extendMemo(memos, slot, held, branch.slice(held.branchCount), branchKey, service); return { tree: held.tree, memo: held }; } const tree = readTreeMapFull(service, root); const parent = parentEntries(service, root); // the facts are read again after the fold: a write that raced it leaves nothing memoized if (parentKeyOf(service, root) === parentKey && statKey(branchLogPath(service, root)) === branchKey) { const memo: TreeMemo = { parentKey, branchKey, branchCount: branch.length, lastBranchId: last(branch), landed: landedIds(parent), aliases: aliasesFrom(parent), tree, steps: [] }; memos.set(slot, memo); return { tree, memo }; } return { tree }; }, { operation: 'tree fold' }); } /** The memo extended in place by `fresh`, the branch log's entries after its own, which leave the log at `branchKey`, * with the step that records the subjects they touched. */ function extendMemo(memos: Map, slot: string, held: TreeMemo, fresh: Entry[], branchKey: string, service: string): void { const keys = touchedKeys(fresh, held.aliases); const from = memoStamp(held); let appended: string[]; try { appended = insertionsDuring(held.tree, () => { foldEntries(held.tree, fresh, held.landed); foldAliases(held.tree, held.aliases, service, keys); }); } catch (error) { memos.delete(slot); throw error; } // a half-folded memo is never read again Object.assign(held, { branchKey, branchCount: held.branchCount + fresh.length, lastBranchId: fresh.length ? fresh[fresh.length - 1]!.id : held.lastBranchId }); held.steps.push({ from, to: memoStamp(held), keys, appended }); if (held.steps.length > TREE_STEPS_KEPT) held.steps.splice(0, held.steps.length - TREE_STEPS_KEPT); } /** Append whole JSONL lines under the history lock. Extend the read memo only when the store proves this was * the sole write, the parent's facts are unchanged and the log grew by exactly these bytes. Answer the log's * resulting size and modification time for callers keyed on those facts. */ export function appendToBranchLog(service: string, root: string | undefined, data: string, append: () => void): string | undefined { const store = getActiveWorldStore(); const memos = treeMemos.get(store); const slot = `${service}\u0000${root ?? ''}`; const held = memos?.get(slot); const branchLog = branchLogPath(service, root); const directory = dirname(branchLog); const kept = keptFacts.get(store)?.get(directory); const standing = held !== undefined && kept !== undefined && kept.parentKey === held.parentKey && kept.branchKey === held.branchKey; const before = standing && store.generation && store.generationAfterOwnWrite ? store.generation(directory) : null; append(); if (!memos || !held || !kept || before === null || kept.generation !== before) return undefined; const after = store.generationAfterOwnWrite!(directory, before); if (after === null) return undefined; // read after the generation, as treeFacts reads its facts. The parent side is read again too: a writer the generation // does not see (one outside this store, or one that died before its second byte) may have moved it under the kept // generation, and carried forward its old key would outlive every append this process makes. const branchKey = statKey(branchLog); if (parentKeyOf(service, root) !== kept.parentKey) return branchKey; const grown = (key: string): number => (key === '-' ? 0 : Number(key.slice(0, key.indexOf(':')))); const fresh: Entry[] = []; // line numbers in a refusal count from this append's first line parseLines(`${branchLog} (appended)`, data.split('\n'), 0, fresh); if (grown(branchKey) !== grown(held.branchKey) + Buffer.byteLength(data) || fresh.some((e) => e.op === 'revert')) return branchKey; // the write has landed: a fold that fails here drops the memo (extendMemo) and the next read folds in full, never failing the write try { extendMemo(memos, slot, held, fresh, branchKey, service); } catch { return branchKey; } keptFacts.get(store)!.set(directory, { parentKey: kept.parentKey, branchKey, generation: after }); return branchKey; } /** What changed in a service's tree since `since` (a `treeStamp` an earlier read was made at): the subjects * written since, as resources; the keys (`type:id`) of those no longer in the tree; and, of the changed, the keys * now at the tree's end in the order they stand there (new to the tree, or deleted and made again), which a * projection kept in the tree's order moves to its end in that order, updating the rest where they stand. * `undefined` when this process cannot say (no memo, the parent moved, a revert, or `since` older than the memo * remembers): the caller refolds. `stamp` is the state the answer brings the caller to. */ export function treeChangesSince(service: string, root: string | undefined, since: string): { stamp: string; changed: TwinResource[]; removed: string[]; appended: string[] } | undefined { const { tree, memo } = currentTree(service, root); if (!memo) return undefined; const stamp = memoStamp(memo); if (since === stamp) return { stamp, changed: [], removed: [], appended: [] }; const first = memo.steps.findIndex((s) => s.from === since); if (first < 0) return undefined; const keys = new Set(); const order = new Map(); for (let i = first; i < memo.steps.length; i++) { if (i > first && memo.steps[i]!.from !== memo.steps[i - 1]!.to) return undefined; for (const k of memo.steps[i]!.keys) keys.add(k); for (const k of memo.steps[i]!.appended) { order.delete(k); order.set(k, true); } } if (memo.steps[memo.steps.length - 1]!.to !== stamp) return undefined; const present: Tree = new Map(); const removed: string[] = []; for (const k of keys) { const s = tree.get(k); if (s) present.set(k, s); else removed.push(k); } return { stamp, changed: treeResources(present), removed, appended: [...order.keys()].filter((k) => tree.has(k)) }; } /** The tree at each of several positions of a twin's history, folded from one capture of it: what * `readTreeMap(service, root, { at })` answers for each, without capturing the history again per position (a * changeset's field changes read one position per write, and a capture reads the whole log). */ export function readTreeMapsAt(service: string, root: string | undefined, positions: Iterable): Map { return withHistoryLock(worldPaths(service, root).dir, () => { const view = captureHistory(service, root).descriptor; const entries = historyEntries(view); const trees = new Map(); for (const at of positions) if (!trees.has(at)) trees.set(at, treeAt(view, entries, at, service)); return trees; }); } /** The tree after a view's first `at` entries; a position inside an observation has none. */ function treeAt(view: ReturnType['descriptor'], entries: Entry[], at: number, service: string): Tree { if (at > 0 && at < entries.length && entries[at]?.batch && entries[at]?.batch === entries[at - 1]?.batch) { let from = at; let to = at; const batch = entries[at]!.batch; while (from > 0 && entries[from - 1]?.batch === batch) from--; while (to < entries.length && entries[to]?.batch === batch) to++; throw new Error(`position ${at} falls inside observation ${batch} — use ${from} or ${to}`); } return foldHistory(entries.slice(0, at), historyLayoutAt(view.layout, at), service); } function readTreeMapFull(service: string, root?: string, opts: { until?: string; at?: number; view?: string } = {}): Tree { return withHistoryLock(worldPaths(service, root).dir, () => { if (opts.at !== undefined || opts.view !== undefined) { const view = opts.view ? readHistoryView(worldPaths(service, root).dir, opts.view) : captureHistory(service, root).descriptor; return treeAt(view, historyEntries(view), opts.at ?? historyLength(view.layout), service); } // a cold read (no memo) trusts a checkpoint cut at exactly these log facts without re-hashing the logs const facts = opts.until === undefined ? `${parentKeyOf(service, root)}#${statKey(branchLogPath(service, root))}` : null; if (facts !== null) { const held = getActiveWorldStore().read(checkpointPath(service, root)); const cut = held === null ? null : parseExactJson(held) as Checkpoint; if (cut?.facts === facts) return new Map(cut.subjects.map(s => [`${s.type}:${s.id}`, { ...s, fields: { ...s.fields } }])); } const inherited = inheritedHistory(service, root); const base = inherited ? historyEntries(inherited) : []; const own = ownParentEntries(service, root); const parent = [...base, ...own]; const branchAll = branchEntries(service, root); const until = opts.until === undefined ? -1 : branchAll.findIndex(e => e.id === opts.until); const branch = until < 0 ? branchAll : branchAll.slice(0, until); const parentDigest = hashFieldValue({ projectionVersion: TREE_PROJECTION_VERSION, inherited, own }); const branchDigest = hashFieldValue(branch); const raw = opts.until === undefined ? getActiveWorldStore().read(checkpointPath(service, root)) : null; const cp = raw === null ? null : parseExactJson(raw) as Checkpoint; if (cp?.parentDigest === parentDigest && cp.branchDigest === branchDigest) return new Map(cp.subjects.map(s => [`${s.type}:${s.id}`, { ...s, fields: { ...s.fields } }])); const layout: HistoryLayout = { ...(inherited ? { base: inherited.layout } : {}), parent: own.length, branch: branch.length }; const incremental = cp?.parentDigest === parentDigest && cp.branchCount <= branch.length && hashFieldValue(branch.slice(0, cp.branchCount)) === cp.branchDigest && !branch.slice(cp.branchCount).some(e => e.op === 'revert'); const tree: Tree = incremental ? new Map(cp.subjects.map(s => [`${s.type}:${s.id}`, { ...s, fields: { ...s.fields } }])) : foldHistory([...parent, ...branch], layout, service); if (incremental) { foldEntries(tree, branch.slice(cp.branchCount), landedIds(parent)); foldAliases(tree, aliasesFrom(parent), service); } if (opts.until === undefined && parent.length + branch.length > CHECKPOINT_EVERY) { // the facts are the ones this fold read; recorded only if no write moved them while it folded const now = `${parentKeyOf(service, root)}#${statKey(branchLogPath(service, root))}`; getActiveWorldStore().writeAtomic(checkpointPath(service, root), JSON.stringify({ parentDigest, branchDigest, branchCount: branch.length, subjects: [...tree.values()], ...(now === facts ? { facts } : {}) })); } return tree; }, { operation: 'tree fold' }); } export function cutCheckpoint(service: string, root?: string): void { return withHistoryLock(worldPaths(service, root).dir, () => { dropCheckpoint(service, root); const subjects = [...readTreeMap(service, root).values()]; const inherited = inheritedHistory(service, root); const own = ownParentEntries(service, root); getActiveWorldStore().writeAtomic(checkpointPath(service, root), JSON.stringify({ parentDigest: hashFieldValue({ projectionVersion: TREE_PROJECTION_VERSION, inherited, own }), branchDigest: hashFieldValue(branchEntries(service, root)), branchCount: branchEntries(service, root).length, subjects })); }, { operation: 'checkpoint' }); } /** The branch's entries the parent does not hold: `set` rows, not reverted, not landed. */ export function unpushedEntries(service: string, root?: string): Entry[] { const landed = landedIds(parentEntries(service, root)); const branch = branchEntries(service, root); const reverted = new Set(branch.filter((e) => e.op === 'revert' && e.revertsActionId).map((e) => e.revertsActionId!)); return branch.filter((e) => e.op === 'set' && !reverted.has(e.id) && !landed.has(e.id)); } /** The position a branch is cut at: how far the parent view and the branch log reach right now. */ /** THE POSITION (contract "Just like Neon", 2): where this twin's whole log stands — one number, the * count of entries, parent view then branch. Durable cuts pair it with an immutable view ID. */ export function position(service: string, root?: string): number { return parentEntries(service, root).length + branchEntries(service, root).length; } /** The position of a twin's log at an instant: the entries that had occurred by then. */ export function positionAt(service: string, instant: string, root?: string, view?: string): number { const t = Date.parse(instant); const log = view ? historyEntries(readHistoryView(worldPaths(service, root).dir, view)) : wholeLog(service, root); let n = 0; for (const e of log) { if (historyEntryTime(e) <= t) n += 1; else break; } if (log.slice(n).some(e => historyEntryTime(e) <= t)) throw new Error('This instant selects noncontiguous history; use historyAtInstant to capture a view instead of a numeric offset'); // an observation is atomic: an instant inside one look resolves to the look's end while (n > 0 && n < log.length && log[n]!.batch !== undefined && log[n]!.batch === log[n - 1]!.batch) n += 1; return n; } /** The batch a position would split, if any: `position` entries taken, and the next entry belongs to the * same observation as the last one taken. Answers the boundaries a caller may use instead. */ export function splitsBatch(service: string, position: number, root?: string): { batch: string; from: number; to: number } | null { const log = wholeLog(service, root); if (position <= 0 || position >= log.length) return null; const batch = log[position]!.batch; if (batch === undefined || log[position - 1]!.batch !== batch) return null; let from = position - 1; while (from > 0 && log[from - 1]!.batch === batch) from -= 1; let to = position; while (to < log.length && log[to]!.batch === batch) to += 1; return { batch, from, to }; } /** Refuse a position inside an observation, naming the boundaries. */ export function assertBatchBoundary(service: string, position: number, root?: string): void { const split = splitsBatch(service, position, root); if (split) throw new Error(`position ${position} falls inside observation ${split.batch} (entries ${split.from + 1}–${split.to}); an observation is atomic — use ${split.from} or ${split.to}`); } /** A landed copy of `entry` for the parent log: the receipt on it, the vendor's id as its subject * when one was minted. Deterministic id, so landing twice is the same row. */ export function landedCopy(entry: Entry, receipt: Receipt, opts: { vendorSubjectId?: string; fields?: SubjectFields; subject?: { type: string; id: string } } = {}): Entry { const subject = opts.subject ?? entry.subject; const adopted = opts.vendorSubjectId !== undefined && opts.vendorSubjectId !== '' && opts.vendorSubjectId !== subject.id ? { type: subject.type, id: opts.vendorSubjectId } : subject; const fields = opts.fields ?? entry.fields ?? {}; const contentHash = hashFieldValue({ landsId: entry.id, subject: adopted, fields, status: receipt.status }); const { event: _event, receipt: _receipt, aliasOf: _aliasOf, landsId: _landsId, ...body } = entry; return { ...body, id: `landed:${entry.service}:${adopted.type}:${adopted.id}:${entry.id}:${contentHash}`, op: 'set', subject: adopted, fields, landsId: entry.id, ...(adopted.id !== subject.id ? { aliasOf: subject.id } : {}), receipt, }; } /** Append an entry to this root's own parent log — what fetch does with what origin sends, and what * a served world does with nothing (its pushes land on its branch log). Deduplicated by id. */ // The parent log's entry ids, per store and path, valid while the file's size and version are the ones // recorded (WorldStore.stat changes on any writer's append): a batch of appends dedupes against an index, // not by re-parsing the whole log each time. const parentIdIndex = new WeakMap }>>(); export function appendParentEntry(entry: Entry, root?: string): { appended: boolean } { const path = parentLogPath(entry.service, root); const store = getActiveWorldStore(); store.mkdir(dirname(path)); return withHistoryLock(worldPaths(entry.service, root).dir, () => store.withLock(`${path}.lock`, () => { let indexes = parentIdIndex.get(store); if (!indexes) { indexes = new Map(); parentIdIndex.set(store, indexes); } let index = indexes.get(path); if (!index || index.key !== statKey(path)) { index = { key: statKey(path), ids: new Set(readRows<{ id?: string }>(path).flatMap((r) => (typeof r.id === 'string' ? [r.id] : []))) }; indexes.set(path, index); } if (index.ids.has(entry.id)) return { appended: false }; store.append(path, `${JSON.stringify(entry)}\n`); index.ids.add(entry.id); index.key = statKey(path); return { appended: true }; }, { operation: 'parent append' }), { operation: 'parent append' }); } /** The whole log of a twin as a served world hands it out: the parent view, then the branch's own * entries, one sequence with a position. A clone's parent is exactly this. */ export function wholeLog(service: string, root?: string): Entry[] { return [...parentEntries(service, root), ...branchEntries(service, root)]; } /** * REBASE a branch onto its base's current position (contract: "rebase replays the branch's * entries over a newer base, conflicts per subject and field"). A branch is a pointer, so the * base moving is invisible until this: the pointer advances to the base's present position, the * branch's own entries stay in place and now fold over the moved base, and every entry whose * preconditions no longer hold against the new parent tree is named as a conflict — data on the * result, never a stop. An unbranched world (no pointer) has nothing to rebase. */ export function rebaseBranch(service: string, root?: string, opts: { origin?: boolean } = {}): { moved: boolean; from: number; to: number; conflicts: Array<{ entryId: string; subject: { type: string; id: string }; field: string; op: string; expected?: unknown; actual?: unknown }> } { return withHistoryLock(worldPaths(service, root).dir, () => { const meta = readBranchMeta(service, root); if (!meta?.parent) return { moved: false, from: 0, to: 0, conflicts: [] }; if (opts.origin && !meta.origin) throw new Error('This local fork has no tracked origin; clone the origin before branching'); const from = meta.parent.position; let tracked = meta.origin && (opts.origin || meta.origin.depth === 0) ? meta.fetchedOrigin ?? { ...meta.origin, depth: 0 } : undefined; if (tracked && !opts.origin && !isUrlParent(tracked.at)) { const live = captureHistory(service, tracked.at); tracked = { ...tracked, directory: live.descriptor.owner.directory, generation: live.descriptor.owner.generation, view: live.view, position: live.position }; } if (tracked && !meta.origin!.incomplete && tracked.directory === meta.origin!.directory && tracked.view === meta.origin!.view && tracked.position === meta.origin!.position && tracked.remoteView === meta.origin!.remoteView) { if (meta.fetchedOrigin) writeBranchMeta(service, { ...meta, fetchedOrigin: undefined }, root); return { moved: false, from, to: from, conflicts: [] }; } const head = tracked ?? (isUrlParent(meta.parent.at) ? originHead(service, root) : captureHistory(service, meta.parent.at)); if (!head) throw new Error('Origin has no completed immutable history view'); const directory = isUrlParent(meta.parent.at) ? worldPaths(service, root).dir : worldPaths(service, meta.parent.at).dir; const previous = inheritedHistory(service, root)!; const next = tracked ? replaceHistoryOrigin(previous, meta.origin!, tracked) : readHistoryView(directory, head.view); const nextView = tracked ? saveHistoryView(worldPaths(service, root).dir, next) : head.view; const to = historyLength(next.layout); const moved = to !== from || nextView !== meta.parent.view; // Compare the evaluated old and new views, including removals and reordered layers. const before = historyEntries(previous); const since = historyChanges(service, previous, next); // only a subject that EXISTED at this branch's position can conflict: two branches each minting the // same local id for different records is not a disagreement (the vendor mints the real id) const existed = new Set(before.filter((e) => e.op === 'set').flatMap((e) => [`${e.subject.type}:${e.subject.id}`, ...(e.aliasOf ? [`${e.subject.type}:${e.aliasOf}`] : [])])); // conflicts: a field this branch set that the parent set since, to something else — named by // entry, subject and field (contract "Drift and rebase in v2") const stable = (v: unknown): string => JSON.stringify(v) ?? 'undefined'; // a field both sides set to an INSTANT (updated_at, created) 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 currentAliases = aliasesFrom(historyEntries(next)); const incomingLanded = landedIds(historyEntries(next)); const conflicts: Array<{ entryId: string; subject: { type: string; id: string }; field: string; op: string; expected?: unknown; actual?: unknown }> = []; // Acknowledged writes, including their counter effects, now belong to the incoming parent. // Comparing them again against a later upstream write creates conflicts with already-landed work. for (const e of unpushedEntries(service, root).filter(e => !incomingLanded.has(e.id))) { if (e.op !== 'set' || !e.fields || !existed.has(`${e.subject.type}:${e.subject.id}`)) continue; const fields = resolveReferences(service, e.subject.type, e.fields, currentAliases); for (const p of since) { if (p.op !== 'set' || !p.fields || p.subject.type !== e.subject.type || (p.subject.id !== e.subject.id && p.aliasOf !== e.subject.id)) continue; if (p.fields.deleted === true && fields.deleted !== true) conflicts.push({ entryId: e.id, subject: e.subject, field: 'deleted', op: 'exists', expected: true, actual: false }); for (const [field, value] of Object.entries(p.fields)) if (field in fields && stable(fields[field]) !== stable(value) && !(instant(value) && instant(fields[field]))) conflicts.push({ entryId: e.id, subject: e.subject, field, op: 'set', expected: fields[field], actual: value }); } } if (moved) { const { viewDirectory: _oldViewDirectory, ...parent } = meta.parent; writeBranchMeta(service, { ...meta, fetchedOrigin: undefined, origin: tracked ? { ...tracked, depth: meta.origin!.depth } : next.origin, parent: { ...parent, position: to, view: nextView, ...(tracked ? { viewDirectory: canonicalStatePath(worldPaths(service, root).dir) } : {}), ...('remoteView' in head ? { remoteView: head.remoteView } : {}) } }, root); dropCheckpoint(service, root); } return { moved, from, to, conflicts }; }, { operation: 'branch-pointer adjustment' }); } /** * HISTORY through the kernel: every entry that touched a subject (or every subject of a type), parent * log then branch log, in order, with reverted entries dropped and landed copies shown once. A pack * that serves a changelog (Jira's), or must never reuse an id it once minted, reads this — never a * log file. Each entry's `fields` is what it set; the fold is the reader's. */ export function subjectHistory(service: string, subject: { type: string; id?: string }, root?: string): Entry[] { const parent = parentEntries(service, root); const held = landedIds(parent); const branch = branchEntries(service, root); const reverted = new Set(branch.filter((e) => e.op === 'revert' && e.revertsActionId).map((e) => e.revertsActionId!)); const touches = (e: Entry): boolean => e.op === 'set' && e.subject.type === subject.type && (subject.id === undefined || e.subject.id === subject.id || e.aliasOf === subject.id); return [...parent.filter((e) => touches(e) && e.fields !== undefined), ...branch.filter((e) => touches(e) && !reverted.has(e.id) && !held.has(e.id))]; }