import { captureHistory, historyEntries, historyLength, historyPrefix, readHistoryView } from './history.ts'; // Local branches share parent history at a position and retain a divergence baseline. // The kernel registers parent ownership before publishing the pointer. Lifecycle removal // refuses while a child depends on that storage; direct filesystem deletion bypasses it. import { dirname, join } from 'node:path'; import { checkParent, withHistoryLock } from './ancestry.ts'; import { getActiveWorldStore } from './world-store.ts'; import { writeBranchMeta } from './log.ts'; import { twinResources } from './serve.ts'; import type { TwinResource } from './serve.ts'; import { worldPaths } from './storage.ts'; export type ForkMeta = { service: string; forkedAt: string; baseRoot: string; baseView: string; baseEventCount: number; baseLatestEventId: string | null; // The base twin's resources at fork time — the divergence baseline. baseline: TwinResource[]; }; function forkMetaPath(service: string, root: string): string { return join(dirname(worldPaths(service, root).events), 'fork-meta.json'); } /** * Create a fork of `service` from `fromRoot` into the fresh isolated `toRoot`. * References the base log at a position, then records the divergence baseline. `occurredAt` is supplied by the caller (deterministic; no clock). */ export function forkTwin(opts: { service: string; toRoot: string; fromRoot?: string; occurredAt: string; /** the position in the base's whole log to branch from (contract "Just like Neon", 3); the head when absent */ at?: number; view?: string; expectedGeneration?: string; }): ForkMeta { // under the new branch's history lock; capturing the base nests the base's inside it (child before ancestor) return withHistoryLock(worldPaths(opts.service, opts.toRoot).dir, () => { // A BRANCH IS A POINTER (log.ts): the base root and the position in its logs, nothing copied. // The branch reads the base's parent view and branch log up to that position as its own // parent, and records only its own entries from there. The base keeps appending past the // position without the branch seeing it; destructive lifecycle operations respect this pin. const { service, toRoot } = opts; if (getActiveWorldStore().exists(forkMetaPath(service, toRoot))) { throw new Error(`fork target already initialized for ${service}: ${toRoot}`); } const fromRoot = worldPaths(service, opts.fromRoot).root; if (opts.expectedGeneration !== undefined) checkParent(worldPaths(service, fromRoot).dir, opts.expectedGeneration); else getActiveWorldStore().mkdir(worldPaths(service, fromRoot).dir); const view = opts.view ?? captureHistory(service, fromRoot).view; const descriptor = readHistoryView(worldPaths(service, fromRoot).dir, view); const head = historyLength(descriptor.layout); const at = opts.at ?? head; if (!Number.isInteger(at) || at < 0 || at > head) throw new Error(`Invalid branch position ${at}; parent head is ${head}`); const entries = historyEntries(descriptor); if (at > 0 && at < entries.length && entries[at]?.batch && entries[at]?.batch === entries[at - 1]?.batch) throw new Error(`position ${at} falls inside observation ${entries[at]!.batch}`); const log = entries.slice(0, at); const selected = historyPrefix(descriptor, at); writeBranchMeta(service, { parent: { at: fromRoot, position: at, view }, branchedAt: opts.occurredAt, ...(selected.origin ? { origin: selected.origin } : {}) }, toRoot); const baseline = twinResources(service, toRoot).sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); const meta: ForkMeta = { service, forkedAt: opts.occurredAt, baseRoot: fromRoot, baseView: view, baseEventCount: at, baseLatestEventId: log.at(-1)?.id ?? null, baseline, }; getActiveWorldStore().write(forkMetaPath(service, toRoot), `${JSON.stringify(meta, null, 2)}\n`); return meta; }, { operation: 'pointer publication' }); }