@sema-agent/core
Version:
Stateless, task-oriented AI agent core
3,884 lines • 174 kB
JavaScript
import { closeSync, constants as fsConstants, copyFileSync, existsSync, fstatSync, fsyncSync, ftruncateSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, utimesSync, writeFileSync, writeSync } from "node:fs";
const { O_WRONLY, O_RDONLY, O_RDWR, O_CREAT, O_NOFOLLOW, O_NONBLOCK, O_EXCL } = fsConstants;
import { homedir } from "node:os";
import { createHash, randomUUID } from "node:crypto";
import { basename, dirname, isAbsolute, join, parse, posix, relative, resolve, sep, win32 } from "node:path";
import { MEMORY_GOVERNANCE_DOC_NAMES, MEMORY_ORIGIN_CAUSES } from "./types.js";
import { parseEntryFile } from "./frontmatter.js";
import { carriesEntry, MEMORY_INDEX_FILENAME } from "./entry-scan.js";
import { normalizeProjectId } from "./scope-contract.js";
import { PRIVATE_FILE_MODE, openExclusiveTemp } from "../exclusive-temp.js";
import { physicalPathOf, physicalPathOfExisting, priorCallerCasedPathOf } from "../physical-path.js";
import { dataRootWrittenFrom, splitSpellingOf } from "../data-root.js";
import { deliverEngineNotice } from "../engine-notice.js";
import { adoptHostPromise } from "../host-promise.js";
import { anchorAtLinkDir } from "../../engine/execution-env/symlink-chain.js";
import { sensitiveRowOf } from "../sensitive-path-policy.js";
import { readMember, thrownLabel, thrownText } from "../thrown-value.js";
import { egressText } from "../untrusted-egress.js";
import { optionKeys, receiptRefusal, receiveMembers } from "../own-property-receipt.js";
import { describeRejectedValue } from "../tool-search-setting.js";
const REANCHOR_OPTION_KEYS = optionKeys()({ controlDir: 0, expectedFrom: 0, onIncident: 0 });
const ANNOUNCEMENT_OPTION_KEYS = optionKeys()({ supersedesPrefix: 0 });
const SCOPES_FILE = "scopes.json";
export const CURSORS_FILE = "cursors.json";
export const CONTROL_PLANE_DIR = ".engine";
export class ControlPlaneCorruptError extends Error {
facet;
code;
detail;
constructor(message, opts) {
super(message, opts?.cause !== undefined ? { cause: opts.cause } : undefined);
this.name = "ControlPlaneCorruptError";
if (opts?.facet !== undefined)
this.facet = opts.facet;
if (opts?.rootAnchor !== undefined) {
this.code = ROOT_ANCHOR_DAMAGED;
this.detail = { path: opts.rootAnchor.path, controlDir: opts.rootAnchor.controlDir };
}
}
}
export const ROOT_ANCHOR_DAMAGED = "memory.root_anchor_damaged";
export function isRootAnchorRefusal(thrown) {
return readMember(thrown, "code") === ROOT_ANCHOR_DAMAGED;
}
function slugifyPath(absPath) {
return absPath.normalize("NFC").replace(/[^A-Za-z0-9]/g, "-");
}
export function deriveRepoKey(repoRoot) {
return slugifyPath(canonicalize(resolve(repoRoot)));
}
function deriveDirKey(dir) {
return slugifyPath(resolve(dir));
}
function subtreeHasFiles(dir) {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
}
catch {
return true;
}
for (const e of entries) {
if (!e.isDirectory())
return true;
if (subtreeHasFiles(join(dir, e.name)))
return true;
}
return false;
}
function pruneFilelessDirTree(dir) {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
}
catch {
return !existsSync(dir);
}
for (const e of entries) {
if (!e.isDirectory())
return false;
if (!pruneFilelessDirTree(join(dir, e.name)))
return false;
}
try {
rmdirSync(dir);
return true;
}
catch {
return false;
}
}
function tryAdoptByRename(fromDir, toDir) {
try {
renameSync(fromDir, toDir);
return { ok: true };
}
catch (err) {
return { ok: false, code: err.code, error: err };
}
}
function migrateKeyedPartition(m) {
const disclose = (code, message) => {
try {
const e = new Error(message);
e.code = code;
m.onIncident?.(e);
}
catch {
}
};
const splitText = `memory partition split detected for ${m.subject}: BOTH ${m.fromDir} and ${m.toDir} hold content. This session uses ${m.toDir}; the other dir is left untouched (never merged — CAS baselines would collide). If it holds the newer memory, move its rows by hand and remove it.`;
try {
if (m.fromDir === m.toDir || canonicalize(m.fromDir) === canonicalize(m.toDir))
return;
if (!existsSync(m.fromDir))
return;
if (existsSync(m.toDir) && subtreeHasFiles(m.toDir)) {
disclose("memory.partition_split", splitText);
return;
}
ensureDirExists(dirname(m.toDir));
let outcome = tryAdoptByRename(m.fromDir, m.toDir);
if (!outcome.ok && (outcome.code === "EEXIST" || outcome.code === "ENOTEMPTY") && !subtreeHasFiles(m.toDir) && pruneFilelessDirTree(m.toDir)) {
outcome = tryAdoptByRename(m.fromDir, m.toDir);
}
if (outcome.ok)
return;
const { code, error } = outcome;
if ((code === "ENOENT" || code === "EEXIST" || code === "ENOTEMPTY") && existsSync(m.toDir)) {
if (!existsSync(m.fromDir))
return;
disclose("memory.partition_split", splitText);
return;
}
disclose("memory.partition_adopt_failed", `could not adopt the memory partition ${m.fromDir} → ${m.toDir} (${code ?? thrownLabel(error)}): this session proceeds on ${m.toDir}; ` +
`${m.fromDir} still holds the prior memory — move it by hand.`);
}
catch {
}
}
export function adoptLegacyRepoDirs(configRoot, repoRoot, onIncident) {
const toDir = join(configRoot, deriveRepoKey(repoRoot));
for (const key of earlierRepoKeysOf(repoRoot)) {
migrateKeyedPartition({ fromDir: join(configRoot, key), toDir, subject: repoRoot, onIncident });
}
}
export function earlierRepoKeysOf(repoRoot) {
const today = deriveRepoKey(repoRoot);
const keys = [deriveDirKey(repoRoot)];
try {
keys.push(slugifyPath(priorCallerCasedPathOf(resolve(repoRoot))));
}
catch {
}
return [...new Set(keys)].filter((k) => k !== today);
}
export function adoptCanonicalKeyedControlDir(configRoot, dir, onIncident) {
migrateKeyedPartition({
fromDir: join(configRoot, deriveRepoKey(dir), CONTROL_PLANE_DIR),
toDir: join(configRoot, deriveDirKey(dir), CONTROL_PLANE_DIR),
subject: dir,
onIncident,
});
}
export function deriveRepoMemoryDir(configRoot, repoRoot) {
return join(configRoot, deriveRepoKey(repoRoot), "memory");
}
export function deriveProjectMemoryDir(configRoot, projectId) {
return join(configRoot, `proj-${normalizeProjectId(projectId)}`, "memory");
}
export function deriveProjectControlDir(configRoot, projectId) {
return join(configRoot, `proj-${normalizeProjectId(projectId)}`, CONTROL_PLANE_DIR);
}
export const PROJECT_ID_HINTS_FILE = "project-id-hints.json";
export function recordProjectIdHint(configRoot, repoRoot, projectId) {
try {
const path = join(configRoot, PROJECT_ID_HINTS_FILE);
let hints = {};
try {
const parsed = JSON.parse(readFileSync(path, "utf8"));
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed))
hints = parsed;
}
catch {
}
const key = resolve(repoRoot);
const norm = normalizeProjectId(projectId);
if (hints[key] === norm)
return;
hints[key] = norm;
ensureDirExists(configRoot);
atomicWriteFileSync(path, `${JSON.stringify(hints, null, 2)}\n`);
}
catch {
}
}
export function lookupProjectIdHint(configRoot, repoRoot) {
try {
const parsed = JSON.parse(readFileSync(join(configRoot, PROJECT_ID_HINTS_FILE), "utf8"));
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
return undefined;
const v = parsed[resolve(repoRoot)];
return typeof v === "string" ? v : undefined;
}
catch {
return undefined;
}
}
export function deriveControlPlaneDir(configRoot, key) {
return join(configRoot, deriveDirKey(key), CONTROL_PLANE_DIR);
}
function pathUnderRoot(root, dir) {
const rel = relative(resolve(root), resolve(dir));
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel) ? rel : undefined;
}
function adoptPlaneMovedWithRoot(configRoot, dir) {
const rel = pathUnderRoot(configRoot, dir);
if (rel === undefined)
return;
const toDir = deriveControlPlaneDir(configRoot, dir);
const travelled = planesTravelledWith(configRoot, dir, rel, toDir);
if (travelled.length === 0)
return;
if (travelled.length > 1)
throw controlPlaneSplitRefusal(dir, { planes: travelled.map(planeKeyOf), documents: [] });
const fromDir = travelled[0];
assertStoreRootsNotSensitive(dir, toDir);
if (moveWholePlane(fromDir, toDir))
return;
mergeTravelledPlane(dir, fromDir, toDir);
}
function planeKeyOf(controlDir) {
return basename(dirname(controlDir));
}
function planesTravelledWith(configRoot, dir, rel, toDir) {
const tail = slugifyPath(`${sep}${rel}`);
let keys;
try {
keys = readdirSync(configRoot);
}
catch (err) {
if (err.code === "ENOENT")
return [];
throw new ControlPlaneCorruptError(`the memory engine root ${configRoot} could not be listed (${err.code ?? thrownLabel(err)}) — whether the control plane of ${dir} travelled there with a moved root cannot be established, so the store was not opened`, { cause: err });
}
const found = [];
for (const key of keys) {
if (key === planeKeyOf(toDir) || !key.endsWith(tail))
continue;
const plane = join(configRoot, key, CONTROL_PLANE_DIR);
let anchor;
try {
const st = lstatOrAbsent(plane);
if (st === undefined || !st.isDirectory())
continue;
anchor = readStoreRootAnchor(plane, dir);
}
catch (err) {
if (err.code === "ENOTDIR")
continue;
throw new ControlPlaneCorruptError(`the memory control plane ${key} under the engine root ${configRoot} may have travelled there for ${dir}, but it cannot be read (${err instanceof ControlPlaneCorruptError ? "its root anchor is damaged or unreadable" : (err.code ?? thrownLabel(err))}) — whether it holds this store's records (capture opt-outs among them) cannot be established, so the store was not opened; repair or remove that plane's root anchor, then reopen`, { cause: err });
}
if (anchor === undefined)
continue;
const had = resolve(anchor.spelling);
if (deriveDirKey(had) !== key || !had.endsWith(`${sep}${rel}`))
continue;
const wasUnder = [had.slice(0, had.length - rel.length - 1)];
if (anchor.realpath.endsWith(`${sep}${rel}`))
wasUnder.push(anchor.realpath.slice(0, anchor.realpath.length - rel.length - 1));
if ([anchor.realpath, had, ...wasUnder].every(nothingStandsAt))
found.push(plane);
}
return found.sort();
}
function moveWholePlane(fromDir, toDir) {
const held = () => existsSync(toDir) && subtreeHasFiles(toDir);
try {
if (!held()) {
ensureDirExists(dirname(toDir));
let outcome = tryAdoptByRename(fromDir, toDir);
if (!outcome.ok && (outcome.code === "EEXIST" || outcome.code === "ENOTEMPTY") && !subtreeHasFiles(toDir) && pruneFilelessDirTree(toDir)) {
outcome = tryAdoptByRename(fromDir, toDir);
}
if (!outcome.ok && !nothingStandsAt(fromDir) && !held())
throw travelledPlaneRefusal(fromDir, toDir, outcome.code ?? thrownLabel(outcome.error), outcome.error);
}
}
catch (err) {
throw err instanceof ControlPlaneCorruptError ? err : travelledPlaneRefusal(fromDir, toDir, err.code ?? thrownLabel(err), err);
}
if (!nothingStandsAt(fromDir))
return false;
removeEmptyKeyDir(fromDir);
return true;
}
function removeEmptyKeyDir(fromDir) {
try {
rmdirSync(dirname(fromDir));
}
catch {
}
}
function travelledPlaneRefusal(fromDir, toDir, why, cause) {
return new ControlPlaneCorruptError(`the memory control plane that moved with the engine root (${fromDir}) could not be moved to ${toDir}, where the store's directory is keyed now (${why}) — a new one opened there would drop what it records (capture opt-outs, the ledger, quarantine), so the store was not opened; move the directory by hand while nothing has the store open, then reopen`, { cause });
}
function heldThere(src, dst) {
const there = lstatOrAbsent(dst);
if (there === undefined)
return "absent";
const here = lstatOrAbsent(src);
if (here === undefined)
return "same";
return here.isFile() && there.isFile() && readFileSync(src).equals(readFileSync(dst)) ? "same" : "differs";
}
function bringOver(fromDir, toDir, rel) {
const src = join(fromDir, rel);
const dst = join(toDir, rel);
try {
const here = lstatOrAbsent(src);
if (here === undefined)
return "same";
if (!here.isFile())
return "differs";
ensureDirExists(dirname(dst));
try {
linkSync(src, dst);
}
catch (err) {
if (err.code === "ENOENT" && nothingStandsAt(src))
return "same";
if (err.code !== "EEXIST")
throw err;
const held = heldThere(src, dst);
if (held === "differs")
return held;
}
rmSync(src, { force: true });
return "absent";
}
catch (err) {
throw travelledPlaneRefusal(fromDir, toDir, `${rel}: ${err.code ?? thrownLabel(err)}`, err);
}
}
function isOneTimeRecord(rel) {
if (rel.length === 1)
return rel[0] === STORE_IDENTITY_FILE;
return rel.length === 2 && Object.values(FILE_CONTROL_OBJECT_DIRS).includes(rel[0]);
}
function isTransientControlEntry(rel) {
const [top] = rel;
if (top === undefined)
return false;
if (rel.length === 1)
return top.startsWith(ATOMIC_WRITE_TMP_PREFIX) || top.startsWith(LINK_PROBE_PREFIX);
return isTransientControlDir(top);
}
function isTransientControlDir(name) {
return name === CONTROL_OBJECT_STAGE_DIR || name.endsWith(".lock") || name.includes(`.lock${LOCK_TOMB_INFIX}`);
}
function controlPlaneItems(dir, under = []) {
const out = [];
for (const e of readdirSync(join(dir, ...under), { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
if (e.isDirectory())
out.push(...controlPlaneItems(dir, [...under, e.name]));
else
out.push([...under, e.name]);
}
return out;
}
function mergeTravelledPlane(dir, fromDir, toDir) {
let items;
try {
items = controlPlaneItems(fromDir).filter((rel) => !isTransientControlEntry(rel) && !(rel.length === 1 && rel[0] === ROOT_ANCHOR_FILE));
}
catch (err) {
if (nothingStandsAt(fromDir))
return;
throw travelledPlaneRefusal(fromDir, toDir, err.code ?? thrownLabel(err), err);
}
const split = [];
for (const rel of items.filter(isOneTimeRecord))
if (bringOver(fromDir, toDir, join(...rel)) === "differs")
split.push(join(...rel));
const rest = items.filter((rel) => !isOneTimeRecord(rel)).map((rel) => join(...rel));
for (const rel of rest) {
let held;
try {
held = heldThere(join(fromDir, rel), join(toDir, rel));
}
catch (err) {
throw travelledPlaneRefusal(fromDir, toDir, `${rel}: ${err.code ?? thrownLabel(err)}`, err);
}
if (held === "differs")
split.push(rel);
}
if (split.length > 0)
throw controlPlaneSplitRefusal(dir, { planes: [planeKeyOf(toDir), planeKeyOf(fromDir)], documents: split.sort() });
for (const rel of rest)
if (bringOver(fromDir, toDir, rel) === "differs")
throw controlPlaneSplitRefusal(dir, { planes: [planeKeyOf(toDir), planeKeyOf(fromDir)], documents: [rel] });
try {
renameSync(join(fromDir, ROOT_ANCHOR_FILE), join(toDir, ROOT_ANCHOR_FILE));
}
catch (err) {
if (err.code !== "ENOENT")
throw travelledPlaneRefusal(fromDir, toDir, `${ROOT_ANCHOR_FILE}: ${err.code ?? thrownLabel(err)}`, err);
}
try {
for (const e of readdirSync(fromDir, { withFileTypes: true })) {
if (e.isDirectory() ? isTransientControlDir(e.name) : isTransientControlEntry([e.name]))
rmSync(join(fromDir, e.name), { recursive: true, force: true });
}
}
catch {
}
pruneFilelessDirTree(fromDir);
removeEmptyKeyDir(fromDir);
}
export function deriveRepoControlPlaneDir(configRoot, repoRoot) {
return join(configRoot, deriveRepoKey(repoRoot), CONTROL_PLANE_DIR);
}
export function directoryPinOf(backend) {
const pinned = backend?.directoryRoot;
return typeof pinned === "string" && pinned !== "" ? pinned : undefined;
}
export function controlPlanePinOf(backend) {
const root = backend?.controlPlaneRoot;
return typeof root === "string" && root !== "" ? root : undefined;
}
export function effectiveControlRootOf(dir, opts = {}) {
const pinned = controlPlanePinOf(opts.pinnedBy);
if (pinned !== undefined)
return pinned;
if (opts.controlDir !== undefined) {
const configRoot = dirname(dirname(opts.controlDir));
if (deriveControlPlaneDir(configRoot, dir) === opts.controlDir)
adoptPlaneMovedWithRoot(configRoot, dir);
return opts.controlDir;
}
const configRoot = resolveMemoryEngineRoot();
const control = deriveControlPlaneDir(configRoot, dir);
assertStoreRootsNotSensitive(dir, control);
adoptCanonicalKeyedControlDir(configRoot, dir, opts.onIncident);
adoptPlaneMovedWithRoot(configRoot, dir);
return control;
}
export function resolveMemoryEngineRoot(explicit) {
return resolveRunMemoryEngineRoot(explicit, undefined);
}
export function resolveRunMemoryEngineRoot(explicit, onNotice) {
const written = dataRootWrittenFrom(explicit, () => process.env.AGENT_DATA_DIR, homedir);
let cwd;
const root = memoryRootOf(written, () => (cwd = process.cwd()));
const split = splitSpellingOf(written, onNotice, cwd);
if (split !== undefined)
announceDataRootSpellingSplit(split, onNotice);
return root;
}
function memoryRootOf(written, cwd) {
const raw = written.normalize("NFC");
return isAbsolute(raw) ? raw : resolve(cwd(), raw);
}
export function resolveMemoryEngineRootFrom(explicit, facts) {
const given = facts;
const bad = (what, value) => {
throw receiptRefusal(`resolveMemoryEngineRootFrom: ${what} (got ${describeRejectedValue(value)})`);
};
if (typeof given !== "object" || given === null)
bad("the facts must be a record { agentDataDir, home, cwd }", given);
const { agentDataDir, home, cwd } = given;
if (!Object.hasOwn(given, "agentDataDir"))
bad("facts.agentDataDir is a required key (write undefined for a process without AGENT_DATA_DIR)", agentDataDir);
if (agentDataDir !== undefined && typeof agentDataDir !== "string")
bad("facts.agentDataDir must be a string or undefined", agentDataDir);
if (typeof home !== "string")
bad("facts.home must be a string", home);
if (typeof cwd !== "string" || cwd === "" || !isAbsolute(cwd))
bad("facts.cwd must be a non-empty absolute path", cwd);
const written = dataRootWrittenFrom(explicit, () => agentDataDir, () => home);
const readsProcess = memoryRootReadsProcess(written, cwd, process.platform === "win32" ? win32 : posix);
if (readsProcess !== undefined)
bad(readsProcess, written);
return memoryRootOf(written, () => cwd);
}
export function memoryRootReadsProcess(written, cwd, api) {
if (api.sep !== "\\")
return undefined;
if (api.isAbsolute(written))
return undefined;
if (api.parse(written).root !== "")
return "a drive-relative value (D:x) is read against that drive's directory, a process fact — give an absolute path";
if (api.parse(cwd).root.length < 3)
return "facts.cwd names no drive or share, so a relative value would be read against the process's current drive";
return undefined;
}
function subdirectoriesNamed(dir) {
let names;
try {
names = readdirSync(dir, { withFileTypes: true })
.filter((e) => e.isDirectory())
.map((e) => e.name)
.sort();
}
catch {
return "(not readable)";
}
if (names.length === 0)
return "none";
return names.length > 16 ? `${names.slice(0, 16).join(", ")} and ${names.length - 16} more` : names.join(", ");
}
function announceDataRootSpellingSplit(split, onNotice) {
deliverEngineNotice(onNotice, {
code: "config.data_root_spelling_split",
message: `[sema] the memory root is written in a decomposed spelling (${JSON.stringify(split.written)}); the engine opens its composed (NFC) ` +
`spelling ${JSON.stringify(split.opened)}, ${split.state === "moved" ? "which does not exist yet — the memory kept under the written spelling is not read" : "and the written spelling's directory holds data too — the memory is split across the two"}. ` +
`Nothing was moved or removed. To keep using it, stop the engine and rename ${JSON.stringify(split.written)} to ${JSON.stringify(split.opened)}` +
`${split.state === "both" ? ` after merging the two (subdirectories under the written spelling: ${subdirectoriesNamed(split.written)}; under the composed spelling: ${subdirectoriesNamed(split.opened)})` : ""}.`,
detail: { written: split.written, opened: split.opened, state: split.state },
});
}
export function scopeDirName(scope) {
if (/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(scope))
return scope;
const cleaned = scope.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[.-]+/, "") || "scope";
const hash = createHash("sha256").update(scope, "utf8").digest("hex").slice(0, 6);
return `${cleaned}-${hash}`;
}
let caseFoldProbeSeq = 0;
function lstatOrAbsent(p) {
try {
return lstatSync(p);
}
catch (err) {
if (err.code === "ENOENT")
return undefined;
throw err;
}
}
function probeDirCaseFolds(dir) {
const name = `${CASEFOLD_PROBE_PREFIX}${process.pid}-${caseFoldProbeSeq++}`;
const writeLeg = (() => {
let fd;
try {
fd = openSync(join(dir, name), O_WRONLY | O_CREAT | O_EXCL, 0o600);
}
catch {
return undefined;
}
let identity;
try {
const st = fstatSync(fd);
identity = { dev: st.dev, ino: st.ino };
}
catch {
}
finally {
closeSync(fd);
}
const isProbe = (st) => identity !== undefined && st.dev === identity.dev && st.ino === identity.ino;
try {
let swapped;
let orig;
try {
swapped = lstatOrAbsent(join(dir, name.toUpperCase()));
orig = lstatOrAbsent(join(dir, name));
}
catch {
return undefined;
}
if (orig === undefined || !isProbe(orig))
return undefined;
if (swapped === undefined)
return false;
return isProbe(swapped) ? true : undefined;
}
finally {
try {
rmSync(join(dir, name), { force: true });
}
catch {
}
}
})();
if (writeLeg !== undefined)
return writeLeg;
try {
for (const entry of readdirSync(dir)) {
if (!/[A-Za-z]/.test(entry))
continue;
const swapped = entry.toLowerCase() !== entry ? entry.toLowerCase() : entry.toUpperCase();
try {
const orig = lstatOrAbsent(join(dir, entry));
if (orig === undefined)
continue;
const other = lstatOrAbsent(join(dir, swapped));
const again = lstatOrAbsent(join(dir, entry));
if (again === undefined || again.dev !== orig.dev || again.ino !== orig.ino)
continue;
if (other === undefined)
return false;
return other.dev === orig.dev && other.ino === orig.ino;
}
catch {
continue;
}
}
}
catch {
}
return undefined;
}
export function dirCaseFolds(dir) {
let before;
try {
ensureDirExists(dir);
before = dirIdentity(dir);
}
catch {
return undefined;
}
const folds = probeDirCaseFolds(dir);
if (folds === undefined)
return undefined;
try {
return dirIdentity(dir) === before ? folds : undefined;
}
catch {
return undefined;
}
}
function dirIdentity(dir) {
const s = statSync(dir, { bigint: true });
return `${s.dev}:${s.ino}`;
}
export const SCOPE_DIR_LABEL_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
export const CASEFOLD_PROBE_PREFIX = ".casefold-probe-";
export const SCOPE_REGISTRY_SHAPES = Object.freeze(["absent", "v1", "v2", "migrating"]);
export const REGISTRY_SHAPE_DERIVES_PATHS = {
absent: true,
v1: false,
v2: true,
migrating: false,
};
function ownLabel(scopes, scope) {
return scopes !== undefined && Object.prototype.hasOwnProperty.call(scopes, scope) ? scopes[scope] : undefined;
}
function readScopesRecord(controlDir) {
const path = join(controlDir, SCOPES_FILE);
const journalPath = `${path}.journal`;
let raw;
let sourcePath = journalPath;
try {
raw = readFileSync(journalPath, "utf8");
}
catch (err) {
if (err.code !== "ENOENT") {
throw new ControlPlaneCorruptError(`scope registry journal unreadable (${err.code ?? "io error"}) — a committed next state may exist that cannot be proven: ${journalPath}`, { cause: err });
}
raw = undefined;
}
if (raw === undefined) {
sourcePath = path;
try {
raw = readFileSync(path, "utf8");
}
catch (err) {
if (err.code === "ENOENT")
return { shape: "absent", rec: { v: 2, scopes: {} } };
throw new ControlPlaneCorruptError(`scope registry unreadable (${err.code ?? "io error"}): ${path}`, { cause: err });
}
}
let parsed;
try {
parsed = JSON.parse(raw);
}
catch {
throw new ControlPlaneCorruptError(`scope registry is unparseable: ${sourcePath}`);
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
throw new ControlPlaneCorruptError(`scope registry has the wrong shape: ${path}`);
}
const rec = parsed;
const scopes = coerceScopeLabels(rec.scopes, path);
if (rec.v === undefined) {
if (rec.rootScope !== undefined && typeof rec.rootScope !== "string") {
throw new ControlPlaneCorruptError(`scope registry rootScope is not a string: ${path}`);
}
return { shape: "v1", ...(rec.rootScope !== undefined ? { rootScope: rec.rootScope } : {}), scopes };
}
if (rec.v !== 2) {
throw new ControlPlaneCorruptError(`scope registry version ${JSON.stringify(rec.v)} is not one this engine reads (expected 2): ${path}`);
}
for (const [k, label] of Object.entries(scopes)) {
if (!SCOPE_DIR_LABEL_RE.test(label)) {
throw new ControlPlaneCorruptError(`scope registry maps ${JSON.stringify(k)} to the label ${JSON.stringify(label)}, which is not a single non-hidden path segment — refusing (fail-closed): ${path}`);
}
}
if (rec.rootOwner !== undefined && typeof rec.rootOwner !== "string") {
throw new ControlPlaneCorruptError(`scope registry rootOwner is not a string: ${path}`);
}
const v2 = { v: 2, scopes, ...(rec.rootOwner !== undefined ? { rootOwner: rec.rootOwner } : {}) };
if (rec.migrating === undefined)
return { shape: "v2", rec: v2 };
const m = rec.migrating;
if (!m || typeof m !== "object" || Array.isArray(m) || typeof m.root !== "string" || typeof m.owner !== "string" || typeof m.label !== "string" || !SCOPE_DIR_LABEL_RE.test(m.label)) {
throw new ControlPlaneCorruptError(`scope registry carries a malformed migrating marker: ${path}`);
}
return { shape: "migrating", rec: { ...v2, migrating: { root: m.root, owner: m.owner, label: m.label } } };
}
function coerceScopeLabels(raw, path) {
if (raw === undefined)
return {};
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new ControlPlaneCorruptError(`scope registry scopes map has the wrong shape: ${path}`);
}
const out = Object.create(null);
for (const [k, v] of Object.entries(raw)) {
if (typeof v !== "string")
throw new ControlPlaneCorruptError(`scope registry entry ${JSON.stringify(k)} is not a string: ${path}`);
out[k] = v;
}
return out;
}
function requireV2Registry(read, controlDir) {
if (REGISTRY_SHAPE_DERIVES_PATHS[read.shape])
return read.rec;
throw new ControlPlaneCorruptError(read.shape === "v1"
? `scope registry is in the v1 (pre-v2, root-owning) form at ${join(controlDir, SCOPES_FILE)} — scope homes cannot be derived until the layout adoption has run (a mount or a locked backend face runs it); refusing (fail-closed)`
: `scope registry carries an unfinished layout move (migrating marker) at ${join(controlDir, SCOPES_FILE)} — scope homes cannot be derived until the move completes (the next mount or locked backend face finishes it); refusing (fail-closed)`);
}
function commitScopesRecord(controlDir, lock, token, next) {
const file = join(controlDir, SCOPES_FILE);
const journal = `${file}.journal`;
const data = `${JSON.stringify(next, null, 2)}\n`;
const fence = () => assertSidecarLockOwnership(lock, token, "scope registry", "strict");
fence();
let current;
try {
current = readFileSync(file, "utf8");
}
catch {
current = undefined;
}
if (current === data)
return;
atomicWriteFileSync(journal, data);
fence();
atomicWriteFileSync(file, data);
fence();
rmSync(journal, { force: true });
}
function withScopesRegistry(controlDir, fn) {
ensureControlPlaneDir(controlDir);
const file = join(controlDir, SCOPES_FILE);
const journal = `${file}.journal`;
const lock = `${file}.lock`;
const token = acquireSidecarLock(lock, { onDeadline: "throw" });
try {
rollForwardStrictSidecar(file, journal, () => assertSidecarLockOwnership(lock, token, "scope registry", "strict"));
return fn({
read: () => readScopesRecord(controlDir),
commit: (next) => commitScopesRecord(controlDir, lock, token, next),
renew: () => {
const now = new Date();
utimesSync(lock, now, now);
assertSidecarLockOwnership(lock, token, "scope registry", "strict");
},
});
}
finally {
releaseSidecarLock(lock, token);
}
}
function assertNoLabelCollision(memoryDir, scopes, scope, label, caseFoldingFs) {
for (const [other, otherLabel] of Object.entries(scopes)) {
if (other === scope)
continue;
if (otherLabel === label) {
throw new ControlPlaneCorruptError(`scope directory collision: ${JSON.stringify(scope)} and ${JSON.stringify(other)} both map to ${JSON.stringify(label)} — refusing (fail-closed)`);
}
if (otherLabel.toLowerCase() === label.toLowerCase()) {
const folds = caseFoldingFs ?? dirCaseFolds(memoryDir);
if (folds !== false) {
throw new ControlPlaneCorruptError(`scope directory collision on a case-folding filesystem: ${JSON.stringify(scope)} → ${JSON.stringify(label)} and ${JSON.stringify(other)} → ${JSON.stringify(otherLabel)} are one physical directory under ${memoryDir}` +
`${folds === undefined ? " (volume case semantics could not be probed — refusing the fold-equal pair rather than risking a silent cross-scope merge)" : ""} — refusing (fail-closed)`);
}
}
}
}
function assertHomePhysicalForm(home) {
const st = lstatOrAbsent(home);
if (st === undefined)
return "absent";
if (st.isDirectory())
return "dir";
throw scopeHomeRefusal(st.isSymbolicLink() ? "symlink" : st.isFile() ? "file" : "other", home);
}
function ensureScopeHome(home) {
if (assertHomePhysicalForm(home) === "absent") {
try {
mkdirSync(home, { recursive: true });
}
catch (err) {
assertHomePhysicalForm(home);
throw err;
}
}
assertHomePhysicalForm(home);
}
export function registerScope(memoryDir, controlDir, scope, opts) {
return withScopesRegistry(controlDir, ({ read, commit }) => {
const rec = requireV2Registry(read(), controlDir);
const registered = ownLabel(rec.scopes, scope);
const label = registered ?? scopeDirName(scope);
assertNoLabelCollision(memoryDir, rec.scopes, scope, label, opts?.caseFoldingFs);
const home = join(memoryDir, label);
if (registered === undefined) {
ensureDirExists(memoryDir);
ensureScopeHome(home);
commit({ ...rec, scopes: { ...rec.scopes, [scope]: label } });
}
else {
assertHomePhysicalForm(home);
}
return home;
});
}
export function registeredScopes(controlDir) {
return requireV2Registry(readScopesRecord(controlDir), controlDir).scopes;
}
export function scopeDirFor(memoryDir, controlDir, scope) {
const rec = requireV2Registry(readScopesRecord(controlDir), controlDir);
return join(memoryDir, ownLabel(rec.scopes, scope) ?? scopeDirName(scope));
}
export function scopeRegistryShape(controlDir) {
return readScopesRecord(controlDir).shape;
}
export function v1MemoryPathKeyResolver(controlDir) {
const read = readScopesRecord(controlDir);
const owner = read.shape === "v1" ? read.rootScope : read.rec.rootOwner;
const scopes = read.shape === "v1" ? read.scopes : read.rec.scopes;
const byLabel = new Map();
for (const [scope, label] of Object.entries(scopes))
if (label !== "" && scope !== owner)
byLabel.set(label, scope);
return (relPath) => {
const norm = relPath.split(sep).join("/");
const cut = norm.indexOf("/");
if (cut > 0) {
const scope = byLabel.get(norm.slice(0, cut));
if (scope !== undefined)
return { scope, rel: norm.slice(cut + 1) };
}
return owner === undefined ? undefined : { scope: owner, rel: norm };
};
}
const UNOWNED_ROOT_CONTENT_NAMES_MAX = 8;
function discloseLayoutIncident(sink, code, message) {
if (sink === undefined)
return;
try {
const e = new Error(message);
e.code = code;
sink(e);
}
catch {
}
}
function sameEntry(a, b) {
const sa = lstatOrAbsent(a);
const sb = lstatOrAbsent(b);
return sa !== undefined && sb !== undefined && sa.dev === sb.dev && sa.ino === sb.ino;
}
function looseRootContent(root, labels, controlDir) {
let names;
try {
names = readdirSync(root);
}
catch (err) {
if (err.code === "ENOENT")
return { names: [], probes: [] };
throw new ControlPlaneCorruptError(`memory root ${root} could not be enumerated for the layout adoption (${err.code ?? "io error"}) — refusing (fail-closed)`, { cause: err });
}
const canonicalControl = canonicalize(controlDir);
const out = [];
const probes = [];
const foldedLabels = new Map();
for (const label of labels)
foldedLabels.set(label.toLowerCase(), label);
for (const name of names.sort()) {
if (labels.has(name))
continue;
if (name.startsWith(CASEFOLD_PROBE_PREFIX)) {
probes.push(name);
continue;
}
if (canonicalize(join(root, name)) === canonicalControl)
continue;
const label = foldedLabels.get(name.toLowerCase());
if (label !== undefined && sameEntry(join(root, name), join(root, label)))
continue;
out.push(name);
}
return { names: out, probes };
}
export function layoutNeedsAdoption(root, controlDir) {
const read = readScopesRecord(controlDir);
if (read.shape === "v1" || read.shape === "migrating")
return true;
const { names, probes } = looseRootContent(root, new Set(Object.values(read.rec.scopes)), controlDir);
return names.length > 0 || probes.length > 0;
}
export function adoptRootScopeLayout(rootPath, controlDir, opts = {}) {
const root = resolve(rootPath);
withScopesRegistry(controlDir, (ctx) => {
const renew = () => {
ctx.renew();
opts.renew?.();
};
const convertSidecars = () => {
renew();
opts.convertSidecars?.(controlDir);
};
const read = ctx.read();
let rec;
let converting = false;
if (read.shape === "v1") {
converting = true;
const scopes = Object.create(null);
for (const [scope, label] of Object.entries(read.scopes)) {
if (label === "")
continue;
if (!SCOPE_DIR_LABEL_RE.test(label)) {
throw new ControlPlaneCorruptError(`scope registry (v1 form) maps ${JSON.stringify(scope)} to the label ${JSON.stringify(label)}, which is not a single non-hidden path segment — refusing (fail-closed): ${join(controlDir, SCOPES_FILE)}`);
}
scopes[scope] = label;
}
rec = { v: 2, scopes, ...(read.rootScope !== undefined ? { rootOwner: read.rootScope } : {}) };
if (read.rootScope !== undefined && ownLabel(scopes, read.rootScope) === undefined) {
const label = scopeDirName(read.rootScope);
assertNoLabelCollision(root, scopes, read.rootScope, label, undefined);
const home = join(root, label);
if (assertHomePhysicalForm(home) === "dir" && readdirSync(home).length > 0) {
throw new ControlPlaneCorruptError(`memory root ${root} holds a non-empty directory ${home} named like the home of its root-owning scope ${JSON.stringify(read.rootScope)} — the layout adoption cannot tell a topic directory from a home; resolve by hand (fail-closed)`);
}
rec.scopes = { ...scopes, [read.rootScope]: label };
}
}
else if (read.shape === "migrating") {
rec = read.rec;
const m = read.rec.migrating;
const { migrating: _m, ...rest } = rec;
rec = { ...rest, scopes: { ...rec.scopes, [m.owner]: m.label }, rootOwner: m.owner };
moveLooseContent(m.root, controlDir, rec, m.owner, m.label, renew, opts.onIncident, true);
convertSidecars();
ctx.commit(rec);
if (canonicalize(m.root) === canonicalize(root))
return;
}
else {
rec = read.rec;
}
const labels = new Set(Object.values(rec.scopes));
const { names, probes } = looseRootContent(root, labels, controlDir);
if (names.length === 0) {
if (converting) {
convertSidecars();
ctx.commit(rec);
}
for (const p of probes)
rmSync(join(root, p), { force: true });
return;
}
const candidate = opts.ownerCandidate ?? undefined;
const owner = rec.rootOwner ?? candidate;
if (owner === undefined) {
if (converting) {
convertSidecars();
ctx.commit(rec);
}
discloseLayoutIncident(opts.onIncident, "memory.layout_unowned_root_content", `memory root ${root} holds ${names.length} loose entr${names.length === 1 ? "y" : "ies"} that belong to no recorded scope (${names.slice(0, UNOWNED_ROOT_CONTENT_NAMES_MAX).join(", ")}${names.length > UNOWNED_ROOT_CONTENT_NAMES_MAX ? ", …" : ""}) — left in place, not served; the next mount with a write scope adopts them into that scope's home`);
return;
}
if (isContainedIn(root, controlDir)) {
throw new ControlPlaneCorruptError(`memory control plane ${controlDir} lies inside the memory root ${root} — the layout adoption refuses to move engine metadata as scope content (fail-closed)`);
}
const label = ownLabel(rec.scopes, owner) ?? scopeDirName(owner);
assertNoLabelCollision(root, rec.scopes, owner, label, undefined);
const home = join(root, label);
renew();
const homeForm = assertHomePhysicalForm(home);
if (homeForm === "dir") {
const inHome = readdirSync(home);
if (inHome.length > 0) {
throw new ControlPlaneCorruptError(`memory root ${root} holds loose content for ${JSON.stringify(owner)} while its home ${home} is already a non-empty directory with no move in progress — the two cannot be merged automatically (a topic directory named like the home, a root re-occupied by an older engine, or a registry that lost this scope's row); resolve by hand (fail-closed)`);
}
}
for (const name of names) {
renew();
if (lstatOrAbsent(join(home, name)) !== undefined) {
throw new ControlPlaneCorruptError(`memory root ${root} and the home ${home} both hold ${JSON.stringify(name)} — the layout adoption refuses to overwrite either (fail-closed)`);
}
}
const next = { v: 2, scopes: { ...rec.scopes, [owner]: label }, rootOwner: owner, migrating: { root, owner, label } };
renew();
ctx.commit(next);
const { migrating: _marker, ...done } = next;
moveLooseContent(root, controlDir, done, owner, label, renew, opts.onIncident, false);
convertSidecars();
renew();
ctx.commit(done);
});
}
function moveLooseContent(root, controlDir, rec, owner, label, renew, sink, resumed) {
const labels = new Set(Object.values(rec.scopes));
const { names, probes } = looseRootContent(root, labels, controlDir);
const home = join(root, label);
if (names.length > 0)
ensureScopeHome(home);
let moved = 0;
for (const name of names) {
renew();
const src = join(root, name);
const dst = join(home, name);
if (sameEntry(src, home)) {
throw new ControlPlaneCorruptError(`memory root ${root}: ${JSON.stringify(name)} is the home ${home} itself under another spelling — the layout adoption refuses to move a directory into itself (fail-closed)`);
}
if (lstatOrAbsent(dst) !== undefined) {
throw new ControlPlaneCorruptError(`memory root ${root} and the home ${home} both hold ${JSON.stringify(name)} — the layout adoption refuses to overwrite either (fail-closed)`);
}
try {
renameSync(src, dst);
moved += 1;
}
catch (err) {
if (err.code === "ENOENT" && lstatOrAbsent(src) === undefined)
continue;
throw err;
}
}
for (const p of probes) {
renew();
rmSync(join(root, p), { force: true });
}
renew();
clearIndexRevs(controlDir);
discloseLayoutIncident(sink, "memory.layout_migrated", `memory layout adopted at ${root}: ${moved} loose entr${moved === 1 ? "y" : "ies"} moved into the home of ${JSON.stringify(owner)} (${label})${resumed ? " — an interrupted move was finished" : ""}`);
}
export const canonicalize = (p) => physicalPathOfExisting(resolve(p));
export function isContainedIn(root, child) {
const r = canonicalize(root);
const c = canonicalize(child);
return c === r || c.startsWith(`${r}${sep}`);
}
export const STORE_FORM_REFUSAL_CODES = Object.freeze(["memory.target_outside_store", "memory.scope_home_not_directory", "memory.control_plane_links_unsupported", "memory.control_plane_strays", "memory.store_root_sensitive", "memory.control_plane_split", "memory.store_absent"]);
export const TARGET_OUTSIDE_STORE = "memory.target_outside_store";
export const SCOPE_HOME_NOT_DIRECTORY = "memory.scope_home_not_directory";
export const CONTROL_PLANE_LINKS_UNSUPPORTED = "memory.control_plane_links_unsupported";
export const CONTROL_PLANE_STRAYS = "memory.control_plane_strays";
export const STORE_ROOT_SENSITIVE = "memory.store_root_sensitive";
export const CONTROL_PLANE_SPLIT = "memory.control_plane_split";
export const STORE_ABSENT = "memory.store_absent";
export const STORE_ABSENT_EXPECTED_BY = Object.freeze(["process", "declaration"]);
export const SCOPE_HOME_FORMS = Object.freeze(["symlink", "file", "other"]);
const SCOPE_HOME_FORM_PHRASE = {
symlink: "a symbolic link",
file: "a regular file",
other: "a special file",
};
export const TARGET_OUTSIDE_STORE_REASONS = Object.freeze(["act_outside", "root_moved", "root_gone", "root_reanchored"]);
const STORE_ROOT_WORDS = {
store: { what: "memory store root", remedy: "point the memory engine root (memoryEngineDir, or the file backend's directory) at a directory outside it" },
control_plane: { what: "memory control plane", remedy: "point the data root (AGENT_DATA_DIR, or the backend's controlDir) at a directory outside it" },
engine_root: { what: "memory engine root", remedy: "point the memory engine root (memoryEngineDir, or AGENT_DATA_DIR) at a directory outside it" },
};
function storeFormRefusal(code, sentence, detail) {
const e = new Error(`${code}: ${sentence}`);
e.code = code;
e.detail = detail;
return e;
}
export function storeFormRefusalReadingOf(thrown) {
const code = readMember(thrown, "code");
if (typeof code !== "string" || !STORE_FORM_REFUSAL_CODES.includes(code))
return undefined;
if (code !== TARGET_OUTSIDE_STORE)
return { code: code };
const outsideReason = readMember(readMember(thrown, "detail"), "outsideReason");
return typeof outsideReason === "string" && TARGET_OUTSIDE_STORE_REASONS.includes(outsideReason) ? { code, outsideReason: outsideReason } : undefined;
}
export function storeActRefusal(act, path) {
return storeFormRefusal(TARGET_OUTSIDE_STORE, `${act} was refused — its directory resolves outside the store root; not performed`, { path, outsideReason: "act_outside" });
}
const PERSONAL_STORE_DIRS = "for a deployment's personal store, `personal/memory` and `personal/.engine` under the memory engine root";
export function storeRootMovedRefusal(path, anchor) {
return storeFormRefusal(TARGET_OUTSIDE_STORE, `the store root now resolves to a different directory than the one its control plane records, and the store holds memory — refused, nothing in the store was written; put the directory back where it was, or, if the store was moved on purpose, re-anchor it where it is now: call reanchorMemoryStoreRoot with the store's directory and { controlDir: its control plane directory } (${PERSONAL_STORE_DIRS}), then reopen`, { path, outsideReason: "root_moved", controlDir: anchor.controlDir, recorded: anchor.recorded, now: anchor.now });
}
export function storeRootReanchoredRefusal(path, anchor) {
return storeFormRefusal(TARGET_OUTSIDE_STORE, `the store is anchored to another directory than the one this session opened it at — refused, nothing in the store was written; the store needs nothing: open a new session, which opens the store where it is anchored now`, { path, outsideReason: "root_reanchored", controlDir: anchor.controlDir, recorded: anchor.recorded, now: anchor.now });
}
export function storeRootAbsentRefusal(path, anchor) {
return storeFormRefusal(TARGET_OUTSIDE_STORE, `the store root no longer exists where its control plane records it — refused, nothing in the store was written; put the directory back, or, if the store was moved on purpose, call reanchorMemoryStoreRoot with its new directory and { controlDir: its control plane directory }; to start over in place, create the directory again and call reanchorMemoryStoreRoot with it and the same control plane directory; then reopen (${PERSONAL_STORE_DIRS})`, { path, outsideReason: "root_gone", controlDir: anchor.controlDir, recorded: anchor.recorded, now: anchor.now });
}
export function scopeHomeRefusal(form, path) {
return storeFormRefusal(SCOPE_HOME_NOT_DIRECTORY, `a scope home must be a real directory, but this one is ${SCOPE_HOME_FORM_PHRASE[form]} — refused (fail-closed); put the real directory back`, { path, form });
}
export function controlPlaneLinksRefusal(path, fault) {
return storeFormRefusal(CONTROL_PLANE_LINKS_UNSUPPORTED, `the memory control plane is on a file system that cannot make hard links (link answered ${fault ?? "an error with no code"}) — the store publishes its control objects (quarantine copies, held files, pollution markers) with link, so it is not opened and no entry or control object was written; move the control plane (controlDir, or the memory engine root) to a volume that supports hard links`, { path });
}
export function storeRootSensitiveRefusal(of, path, row) {
const { what, remedy } = STORE_ROOT_WORDS[of];
return storeFormRefusal(STORE_ROOT_SENSITIVE, `the ${what} is inside a path the write guard protects (its \`${row}\` row) — a library kept there is a library that path's escalation vector holds, so it is refused (fail-closed) and nothing was created or written; ${remedy}`, { path, row, of });
}
export function controlPlaneStraysRefusal(path, strays) {
const named = [...strays.docs.map((d) => `the ${d} document`), ...Object.entries(strays.objects).map(([kind, n]) => `${n} ${kind} entr${n === 1 ? "y" : "ies"}`)];
return storeFormRefusal(CONTROL_PLANE_STRAYS, `the memory backend carries its own governance store, and the engine's control plane still holds that store's records from before (${named.join(", ")}) — they would be read by nobody, so the engine is not opened and nothing was written; adopt them into the carrier first (call adoptReplicaControlPlane with the engine's control plane directory and the backend's governance store; it removes each record it hands over), then reopen`, { path });
}
export function controlPlaneSplitRefusal(path, split) {
const sentence = split.documents.length === 0
? `more than one control plane under the memory engine root records this store under a path it had before the engine root moved (the directories ${split.planes.join(", ")}) — refused, nothing was moved; keep the one that holds the store's records, remove the others while nothing has the store open, then reopen`
: `this store's control plane stands in two places since the engine root moved — the directory ${split.planes[0]}, at its key now, and ${split.planes[1]}, under the path it had — and both hold ${split.documents.join(", ")} with different contents — refused; the records written once that are not named (capture opt-outs among them) were brought over already, nothing else was moved; for each record named, keep the one you want in ${split.planes[0]} and remove the other from ${split.planes[1]}, then reopen`;
return storeFormRefusal(CONTROL_PLANE_SPLIT, sentence, { path });
}
const STORE_ABSENT_SENTENCE = {
process: "this process saw this memory store hold records, and its control plane no longer holds its root anchor or its account — the store was moved away, or the volume it lives on was unmounted, while in use; refused: no new store was recorded in its place (no root anchor written, no store directory or anchor lock created); put the store's directory and its control plane back where they were (it opens again as it was, no restart needed), or, to start over with an empty store on purpose, open it from a new process that does not declare it an existing store (a deployment's personal store lives in the personal folder under the memory engine root)",
declaration: "this memory store was declared as one that already exists, but its control plane holds neither its root anchor nor its account — its directory was moved away, or the volume it lives on is not mounted; refused: no new store was recorded (no root anchor written, no store directory or anchor lock created); put the store's directory and its control plane back where they were (or mount the volume), then reopen; to start over with an empty store on purpose, open it without declaring it existing",
};
export function storeAbsentRefusal(path, controlDir, expectedBy) {
return storeFormRefusal(STORE_ABSENT, STORE_ABSENT_SENTENCE[expectedBy], { path, controlDir, expectedBy });
}
export function landingPathOf(p) {
return landingPathWithin(resolve(p), 0);
}
const MAX_LANDING_LINK_HOPS = 40;
function withoutTrailingSeparators(p) {
const floor = parse(p).root.length;
let end = p.length;
while (end > floor && (p[end - 1] === "/" || (sep === "\\" && p[end - 1] === "\\")))
end--;
return p.slice(0, end);
}
function landingPathWithin(normalized, hops) {
try {
return physicalPathOf(normalized);
}
catch (err) {
if (err.code !== "ENOENT")
throw err;
}
const tail = [];
for (let cur = normalized;;) {
const st = lstatOrAbsent(cur);
if (st?.isSymbolicLink() === true) {
if (hops >= MAX_LANDING_LINK_HOPS) {
const e = new Error(`ELOOP: too many symbolic links resolving ${normalized}`);
e.code = "ELOOP";
throw e;
}
const target = withoutTrailingSeparators(readlinkSync(cur));
const anchored = isAbsolute(target) ? target : anchorAtLinkDir(dirname(cur), target, sep);
return landingPathWithin([...tail].reverse().reduce((at, part) => anchorAtLinkDir(at, part, sep), anchored), hops + 1);
}
if (st !== undefined)
return join(physicalPathOf(cur), ...[...tail].reverse());
const parent = dirname(cur);
if (parent === cur)
return normalized;
const name = basename(cur);
if (name === ".." || name === ".") {
const e = new Error(`ENOENT: no such file or directory, resolving ${normalized}`);
e.code = "ENOENT";
throw e;
}
tail.push(name);
cur = parent;
}
}
export function landsOutsideStore(physicalRoot, target) {
const dir = landingPathOf(dirname(target));
return dir !== physicalRoot && !dir.startsWith(`${physicalRoot}${sep}`);
}
export function ensureDirExists(dir) {
if (!existsSync(dir))
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
export const LEDGER_FILE = "revs.json";
export const ROOT_ANCHOR_FILE = "root-anchor.json";
export function absentAnchorReading(controlPlaneHoldsStore) {
return controlPlaneHoldsStore ? "refuse" : "record";
}
function reanchorRemedy(dir, controlDir) {
return `once the store root is where it belongs, call reanchorMemoryStoreRoot(${JSON.stringify(dir)}, { controlDir: ${JSON.stringify(controlDir)} }) and reopen`;
}
function rootAnchorRefusal(controlDir, dir, anchor, cause, coded = true) {
const at = join(controlDir, ROOT_ANCHOR_FILE);
const what = anchor.absent === true
? `memory store root anchor ${at} is absent while the control plane holds a store — the store was last opened by an engine that recorded no anchor (before 7.49.0), or the anchor was removed`
: `memory store root anchor ${at} is damaged (${anchor.why})`;
return new ControlPlaneCorruptError(`${what} — the store root cannot be checked against it, so nothing in the store was opened; ${reanchorRemedy(dir, controlDir)}`, { ...(cause !== undefined ? { cause } : {}), ...(coded ? { rootAnchor: { path: dir, controlDir } } : {}) });
}
function damagedAnchorError(controlDir, dir, why, cause, coded = true) {
return rootAnchorRefusal(controlDir, dir, { why }, cause, coded);
}
function readStoreRootAnchor(controlDir, dir) {
let raw;
let fd;
try {
fd = openSync(join(controlDir, ROOT_ANCHOR_FILE), O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
if (!fstatSync(fd).isFile())
throw damagedAnchorError(controlDir, dir, "not a regular file");
raw = readFileSync(fd, "utf8");
}
catch (err) {
if (err instanceof ControlPlaneCorruptError)
throw err;
const code = err.code;
if (code === "ENOENT" && fd === undefined)
return undefined;
if (code === "ELOOP")
throw damagedAnchorError(controlDir, dir, "a symbolic link, not the record", err);
throw damagedAnchorError(controlDir, dir, `unreadable: ${code ?? thrownLabel(err)}`, err, false);
}
finally {
if (fd !== undefined)
closeSync(fd);
}
let parsed;
try {
parsed = JSON.parse(raw);
}
catch (err) {
throw damagedAnchorError(controlDir, dir, "not JSON", err);
}
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
throw damagedAnchorError(controlDir, dir, "not an object");
const a = parsed;
if (a.v !== 1)
throw damagedAnchorError(controlDir, dir, `unknown version ${JSON.stringify(a.v) ?? typeof a.v}`);
if (typeof a.realpath !== "string" || !isAbsolute(a.realpath))
throw damagedAnchorError(controlDir, dir, "realpath is not an absolute path");
if (typeof a.spelling !== "string" || typeof a.recordedAt !== "number" || !Number.isFinite(a.recordedAt))
throw damagedAnchorError(controlDir, dir, "spelling / recordedAt out of shape");
return { v: 1, realpath: a.realpath, spelling: a.spelling, recordedAt: a.recordedAt };
}
function controlPlaneHoldsStore(controlDir) {
return lstatOrAbsent(join(controlDir, SCOPES_FILE)) !== undefined || lstatOrAbsent(join(controlDir, LEDGER_FILE)) !== undefined;
}
const storesInProcess = new Map();
export function forgetStoresSeenInProcess() {
storesInProcess.clear();
}
export function storeAbsence(controlDir, declared = false) {
const seen = storesInProcess.get(resolve(controlDir))?.heldContent === true;
if (!seen && !declared)
return undefined;
if (lstatOrAbsent(join(controlDir, ROOT_ANCHOR_FILE)) !== undefined || controlPlaneHoldsStore(controlDir))
return undefined;
return seen ? "process" : "declaration";
}
export function refuseAbsentStore(dir, controlDir, declared = false) {
const expectedBy = storeAbsence(controlDir, declared);
if (expectedBy !== undefined)
throw storeAbsentRefusal(dir ?? storesInProcess.get(resolve(controlDir))?.dir ?? controlDir, controlDir, expectedBy);
}
export function ensureControlPlaneDir(controlDir, sub) {
refuseAbsentStore(undefined, controlDir);
ensureDirExists(sub === undefined ? controlDir : join(controlDir, sub));
}
export function refuseAbsentPinnedStore(backend) {
const dir = directoryPinOf(backend);
const controlDir = controlPlanePinOf(backend);
if (dir !== undefined && controlDir !== undefined)
refuseAbsentStore(dir, controlDir);
}
export function captureRecordsExpectingStore(store, controlDir) {
const recordOrRefuse = (record) => {
if (record === undefined)
refuseAbsentStore(undefined, controlDir);
return record;
};
return {
mark: (...args) => (storeAbsence(controlDir) !== undefined ? "unpersisted" : store.mark(...args)),
read: (...args) => {
const raw = store.read(...args);
const rawAsync = adoptHostPromise(raw);
return rawAsync !== undefined ? rawAsync.then(recordOrRefuse) : recordOrRefuse(raw);
},
list: () => {
refuseAbsentStore(undefined, controlDir);
return store.list();
},
};
}
function rememberStoreSeen(dir, controlDir) {
const key = resolve(controlDir);
storesInProcess.set(key, { dir, heldContent: storesInProcess.get(key)?.heldContent === true || storeHoldsContent(dir, controlDir) });
}
export function rememberStoreWrite(path) {
if (storesInProcess.size === 0)
return;
const landed = resolve(path);
for (let at = dirname(landed); dirname(at) !== at; at = dirname(at)) {
const store = storesInProcess.get(at);
if (store === undefined)
continue;
if (!store.heldContent && isStoreContent("control", relative(at, landed).split(sep), landed))
store.heldContent = true;
return;
}
}
const ANCHOR_GUARDS_NOTHING = Symbol("anchor guards nothing");
function nothingStandsAt(path) {
try {
return lstatOrAbsent(path) === undefined;
}
catch {
return false;
}
}
function judgeAgainstAnchor(dir, controlDir, anchor) {
const now = landingPathOf(dir);
if (now !== anchor.realpath) {
if (!storeHoldsRecord(dir, controlDir) && nothingStandsAt(anchor.realpath))
return ANCHOR_GUARDS_NOTHING;
throw storeRootMovedRefusal(dir, { controlDir, recorded: anchor.realpath, now });
}
if (lstatOrAbsent(now) === undefined && controlPlaneHoldsStore(controlDir))
throw storeRootAbsentRefusal(dir, { controlDir, recorded: anchor.realpath, now });
return now;
}
function writeStoreRootAnchor(controlDir, lock, token, anchor) {
assertSidecarLockOwnership(lock, token, "memory store root anchor", "strict");
atomicWriteFileSync(join(controlDir, ROOT_ANCHOR_FILE), `${JSON.stringify(anchor, null, 2)}\n`);
}
export function assertRootNotSensitive(of, root) {
const spellings = [resolve(root)];
try {
const landed = landingPathOf(root);
if (landed !== spellings[0])
spellings.push(landed);
}
catch {
}
const row = sensitiveRowOf(spellings);
if (row !== undefined)
throw storeRootSensitiveRefusal(of, root, row);
}
export function assertStoreRootsNotSensitive(dir, controlDir) {
assertRootNotSensitive("store", dir);
assertRootNotSensitive("control_plane", controlDir);
}
export function anchorStoreRoot(dir, controlDir, opts = {}) {
const root = judgeStoreRootAnchor(dir, controlDir, opts);
if (opts.remember === true)
rememberStoreSeen(dir, controlDir);
return root;
}
function judgeStoreRootAnchor(dir, controlDir, opts) {
assertStoreRootsNotSensitive(dir, controlDir);
const anchor = readStoreRootAnchor(controlDir, dir);
const judged = anchor !== undefined ? judgeAgainstAnchor(dir, controlDir, anchor) : undefined;
if (typeof judged === "string")
return judged;
if (anchor === undefined)
refuseAbsentStore(dir, controlDir, opts.expectExisting === true);
ensureDirExists(controlDir);
const lock = join(controlDir, `${ROOT_ANCHOR_FILE}.lock`);
const token = acquireSidecarLock(lock, { onDeadline: "throw" });
try {
const raced = readStoreRootAnchor(controlDir, dir);
const racedJudged = raced !== undefined ? judgeAgainstAnchor(dir, controlDir, raced) : undefined;
if (typeof racedJudged === "string")
return racedJudged;
const reading = raced !== undefined ? "rerecord" : absentAnchorReading(controlPlaneHoldsStore(controlDir));
if (reading === "refuse")
throw rootAnchorRefusal(controlDir, dir, { absent: true });
const overMemory = reading === "record" && treeHoldsRecord(dir, "memory");
ensureDirExists(dir);
const realpath = landingPathOf(dir);
writeStoreRootAnchor(controlDir, lock, token, { v: 1, realpath, spelling: dir, recordedAt: (opts.now ?? Date.now)() });
if (reading === "rerecord") {
discloseLayoutIncident(opts.onIncident, "memory.root_anchor_rerecorded", `memory store root anchor recorded again: ${dir} now resolves to ${realpath}, not to ${raced?.realpath ?? "(unreadable)"} its control plane ${controlDir} had recorded; nothing stands at the old root any more and the store held no memory — only what opening or reading it leaves — so there was nothing to guard; from now on the store opens at ${realpath}`);
}
else if (overMemory) {
discloseLayoutIncident(opts.onIncident, "memory.control_plane_new_over_memory", `memory store opened for the first time over a directory that already holds memory (${dir}); what the engine keeps beside it — capture opt-outs, the ledger of committed entries, quarantined files — starts empty at ${controlDir}. If the directory was copied or cloned here, nothing needs doing. If it was moved here or its configured path changed, what was kept beside it before is still under the memory engine root, in the folder named after its earlier path, and is not read: to keep it, capture opt-outs included, stop the service, replace ${controlDir} with that folder's .engine directory, and start again`);
}
return realpath;
}
finally {
releaseSidecarLock(lock, token);
}
}
export const STORE_JOURNAL_FILE = "journal.json";
export const STORE_TXN_LOCK_DIR = "txn.lock";
export const TXN_LOCK_STALE_MS = 30_000;
const TXN_LOCK_WAIT_MS = 15_000;
const TXN_LOCK_STEAL_GRACE_MS = 250;
export function tryStoreTxnLock(controlDir, opts) {
assertRootNotSensitive("control_plane", controlDir);
const lockDir = join(controlDir, STORE_TXN_LOCK_DIR);
const ownerPath = join(lockDir, "owner");
const staleMs = opts.staleMs ?? TXN_LOCK_STALE_MS;
const faultText = (err) => err.code ?? "io error";
const tryMkdir = () => {
try {
ensureControlPlaneDir(controlDir);
}
catch (err) {
if (err.code === STORE_ABSENT)
throw err;
throw new ControlPlaneCorruptError(`memory control-plane root could not be created (${faultText(err)}) at ${controlDir} — a lock-acquisition fault is not contention (fail-closed)`, { cause: err });
}
try {
mkdirSync(lockDir, { mode: 0o700 });
return true;
}
catch (err) {
if (err.code === "EEXIST")
return false;
throw new ControlPlaneCorruptError(`memory txn lock could not be created (${faultText(err)}) at ${lockDir} — a lock-acquisition fault is not contention (fail-closed)`, { cause: err });
}
};
let acquired = tryMkdir();
if (!acquired) {
let mtimeMs;
try {
mtimeMs = statSync(lockDir).mtimeMs;
opts.observed?.(mtimeMs);
}
catch (err) {
if (err.code !== "ENOENT") {
throw new ControlPlaneCorruptError(`memory txn lock state could not be probed (${faultText(err)}) at ${lockDir} — a probe failure is not contention (fail-closed)`, { cause: err });
}
let occupant;
try {
occupant = lstatSync(lockDir);
}
catch (lerr) {
if (lerr.code !== "ENOENT") {
throw new ControlPlaneCorruptError(`memory txn lock re-probe failed (${faultText(lerr)}) at ${lockDir} — a probe failure is not contention (fail-closed)`, { cause: lerr });
}
}
if (occupant !== undefined && !occupant.isDirectory()) {
throw new ControlPlaneCorruptError(`memory txn lock path is occupied by an invalid node (a dangling symlink?) at ${lockDir} — not contention and not a release race; remove the occupant (fail-closed)`, { cause: err });
}
mtimeMs = undefined;
}
if (mtimeMs !== undefined && opts.now() - mtimeMs > staleMs) {
let tokenPresent = false;
try {
statSync(ownerPath);
tokenPresent = true;
}
catch (err) {
if (err.code !== "ENOENT") {
throw new ControlPlaneCorruptError(`memory txn lock owner token could not be probed (${faultText(err)}) at ${ownerPath} — a probe failure is not a mid-acquisition (fail-closed)`, { cause: err });
}
}
if (tokenPresent) {
const tomb = join(controlDir, `${STORE_TXN_LOCK_DIR}${LOCK_TOMB_INFIX}${randomUUID()}`);
let stolen = false;
try {
renameSync(lockDir, tomb);
stolen = true;
}
catch (err) {
if (err.code !== "ENOENT") {
throw new ControlPlaneCorruptError(`memory txn lock stale-steal rename failed (${faultText(err)}) at ${lockDir} — a rename fault is not a lost race (fail-closed)`, { cause: err });
}
}
if (stolen) {
rmSync(tomb, { recursive: true, force: true });
acquired = tryMkdir();
}
}
}
if (!acquired)
return undefined;
}
const token = randomUUID();
try {
const fd = openSync(ownerPath, "wx", 0o600);
try {
writeAllSync(fd, token);
fsyncSync(fd);
}
finally {
closeSync(fd);
}
}
catch (err) {
try {
rmSync(lockDir, { recursive: true, force: true });
}
catch {
}
throw new Error(`memory txn lock owner token could not be written at ${ownerPath}: ${thrownText(err)}`);
}
return {
token,
release: () => {
try {
if (readFileSync(ownerPath, "utf8") !== token)
return;
}
catch {
return;
}
try {
rmSync(lockDir, { recursive: true, force: true });
}
catch {
}
},
};
}
export function assertStoreTxnLockOwnership(controlDir, token) {
let held;
try {
held = readFileSync(join(controlDir, STORE_TXN_LOCK_DIR, "owner"), "utf8");
}
catch {
held = undefined;
}
if (held !== token) {
throw new ControlPlaneCorruptError("txn lock ownership lost before commit (holder stalled past the stale deadline and was stolen from?) — transaction aborted, nothing was committed", { facet: "lock-ownership" });
}
}
export function renewStoreTxnLock(controlDir, token) {
const now = new Date();
utimesSync(join(controlDir, STORE_TXN_LOCK_DIR), now, now);
assertStoreTxnLockOwnership(controlDir, token);
}
export async function acquireStoreTxnLock(controlDir, opts) {
const staleMs = opts.timings?.staleMs ?? TXN_LOCK_STALE_MS;
const waitMs = opts.timings?.waitMs ?? TXN_LOCK_WAIT_MS;
const stealGraceMs = opts.timings?.stealGraceMs ?? TXN_LOCK_STEAL_GRACE_MS;
let deadline = Date.now() + waitMs;
for (;;) {
const lock = tryStoreTxnLock(controlDir, { now: opts.now, staleMs, observed: (mtimeMs) => (deadline = Math.max(deadline, mtimeMs + staleMs + stealGraceMs)) });
if (lock !== undefined)
return lock;
if (Date.now() > deadline) {
throw new Error(`memory txn lock timeout (${waitMs}ms, extended to the lock's stale line) at ${join(controlDir, STORE_TXN_LOCK_DIR)} — another writer is wedged?`);
}
await new Promise((r) => setTimeout(r, 20 + Math.floor(Math.random() * 40)));
}
}
function reanchorDestination(dir) {
let to;
try {
to = physicalPathOf(resolve(dir));
}
catch (err) {
throw reanchorRefusal(`the store root ${JSON.stringify(dir)} does not resolve (${err.code ?? thrownLabel(err)}) — put the directory in place first`);
}
if (lstatOrAbsent(to)?.isDirectory() !== true)
throw reanchorRefusal(`the store root ${JSON.stringify(dir)} resolves to ${to}, which is not a directory`);
return to;
}
export const ERASURE_SWEEP_RECORD_FILE = "erasure-sweeps.json";
export const ERASURE_SWEEP_RECORD_WHAT = "memory erasure sweep record";
function isStoreRelativePath(p) {
return p.length > 0 && !isAbsolute(p) && !p.split(sep === "/" ? "/" : /[\\/]/).includes("..");
}
export function coerceErasureSweepRecord(raw) {
if (raw === undefined)
return { v: 1, requests: Object.create(null) };
const requests = raw?.requests;
if (typeof raw !== "object" || raw === null || raw.v !== 1 || typeof requests !== "object" || requests === null || Array.isArray(requests)) {
throw new ControlPlaneCorruptError(`${ERASURE_SWEEP_RECORD_WHAT} has an unrecognized shape (fail-closed sidecar)`);
}
const out = Object.create(null);
for (const [req, paths] of Object.entries(requests)) {
if (!Array.isArray(paths) || paths.some((p) => typeof p !== "string" || !isStoreRelativePath(p)))
throw new ControlPlaneCorruptError(`${ERASURE_SWEEP_RECORD_WHAT} row for request ${JSON.stringify(req.slice(0, 80))} is malformed — a row names paths relative to the store root (fail-closed sidecar)`);
out[req] = paths;
}
return { v: 1, requests: out };
}
export function erasureSweepRecordPathOf(storeRoot, requestId, target) {
const rel = join(relative(landingPathOf(storeRoot), landingPathOf(dirname(target))), basename(target));
if (!isStoreRelativePath(rel))
throw new ControlPlaneCorruptError(`${ERASURE_SWEEP_RECORD_WHAT}: a path request ${JSON.stringify(requestId.slice(0, 80))} deleted is not under the store root ${storeRoot} — a row names paths relative to the root (fail-closed sidecar)`);
return rel;
}
export function erasureSweepOwedAt(file, storeRoot, requestId) {
return (file.requests[requestId] ?? []).map((rel) => join(storeRoot, rel));
}
function rootBoundObligationOf(controlDir) {
if (lstatOrAbsent(join(controlDir, STORE_JOURNAL_FILE)) === undefined)
return undefined;
return { owed: "a committed transaction is still pending recovery", remedy: "open it once so the journal replays" };
}
function reanchorRefusal(sentence) {
const e = new Error(`Moving the memory store's root is refused: ${sentence}`);
e.code = "config.memory_reanchor";
return e;
}
export async function reanchorMemoryStoreRoot(dir, opts = {}) {
const o = receiveMembers(opts, { subject: "reanchorMemoryStoreRoot options", unit: "option", moment: "at reanchorMemoryStoreRoot" }, REANCHOR_OPTION_KEYS);
const controlDir = effectiveControlRootOf(dir, { controlDir: o.controlDir, onIncident: o.onIncident });
const to = reanchorDestination(dir);
const lock = join(controlDir, `${ROOT_ANCHOR_FILE}.lock`);
if (lstatOrAbsent(join(controlDir, ROOT_ANCHOR_FILE)) === undefined && !controlPlaneHoldsStore(controlDir)) {
throw reanchorRefusal(`the control plane ${controlDir} holds no store and no root anchor — nothing to re-anchor; pass the controlDir this store's backend / engine is opened with`);
}
const txn = await acquireStoreTxnLock(controlDir, { now: Date.now });
let from;
try {
const token = acquireSidecarLock(lock, { onDeadline: "throw" });
try {
let unreadable = false;
try {
from = readStoreRootAnchor(controlDir, dir)?.realpath;
}
catch {
from = undefined;
unreadable = true;
}
if (o.expectedFrom !== undefined && from !== o.expectedFrom) {
throw reanchorRefusal(from !== undefined
? `the store's anchor records ${from}, not ${o.expectedFrom} — the root you confirmed is not the one recorded, so nothing was recorded; read the store's refusal again and confirm the root it names (control plane ${controlDir})`
: `the store's anchor ${unreadable ? "cannot be read" : "is absent"}, so it cannot be shown to record ${o.expectedFrom} — nothing was recorded; to replace a damaged anchor, call reanchorMemoryStoreRoot without expectedFrom (control plane ${controlDir})`);
}
try {
assertStoreTxnLockOwnership(controlDir, txn.token);
}
catch {
throw reanchorRefusal(`the store's transaction lock was lost while re-anchoring (held past its stale line and taken by another writer) — nothing changed; retry (control plane ${controlDir})`);
}
const obligation = rootBoundObligationOf(controlDir);
if (obligation !== undefined) {
throw reanchorRefusal(from === undefined && !unreadable
? `${obligation.owed}, and the store has no root anchor (it was last opened by an engine before 7.49.0, which recorded none, or the anchor was removed) — this engine opens such a store only once it is re-anchored, and re-anchors it only once nothing is owed: put the store back at the root it was last opened at, open it once there with any release from 7.49.0 to 7.70.x (that records its anchor and replays the journal; 7.63.x or below when the journal carries the bare-map ledger form, which 7.64.0 and later refuse), then upgrade (control plane ${controlDir})`
: from === undefined
? `${obligation.owed}, and the store's root anchor cannot be used (it is damaged, or this process cannot read it) — a release that refuses the anchor cannot replay the journal, and this engine re-anchors only once nothing is owed: if the anchor file is intact and only unreadable to this process (permissions, an I/O fault), restore access and call again; if it is damaged, remove ${ROOT_ANCHOR_FILE} from the control plane first, put the store back at the root it was last opened at, open it once there with any release from 7.49.0 to 7.70.x (that records its anchor and replays the journal; 7.63.x or below when the journal carries the bare-map ledger form, which 7.64.0 and later refuse), then upgrade (control plane ${controlDir})`
: `${obligation.owed} at the recorded root — put the store back at ${from}, ${obligation.remedy}, then re-anchor (control plane ${controlDir})`);
}
let still;
try {
still = reanchorDestination(dir);
}
catch {
still = undefined;
}
if (still !== to)
throw reanchorRefusal(`the store root ${JSON.stringify(dir)} moved while re-anchoring (it resolved to ${to} when the call began) — nothing changed; retry`);
writeStoreRootAnchor(controlDir, lock, token, { v: 1, realpath: to, spelling: dir, recordedAt: Date.now() });
}
finally {
releaseSidecarLock(lock, token);
}
}
finally {
txn.release();
}
discloseLayoutIncident(o.onIncident, "memory.root_reanchored", `memory store root re-anchored: ${dir} now opens at ${to}${from !== undefined ? ` (was ${from})` : ""} — control plane ${controlDir}`);
return from !== undefined ? { from, to, controlDir } : { to, controlDir };
}
export function permissionRemedyOf(err, memoryDir) {
const e = typeof err === "object" && err !== null ? err : undefined;
if (e === undefined || (e.code !== "EACCES" && e.code !== "EPERM") || typeof e.path !== "string" || !isContainedIn(memoryDir, e.path))
return undefined;
return `file permissions refused this memory write (the engine never changes permission bits) — if an engine from 7.30.x or earlier left read-only bits on this store, run \`chmod -R u+w ${shellQuoted(memoryDir)}\` once no such engine still runs on it (an older engine sets the bits again whenever it mounts a layer read-only)`;
}
function shellQuoted(s) {
return `'${s.replace(/'/g, "'\\''")}'`;
}
const remedied = new WeakSet();
export function withPermissionRemedy(err, memoryDir) {
const remedy = permissionRemedyOf(err, memoryDir);
if (remedy === undefined || !(err instanceof Error) || remedied.has(err))
return err;
err.message = `${err.message} — ${remedy}`;
remedied.add(err);
return err;
}
export const QUARANTINE_DIR = "quarantine";
const DELETED_TOMBSTONE = "---\ndeleted: true\n---\n";
export function writeFileNoFollow(path, content) {
const fd = openSync(path, O_WRONLY | O_CREAT | O_NOFOLLOW, 0o644);
let names;
try {
const opened = fstatSync(fd);
names = opened.nlink > 1 && dropStagingSecondNames(path, opened) > 0 ? fstatSync(fd).nlink : opened.nlink;
if (names <= 1) {
ftruncateSync(fd, 0);
writeFileSync(fd, content, "utf8");
}
}
finally {
closeSync(fd);
}
if (names > 1)
atomicWriteFileSync(path, content);
}
export function writeFileNoReplace(path, content, mode = PRIVATE_FILE_MODE) {
let fd;
try {
fd = openSync(path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, mode);
}
catch (err) {
if (err.code === "EEXIST")
return "kept";
throw err;
}
try {
writeFileSync(fd, content, "utf8");
}
finally {
closeSync(fd);
}
return "written";
}
export function putBackOverNothingOrBlank(path, content) {
let fd;
try {
fd = openSync(path, O_RDWR | O_NOFOLLOW | O_NONBLOCK);
}
catch (err) {
const code = err.code;
if (code === "ENOENT")
return writeFileNoReplace(path, content) === "written" ? "written" : "kept";
if (code === "ELOOP" || code === "EMLINK" || code === "EISDIR" || code === "ENXIO" || code === "EOPNOTSUPP")
return "blocked";
throw err;
}
let manyNames = false;
try {
const seat = fstatSync(fd);
if (!seat.isFile())
return "blocked";
if (carriesEntry(readFileSync(fd, "utf8")))
return "kept";
manyNames = seat.nlink > 1;
if (!manyNames) {
ftruncateSync(fd, 0);
const bytes = Buffer.from(content, "utf8");
for (let at = 0; at < bytes.length;)
at += writeSync(fd, bytes, at, bytes.length - at, at);
return "written";
}
}
finally {
closeSync(fd);
}
writeFileNoFollow(path, content);
return "written";
}
let stagingSeq = 0;
export function mintStagingName(owner, now) {
stagingSeq += 1;
return `${owner}.staging-${now()}-${process.pid}-${stagingSeq}`;
}
export const RETIRED_STAGING_OWNER = "retired";
export function stagingNamePattern(owner) {
const head = owner === undefined
? String.raw `(?:(?:hold-\d+-[0-9a-f]{12}|${RETIRED_STAGING_OWNER})\.staging-\d+-\d+-\d+|(?:\d+|[0-9a-f]{16})-residue-[^/]+\.md\.staging(?:-\d+-\d+-\d+)?)`
: String.raw `${owner.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\.staging-\d+-\d+-\d+`;
return new RegExp(String.raw `^${head}(?:\.claim-\d+-\d+)*$`);
}
export function claimStaging(stagingPath) {
stagingSeq += 1;
const claimed = `${stagingPath}.claim-${process.pid}-${stagingSeq}`;
try {
renameSync(stagingPath, claimed);
return claimed;
}
catch {
return stagingPath;
}
}
export function isSameFile(path, ref) {
try {
const st = lstatSync(path);
return st.isFile() && st.dev === ref.dev && st.ino === ref.ino;
}
catch {
return false;
}
}
export function dropStagingSecondNames(seat, opened) {
const dir = dirname(seat);
let names;
try {
names = readdirSync(dir);
}
catch {
return 0;
}
const minted = stagingNamePattern();
let dropped = 0;
for (const name of names) {
const at = join(dir, name);
if (name === basename(seat) || !minted.test(name) || !isSameFile(at, opened))
continue;
try {
unlinkSync(at);
dropped += 1;
}
catch {
}
}
return dropped;
}
function readForVerification(path, maxBytes) {
let fd;
try {
fd = openSync(path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
}
catch {
return undefined;
}
try {
if (!fstatSync(fd).isFile())
return undefined;
const buf = Buffer.allocUnsafe(maxBytes);
let got = 0;
for (;;) {
const n = readSync(fd, buf, got, maxBytes - got, got);
if (n <= 0 || got + n >= maxBytes)
return buf.subarray(0, got + Math.max(0, n)).toString("utf8");
got += n;
}
}
catch {
return undefined;
}
finally {
closeSync(fd);
}
}
export function restoreContainedBaseline(path, committed, leftOnPlane, mode) {
try {
if (leftOnPlane === undefined || readForVerification(path, Buffer.byteLength(leftOnPlane) + 1) !== leftOnPlane) {
return writeFileNoReplace(path, committed, mode);
}
writeFileNoFollow(path, committed);
return "written";
}
catch {
return "failed";
}
}
let quarantineSeq = 0;
export async function putControlObjectOnce(objects, kind, name, bytes) {
try {
return await objects.putObject(kind, name, bytes);
}
catch (err) {
let standing;
try {
standing = await objects.getObject(kind, name);
}
catch {
throw err;
}
if (standing === undefined)
throw err;
return "existed";
}
}
export const CONTROL_OBJECT_NAME_MAX_BYTES = 255;
export function quarantineObjectNameOf(content, source) {
const digest = content instanceof Uint8Array ? createHash("sha256").update(content).digest("hex") : content.sha256;
const head = `${digest.slice(0, 16)}-`;
let room = CONTROL_OBJECT_NAME_MAX_BYTES - 2 - Buffer.byteLength(head, "utf8");
let label = "";
for (const char of basename(source)) {
const spelled = labelCharSpelled(char);
room -= Buffer.byteLength(spelled, "utf8");
if (room < 0)
break;
label += spelled;
}
return head + label;
}
function labelCharSpelled(char) {
if (!/[\p{Cc}\\]/u.test(char))
return char;
return [...Buffer.from(char, "utf8")].map((byte) => `%${byte.toString(16).toUpperCase().padStart(2, "0")}`).join("");
}
export function quarantineCaptureName(base, attempt) {
return attempt === 0 ? base : attempt < 10 ? `${base}.${attempt}` : `${base}.${process.pid}.${quarantineSeq++}`;
}
export async function captureIntoQuarantine(objects, source, content) {
const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
const base = quarantineObjectNameOf(bytes, source);
try {
for (let attempt = 0; attempt <= 10; attempt++) {
const name = quarantineCaptureName(base, attempt);
if ((await putControlObjectOnce(objects, "quarantine", name, bytes)) === "created")
return { name };
const standing = await objects.getObject("quarantine", name);
if (standing !== undefined && Buffer.from(standing).equals(bytes))
return { name };
}
return { failed: "quarantine copy failed: every capture name already stands" };
}
catch (err) {
return { failed: `quarantine copy failed: ${thrownText(err)}` };
}
}
export async function eraseQuarantineCopies(objects, ids) {
let listed;
try {
listed = await objects.listObjects("quarantine");
}
catch (err) {
throw new ControlPlaneCorruptError(`memory erasure: the quarantine objects could not be listed (${thrownText(err)}) — the attestation must not silently claim an empty residual set; retry after the store's fault clears (the deletions themselves are committed and a replay converges)`, { cause: err });
}
if (!Array.isArray(listed) || !Array.from(listed).every((name) => typeof name === "string")) {
throw new ControlPlaneCorruptError("memory erasure: the store's listing of its quarantine objects is not a list of names — the attestation must not silently claim an empty residual set; retry after the store's fault clears (the deletions themselves are committed and a replay converges)");
}
const out = { removed: 0, remaining: 0, unreadable: 0, unattributed: 0 };
for (const name of new Set(listed)) {
let text;
try {
const bytes = await objects.getObject("quarantine", name);
if (bytes === undefined)
continue;
text = new TextDecoder().decode(bytes);
}
catch {
text = undefined;
}
if (text === undefined) {
out.remaining++;
out.unreadable++;
continue;
}
const id = parseEntryFile(text).id;
if (id === undefined) {
out.unattributed++;
continue;
}
if (!ids.has(id))
continue;
try {
const deleted = await objects.deleteObject("quarantine", name);
if (deleted === true)
out.removed++;
else if (deleted !== false)
out.remaining++;
}
catch {
out.remaining++;
}
}
return out;
}
export function clearContainedPath(path, content, capture) {
const captured = "name" in capture ? capture.name : undefined;
let detail = "failed" in capture ? capture.failed : undefined;
let onDisk;
try {
onDisk = readFileSync(path, "utf8");
}
catch {
onDisk = undefined;
}
if (onDisk !== undefined && onDisk !== content) {
return {
...(captured !== undefined ? { dest: captured } : {}),
removed: false,
leftOnPlane: content,
detail: `${detail !== undefined ? `${detail}; ` : ""}the file was rewritten after it was read — the newer bytes are not the captured copy and were left in place`,
};
}
let left = content;
let removed = false;
try {
rmSync(path, { force: true });
left = undefined;
removed = true;
}
catch (rmErr) {
try {
writeFileNoFollow(path, DELETED_TOMBSTONE);
left = DELETED_TOMBSTONE;
removed = true;
detail = `${detail !== undefined ? `${detail}; ` : ""}delete failed (${thrownText(rmErr)}) — tombstoned in place`;
}
catch (clearErr) {
detail = `${detail !== undefined ? `${detail}; ` : ""}suspect file could not be deleted or cleared: ${thrownText(clearErr)}`;
}
}
return {
...(captured !== undefined ? { dest: captured } : {}),
removed,
...(left !== undefined ? { leftOnPlane: left } : {}),
...(detail !== undefined ? { detail } : {}),
};
}
export async function keepCopiesBeforeOverwrite(text, keep, reread) {
const failed = [];
let held = text;
for (let copies = 0; copies < 3; copies++) {
const outcome = await keep(held);
if (outcome !== true)
failed.push(outcome);
let onDisk;
try {
onDisk = reread();
}
catch (err) {
return { landed: false, failed: [...failed, `the file could not be read again after its copy: ${thrownText(err)}`] };
}
if (onDisk === undefined || onDisk === held)
return { landed: failed.length === 0, failed };
held = onDisk;
}
return { landed: false, failed: [...failed, "the file kept being rewritten while its copy was kept — its last version was not captured"] };
}
export const ATOMIC_WRITE_TMP_PREFIX = ".tmp-";
export const LINK_PROBE_PREFIX = ".link-probe-";
export const LOCK_TOMB_INFIX = ".stale-";
export const STORE_IDENTITY_FILE = "store-identity.json";
export function readStoreIdentity(controlDir) {
const path = join(controlDir, STORE_IDENTITY_FILE);
let raw;
try {
raw = readFileSync(path, "utf8");
}
catch (err) {
const code = err.code;
if (code === "ENOENT")
return undefined;
throw new ControlPlaneCorruptError(`store identity could not be read (${code ?? "io error"}) at ${path} — a read failure is not absence (fail-closed); fix the filesystem fault and retry`, { cause: err });
}
let parsed;
try {
parsed = JSON.parse(raw);
}
catch {
throw new ControlPlaneCorruptError(`store identity is unparseable: ${path}`);
}
const rec = parsed;
if (!rec || typeof rec !== "object" || rec.v !== 1 || typeof rec.storeId !== "string" || rec.storeId.length === 0) {
throw new ControlPlaneCorruptError(`store identity has the wrong shape: ${path}`);
}
return rec.storeId;
}
export const STORE_OPEN_ARTIFACTS = Object.freeze({
files: Object.freeze([ROOT_ANCHOR_FILE, SCOPES_FILE, `${SCOPES_FILE}.journal`, STORE_IDENTITY_FILE]),
filePrefixes: Object.freeze([ATOMIC_WRITE_TMP_PREFIX, LINK_PROBE_PREFIX]),
lockDirs: Object.freeze([`${ROOT_ANCHOR_FILE}.lock`, `${SCOPES_FILE}.lock`, STORE_TXN_LOCK_DIR]),
memoryFilePrefixes: Object.freeze([CASEFOLD_PROBE_PREFIX]),
});
export function isStoreOpenArtifact(where, rel) {
const [top] = rel;
if (top === undefined)
return false;
const starts = (prefixes) => prefixes.some((p) => top.startsWith(p));
if (where === "memory")
return rel.length === 1 && starts(STORE_OPEN_ARTIFACTS.memoryFilePrefixes);
if (rel.length === 1)
return STORE_OPEN_ARTIFACTS.files.includes(top) || starts(STORE_OPEN_ARTIFACTS.filePrefixes);
return isLockTreeName(top);
}
function isLockTreeName(name) {
return STORE_OPEN_ARTIFACTS.lockDirs.some((lock) => name === lock || name.startsWith(`${lock}${LOCK_TOMB_INFIX}`));
}
export function storeHoldsRecord(memoryDir, controlDir) {
return treeHoldsRecord(controlDir, "control", (name) => namedArtifactFault(memoryDir, controlDir, name) !== undefined) || treeHoldsRecord(memoryDir, "memory");
}
export function storeHoldsContent(memoryDir, controlDir) {
return (treeHoldsRecord(controlDir, "control", (name) => namedArtifactFault(memoryDir, controlDir, name) !== undefined, (rel, path) => isStoreContent("control", rel, path)) ||
treeHoldsRecord(memoryDir, "memory", undefined, (rel, path) => isStoreContent("memory", rel, path)));
}
function isStoreContent(where, rel, path) {
if (where === "memory")
return isMemoryContent(rel[rel.length - 1] ?? "", path);
const bookkeeping = [INDEX_REVS_FILE, SESSION_ACCOUNTS_FILE, `${SESSION_ACCOUNTS_FILE}.journal`];
return !isStoreOpenArtifact("control", rel) && !(rel.length === 1 && bookkeeping.includes(rel[0] ?? ""));
}
function isMemoryContent(name, path) {
if (name.startsWith(".") || !name.endsWith(".md"))
return false;
if (name !== MEMORY_INDEX_FILENAME)
return true;
let text;
try {
if (!lstatSync(path).isFile())
return true;
text = readFileSync(path, "utf8");
}
catch (err) {
return err.code !== "ENOENT";
}
return text.split("\n").some(indexLineHoldsText);
}
function namedArtifactFault(memoryDir, controlDir, name) {
try {
if (name === ROOT_ANCHOR_FILE)
readStoreRootAnchor(controlDir, memoryDir);
else if (name === SCOPES_FILE || name === `${SCOPES_FILE}.journal`) {
for (const file of [`${SCOPES_FILE}.journal`, SCOPES_FILE]) {
if (!absentOrRegularFile(join(controlDir, file)))
return new ControlPlaneCorruptError(`memory store file ${join(controlDir, file)} is no regular file the scope registry can be read from (a pipe, a device, a directory, or a link that leads nowhere) — the store's registry cannot be checked, so nothing in the store was opened`);
}
readScopesRecord(controlDir);
}
else if (name === STORE_IDENTITY_FILE) {
if (!absentOrRegularFile(join(controlDir, name)))
return new ControlPlaneCorruptError(`memory store file ${join(controlDir, name)} is no regular file the store identity can be read from (a pipe, a device, a directory, or a link that leads nowhere) — the store's identity cannot be checked, so nothing in the store was opened`);
readStoreIdentity(controlDir);
}
return undefined;
}
catch (err) {
return err instanceof ControlPlaneCorruptError ? err : new ControlPlaneCorruptError(`memory store artifact ${name} could not be read (${err.code ?? thrownLabel(err)}): ${thrownText(err)}`, { cause: err });
}
}
export function storeOpenArtifactFault(memoryDir, controlDir) {
for (const name of STORE_OPEN_ARTIFACTS.files) {
const fault = namedArtifactFault(memoryDir, controlDir, name);
if (fault !== undefined)
return fault;
}
return undefined;
}
function absentOrRegularFile(path) {
const entry = lstatOrAbsent(path);
if (entry === undefined)
return true;
return entry.isSymbolicLink() ? statSync(path).isFile() : entry.isFile();
}
const STORE_CENSUS_WALKS = 4;
function treeHoldsRecord(dir, where, damaged, isRecord = (rel) => !isStoreOpenArtifact(where, rel)) {
const walk = (path, rel) => {
let items;
try {
items = readdirSync(path, { withFileTypes: true });
}
catch (err) {
if (err.code !== "ENOENT")
return true;
return rel.length === 0 ? absentDirReading(path) : "moved";
}
for (const item of items) {
const at = [...rel, item.name];
if (rel.length === 0 && damaged?.(item.name) === true)
return true;
const reading = !item.isDirectory() ? isRecord(at, join(path, item.name)) : where === "control" && rel.length === 0 && isLockTreeName(item.name) ? false : walk(join(path, item.name), at);
if (reading !== false)
return reading;
}
return false;
};
let quiet = 0;
for (let n = 0; n < STORE_CENSUS_WALKS; n += 1) {
const reading = walk(dir, []);
if (reading === true)
return true;
quiet = reading === false ? quiet + 1 : 0;
if (quiet === 2)
return false;
}
return true;
}
function absentDirReading(dir) {
for (let at = dir;; at = dirname(at)) {
let item;
try {
item = lstatSync(at, { throwIfNoEntry: false });
}
catch {
return true;
}
if (item === undefined) {
if (dirname(at) === at)
return false;
continue;
}
if (item.isSymbolicLink()) {
try {
if (statSync(at, { throwIfNoEntry: false }) === undefined)
return true;
}
catch {
return true;
}
}
return at === dir ? "moved" : false;
}
}
export const ANNOUNCEMENTS_FILE = "announcements.json";
export const MEMORY_ANNOUNCEMENTS_MAX = 20;
export const SCAN_FUSE_FILE = "scan-fuse.json";
export const SCAN_FUSE_THRESHOLD = 3;
function sleepSync(ms) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
const LOCK_STALE_MS = 1_500;
const LOCK_WAIT_CAP_MS = 3_000;
const LOCK_SPIN_PAUSE_MS = 5;
const MAX_FAIL_OPEN_DEADLINE_ROUNDS = 3;
export function acquireSidecarLock(lockDir, opts = {}) {
const waitCapMs = opts.waitCapMs ?? LOCK_WAIT_CAP_MS;
const deadline = Date.now() + waitCapMs;
const mintToken = () => `${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
let deadlineRounds = 0;
const stealOnce = () => {
const tomb = `${lockDir}${LOCK_TOMB_INFIX}${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
try {
renameSync(lockDir, tomb);
}
catch {
return false;
}
rmSync(tomb, { recursive: true, force: true });
return true;
};
for (;;) {
try {
mkdirSync(lockDir, { mode: 0o700 });
const token = mintToken();
let fd;
try {
fd = openSync(join(lockDir, "owner"), "wx", 0o600);
writeAllSync(fd, token);
}
catch {
}
finally {
if (fd !== undefined) {
try {
closeSync(fd);
}
catch {
}
}
}
return token;
}
catch (err) {
if (err.code !== "EEXIST")
throw err;
}
try {
const age = Date.now() - statSync(lockDir).mtimeMs;
if (age > LOCK_STALE_MS)
stealOnce();
}
catch {
}
if (Date.now() > deadline) {
if (opts.onDeadline === "throw") {
throw new Error(`sidecar lock wait timed out (${waitCapMs}ms) at ${lockDir} — refusing to proceed without the lock (fail-closed sidecar)`);
}
deadlineRounds += 1;
if (deadlineRounds > MAX_FAIL_OPEN_DEADLINE_ROUNDS)
return mintToken();
stealOnce();
}
sleepSync(LOCK_SPIN_PAUSE_MS);
}
}
function rollForwardSidecar(file, journal) {
let raw;
try {
raw = readFileSync(journal, "utf8");
}
catch {
return;
}
try {
JSON.parse(raw);
atomicWriteFileSync(file, raw);
}
catch {
}
rmSync(journal, { force: true });
}
function lockedJournaledUpdate(controlDir, fileName, mutate) {
ensureControlPlaneDir(controlDir);
const file = join(controlDir, fileName);
const journal = `${file}.journal`;
const lock = `${file}.lock`;
const token = acquireSidecarLock(lock);
try {
rollForwardSidecar(file, journal);
let current;
try {
current = JSON.parse(readFileSync(file, "utf8"));
}
catch {
current = undefined;
}
const next = mutate(current);
if (next === undefined)
return;
const data = `${JSON.stringify(next, null, 2)}\n`;
atomicWriteFileSync(journal, data);
atomicWriteFileSync(file, data);
rmSync(journal, { force: true });
}
finally {
releaseSidecarLock(lock, token);
}
}
export function assertSidecarLockOwnership(lockDir, token, what, mode = "lenient") {
let held;
try {
held = readFileSync(join(lockDir, "owner"), "utf8");
}
catch (err) {
if (mode === "strict" && err.code !== undefined) {
throw new ControlPlaneCorruptError(`${what}: sidecar lock ownership UNPROVABLE at commit (owner file ${err.code === "ENOENT" ? "absent" : `unreadable: ${err.code}`}) — a fail-closed ledger must not commit on a fence it cannot prove; update aborted`, { cause: err, facet: "lock-ownership" });
}
return;
}
if (held !== token) {
throw new ControlPlaneCorruptError(`${what}: sidecar lock ownership lost before commit (holder stalled past ${LOCK_STALE_MS}ms and was stolen from) — update aborted`, { facet: "lock-ownership" });
}
}
function releaseSidecarLock(lockDir, token) {
try {
const held = readFileSync(join(lockDir, "owner"), "utf8");
if (held !== token)
return;
}
catch {
}
rmSync(lockDir, { recursive: true, force: true });
}
function readSidecarJson(controlDir, fileName) {
const file = join(controlDir, fileName);
for (const p of [`${file}.journal`, file]) {
try {
return JSON.parse(readFileSync(p, "utf8"));
}
catch {
}
}
return undefined;
}
const ANNOUNCEMENTS_FORM = 2;
function emptyAnnouncements() {
return { v: ANNOUNCEMENTS_FORM, scopes: Object.create(null) };
}
function wholeCount(v) {
return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0;
}
function coerceAnnouncement(e, scope) {
const a = e;
if (!a ||
typeof a !== "object" ||
(a.kind !== "gate" && a.kind !== "external") ||
typeof a.at !== "number" ||
!Array.isArray(a.items) ||
!a.items.every((i) => typeof i === "string") ||
a.scope !== scope) {
return undefined;
}
return {
kind: a.kind,
scope,
at: a.at,
...(typeof a.sessionId === "string" ? { sessionId: a.sessionId } : {}),
...(typeof a.reportId === "string" ? { reportId: a.reportId } : {}),
items: mintedItems(a.items),
};
}
const mintedItems = (items) => items.map((item) => egressText("same-principal", item));
function coerceAnnouncements(raw) {
const rec = emptyAnnouncements();
if (!raw || typeof raw !== "object" || Array.isArray(raw))
return rec;
const r = raw;
if (r.v !== ANNOUNCEMENTS_FORM)
return withUnscoped(rec, (Array.isArray(r.queue) ? r.queue.length : 0) + wholeCount(r.folded));
let unscoped = wholeCount(r.unscopedDiscarded);
if (!r.scopes || typeof r.scopes !== "object" || Array.isArray(r.scopes))
return withUnscoped(rec, unscoped);
for (const scope of Object.keys(r.scopes)) {
const q = r.scopes[scope];
if (scope === "" || !q || typeof q !== "object")
continue;
const queue = [];
if (Array.isArray(q.queue)) {
for (const e of q.queue) {
const a = coerceAnnouncement(e, scope);
if (a !== undefined)
queue.push(a);
else
unscoped += 1;
}
}
const folded = wholeCount(q.folded);
if (queue.length > 0 || folded > 0)
rec.scopes[scope] = { folded, queue };
}
return withUnscoped(rec, unscoped);
}
function withUnscoped(rec, n) {
if (n > 0)
rec.unscopedDiscarded = n;
else
delete rec.unscopedDiscarded;
return rec;
}
function persistedAnnouncements(rec) {
return { v: ANNOUNCEMENTS_FORM, scopes: rec.scopes, ...((rec.unscopedDiscarded ?? 0) > 0 ? { unscopedDiscarded: rec.unscopedDiscarded } : {}) };
}
const ANNOUNCEMENTS_DOC = "announcements";
export function sayAnnounceFailure(sink, stage, cause) {
if (sink === undefined)
return;
try {
const err = new Error(`memory announcement queue ${stage} failed: ${thrownText(cause)}`);
err.code = "memory.announce_failed";
sink(err);
}
catch {
}
}
export const PATCH_PLAN_IO_CONFLICT_REASON = "planning_io_error: patch planning failed (see operator incident log for details)";
const RAW_PLAN_IO_PREFIX = "io error:";
const importPlanIncidentSinks = new WeakMap();
function emitMemoryIncident(sink, err) {
if (sink === undefined)
return;
try {
void Promise.resolve(sink(err)).catch(() => { });
}
catch {
}
}
export function bindImportPlanIncidentSink(plan, sink) {
if (sink !== undefined)
importPlanIncidentSinks.set(plan, sink);
}
export function sanitizeImportPatchConflicts(conflicts, plan, fallbackSink, planFaults) {
const sink = importPlanIncidentSinks.get(plan) ?? fallbackSink;
return conflicts.map((c) => {
if (!planFaults.has(c.id) && !c.reason.startsWith(RAW_PLAN_IO_PREFIX))
return { id: c.id, reason: c.reason };
const cause = planFaults.get(c.id);
const detail = cause !== undefined ? thrownText(cause) : c.reason;
const err = new Error(`memory bundle import planning failed (${c.id}): ${detail}`, ...(cause !== undefined ? [{ cause }] : []));
try {
const causeCode = cause?.code;
if (typeof causeCode === "string")
err.code = causeCode;
}
catch { }
emitMemoryIncident(sink, err);
return { id: c.id, reason: PATCH_PLAN_IO_CONFLICT_REASON };
});
}
export function normalizeReplayedImportReport(report, plan, fallbackSink) {
const sink = importPlanIncidentSinks.get(plan) ?? fallbackSink;
let changed = false;
const conflicts = report.conflicts.map((c) => {
if (typeof c?.reason !== "string" || !c.reason.startsWith(RAW_PLAN_IO_PREFIX))
return c;
changed = true;
emitMemoryIncident(sink, new Error(`memory bundle import replayed raw planning conflict (${typeof c.id === "string" ? c.id : "unknown"}): ${c.reason}`));
return { ...c, reason: PATCH_PLAN_IO_CONFLICT_REASON };
});
return changed ? { ...report, conflicts } : report;
}
function askedScopes(scopes, verb) {
if (!Array.isArray(scopes) || !scopes.every((s) => typeof s === "string" && s !== "")) {
throw new TypeError(`${verb}: scopes must be an array of non-empty scope keys — the queue is read per scope`);
}
return [...new Set(scopes)];
}
function mergeScopeQueues(rec, scopes) {
let folded = 0;
const lines = [];
scopes.forEach((scope, s) => {
const q = Object.prototype.hasOwnProperty.call(rec.scopes, scope) ? rec.scopes[scope] : undefined;
if (q === undefined)
return;
folded += q.folded;
q.queue.forEach((a, i) => lines.push({ a, s, i }));
});
lines.sort((x, y) => x.a.at - y.a.at || x.s - y.s || x.i - y.i);
return { folded, queue: lines.map((l) => l.a) };
}
export async function enqueueMemoryAnnouncement(docs, ann, opts) {
const o = opts === undefined ? undefined : receiveMembers(opts, { subject: "enqueueMemoryAnnouncement options", unit: "option", moment: "at enqueueMemoryAnnouncement" }, ANNOUNCEMENT_OPTION_KEYS);
if (typeof ann.scope !== "string" || ann.scope === "") {
throw new TypeError("enqueueMemoryAnnouncement: announcement.scope is required — each notice is filed under the one scope it reports on");
}
const scope = ann.scope;
ann = { ...ann, items: mintedItems(ann.items) };
const family = o?.supersedesPrefix === undefined ? undefined : egressText("same-principal", o.supersedesPrefix);
if (ann.items.length === 0 && family === undefined)
return;
const line = { ...ann, scope };
await docs.updateDoc(ANNOUNCEMENTS_DOC, coerceAnnouncements, (rec) => {
const own = Object.prototype.hasOwnProperty.call(rec.scopes, scope) ? rec.scopes[scope] : { folded: 0, queue: [] };
if (family !== undefined) {
const queued = own.queue.flatMap((a) => a.items.filter((i) => i.startsWith(family)));
if (queued.length === ann.items.length && ann.items.every((i) => queued.includes(i)))
return { result: undefined };
for (const a of own.queue)
a.items = a.items.filter((i) => !i.startsWith(family));
own.queue = own.queue.filter((a) => a.items.length > 0);
}
if (line.items.length > 0)
own.queue.push({ ...line });
if (own.queue.length > MEMORY_ANNOUNCEMENTS_MAX) {
own.folded += own.queue.length - MEMORY_ANNOUNCEMENTS_MAX;
own.queue = own.queue.slice(-MEMORY_ANNOUNCEMENTS_MAX);
}
if (own.queue.length > 0 || own.folded > 0)
rec.scopes[scope] = own;
else
delete rec.scopes[scope];
return { next: persistedAnnouncements(rec), result: undefined };
});
}
export async function drainMemoryAnnouncements(docs, scopes) {
const asked = askedScopes(scopes, "drainMemoryAnnouncements");
if ((await docs.readDoc(ANNOUNCEMENTS_DOC)) === undefined)
return { folded: 0, queue: [], unscopedDiscarded: 0 };
let otherForm = false;
return docs.updateDoc(ANNOUNCEMENTS_DOC, (raw) => {
otherForm = !raw || typeof raw !== "object" || raw.v !== ANNOUNCEMENTS_FORM;
return coerceAnnouncements(raw);
}, (rec) => {
const mine = mergeScopeQueues(rec, asked);
const drained = { ...mine, unscopedDiscarded: rec.unscopedDiscarded ?? 0 };
if (mine.queue.length === 0 && mine.folded === 0 && drained.unscopedDiscarded === 0 && !otherForm)
return { result: drained };
for (const scope of asked)
delete rec.scopes[scope];
return { next: persistedAnnouncements(withUnscoped(rec, 0)), result: drained };
});
}
export async function peekMemoryAnnouncements(docs, scopes) {
const asked = askedScopes(scopes, "peekMemoryAnnouncements");
const rec = coerceAnnouncements(await docs.readDoc(ANNOUNCEMENTS_DOC));
return { ...mergeScopeQueues(rec, asked), unscopedDiscarded: rec.unscopedDiscarded ?? 0 };
}
export async function transferMemoryAnnouncements(from, to) {
const raw = await from.readDoc(ANNOUNCEMENTS_DOC);
if (raw === undefined)
return;
const taken = coerceAnnouncements(raw);
const takenUnscoped = taken.unscopedDiscarded ?? 0;
const carried = Object.keys(taken.scopes).flatMap((scope) => taken.scopes[scope].queue);
const lineKey = (a) => JSON.stringify(a);
await to.updateDoc(ANNOUNCEMENTS_DOC, coerceAnnouncements, (rec) => {
for (const scope of Object.keys(taken.scopes)) {
const src = taken.scopes[scope];
const own = Object.prototype.hasOwnProperty.call(rec.scopes, scope) ? rec.scopes[scope] : { folded: 0, queue: [] };
own.queue.push(...[...src.queue].sort((x, y) => x.at - y.at));
own.folded += src.folded;
if (own.queue.length > MEMORY_ANNOUNCEMENTS_MAX) {
own.folded += own.queue.length - MEMORY_ANNOUNCEMENTS_MAX;
own.queue = own.queue.slice(-MEMORY_ANNOUNCEMENTS_MAX);
}
if (own.queue.length > 0 || own.folded > 0)
rec.scopes[scope] = own;
}
return { next: persistedAnnouncements(withUnscoped(rec, (rec.unscopedDiscarded ?? 0) + takenUnscoped)), result: undefined };
});
await from.updateDoc(ANNOUNCEMENTS_DOC, coerceAnnouncements, (rec) => {
const moved = new Map();
for (const ann of carried)
moved.set(lineKey(ann), (moved.get(lineKey(ann)) ?? 0) + 1);
for (const scope of Object.keys(rec.scopes)) {
const own = rec.scopes[scope];
own.queue = own.queue.filter((a) => {
const key = lineKey(a);
const n = moved.get(key) ?? 0;
if (n === 0)
return true;
moved.set(key, n - 1);
return false;
});
own.folded = Math.max(0, own.folded - (taken.scopes[scope]?.folded ?? 0));
if (own.queue.length === 0 && own.folded === 0)
delete rec.scopes[scope];
}
return { next: persistedAnnouncements(withUnscoped(rec, Math.max(0, (rec.unscopedDiscarded ?? 0) - takenUnscoped))), result: undefined };
});
}
export function scanFuseKey(scope, rel) {
return JSON.stringify([scope, rel.split(sep).join("/")]);
}
function coerceFuse(raw) {
if (!raw || typeof raw !== "object" || Array.isArray(raw))
return {};
const rec = raw;
if (rec.v !== 2 || !rec.counts || typeof rec.counts !== "object" || Array.isArray(rec.counts))
return {};
const out = {};
for (const [k, v] of Object.entries(rec.counts)) {
if (typeof v === "number" && Number.isFinite(v) && v > 0)
out[k] = Math.floor(v);
}
return out;
}
export function bumpScanFuse(controlDir, key) {
let prior = 0;
lockedJournaledUpdate(controlDir, SCAN_FUSE_FILE, (current) => {
const counts = coerceFuse(current);
prior = counts[key] ?? 0;
counts[key] = prior + 1;
return { v: 2, counts };
});
return prior;
}
const INDEX_REVS_FILE = "index-revs.json";
export function readIndexRevs(controlDir) {
const parsed = readSidecarJson(controlDir, INDEX_REVS_FILE);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
return {};
const pairs = [];
for (const [k, v] of Object.entries(parsed)) {
if (typeof v === "string")
pairs.push([k, { rev: v }]);
else if (v !== null && typeof v === "object" && typeof v.rev === "string") {
const { rev, line } = v;
pairs.push([k, typeof line === "string" ? { rev, line } : { rev }]);
}
}
return Object.fromEntries(pairs);
}
export function normalizeIndexLine(line) {
return line.trim().replace(/\s+/g, " ");
}
export function indexLineHoldsText(line) {
return line.trim() !== "";
}
export function indexLineIsStale(snapshot, entryRev, line) {
return snapshot !== undefined && snapshot.rev !== entryRev && snapshot.line !== undefined && normalizeIndexLine(snapshot.line) === normalizeIndexLine(line);
}
export function writeIndexRevs(controlDir, revs) {
try {
ensureControlPlaneDir(controlDir);
const recorded = Object.fromEntries(Object.entries(revs).map(([target, v]) => [target, { rev: v.rev, line: normalizeIndexLine(v.line) }]));
writeIfChanged(join(controlDir, INDEX_REVS_FILE), `${JSON.stringify(recorded, null, 2)}\n`);
}
catch {
}
}
function clearIndexRevs(controlDir) {
let present = true;
try {
present = lstatSync(join(controlDir, INDEX_REVS_FILE), { throwIfNoEntry: false }) !== undefined;
}
catch {
}
if (present)
writeIndexRevs(controlDir, {});
}
export function scanFuseCount(controlDir, key) {
return coerceFuse(readSidecarJson(controlDir, SCAN_FUSE_FILE))[key] ?? 0;
}
export function sessionRecordBindsIncarnation(recorded, asking) {
return recorded === undefined || asking === undefined || recorded === asking;
}
function readIncarnationSeat(parsed) {
return isIncarnationSeat(parsed.incarnation) && parsed.incarnation !== undefined ? parsed.incarnation : undefined;
}
function isIncarnationSeat(raw) {
if (raw === undefined)
return true;
if (typeof raw !== "string" || raw === "")
return false;
try {
encodeURIComponent(raw);
return true;
}
catch {
return false;
}
}
export function usableSessionIncarnation(raw) {
return isIncarnationSeat(raw) ? raw : undefined;
}
function sessionRecordName(sessionId, incarnation) {
return incarnation === undefined ? `${encodeURIComponent(sessionId)}.json` : `${encodeURIComponent(sessionId)}@${encodeURIComponent(incarnation)}.json`;
}
async function mintSessionRecordObjects(objects, kind, sessionId, incarnation, bytes) {
try {
if ((await putControlObjectOnce(objects, kind, sessionRecordName(sessionId), bytes)) === "created")
return "created";
}
catch {
return "unpersisted";
}
const own = usableSessionIncarnation(incarnation);
const standing = await sessionRecordOwnerOf(objects, kind, sessionRecordName(sessionId));
const vouches = standing !== "unattributable" && (standing.owner === undefined || standing.owner === own);
const unnamed = vouches || own === undefined ? undefined : await sessionRecordOwnerOf(objects, kind, sessionRecordName(sessionId, ""));
if (vouches || (unnamed !== undefined && unnamed !== "unattributable" && unnamed.owner === undefined))
return "existed";
try {
return (await putControlObjectOnce(objects, kind, sessionRecordName(sessionId, own ?? ""), bytes)) === "created" ? "created" : "existed";
}
catch {
return "unpersisted";
}
}
async function sessionRecordOwnerOf(objects, kind, name) {
let bytes;
try {
bytes = await objects.getObject(kind, name);
}
catch {
return "unattributable";
}
if (bytes === undefined)
return "unattributable";
try {
const parsed = JSON.parse(new TextDecoder().decode(bytes));
if (parsed !== null && typeof parsed === "object")
return { owner: readIncarnationSeat(parsed) };
}
catch {
}
return "unattributable";
}
function bindOrSeparate(record, identity, asking, unknownSlot) {
if (sessionRecordBindsIncarnation(record.incarnation, asking))
return record;
const unnamed = unknownSlot();
if (unnamed !== undefined && sessionRecordBindsIncarnation(unnamed.incarnation, asking))
return unnamed;
if (record.incarnation !== undefined)
identity?.onSeparated?.(record.incarnation);
return undefined;
}
function sessionIdOfRecordName(name) {
if (!name.endsWith(".json"))
return undefined;
const stem = name.slice(0, -".json".length);
const at = stem.indexOf("@");
try {
return decodeURIComponent(at < 0 ? stem : stem.slice(0, at));
}
catch {
return undefined;
}
}
export const SESSION_POLLUTION_DIR = "session-pollution";
export async function markSessionPolluted(objects, sessionId, reason, now, cause, incarnation) {
const record = { at: now(), reason, ...(cause !== undefined ? { cause } : {}), ...(incarnation !== undefined ? { incarnation } : {}) };
return mintSessionRecordObjects(objects, "pollution", sessionId, incarnation, new TextEncoder().encode(`${JSON.stringify(record, null, 2)}\n`));
}
export async function readSessionPollution(objects, sessionId, identity) {
const asking = usableSessionIncarnation(identity?.incarnation);
if (asking !== undefined) {
const own = await readPollutionObject(objects, sessionRecordName(sessionId, asking));
if (own !== undefined)
return own;
}
const unnamed = await readPollutionObject(objects, sessionRecordName(sessionId, ""));
const standing = await readPollutionObject(objects, sessionRecordName(sessionId));
return standing === undefined ? unnamed : bindOrSeparate(standing, identity, asking, () => unnamed);
}
async function readPollutionObject(objects, name) {
let bytes;
try {
bytes = await objects.getObject("pollution", name);
}
catch {
return { at: 0, reason: "pollution marker present but unreadable (kept fail-closed)" };
}
return bytes === undefined ? undefined : pollutionRecordOf(new TextDecoder().decode(bytes));
}
function pollutionRecordOf(raw) {
try {
const parsed = JSON.parse(raw);
if (parsed !== null && typeof parsed === "object") {
const at = parsed.at;
const reason = parsed.reason;
const cause = parsed.cause;
const knownCause = typeof cause === "string" && MEMORY_ORIGIN_CAUSES.includes(cause) ? cause : undefined;
const incarnation = readIncarnationSeat(parsed);
if (typeof at === "number" && typeof reason === "string")
return { at, reason, ...(knownCause !== undefined ? { cause: knownCause } : {}), ...(incarnation !== undefined ? { incarnation } : {}) };
}
}
catch {
}
return { at: 0, reason: "pollution marker present but unreadable (kept fail-closed)" };
}
export async function listSessionPollution(objects) {
const names = await objects.listObjects("pollution");
const out = Object.create(null);
for (const name of [...names].sort()) {
const sessionId = sessionIdOfRecordName(name);
if (sessionId === undefined || Object.prototype.hasOwnProperty.call(out, sessionId))
continue;
const rec = await readPollutionObject(objects, name);
if (rec !== undefined)
out[sessionId] = rec;
}
return out;
}
export async function importSessionPollution(objects, sessionId, record) {
const text = `${JSON.stringify({ at: record.at, reason: record.reason, ...(record.cause !== undefined ? { cause: record.cause } : {}) }, null, 2)}\n`;
if ((await putControlObjectOnce(objects, "pollution", sessionRecordName(sessionId), new TextEncoder().encode(text))) === "created")
return "written";
const standing = await readSessionPollution(objects, sessionId);
return standing !== undefined && standing.at === record.at && standing.reason === record.reason ? "already" : "divergent";
}
export const SESSION_CAPTURE_OPTOUT_DIR = "session-capture-optout";
const UNREADABLE_CAPTURE_RECORD = Object.freeze({ at: 0, reason: "capture opt-out record present but unreadable (kept fail-closed)" });
function captureIndeterminate(name, err) {
return new ControlPlaneCorruptError(`session capture opt-out record state is INDETERMINATE for ${JSON.stringify(name)} (${thrownText(err)}) — the store cannot establish whether a record exists; consumers must suppress on the fault axis (an outage is never reported as a user request)`, { cause: err });
}
export async function markSessionCaptureObjects(objects, sessionId, record) {
try {
const stored = { at: record.at, reason: record.reason, ...(record.incarnation !== undefined ? { incarnation: record.incarnation } : {}) };
return await mintSessionRecordObjects(objects, "capture", sessionId, record.incarnation, new TextEncoder().encode(`${JSON.stringify(stored, null, 2)}\n`));
}
catch {
return "unpersisted";
}
}
export async function readSessionCaptureObjects(objects, sessionId, identity) {
const asking = usableSessionIncarnation(identity?.incarnation);
if (asking !== undefined) {
const own = await readCaptureObject(objects, sessionRecordName(sessionId, asking));
if (own !== undefined)
return own;
}
const standing = await readCaptureObject(objects, sessionRecordName(sessionId));
if (standing === undefined)
return readCaptureObject(objects, sessionRecordName(sessionId, ""));
const unnamed = sessionRecordBindsIncarnation(standing.incarnation, asking) ? undefined : await readCaptureObject(objects, sessionRecordName(sessionId, ""));
return bindOrSeparate(standing, identity, asking, () => unnamed);
}
async function readCaptureObject(objects, name) {
let bytes;
try {
bytes = await objects.getObject("capture", name);
}
catch (err) {
let standing;
try {
standing = await objects.listObjects("capture");
}
catch (lerr) {
throw captureIndeterminate(name, lerr);
}
if (Array.isArray(standing) && standing.includes(name))
return UNREADABLE_CAPTURE_RECORD;
throw captureIndeterminate(name, err);
}
if (bytes === undefined)
return undefined;
try {
const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
if (parsed !== null && typeof parsed === "object") {
const at = parsed.at;
const reason = parsed.reason;
const incarnation = readIncarnationSeat(parsed);
if (typeof at === "number" && typeof reason === "string")
return { at, reason, ...(incarnation !== undefined ? { incarnation } : {}) };
}
}
catch {
}
return UNREADABLE_CAPTURE_RECORD;
}
export async function listSessionCaptureObjects(objects) {
let names;
try {
names = await objects.listObjects("capture");
}
catch (err) {
throw new ControlPlaneCorruptError(`session capture opt-out records could not be enumerated (${thrownText(err)}) — an enumeration failure is not an empty set (fail-closed)`, { cause: err });
}
if (!Array.isArray(names) || !Array.from(names).every((n) => typeof n === "string")) {
throw new ControlPlaneCorruptError("session capture opt-out records: the store's listing is not a list of names — an enumeration failure is not an empty set (fail-closed)");
}
const out = Object.create(null);
for (const name of [...names].sort()) {
const sessionId = sessionIdOfRecordName(name);
if (sessionId === undefined || Object.prototype.hasOwnProperty.call(out, sessionId))
continue;
const rec = await readCaptureObject(objects, name);
if (rec !== undefined)
out[sessionId] = rec;
}
return out;
}
export const USAGE_RETRIEVED_FILE = "usage-retrieved.json";
export const USAGE_RETRIEVED_MAX_IDS = 4096;
function coerceRetrievedAccount(raw) {
if (!raw || typeof raw !== "object" || Array.isArray(raw))
return Object.create(null);
const out = Object.create(null);
for (const [k, v] of Object.entries(raw)) {
const row = v;
if (row && typeof row === "object" && typeof row.count === "number" && Number.isFinite(row.count) && row.count > 0 && typeof row.lastAt === "number" && Number.isFinite(row.lastAt)) {
out[k] = { count: Math.floor(row.count), lastAt: row.lastAt };
}
}
return out;
}
export function recordRetrievedAccount(controlDir, ids, now) {
if (ids.length === 0)
return;
const at = now();
lockedJournaledUpdate(controlDir, USAGE_RETRIEVED_FILE, (current) => {
const rows = coerceRetrievedAccount(current);
for (const id of ids) {
const prior = rows[id];
rows[id] = { count: (prior?.count ?? 0) + 1, lastAt: at };
}
const keys = Object.keys(rows);
if (keys.length > USAGE_RETRIEVED_MAX_IDS) {
keys.sort((a, b) => rows[a].lastAt - rows[b].lastAt || (a < b ? -1 : 1));
for (const cold of keys.slice(0, keys.length - USAGE_RETRIEVED_MAX_IDS))
delete rows[cold];
}
return rows;
});
}
export function readRetrievedAccount(controlDir) {
return coerceRetrievedAccount(readSidecarJson(controlDir, USAGE_RETRIEVED_FILE));
}
export function clearScanFuse(controlDir, keys) {
const wanted = [...keys];
if (wanted.length === 0)
return;
const file = join(controlDir, SCAN_FUSE_FILE);
if (!existsSync(file) && !existsSync(`${file}.journal`))
return;
lockedJournaledUpdate(controlDir, SCAN_FUSE_FILE, (current) => {
const counts = coerceFuse(current);
let changed = false;
for (const k of wanted) {
if (counts[k] !== undefined) {
delete counts[k];
changed = true;
}
}
return changed ? { v: 2, counts } : undefined;
});
}
export const LINEAGE_FILE = "lineage.json";
export const CHALLENGES_FILE = "challenges.json";
export const DELEGATION_SETTLEMENT_FILE = "delegation-settlement.json";
export const SESSION_ACCOUNTS_FILE = "session-accounts.json";
const FILE_GOVERNANCE_DOCS = Object.freeze({
lineage: Object.freeze({ file: LINEAGE_FILE, what: "memory lineage ledger" }),
challenges: Object.freeze({ file: CHALLENGES_FILE, what: "memory challenge ledger" }),
settlements: Object.freeze({ file: DELEGATION_SETTLEMENT_FILE, what: "memory delegation-settlement ledger" }),
"session-accounts": Object.freeze({ file: SESSION_ACCOUNTS_FILE, what: "memory session-account ledger" }),
announcements: Object.freeze({ file: ANNOUNCEMENTS_FILE, what: "memory announcement queue" }),
holds: Object.freeze({ file: "holds.json", what: "memory instruction-hold ledger" }),
"origin-clearances": Object.freeze({ file: "origin-clearances.json", what: "memory origin-clearance ledger" }),
});
export function fileGovernanceDocOf(name) {
if (typeof name !== "string" || !Object.prototype.hasOwnProperty.call(FILE_GOVERNANCE_DOCS, name)) {
const e = new Error(`memory governance store: ${JSON.stringify(String(name))} is not a governance document (one of ${MEMORY_GOVERNANCE_DOC_NAMES.join(", ")})`);
e.code = "memory.governance_doc_unknown";
throw e;
}
return FILE_GOVERNANCE_DOCS[name];
}
export const LINEAGE_AUDIT_FILE = "lineage-audit.json";
export const LINEAGE_AUDIT_MAX_ROWS = 2048;
export const CHALLENGED_HISTORY_FILE = "usage-challenged-history.json";
function rollForwardStrictSidecar(file, journal, fence) {
let raw;
try {
raw = readFileSync(journal, "utf8");
}
catch {
return;
}
try {
JSON.parse(raw);
}
catch {
throw new ControlPlaneCorruptError(`control-plane journal is unparseable (fail-closed sidecar): ${journal}`);
}
fence?.();
atomicWriteFileSync(file, raw);
fence?.();
rmSync(journal, { force: true });
}
export function lockedStrictUpdate(controlDir, fileName, what, coerce, fn, onUnreadable) {
ensureControlPlaneDir(controlDir);
const file = join(controlDir, fileName);
const journal = `${file}.journal`;
const lock = `${file}.lock`;
const token = acquireSidecarLock(lock, { onDeadline: "throw" });
try {
let current;
try {
rollForwardStrictSidecar(file, journal, () => assertSidecarLockOwnership(lock, token, what, "strict"));
current = coerce(readStrictSidecarRaw(file, what));
}
catch (err) {
if (onUnreadable === undefined || !(err instanceof ControlPlaneCorruptError) || err.facet === "lock-ownership")
throw err;
current = onUnreadable(err);
}
const { next, result } = fn(current);
if (next !== undefined) {
const data = `${JSON.stringify(next, null, 2)}\n`;
const fence = () => assertSidecarLockOwnership(lock, token, what, "strict");
fence();
atomicWriteFileSync(journal, data);
fence();
atomicWriteFileSync(file, data);
fence();
rmSync(journal, { force: true });
}
return result;
}
finally {
releaseSidecarLock(lock, token);
}
}
export function lockedStrictRemove(controlDir, fileName, what, removable) {
const file = join(controlDir, fileName);
const journal = `${file}.journal`;
const lock = `${file}.lock`;
const token = acquireSidecarLock(lock, { onDeadline: "throw" });
try {
const fence = () => assertSidecarLockOwnership(lock, token, what, "strict");
rollForwardStrictSidecar(file, journal, fence);
const committed = readStrictSidecarRaw(file, what);
if (committed === undefined)
return "absent";
if (!removable(committed))
return "kept";
fence();
rmSync(file);
return "removed";
}
finally {
releaseSidecarLock(lock, token);
}
}
function readStrictSidecarRaw(file, what) {
let raw;
try {
raw = readFileSync(file, "utf8");
}
catch (err) {
if (err.code === "ENOENT")
return undefined;
throw new ControlPlaneCorruptError(`${what} unreadable (${err.code ?? "io error"}): ${file}`, { cause: err });
}
try {
return JSON.parse(raw);
}
catch {
throw new ControlPlaneCorruptError(`${what} is unparseable: ${file}`);
}
}
export function readStrictSidecar(controlDir, fileName, what) {
const file = join(controlDir, fileName);
const journal = `${file}.journal`;
let journalRaw;
try {
journalRaw = readFileSync(journal, "utf8");
}
catch (err) {
if (err.code !== "ENOENT") {
throw new ControlPlaneCorruptError(`control-plane journal unreadable ((${err.code ?? "io error"})) — a committed next state may exist that cannot be proven; repair the read fault rather than serving the pre-transaction state: ${journal}`, { cause: err });
}
journalRaw = undefined;
}
if (journalRaw !== undefined) {
try {
return JSON.parse(journalRaw);
}
catch {
throw new ControlPlaneCorruptError(`control-plane journal is unparseable (fail-closed sidecar): ${journal}`);
}
}
return readStrictSidecarRaw(file, what);
}
function landContribution(sessions, sessionId, incoming) {
const standing = Object.prototype.hasOwnProperty.call(sessions, sessionId) ? sessions[sessionId] : undefined;
if (incoming.attribution !== undefined && standing !== undefined && standing.attribution === undefined) {
const { attribution: _overlap, ...asWriter } = incoming;
sessions[sessionId] = asWriter;
return;
}
sessions[sessionId] = incoming;
}
function coerceLineage(raw) {
if (raw === undefined) {
return { version: 1, committed: Object.create(null), pending: Object.create(null) };
}
if (!raw || typeof raw !== "object" || Array.isArray(raw))
throw new ControlPlaneCorruptError("memory lineage ledger has the wrong shape");
const r = raw;
if (r.version !== 1)
throw new ControlPlaneCorruptError(`memory lineage ledger has an unrecognized version (${String(r.version)}) — refusing (fail-closed)`);
const badShape = (part) => new ControlPlaneCorruptError(`memory lineage ledger ${part} has the wrong shape`);
if (!r.committed || typeof r.committed !== "object" || Array.isArray(r.committed))
throw badShape("committed set");
if (!r.pending || typeof r.pending !== "object" || Array.isArray(r.pending))
throw badShape("pending set");
for (const [entryId, sessions] of Object.entries(r.committed)) {
if (!sessions || typeof sessions !== "object" || Array.isArray(sessions))
throw badShape(`committed[${JSON.stringify(entryId)}]`);
for (const [sid, c] of Object.entries(sessions)) {
const row = c;
if (!row || typeof row !== "object" || typeof row.lastRev !== "string" || typeof row.lastAt !== "number") {
throw badShape(`committed[${JSON.stringify(entryId)}][${JSON.stringify(sid)}]`);
}
if (row.marked !== undefined && row.marked !== true)
throw badShape(`committed[${JSON.stringify(entryId)}][${JSON.stringify(sid)}] marked`);
if (!isIncarnationSeat(row.incarnation)) {
throw badShape(`committed[${JSON.stringify(entryId)}][${JSON.stringify(sid)}] incarnation`);
}
if (row.attribution !== undefined && row.attribution !== "overlap") {
throw badShape(`committed[${JSON.stringify(entryId)}][${JSON.stringify(sid)}] attribution`);
}
}
}
for (const [txnId, t] of Object.entries(r.pending)) {
const txn = t;
if (!txn || typeof txn !== "object" || typeof txn.sessionId !== "string" || typeof txn.at !== "number" || !Array.isArray(txn.rows)) {
throw badShape(`pending[${JSON.stringify(txnId)}]`);
}
if (txn.kind !== undefined && txn.kind !== "latch-only")
throw badShape(`pending[${JSON.stringify(txnId)}] kind`);
if (!isIncarnationSeat(txn.incarnation))
throw badShape(`pending[${JSON.stringify(txnId)}] incarnation`);
for (const row of txn.rows) {
const p = row;
if (!p || typeof p !== "object" || typeof p.entryId !== "string" || typeof p.rev !== "string")
throw badShape(`pending[${JSON.stringify(txnId)}] row`);
if ((p.sessionId === undefined) !== (p.attribution === undefined) || (p.sessionId !== undefined && (typeof p.sessionId !== "string" || p.sessionId.length === 0)) || (p.attribution !== undefined && p.attribution !== "overlap")) {
throw badShape(`pending[${JSON.stringify(txnId)}] row attribution`);
}
if (p.kind !== undefined && p.kind !== "latch-only")
throw badShape(`pending[${JSON.stringify(txnId)}] row kind`);
if (p.marked !== undefined && p.marked !== true)
throw badShape(`pending[${JSON.stringify(txnId)}] row marked`);
}
if (txn.credential !== undefined) {
const c = txn.credential;
if (!c || typeof c !== "object" || !Array.isArray(c.appliedIds) || c.appliedIds.some((x) => typeof x !== "string") || typeof c.at !== "number") {
throw badShape(`pending[${JSON.stringify(txnId)}] credential`);
}
}
}
const committed = Object.create(null);
for (const [entryId, sessions] of Object.entries(r.committed)) {
const s = Object.create(null);
for (const [sid, c] of Object.entries(sessions))
s[sid] = c;
committed[entryId] = s;
}
const pending = Object.create(null);
for (const [txnId, t] of Object.entries(r.pending))
pending[txnId] = t;
return { version: 1, committed, pending };
}
export async function stageLineagePending(docs, txnId, sessionId, rows, now, incarnation) {
await docs.updateDoc("lineage", coerceLineage, (rec) => {
rec.pending[txnId] = { sessionId, at: now(), rows: [...rows], ...(incarnation !== undefined ? { incarnation } : {}) };
return { next: rec, result: undefined };
});
}
export async function discardLineagePending(docs, txnId) {
await docs.updateDoc("lineage", coerceLineage, (rec) => {
if (rec.pending[txnId] === undefined)
return { result: undefined };
delete rec.pending[txnId];
return { next: rec, result: undefined };
});
}
export async function recordLineageCredential(docs, txnId, appliedIds, now) {
await docs.updateDoc("lineage", coerceLineage, (rec) => {
const txn = rec.pending[txnId];
if (txn === undefined)
throw new ControlPlaneCorruptError(`memory lineage ledger: credential for unknown pending transaction ${txnId}`);
txn.credential = { appliedIds: [...appliedIds], at: now() };
return { next: rec, result: undefined };
});
}
function promotedContribution(txn, row, at) {
const marked = row.marked === true ? { marked: true } : {};
if (row.sessionId !== undefined)
return { sessionId: row.sessionId, contribution: { lastRev: row.rev, lastAt: at, ...marked, attribution: "overlap" } };
return { sessionId: txn.sessionId, contribution: { lastRev: row.rev, lastAt: at, ...marked, ...(txn.incarnation !== undefined ? { incarnation: txn.incarnation } : {}) } };
}
export async function promoteLineagePending(docs, txnId) {
return docs.updateDoc("lineage", coerceLineage, (rec) => {
const txn = rec.pending[txnId];
if (txn === undefined)
return { result: [] };
if (txn.credential === undefined) {
throw new ControlPlaneCorruptError(`memory lineage ledger: refusing to promote uncredentialed pending transaction ${txnId} (the commit outcome is not durably known)`);
}
const applied = new Set(txn.credential.appliedIds);
const at = txn.credential.at;
const promoted = [];
for (const row of txn.rows) {
if (!applied.has(row.entryId))
continue;
const sessions = (rec.committed[row.entryId] ??= Object.create(null));
const promotion = promotedContribution(txn, row, at);
landContribution(sessions, promotion.sessionId, promotion.contribution);
promoted.push({ entryId: row.entryId, sessionId: promotion.sessionId, rev: row.rev, ...(row.marked === true ? { marked: true } : {}) });
}
delete rec.pending[txnId];
return { next: rec, result: promoted };
});
}
export async function adjudicateLineagePending(docs, txnId, action, now) {
return docs.updateDoc("lineage", coerceLineage, (rec) => {
const txn = rec.pending[txnId];
if (txn === undefined)
return { result: [] };
if (isLatchOnlyTxn(txn)) {
throw new ControlPlaneCorruptError(`memory lineage ledger: pending transaction ${txnId} is a bundle-import latch — it cannot be ${action === "promote" ? "promoted (its rows are not contributions)" : "discarded (its withhold guards not-yet-governed imported entries)"}; re-run the same bundle import to converge it (releaseImportLatch is receipt-gated)`);
}
if (action === "discard") {
delete rec.pending[txnId];
return { next: rec, result: [] };
}
const applied = txn.credential !== undefined ? new Set(txn.credential.appliedIds) : undefined;
const at = txn.credential?.at ?? now();
const promoted = [];
for (const row of txn.rows) {
if (applied !== undefined && !applied.has(row.entryId))
continue;
const sessions = (rec.committed[row.entryId] ??= Object.create(null));
const promotion = promotedContribution(txn, row, at);
landContribution(sessions, promotion.sessionId, promotion.contribution);
promoted.push({ entryId: row.entryId, sessionId: promotion.sessionId, rev: row.rev, ...(row.marked === true ? { marked: true } : {}) });
}
delete rec.pending[txnId];
return { next: rec, result: promoted };
});
}
export async function reconcileLineage(docs) {
return docs.updateDoc("lineage", coerceLineage, (rec) => {
const promoted = [];
const undecidable = [];
let changed = false;
for (const [txnId, txn] of Object.entries(rec.pending)) {
if (txn.credential === undefined) {
undecidable.push({ txnId, sessionId: txn.sessionId, entryIds: txn.rows.map((r) => r.entryId), ...(isLatchOnlyTxn(txn) ? { kind: "latch-only" } : {}) });
continue;
}
const applied = new Set(txn.credential.appliedIds);
for (const row of txn.rows) {
if (!applied.has(row.entryId))
continue;
const sessions = (rec.committed[row.entryId] ??= Object.create(null));
const promotion = promotedContribution(txn, row, txn.credential.at);
landContribution(sessions, promotion.sessionId, promotion.contribution);
promoted.push({ entryId: row.entryId, sessionId: promotion.sessionId, rev: row.rev, ...(row.marked === true ? { marked: true } : {}) });
}
delete rec.pending[txnId];
changed = true;
}
return { ...(changed ? { next: rec } : {}), result: { promoted, undecidable } };
});
}
function isLatchOnlyTxn(txn) {
if (txn.kind === "latch-only")
return true;
return txn.rows.some((row) => row.kind === "latch-only");
}
export const IMPORT_RECEIPTS_DIR = "import-receipts";
export const FILE_CONTROL_OBJECT_DIRS = Object.freeze({
pollution: SESSION_POLLUTION_DIR,
"import-receipt": IMPORT_RECEIPTS_DIR,
quarantine: QUARANTINE_DIR,
hold: "hold",
"clearance-custody": "origin-clearance-custody",
capture: SESSION_CAPTURE_OPTOUT_DIR,
});
export const CONTROL_OBJECT_STAGE_DIR = ".control-object-stage";
export function importLatchTxnId(bundleHash) {
return `import:${bundleHash}`;
}
export function importReceiptName(bundleHash) {
return `${bundleHash}.json`;
}
export async function stageImportLatch(docs, bundleHash, rows, now) {
const txnId = importLatchTxnId(bundleHash);
await docs.updateDoc("lineage", coerceLineage, (rec) => {
const existing = rec.pending[txnId];
if (existing !== undefined && !isLatchOnlyTxn(existing)) {
throw new ControlPlaneCorruptError(`memory lineage ledger: pending transaction ${txnId} exists and is NOT an import latch — refusing to overwrite a real staged transaction`);
}
rec.pending[txnId] = {
sessionId: txnId,
at: now(),
kind: "latch-only",
rows: rows.map((r) => ({ entryId: r.entryId, rev: r.rev, kind: "latch-only" })),
};
return { next: rec, result: undefined };
});
return txnId;
}
export async function releaseImportLatch(store, txnId) {
const prefix = "import:";
if (!txnId.startsWith(prefix) || !/^[0-9a-f]{64}$/.test(txnId.slice(prefix.length))) {
throw new ControlPlaneCorruptError(`The import latch was not released: ${JSON.stringify(txnId)} is not an import-latch transaction id (import:<64-hex bundleHash>)`);
}
const receipt = importReceiptName(txnId.slice(prefix.length));
let bytes;
try {
bytes = await store.getObject("import-receipt", receipt);
}
catch (err) {
throw new ControlPlaneCorruptError(`The import latch was not released: the completion receipt ${receipt} could not be read (${thrownText(err)}) — a probe failure is not absence (fail-closed), and absence would refuse the release`, { cause: err });
}
if (bytes === undefined) {
throw new ControlPlaneCorruptError(`The import latch was not released: no completion receipt ${receipt} — the import's governance legs are not proven landed, the latch stays; re-run the same bundle import to converge`);
}
await store.updateDoc("lineage", coerceLineage, (rec) => {
const txn = rec.pending[txnId];
if (txn === undefined)
return { result: undefined };
if (!isLatchOnlyTxn(txn)) {
throw new ControlPlaneCorruptError(`The import latch was not released: pending transaction ${txnId} is NOT an import latch — refusing (this channel never discards a real staged transaction)`);
}
delete rec.pending[txnId];
return { next: rec, result: undefined };
});
}
export async function lineageLatchedIds(docs) {
const rec = coerceLineage(await docs.readDoc("lineage"));
const out = new Set();
for (const txn of Object.values(rec.pending))
for (const row of txn.rows)
out.add(row.entryId);
return out;
}
export async function lineageContributionsOfSession(docs, sessionId, asking) {
const rec = coerceLineage(await docs.readDoc("lineage"));
const out = [];
for (const [entryId, sessions] of Object.entries(rec.committed)) {
const c = Object.prototype.hasOwnProperty.call(sessions, sessionId) ? sessions[sessionId] : undefined;
if (c === undefined || !sessionRecordBindsIncarnation(c.incarnation, asking))
continue;
out.push({ entryId, lastRev: c.lastRev, lastAt: c.lastAt, ...(c.marked === true ? { marked: true } : {}), ...(c.attribution !== undefined ? { attribution: c.attribution } : {}) });
}
return out;
}
export async function lineageAccountOfEntry(docs, entryId) {
const rec = coerceLineage(await docs.readDoc("lineage"));
const sessions = Object.prototype.hasOwnProperty.call(rec.committed, entryId) ? rec.committed[entryId] : undefined;
const contributors = sessions === undefined ? [] : Object.entries(sessions).map(([sessionId, c]) => ({ sessionId, lastRev: c.lastRev, lastAt: c.lastAt, ...(c.attribution !== undefined ? { attribution: c.attribution } : {}) }));
let pendingLatched = false;
for (const txn of Object.values(rec.pending)) {
if (txn.rows.some((r) => r.entryId === entryId)) {
pendingLatched = true;
break;
}
}
return { contributors, pendingLatched };
}
export async function clearLineageForEntries(docs, entryIds) {
if (entryIds.length === 0)
return;
await docs.updateDoc("lineage", coerceLineage, (rec) => {
let changed = false;
for (const id of entryIds) {
if (rec.committed[id] !== undefined) {
delete rec.committed[id];
changed = true;
}
}
return { ...(changed ? { next: rec } : {}), result: undefined };
});
}
export async function captureAndClearLineageForEntries(docs, entryIds) {
if (entryIds.length === 0)
return new Map();
return docs.updateDoc("lineage", coerceLineage, (rec) => {
const want = new Set(entryIds);
const captured = new Map();
const add = (id, sessionId) => {
const set = captured.get(id) ?? new Set();
set.add(sessionId);
captured.set(id, set);
};
let changed = false;
for (const id of entryIds) {
if (!Object.prototype.hasOwnProperty.call(rec.committed, id))
continue;
for (const sessionId of Object.keys(rec.committed[id] ?? {}))
add(id, sessionId);
delete rec.committed[id];
changed = true;
}
for (const txn of Object.values(rec.pending)) {
const keep = [];
for (const row of txn.rows) {
if (!want.has(row.entryId)) {
keep.push(row);
continue;
}
changed = true;
if (row.kind !== "latch-only")
add(row.entryId, row.sessionId ?? txn.sessionId);
}
txn.rows = keep;
}
const result = new Map();
for (const [id, sessions] of captured)
result.set(id, [...sessions].sort());
return { ...(changed ? { next: rec } : {}), result };
});
}
export async function importLineageCommitted(docs, rows) {
if (rows.length === 0)
return [];
return docs.updateDoc("lineage", coerceLineage, (rec) => {
const divergence = [];
let changed = false;
for (const row of rows) {
const sessions = (rec.committed[row.entryId] ??= Object.create(null));
const standing = Object.prototype.hasOwnProperty.call(sessions, row.sessionId) ? sessions[row.sessionId] : undefined;
if (standing === undefined || row.lastAt > standing.lastAt) {
landContribution(sessions, row.sessionId, { lastRev: row.lastRev, lastAt: row.lastAt, ...(row.marked === true ? { marked: true } : {}), ...(row.attribution === "overlap" ? { attribution: "overlap" } : {}) });
changed = true;
continue;
}
if (row.lastAt === standing.lastAt && row.lastRev !== standing.lastRev) {
divergence.push({ entryId: row.entryId, sessionId: row.sessionId, kept: "destination" });
continue;
}
if (row.lastAt === standing.lastAt && row.lastRev === standing.lastRev && row.marked === true && standing.marked !== true) {
sessions[row.sessionId] = { ...standing, marked: true };
changed = true;
continue;
}
}
return { ...(changed ? { next: rec } : {}), result: divergence };
});
}
export async function readLineageRecord(docs) {
const rec = coerceLineage(await docs.readDoc("lineage"));
return { committed: rec.committed, pending: rec.pending };
}
export function appendLineageAudit(controlDir, rows) {
if (rows.length === 0)
return;
lockedJournaledUpdate(controlDir, LINEAGE_AUDIT_FILE, (current) => {
const list = Array.isArray(current) ? current.filter((r) => r && typeof r === "object") : [];
list.push(...rows);
return list.length > LINEAGE_AUDIT_MAX_ROWS ? list.slice(-LINEAGE_AUDIT_MAX_ROWS) : list;
});
}
function coerceChallenges(raw) {
if (raw === undefined)
return { version: 1, events: [] };
if (!raw || typeof raw !== "object" || Array.isArray(raw))
throw new ControlPlaneCorruptError("memory challenge ledger has the wrong shape");
const r = raw;
if (r.version !== 1)
throw new ControlPlaneCorruptError(`memory challenge ledger has an unrecognized version (${String(r.version)}) — refusing (fail-closed)`);
if (!Array.isArray(r.events))
throw new ControlPlaneCorruptError("memory challenge ledger events list has the wrong shape");
for (const e of r.events) {
const ev = e;
if (!ev ||
typeof ev !== "object" ||
typeof ev.eventId !== "string" ||
typeof ev.entryId !== "string" ||
(ev.kind !== "challenge" && ev.kind !== "resolve") ||
typeof ev.generation !== "number" ||
typeof ev.at !== "number" ||
typeof ev.reason !== "string") {
throw new ControlPlaneCorruptError("memory challenge ledger event has the wrong shape");
}
}
return raw;
}
export const CHALLENGE_LEDGER_MAX_EVENTS = 10_000;
export async function appendChallengeEvents(docs, events, now) {
if (events.length === 0)
return { assignments: [], eventCount: undefined };
return docs.updateDoc("challenges", coerceChallenges, (rec) => {
const byEventId = new Map(rec.events.map((e) => [e.eventId, e]));
const maxGen = new Map();
for (const e of rec.events) {
if (e.kind !== "challenge")
continue;
maxGen.set(e.entryId, Math.max(maxGen.get(e.entryId) ?? 0, e.generation));
}
const out = [];
let changed = false;
for (const req of events) {
const existing = byEventId.get(req.eventId);
if (existing !== undefined) {
out.push({ entryId: existing.entryId, eventId: existing.eventId, generation: existing.generation, at: existing.at, replayed: true });
continue;
}
const generation = (maxGen.get(req.entryId) ?? 0) + 1;
maxGen.set(req.entryId, generation);
const ev = {
eventId: req.eventId,
entryId: req.entryId,
kind: "challenge",
generation,
at: now(),
reason: req.reason,
grade: "S",
...(req.challengedRev !== undefined ? { challengedRev: req.challengedRev } : {}),
};
rec.events.push(ev);
byEventId.set(ev.eventId, ev);
out.push({ entryId: ev.entryId, eventId: ev.eventId, generation, at: ev.at, replayed: false });
changed = true;
}
return { ...(changed ? { next: rec } : {}), result: { assignments: out, eventCount: rec.events.length } };
});
}
export async function resolveChallengeEvent(docs, entryId, generation, reason, now, requestId) {
return docs.updateDoc("challenges", coerceChallenges, (rec) => {
const opened = rec.events.some((e) => e.kind === "challenge" && e.entryId === entryId && e.generation === generation);
if (!opened)
return { result: { resolved: false, eventCount: undefined } };
const alreadyResolved = rec.events.some((e) => e.kind === "resolve" && e.entryId === entryId && e.generation === generation);
if (alreadyResolved)
return { result: { resolved: true, eventCount: undefined } };
rec.events.push({
eventId: requestId !== undefined && requestId !== "" ? `${requestId}:${entryId}` : `resolve:${entryId}:${generation}`,
entryId,
kind: "resolve",
generation,
at: now(),
reason,
});
return { next: rec, result: { resolved: true, eventCount: rec.events.length } };
});
}
export async function challengedEntryIds(docs) {
const rec = coerceChallenges(await docs.readDoc("challenges"));
const resolved = new Set();
for (const e of rec.events)
if (e.kind === "resolve")
resolved.add(`${e.entryId}#${e.generation}`);
const out = new Map();
for (const e of rec.events) {
if (e.kind !== "challenge" || resolved.has(`${e.entryId}#${e.generation}`))
continue;
const prior = out.get(e.entryId);
if (prior === undefined || e.generation > prior.generation)
out.set(e.entryId, { generation: e.generation, at: e.at });
}
return out;
}
export async function readChallengeEvents(docs) {
return coerceChallenges(await docs.readDoc("challenges")).events;
}
const STRICT_LEDGER_SHAPES = Object.freeze({
lineage: Object.freeze({ coerce: (raw) => coerceLineage(raw), empty: () => ({ version: 1, committed: {}, pending: {} }) }),
challenges: Object.freeze({ coerce: (raw) => coerceChallenges(raw), empty: () => ({ version: 1, events: [] }) }),
});
export const STRICT_CONTROL_PLANE_LEDGERS = Object.freeze(Object.keys(STRICT_LEDGER_SHAPES));
export function isStrictControlPlaneLedgerCorrupt(controlDir, ledger) {
const { file: fileName, what } = fileGovernanceDocOf(ledger);
const { coerce } = STRICT_LEDGER_SHAPES[ledger];
try {
coerce(readStrictSidecar(controlDir, fileName, what));
return false;
}
catch (err) {
if (err instanceof ControlPlaneCorruptError)
return true;
throw err;
}
}
export function rebuildStrictControlPlaneLedger(controlDir, ledger, now) {
const { file: fileName, what } = fileGovernanceDocOf(ledger);
const { coerce } = STRICT_LEDGER_SHAPES[ledger];
const empty = STRICT_LEDGER_SHAPES[ledger].empty();
ensureControlPlaneDir(controlDir);
const file = join(controlDir, fileName);
const journal = `${file}.journal`;
const lock = `${file}.lock`;
const token = acquireSidecarLock(lock, { onDeadline: "throw" });
try {
let healthy = false;
try {
coerce(readStrictSidecar(controlDir, fileName, what));
healthy = true;
}
catch (err) {
if (!(err instanceof ControlPlaneCorruptError))
throw err;
}
if (healthy) {
const e = new Error(`${what} reads cleanly — refusing to rebuild it. This call exists to recover a ledger whose corruption already refuses every read; resetting a healthy one would drop taint evidence that is still doing its job.`);
e.code = "memory.control_plane_not_corrupt";
throw e;
}
const at = now();
const quarantinedTo = [];
assertSidecarLockOwnership(lock, token, what, "strict");
for (const path of [file, journal]) {
if (!existsSync(path))
continue;
let dest = `${path}.corrupt-${at}`;
for (let n = 2;; n++) {
try {
copyFileSync(path, dest, fsConstants.COPYFILE_EXCL);
break;
}
catch (err) {
if (err.code !== "EEXIST")
throw err;
dest = `${path}.corrupt-${at}-${n}`;
}
}
quarantinedTo.push(dest);
}
assertSidecarLockOwnership(lock, token, what, "strict");
atomicWriteFileSync(file, `${JSON.stringify(empty, null, 2)}\n`);
rmSync(journal, { force: true });
return { ledger, quarantinedTo, at };
}
finally {
releaseSidecarLock(lock, token);
}
}
function coerceChallengedHistory(raw) {
if (!raw || typeof raw !== "object" || Array.isArray(raw))
return {};
const out = {};
for (const [k, v] of Object.entries(raw)) {
const row = v;
if (row &&
typeof row === "object" &&
typeof row.count === "number" &&
Number.isFinite(row.count) &&
row.count > 0 &&
typeof row.lastAt === "number" &&
(row.lastOp === "update" || row.lastOp === "tombstone")) {
out[k] = { count: Math.floor(row.count), lastAt: row.lastAt, lastOp: row.lastOp };
}
}
return out;
}
export function recordChallengedHistory(controlDir, rows, now) {
if (rows.length === 0)
return;
const at = now();
lockedJournaledUpdate(controlDir, CHALLENGED_HISTORY_FILE, (current) => {
const acc = coerceChallengedHistory(current);
for (const r of rows) {
const prior = acc[r.entryId];
acc[r.entryId] = { count: (prior?.count ?? 0) + 1, lastAt: at, lastOp: r.op };
}
return acc;
});
}
export function readChallengedHistory(controlDir) {
return coerceChallengedHistory(readSidecarJson(controlDir, CHALLENGED_HISTORY_FILE));
}
export const PROJECTION_DEBTS_FILE = "projection-debts.json";
function safeLedgerRel(rel) {
return typeof rel === "string" && rel.length > 0 && !rel.startsWith("/") && !rel.split(/[\\/]/).includes("..");
}
function malformedDebtRow(row) {
return (typeof row !== "object" ||
row === null ||
typeof row.entryId !== "string" ||
row.entryId.length === 0 ||
typeof row.rev !== "string" ||
row.rev.length === 0 ||
typeof row.at !== "number" ||
!Number.isFinite(row.at));
}
function coerceProjectionDebts(raw) {
if (raw === undefined)
return { version: 2, rows: [] };
const rec = raw;
if (typeof rec !== "object" || rec === null || (rec.version !== 1 && rec.version !== 2) || !Array.isArray(rec.rows)) {
throw new ControlPlaneCorruptError("memory projection-debt ledger has the wrong shape — refusing (fail-closed; an unreadable debt account must not read as 'no debts')");
}
const bad = () => {
throw new ControlPlaneCorruptError("memory projection-debt ledger: a row is malformed — refusing (fail-closed)");
};
const rows = rec.rows;
if (rec.version === 1) {
for (const r of rows) {
const row = r;
if (malformedDebtRow(row) || !safeLedgerRel(row.relPath))
bad();
}
return { version: 1, rows: rows };
}
for (const r of rows) {
const row = r;
if (malformedDebtRow(row) || typeof row.scope !== "string" || row.scope.length === 0 || !safeLedgerRel(row.rel))
bad();
}
const unresolved = rec.unresolved === undefined ? undefined : Array.isArray(rec.unresolved) ? rec.unresolved : bad();
for (const r of unresolved ?? []) {
const row = r;
if (malformedDebtRow(row) || !safeLedgerRel(row.relPath))
bad();
}
return { version: 2, rows: rows, ...(unresolved !== undefined ? { unresolved: unresolved } : {}) };
}
function convertProjectionDebts(read, controlDir) {
if (read.version === 2)
return { rec: read, converted: false };
const resolve = v1MemoryPathKeyResolver(controlDir);
const rows = [];
const unresolved = [];
for (const r of read.rows) {
const key = resolve(r.relPath);
if (key === undefined)
unresolved.push(r);
else
rows.push({ scope: key.scope, rel: key.rel, entryId: r.entryId, rev: r.rev, at: r.at });
}
return { rec: { version: 2, rows, ...(unresolved.length > 0 ? { unresolved } : {}) }, converted: true };
}
function debtSeatKey(scope, rel) {
return JSON.stringify([scope, rel]);
}
export function stageProjectionDebts(controlDir, rows, now) {
if (rows.length === 0)
return { refused: [] };
const at = now();
return lockedStrictUpdate(controlDir, PROJECTION_DEBTS_FILE, "memory projection-debt ledger", coerceProjectionDebts, (read) => {
const { rec } = convertProjectionDebts(read, controlDir);
const bySeat = new Map(rec.rows.map((r) => [debtSeatKey(r.scope, r.rel), r]));
const refused = [];
for (const r of rows) {
const seat = debtSeatKey(r.scope, r.rel);
const existing = bySeat.get(seat);
if (existing !== undefined && existing.entryId !== r.entryId && existing.entryId !== r.replaces) {
refused.push({ scope: r.scope, rel: r.rel, entryId: r.entryId });
continue;
}
bySeat.set(seat, { scope: r.scope, rel: r.rel, entryId: r.entryId, rev: r.rev, at });
}
return { next: { ...rec, version: 2, rows: [...bySeat.values()] }, result: { refused } };
});
}
export function settleProjectionDebts(controlDir, rows) {
if (rows.length === 0)
return;
const drop = new Set(rows.map((r) => JSON.stringify([r.entryId, r.scope, r.rel])));
lockedStrictUpdate(controlDir, PROJECTION_DEBTS_FILE, "memory projection-debt ledger", coerceProjectionDebts, (read) => {
const { rec, converted } = convertProjectionDebts(read, controlDir);
const kept = rec.rows.filter((r) => !drop.has(JSON.stringify([r.entryId, r.scope, r.rel])));
if (kept.length === rec.rows.length && !converted)
return { result: undefined };
return { next: { ...rec, version: 2, rows: kept }, result: undefined };
});
}
export function readProjectionDebts(controlDir) {
const read = coerceProjectionDebts(readStrictSidecar(controlDir, PROJECTION_DEBTS_FILE, "memory projection-debt ledger"));
if (read.version === 2)
return read.rows;
return lockedStrictUpdate(controlDir, PROJECTION_DEBTS_FILE, "memory projection-debt ledger", coerceProjectionDebts, (again) => {
const { rec, converted } = convertProjectionDebts(again, controlDir);
return converted ? { next: rec, result: rec.rows } : { result: rec.rows };
});
}
export function unresolvedProjectionDebts(controlDir) {
const read = coerceProjectionDebts(readStrictSidecar(controlDir, PROJECTION_DEBTS_FILE, "memory projection-debt ledger"));
if (read.version === 1)
return read.rows.map((r) => ({ relPath: r.relPath, entryId: r.entryId }));
return (read.unresolved ?? []).map((r) => ({ relPath: r.relPath, entryId: r.entryId }));
}
const PROJECTION_LEDGER_FILE = "projection-ledger.json";
function joinableSeatRel(rel) {
if (!safeLedgerRel(rel) || rel.includes("\\") || !rel.endsWith(".md"))
return false;
const segments = rel.split("/");
return segments.every((s) => s !== "" && s !== ".") && segments[segments.length - 1] !== MEMORY_INDEX_FILENAME;
}
function coerceProjectionLedger(raw) {
const rows = typeof raw === "object" && raw !== null && Reflect.get(raw, "version") === 1 ? Reflect.get(raw, "rows") : undefined;
if (!Array.isArray(rows))
throw new Error("the record has the wrong shape");
const text = (row, key) => {
const v = Reflect.get(row, key);
if (typeof v !== "string" || v === "" || (key === "rel" && !joinableSeatRel(v)))
throw new Error("a row is malformed");
return v;
};
return rows.map((row) => {
if (typeof row !== "object" || row === null)
throw new Error("a row is malformed");
return { scope: text(row, "scope"), rel: text(row, "rel"), id: text(row, "id"), rev: text(row, "rev") };
});
}
export function readProjectionLedger(controlDir) {
try {
const raw = readStrictSidecar(controlDir, PROJECTION_LEDGER_FILE, "memory projection ledger");
return { rows: raw === undefined ? [] : coerceProjectionLedger(raw) };
}
catch (err) {
return { unreadable: thrownText(err) };
}
}
export function updateProjectionLedger(controlDir, change) {
const identity = (r) => JSON.stringify([r.scope, r.rel, r.id, r.rev]);
const ordered = (rows) => [...rows].sort((a, b) => (debtSeatKey(a.scope, a.rel) < debtSeatKey(b.scope, b.rel) ? -1 : 1));
const unreadable = () => ({ version: 1, rows: [], rebuilt: true });
const coerce = (raw) => {
if ("unreadable" in readProjectionLedger(controlDir))
return unreadable();
if (raw === undefined)
return { version: 1, rows: [] };
try {
return { version: 1, rows: coerceProjectionLedger(raw) };
}
catch {
return unreadable();
}
};
return lockedStrictUpdate(controlDir, PROJECTION_LEDGER_FILE, "memory projection ledger", coerce, (cur) => {
const dropped = new Set((change.drop ?? []).map(identity));
const bySeat = new Map(cur.rows.filter((r) => !dropped.has(identity(r))).map((r) => [debtSeatKey(r.scope, r.rel), r]));
for (const r of change.upsert ?? [])
if (joinableSeatRel(r.rel) && r.scope !== "" && r.id !== "" && r.rev !== "")
bySeat.set(debtSeatKey(r.scope, r.rel), { scope: r.scope, rel: r.rel, id: r.id, rev: r.rev });
const next = ordered(bySeat.values());
if (cur.rebuilt ? next.length === 0 : JSON.stringify(next) === JSON.stringify(ordered(cur.rows)))
return { result: { rebuilt: false } };
return { next: { version: 1, rows: next }, result: { rebuilt: cur.rebuilt === true } };
}, unreadable);
}
export function writeAllSync(fd, data) {
const buf = Buffer.from(data, "utf8");
let written = 0;
while (written < buf.length) {
const n = writeSync(fd, buf, written, buf.length - written);
if (n <= 0)
throw new Error(`writeAllSync: write made no progress (${written}/${buf.length} bytes) — refusing to leave a truncated file`);
written += n;
}
}
export function atomicWriteFileSync(path, data) {
ensureDirExists(dirname(path));
const { fd, path: tmp } = openExclusiveTemp(join(dirname(path), ATOMIC_WRITE_TMP_PREFIX));
try {
writeAllSync(fd, data);
fsyncSync(fd);
}
finally {
closeSync(fd);
}
try {
renameSync(tmp, path);
}
catch (err) {
try {
unlinkSync(tmp);
}
catch {
}
throw err;
}
rememberStoreWrite(path);
}
export function writeIfChanged(path, data) {
let current;
try {
current = readFileSync(path, "utf8");
}
catch {
current = undefined;
}
if (current === data)
return;
atomicWriteFileSync(path, data);
}