@sema-agent/core
Version:
Stateless, task-oriented AI agent core
1,215 lines • 56.3 kB
JavaScript
import { createHash } from "node:crypto";
import { describeRejectedValue } from "../tool-search-setting.js";
import { existsSync, linkSync, lstatSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { appendChallengeEvents, claimStaging, fileGovernanceDocOf, isSameFile, lockedStrictUpdate, mintStagingName, readStrictSidecar, stagingNamePattern, v1MemoryPathKeyResolver, lineageContributionsOfSession, markSessionPolluted, readProjectionDebts, readSessionPollution, putControlObjectOnce, quarantineObjectNameOf, ControlPlaneCorruptError } from "./layout.js";
import { thrownText } from "../thrown-value.js";
import { deliverEngineNotice } from "../engine-notice.js";
import { processCensus, processFingerprint, uncheckableProcessText } from "../process-identity.js";
import { fileControlObjectDirOf, fileControlObjectFaultCode } from "./control-objects.js";
import { relativeInEveryFamily } from "../../tools/fs/safety.js";
function reqStr(v) {
return typeof v === "string" && v.length > 0;
}
function safeBasename(v) {
return typeof v === "string" && v.length > 0 && !v.includes("/") && !v.includes("\\") && v !== "." && v !== "..";
}
function safeRelPath(v) {
if (typeof v !== "string" || v.length === 0 || !relativeInEveryFamily(v))
return false;
return v.split(/[\/\\]/).every((seg) => seg.length > 0 && seg !== "." && seg !== "..");
}
const SETTLEMENT_EVENT_STATUSES = new Set(["clean", "external", "expired", "void", "unattestable"]);
function coerceSettlement(raw) {
if (raw === undefined)
return { version: 1, rows: [], events: [], effects: {} };
const rec = raw;
if (typeof rec !== "object" || rec === null || !Array.isArray(rec.rows) || !Array.isArray(rec.events) || typeof rec.effects !== "object" || rec.effects === null || Array.isArray(rec.effects)) {
throw new ControlPlaneCorruptError("memory delegation-settlement ledger has the wrong shape");
}
if (rec.version !== 1)
throw new ControlPlaneCorruptError(`memory delegation-settlement ledger has an unrecognized version (${String(rec.version)}) — refusing (fail-closed)`);
for (const r of rec.rows) {
const row = r;
if (typeof row !== "object" || row === null || !reqStr(row.settleId) || !reqStr(row.sessionId) || typeof row.launchedAt !== "number" || !Number.isFinite(row.launchedAt) || (row.lane !== "background" && row.lane !== "sync") || (row.status !== "pending" && row.status !== "unattestable") || (row.toolUseId !== undefined && !reqStr(row.toolUseId))) {
throw new ControlPlaneCorruptError("memory delegation-settlement ledger: a row is malformed (unknown status/lane, missing id, or a non-finite timestamp) — refusing (fail-closed; an unevaluable row must not fold as clean)");
}
}
for (const e of rec.events) {
const ev = e;
const kindOk = ev?.kind === "settle" || ev?.kind === "admin-resolve" || ev?.kind === "annotation";
const statusOk = ev?.status === undefined || SETTLEMENT_EVENT_STATUSES.has(ev.status);
if (typeof ev !== "object" || ev === null || !reqStr(ev.settleId) || !reqStr(ev.eventId) || typeof ev.at !== "number" || !Number.isFinite(ev.at) || !kindOk || !statusOk || (ev.kind === "settle" && ev.status === undefined) || (ev.kind === "admin-resolve" && (ev.status === undefined || !reqStr(ev.requestId)))) {
throw new ControlPlaneCorruptError("memory delegation-settlement ledger: an event is malformed (unknown kind/status, missing ids, an unattributed admin ruling, or a non-finite timestamp) — refusing (fail-closed)");
}
}
for (const [k, v] of Object.entries(rec.effects)) {
if (!reqStr(k) || !reqStr(v))
throw new ControlPlaneCorruptError("memory delegation-settlement ledger: an effects watermark entry is malformed — refusing (fail-closed)");
}
return rec;
}
export function syncSettleId(sessionId, toolCallId) {
return `sync:${encodeURIComponent(sessionId)}:${encodeURIComponent(toolCallId)}`;
}
export async function registerDelegationLaunch(docs, input) {
await docs.updateDoc("settlements", coerceSettlement, (rec) => {
if (rec.rows.some((r) => r.settleId === input.settleId))
return { result: undefined };
rec.rows.push({ settleId: input.settleId, sessionId: input.sessionId, launchedAt: input.now(), lane: "background", status: "pending", ...(input.toolUseId !== undefined ? { toolUseId: input.toolUseId } : {}) });
return { next: rec, result: undefined };
});
}
export async function recordSyncUnattestable(docs, input) {
const settleId = syncSettleId(input.sessionId, input.toolCallId);
await docs.updateDoc("settlements", coerceSettlement, (rec) => {
if (rec.rows.some((r) => r.settleId === settleId))
return { result: undefined };
rec.rows.push({ settleId, sessionId: input.sessionId, launchedAt: input.now(), lane: "sync", status: "unattestable" });
return { next: rec, result: undefined };
});
}
export async function settleDelegation(docs, input) {
const eventId = input.eventId ?? `settle:${input.settleId}:${input.status}`;
await docs.updateDoc("settlements", coerceSettlement, (rec) => {
if (rec.events.some((e) => e.eventId === eventId))
return { result: undefined };
rec.events.push({ settleId: input.settleId, eventId, at: input.now(), kind: "settle", status: input.status, ...(input.note !== undefined ? { note: input.note } : {}) });
return { next: rec, result: undefined };
});
}
export async function resolveSettlementRecord(docs, input) {
if (typeof input.requestId !== "string" || input.requestId.length === 0) {
const e = new Error("resolveSettlement requires a non-empty requestId (the audit attribution of who resolved) — refused, never defaulted.");
e.code = "memory.settlement_resolve_unattributed";
throw e;
}
if (input.to !== "clean" && input.to !== "external") {
const e = new Error(`resolveSettlement verdict must be "clean" or "external" (got ${describeRejectedValue(input.to)}) — refused loudly, never folded.`);
e.code = "memory.settlement_resolve_invalid";
throw e;
}
const eventId = `admin:${input.requestId}:${input.settleId}:${input.to}`;
await docs.updateDoc("settlements", coerceSettlement, (rec) => {
if (!rec.rows.some((r) => r.settleId === input.settleId)) {
const e = new Error(`This settlement resolution is refused: unknown settleId ${JSON.stringify(input.settleId)}`);
e.code = "memory.settlement_resolve_unknown";
throw e;
}
if (rec.events.some((e2) => e2.eventId === eventId))
return { result: undefined };
rec.events.push({ settleId: input.settleId, eventId, at: input.now(), kind: "admin-resolve", status: input.to, requestId: input.requestId });
return { next: rec, result: undefined };
});
}
function foldOne(row, events) {
let effective = row.status;
let everExternal = false;
let terminalEventId;
let adminRuled = false;
for (const e of events) {
const s = e.status;
if (s === undefined)
continue;
if (e.kind === "settle") {
if (s === "external") {
everExternal = true;
if (effective !== "external" && (effective !== "clean" || adminRuled)) {
effective = "external";
terminalEventId = e.eventId;
}
}
else if (s === "clean" || s === "void") {
if (effective === "pending") {
effective = s;
terminalEventId = e.eventId;
}
}
else if (s === "expired" || s === "unattestable") {
if (effective === "pending") {
effective = s;
terminalEventId = e.eventId;
}
}
}
else if (e.kind === "admin-resolve") {
adminRuled = true;
if (s === "external") {
everExternal = true;
effective = "external";
terminalEventId = e.eventId;
}
else if (s === "clean") {
effective = "clean";
terminalEventId = e.eventId;
}
}
}
return { row, effective, everExternal, ...(terminalEventId !== undefined ? { terminalEventId } : {}) };
}
export async function effectiveSettlements(docs) {
const rec = coerceSettlement(await docs.readDoc("settlements"));
const bySettle = new Map();
for (const e of rec.events) {
const arr = bySettle.get(e.settleId);
if (arr === undefined)
bySettle.set(e.settleId, [e]);
else
arr.push(e);
}
return rec.rows.map((row) => foldOne(row, bySettle.get(row.settleId) ?? []));
}
export async function sessionSettlements(docs, sessionId) {
return (await effectiveSettlements(docs)).filter((s) => s.row.sessionId === sessionId);
}
export function classifySessionSettlements(rows) {
let sawPending = false;
let exposedCause;
let reason;
for (const s of rows) {
if (s.effective === "external") {
exposedCause = "observed";
reason = "a delegated child of this session settled with an observed external-content attestation";
break;
}
if (s.effective === "unattestable" || s.effective === "expired") {
if (exposedCause === undefined) {
exposedCause = "static";
reason = s.effective === "unattestable" ? "a delegation of this session delivered without a provable attestation (permanently unprovable is not clean)" : "a delegation of this session never settled inside its evidence window (expired unprovable is not clean)";
}
continue;
}
if (s.effective === "pending")
sawPending = true;
}
if (exposedCause !== undefined)
return { state: "exposed", cause: exposedCause, ...(reason !== undefined ? { reason } : {}) };
if (sawPending)
return { state: "pending" };
return { state: "clean" };
}
export async function expireOverdueSettlements(docs, input) {
const overdue = (await effectiveSettlements(docs)).filter((s) => s.effective === "pending" && input.now() - s.row.launchedAt > input.timeoutMs);
for (const s of overdue)
await settleDelegation(docs, { settleId: s.row.settleId, status: "expired", now: input.now });
return overdue.map((s) => s.row.settleId);
}
export async function replayExternalSettlementEffects(docs, input) {
const applied = [];
const folded = (await effectiveSettlements(docs)).filter((s) => s.effective === "external" && s.terminalEventId !== undefined);
if (folded.length === 0)
return applied;
const rec = coerceSettlement(await docs.readDoc("settlements"));
for (const s of folded) {
if (rec.effects[s.row.settleId] === s.terminalEventId)
continue;
const sessionId = s.row.sessionId;
const outcome = await markSessionPolluted(docs, sessionId, "a delegated child of this session settled external after launch (delegation settlement account)", input.now, "observed");
if (outcome === "unpersisted")
continue;
try {
const swept = await lineageContributionsOfSession(docs, sessionId);
const contributions = input.carry ? swept.filter((c) => c.marked !== true) : swept;
await appendChallengeEvents(docs, contributions.map((c) => ({
eventId: `settlement:${s.row.settleId}:${s.terminalEventId}:${c.entryId}`,
entryId: c.entryId,
reason: "challenged: the contributing session's delegation settled external",
challengedRev: c.lastRev,
})), input.now);
}
catch {
continue;
}
deliverEngineNotice(undefined, {
code: "delegation.settlement_external",
message: `[sema] delegation settlement: a background delegation of session ${JSON.stringify(sessionId)} settled EXTERNAL after launch — the session is marked and its unmarked committed contributions are challenged`,
detail: { sessionId },
});
await docs.updateDoc("settlements", coerceSettlement, (r) => {
r.effects[s.row.settleId] = s.terminalEventId;
return { next: r, result: undefined };
});
applied.push({ settleId: s.row.settleId, sessionId });
}
return applied;
}
function malformedAccountRow(row) {
return (typeof row !== "object" ||
row === null ||
!reqStr(row.sessionId) ||
typeof row.openedAt !== "number" ||
!Number.isFinite(row.openedAt) ||
!Array.isArray(row.unattributed) ||
(row.closedAt !== undefined && (typeof row.closedAt !== "number" || !Number.isFinite(row.closedAt))) ||
(row.terminatedAt !== undefined && (typeof row.terminatedAt !== "number" || !Number.isFinite(row.terminatedAt))) ||
(row.leg !== undefined && !reqStr(row.leg)) ||
(row.holder !== undefined && malformedHolder(row.holder)) ||
(row.unadjudicated !== undefined && row.unadjudicated !== true));
}
function malformedHolder(h) {
if (typeof h !== "object" || h === null || Array.isArray(h))
return true;
const x = h;
const measure = (v) => v === null || (typeof v === "number" && Number.isFinite(v));
return (!reqStr(x.leg) ||
typeof x.pid !== "number" ||
!Number.isSafeInteger(x.pid) ||
x.pid <= 0 ||
!measure(x.startedAtMs) ||
!measure(x.startedSinceBootMs) ||
!reqStr(x.host) ||
(x.pidNs !== undefined && !reqStr(x.pidNs)));
}
function isUnattributedMember(x) {
return typeof x === "object" && x !== null && reqStr(x.scope) && safeRelPath(x.rel);
}
function coerceSessionAccounts(raw) {
if (raw === undefined)
return { version: 2, rows: [] };
const rec = raw;
if (typeof rec !== "object" || rec === null || !Array.isArray(rec.rows))
throw new ControlPlaneCorruptError("memory session-account ledger has the wrong shape");
if (rec.version !== 1 && rec.version !== 2)
throw new ControlPlaneCorruptError(`memory session-account ledger has an unrecognized version (${String(rec.version)}) — refusing (fail-closed)`);
const bad = () => {
throw new ControlPlaneCorruptError("memory session-account ledger: a row is malformed — refusing (fail-closed; an unevaluable row must not read as adjudicated)");
};
const rows = rec.rows;
for (const r of rows) {
const row = r;
if (malformedAccountRow(row))
bad();
const members = Array.isArray(row.unattributed) ? row.unattributed : bad();
if (rec.version === 1) {
if (members.some((x) => typeof x !== "string"))
bad();
}
else {
if (!members.every(isUnattributedMember))
bad();
if (row.unattributable !== undefined && (!Array.isArray(row.unattributable) || row.unattributable.some((x) => typeof x !== "string")))
bad();
if (row.writeScope !== undefined && !reqStr(row.writeScope))
bad();
}
}
return rec.version === 1 ? { version: 1, rows: rows } : { version: 2, rows: rows };
}
function convertSessionAccounts(read, controlDir) {
if (read.version === 2)
return { rec: read, converted: false };
const resolve = v1MemoryPathKeyResolver(controlDir);
const rows = read.rows.map((r) => {
const unattributed = [];
const unattributable = [];
for (const relPath of r.unattributed) {
const key = resolve(relPath);
if (key === undefined)
unattributable.push(relPath);
else
unattributed.push(key);
}
return {
sessionId: r.sessionId,
openedAt: r.openedAt,
unattributed,
...(unattributable.length > 0 ? { unattributable } : {}),
...(r.closedAt !== undefined ? { closedAt: r.closedAt } : {}),
...(r.unadjudicated !== undefined ? { unadjudicated: r.unadjudicated } : {}),
};
});
return { rec: { version: 2, rows }, converted: true };
}
export function convertV1SidecarKeys(controlDir) {
readProjectionDebts(controlDir);
const holds = readStrictSidecar(controlDir, HOLDS_FILE, HOLDS_WHAT);
if (holdsOnDiskAreV1(holds))
lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (again) => ({ next: again, result: undefined }));
else
coerceHolds(holds);
const accounts = fileGovernanceDocOf("session-accounts");
if (coerceSessionAccounts(readStrictSidecar(controlDir, accounts.file, accounts.what)).version !== 2) {
lockedStrictUpdate(controlDir, accounts.file, accounts.what, coerceSessionAccounts, (again) => {
const { rec, converted } = convertSessionAccounts(again, controlDir);
return converted ? { next: rec, result: undefined } : { result: undefined };
});
}
}
export function convertV1SessionAccountsAt(controlDir) {
const accounts = fileGovernanceDocOf("session-accounts");
lockedStrictUpdate(controlDir, accounts.file, accounts.what, (raw) => raw, (raw) => {
let read;
try {
read = coerceSessionAccounts(raw);
}
catch {
return { result: undefined };
}
const { rec, converted } = convertSessionAccounts(read, controlDir);
return converted ? { next: rec, result: undefined } : { result: undefined };
});
}
function sessionAccountsV2(read) {
if (read.version === 2)
return read;
throw new ControlPlaneCorruptError("memory session-account ledger is still in the v1 key form — the next mount of its control plane converts it (the File layout's upgrade step); refusing to read it until then (fail-closed)");
}
async function readSessionAccounts(docs) {
return sessionAccountsV2(coerceSessionAccounts(await docs.readDoc("session-accounts")));
}
export function legLive(row, census) {
if (row.writeScope === undefined && row.leg === undefined)
return row.closedAt === undefined ? { state: "unprovable", why: "no_holder" } : { state: "ended" };
if (row.terminatedAt !== undefined)
return { state: "ended" };
const holder = row.holder;
if (holder === undefined)
return { state: "unprovable", why: "no_holder" };
if (holder.leg !== row.leg)
return { state: "unprovable", why: "earlier_leg" };
const verdict = census.verdict(holder);
if (verdict.state === "gone")
return { state: "gone", holder };
return verdict.state === "running" ? { state: "running" } : { state: "unprovable", why: verdict.why };
}
export function legUnprovableText(why) {
switch (why) {
case "no_holder":
return "its account records no process for the leg (it was opened by an engine before this one)";
case "earlier_leg":
return "the process its account records opened an earlier leg (a later open did not record its own)";
case "contended":
return "its account kept changing while it was being checked";
default:
return uncheckableProcessText(why);
}
}
export async function foreignWriterCandidates(docs, input) {
const asked = (r) => !(input.self.leg !== undefined && r.leg === input.self.leg) &&
!(input.self.sessionId !== undefined && r.sessionId === input.self.sessionId) &&
(input.layer === undefined || r.writeScope === undefined || r.writeScope === input.layer);
const candidate = (r, open) => open || r.unadjudicated === true || r.closedAt === undefined || ((r.writeScope !== undefined || r.leg !== undefined) && r.terminatedAt !== undefined && r.terminatedAt > input.since);
for (let pass = 0;; pass++) {
const rows = (await readSessionAccounts(docs)).rows.filter(asked);
const census = processCensus();
const candidates = [];
let again = false;
for (const row of rows) {
const live = legLive(row, census);
if (live.state !== "gone") {
if (candidate(row, live.state !== "ended"))
candidates.push({ ...row, standing: live });
continue;
}
const at = input.now();
if ((await endProvenGoneLeg(docs, { sessionId: row.sessionId, holder: live.holder, at })) === "written") {
input.onEnded({ sessionId: row.sessionId, leg: live.holder.leg, ...(row.writeScope !== undefined ? { writeScope: row.writeScope } : {}) });
const over = { ...row, terminatedAt: at };
if (candidate(over, false))
candidates.push({ ...over, standing: { state: "ended" } });
continue;
}
if (pass === 0) {
again = true;
break;
}
const { writeScope: _changing, ...anyLayer } = row;
candidates.push({ ...anyLayer, standing: { state: "unprovable", why: "contended" } });
}
if (!again)
return candidates;
}
}
async function endProvenGoneLeg(docs, input) {
return docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
const rec = sessionAccountsV2(read);
const row = rec.rows.find((r) => r.sessionId === input.sessionId);
if (row === undefined)
return { result: "absent" };
if (row.terminatedAt !== undefined || row.leg !== input.holder.leg || !sameHolder(row.holder, input.holder))
return { result: "stale" };
row.terminatedAt = input.at;
return { next: rec, result: "written" };
});
}
function sameHolder(a, b) {
return (a !== undefined &&
a.leg === b.leg &&
a.pid === b.pid &&
a.startedAtMs === b.startedAtMs &&
a.startedSinceBootMs === b.startedSinceBootMs &&
a.host === b.host &&
a.pidNs === b.pidNs);
}
function holderOf(leg) {
const fp = processFingerprint();
return {
leg,
pid: fp.pid,
startedAtMs: fp.startedAtMs,
startedSinceBootMs: fp.startedSinceBootMs,
host: fp.host,
...(fp.pidNs !== undefined ? { pidNs: fp.pidNs } : {}),
};
}
export async function sessionAccountLeg(docs, sessionId) {
return (await readSessionAccounts(docs)).rows.find((r) => r.sessionId === sessionId)?.leg;
}
export async function sessionAccountWriteHome(docs, sessionId) {
const row = (await readSessionAccounts(docs)).rows.find((r) => r.sessionId === sessionId);
return row?.writeScope === undefined ? undefined : { writeScope: row.writeScope, openedAt: row.openedAt };
}
export function emptyUnattributedSet() {
return { has: () => false, empty: true };
}
function memberKey(scope, rel) {
return JSON.stringify([scope, rel]);
}
export async function openSessionAccount(docs, input) {
const holder = input.leg !== undefined ? holderOf(input.leg) : undefined;
await docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
const rec = sessionAccountsV2(read);
const row = rec.rows.find((r) => r.sessionId === input.sessionId);
if (row !== undefined && input.writeScope !== undefined) {
const priorOpen = row.closedAt === undefined || row.unadjudicated !== undefined;
if (!priorOpen)
row.writeScope = input.writeScope;
else if (row.writeScope !== input.writeScope)
delete row.writeScope;
}
if (row !== undefined) {
delete row.terminatedAt;
if (input.leg !== undefined)
row.leg = input.leg;
else
delete row.leg;
if (holder !== undefined)
row.holder = holder;
else
delete row.holder;
}
if (row === undefined) {
rec.rows.push({
sessionId: input.sessionId,
openedAt: input.now(),
...(input.writeScope !== undefined ? { writeScope: input.writeScope } : {}),
...(input.leg !== undefined ? { leg: input.leg } : {}),
...(holder !== undefined ? { holder } : {}),
unattributed: [...input.unattributed],
});
}
else if (row.closedAt !== undefined && row.unadjudicated === undefined) {
row.openedAt = input.now();
delete row.closedAt;
row.unattributed = [...input.unattributed];
}
else {
row.openedAt = input.now();
delete row.closedAt;
delete row.unadjudicated;
const merged = new Map(row.unattributed.map((m) => [memberKey(m.scope, m.rel), m]));
for (const m of input.unattributed)
merged.set(memberKey(m.scope, m.rel), { scope: m.scope, rel: m.rel });
row.unattributed = [...merged.values()];
}
return { next: rec, result: undefined };
});
}
export async function sessionUnattributedSet(docs, sessionId) {
const row = (await readSessionAccounts(docs)).rows.find((r) => r.sessionId === sessionId);
if (row === undefined)
return emptyUnattributedSet();
const all = (row.unattributable?.length ?? 0) > 0;
const keys = new Set(row.unattributed.map((m) => memberKey(m.scope, m.rel)));
return { has: (scope, rel) => all || keys.has(memberKey(scope, rel.split("\\").join("/"))), empty: !all && keys.size === 0 };
}
export async function closeSessionAccount(docs, input) {
return docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
const rec = sessionAccountsV2(read);
const row = rec.rows.find((r) => r.sessionId === input.sessionId);
if (row === undefined)
return { result: "absent" };
if (input.leg !== undefined && row.leg !== input.leg)
return { result: "stale" };
row.closedAt = input.now();
delete row.unadjudicated;
for (const r of rec.rows)
delete r.unadjudicated;
return { next: rec, result: "written" };
});
}
export async function terminateSessionAccount(docs, input) {
return docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
const rec = sessionAccountsV2(read);
const row = rec.rows.find((r) => r.sessionId === input.sessionId);
if (row === undefined)
return { result: "absent" };
if (input.leg !== undefined && row.leg !== input.leg)
return { result: "stale" };
row.terminatedAt = input.now();
return { next: rec, result: "written" };
});
}
export async function resolveSessionAccountRecord(docs, input) {
if (typeof input.requestId !== "string" || input.requestId.length === 0) {
const e = new Error("resolveSessionAccount requires a non-empty requestId (the audit attribution of who closed) — refused, never defaulted.");
e.code = "memory.session_account_resolve_unattributed";
throw e;
}
await docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
const rec = sessionAccountsV2(read);
const row = rec.rows.find((r) => r.sessionId === input.sessionId);
if (row === undefined) {
const e = new Error(`This session account resolution is refused: unknown sessionId ${JSON.stringify(input.sessionId)}`);
e.code = "memory.session_account_resolve_unknown";
throw e;
}
const held = row.leg ?? null;
if (input.leg !== held) {
const named = typeof input.leg === "string" || input.leg === null ? JSON.stringify(input.leg) : `a ${typeof input.leg}`;
const e = new Error(`resolveSessionAccount: session ${JSON.stringify(input.sessionId)} is held by leg ${JSON.stringify(held)}, not ${named} — ` +
`the row was re-opened or never held that leg; nothing was closed (read the refusal again for the leg it names now)`);
e.code = "memory.session_account_resolve_stale";
throw e;
}
row.closedAt = input.now();
row.unadjudicated = true;
row.terminatedAt = row.closedAt;
return { next: rec, result: undefined };
});
}
export const HOLDS_FILE = fileGovernanceDocOf("holds").file;
const HOLDS_WHAT = fileGovernanceDocOf("holds").what;
export const HOLD_DIR = fileControlObjectDirOf("hold");
const HOLD_STATUSES = new Set(["capturing", "held", "released", "disposed"]);
const HOLD_TERMINALS = new Set(["dirty", "expired", "conflict", "discarded", "capture_lost"]);
function coerceHolds(raw) {
if (raw === undefined)
return { version: 2, rows: [] };
const rec = raw;
if (typeof rec !== "object" || rec === null || !Array.isArray(rec.rows))
throw new ControlPlaneCorruptError("memory instruction-hold ledger has the wrong shape");
if (rec.version !== 1 && rec.version !== 2)
throw new ControlPlaneCorruptError(`memory instruction-hold ledger has an unrecognized version (${String(rec.version)}) — refusing (fail-closed)`);
const v1 = rec.version === 1;
const rows = [];
const raws = rec.rows;
for (const r of raws) {
const row = r;
if (typeof row !== "object" ||
row === null ||
!reqStr(row.holdId) ||
!reqStr(row.sessionId) ||
(row.op !== "add" && row.op !== "update") ||
!safeRelPath(row.slug) ||
!reqStr(row.scope) ||
!reqStr(row.captureName) ||
!reqStr(row.contentDigest) ||
typeof row.capturedAt !== "number" ||
!Number.isFinite(row.capturedAt) ||
!HOLD_STATUSES.has(row.status) ||
(row.disposition !== undefined && (typeof row.disposition !== "object" || row.disposition === null || !HOLD_TERMINALS.has(row.disposition.terminal) || (row.disposition.quarantineName !== undefined && !safeBasename(row.disposition.quarantineName)))) ||
(row.resolved !== undefined && row.resolved !== "release" && row.resolved !== "discard") ||
(row.resolvedAt !== undefined && (typeof row.resolvedAt !== "number" || !Number.isSafeInteger(row.resolvedAt) || row.resolvedAt < 0 || row.resolvedAt >= 2 ** 50 || row.resolved === undefined)) ||
(row.entryId !== undefined && typeof row.entryId !== "string") ||
(row.baseRev !== undefined && typeof row.baseRev !== "string") ||
(row.op === "update" && (!reqStr(row.entryId) || !reqStr(row.baseRev))) ||
(v1 ? !safeRelPath(row.relPath) : !safeRelPath(row.rel)) ||
!safeBasename(row.captureName)) {
throw new ControlPlaneCorruptError("memory instruction-hold ledger: a row is malformed — refusing (fail-closed; an unevaluable hold must not read as settled)");
}
const { settleIds: _settleIds, ...current } = row;
if (v1) {
const { relPath: _relPath, ...rest } = current;
rows.push({ ...rest, rel: `${row.slug}.md` });
}
else {
rows.push(current);
}
}
return { version: 2, rows };
}
function holdsOnDiskAreV1(raw) {
return typeof raw === "object" && raw !== null && raw.version === 1;
}
export async function readHolds(docs) {
const raw = await docs.readDoc("holds");
if (!holdsOnDiskAreV1(raw))
return coerceHolds(raw).rows;
return docs.updateDoc("holds", coerceHolds, (again) => ({ next: again, result: again.rows }));
}
function sha256(buf) {
return createHash("sha256").update(buf).digest("hex");
}
function dropStaging(claimedPath) {
try {
unlinkSync(claimedPath);
}
catch {
}
}
export function stagingPathBeside(absPath, stagingName) {
return join(dirname(absPath), stagingName);
}
async function heldBytesAt(objects, kind, name, digest) {
let bytes;
try {
bytes = await objects.getObject(kind, name);
}
catch {
return "other";
}
if (bytes === undefined)
return "absent";
return sha256(Buffer.from(bytes)) === digest ? "holds" : "other";
}
async function holdCustodyVerified(objects, captureName, bytes) {
try {
await putControlObjectOnce(objects, "hold", captureName, bytes);
}
catch {
return false;
}
return (await heldBytesAt(objects, "hold", captureName, sha256(bytes))) === "holds";
}
export async function retireStagingToObject(objects, claimedPath, kind, name, refusedAt) {
const unsettled = (why) => ({ settled: false, at: `${claimedPath} (${why})` });
let bytes;
try {
bytes = readFileSync(claimedPath);
}
catch {
return unsettled("the staged bytes could not be read into the control plane");
}
try {
if ((await putControlObjectOnce(objects, kind, name, bytes)) !== "created")
return unsettled(`a control-plane ${kind} object named ${name} already stands`);
const back = await objects.getObject(kind, name);
if (back === undefined || sha256(Buffer.from(back)) !== sha256(bytes))
return unsettled("the control-plane custody copy could not be read back");
}
catch {
return unsettled("the control-plane custody copy could not be written");
}
const refused = refusedAt();
if (refused !== undefined)
return unsettled(`a copy reached the control plane; this one was not removed: ${refused}`);
try {
unlinkSync(claimedPath);
}
catch {
return unsettled("a copy reached the control plane; this one could not be removed");
}
return { settled: true, at: `${kind} object ${name} in the memory control plane` };
}
export function noReplaceRestore(stagingPath, destPath) {
try {
linkSync(stagingPath, destPath);
}
catch (err) {
if (err.code !== "EEXIST") {
try {
writeFileSync(destPath, readFileSync(stagingPath), { flag: "wx" });
}
catch (err2) {
return err2.code === "EEXIST" ? "kept" : "stranded";
}
try {
unlinkSync(stagingPath);
}
catch {
}
return "restored";
}
return "kept";
}
try {
unlinkSync(stagingPath);
}
catch {
}
return "restored";
}
export async function openInstructionHold(store, input) {
const holdId = `hold-${input.now()}-${createHash("sha256").update(`${input.sessionId}\n${input.rel}\n${input.content}`).digest("hex").slice(0, 12)}`;
const buf = Buffer.from(input.content, "utf8");
const digest = sha256(buf);
const captureName = `${holdId}.md`;
let thirdWriterStrandedAt;
const refuse = async (rawReason, terminal) => {
const reason = thirdWriterStrandedAt === undefined ? rawReason : `${rawReason}; a concurrent writer's bytes are preserved at ${thirdWriterStrandedAt}`;
try {
await disposeHold(store, { holdId, terminal });
}
catch {
}
return { ok: false, holdId, reason };
};
try {
await store.updateDoc("holds", coerceHolds, (rec) => {
if (rec.rows.some((r) => r.holdId === holdId))
return { result: undefined };
rec.rows.push({
holdId,
sessionId: input.sessionId,
...(input.entryId !== undefined ? { entryId: input.entryId } : {}),
op: input.op,
...(input.baseRev !== undefined ? { baseRev: input.baseRev } : {}),
rel: input.rel,
slug: input.slug,
scope: input.scope,
captureName,
contentDigest: digest,
capturedAt: input.now(),
status: "capturing",
});
return { next: rec, result: undefined };
});
}
catch (err) {
return { ok: false, reason: `hold ledger refused: ${thrownText(err)}` };
}
if (!(await holdCustodyVerified(store, captureName, buf))) {
return refuse("hold capture verification failed (the custody copy could not be written, made durable, or hashed back to the captured digest)", "capture_lost");
}
const refused = input.actRefused(input.absPath, "holding an instruction-form file");
if (refused !== undefined)
return refuse(`hold removal refused: ${refused}`, "discarded");
const stagingName = mintStagingName(holdId, input.now);
const stagingPath = stagingPathBeside(input.absPath, stagingName);
try {
renameSync(input.absPath, stagingPath);
}
catch (err) {
const code = err.code;
if (code === "ENOENT") {
}
else {
return refuse(`hold removal failed (${code ?? "rename error"}): the plane file was not moved`, "discarded");
}
}
const claimedPath = existsSync(stagingPath) ? claimStaging(stagingPath) : stagingPath;
if (existsSync(claimedPath)) {
const moved = readFileSync(claimedPath);
if (sha256(moved) === digest) {
dropStaging(claimedPath);
}
else {
const restore = noReplaceRestore(claimedPath, input.absPath);
if (restore !== "restored") {
const retired = await retireStagingToObject(store, claimedPath, "hold", stagingName, () => input.actRefused(claimedPath, "removing a hold's staged copy"));
if (restore === "stranded" || !retired.settled)
thirdWriterStrandedAt = retired.at;
}
}
}
try {
await store.updateDoc("holds", coerceHolds, (rec) => {
const row = rec.rows.find((r) => r.holdId === holdId);
if (row === undefined || row.status !== "capturing")
return { result: undefined };
row.status = "held";
return { next: rec, result: undefined };
});
}
catch (err) {
return refuse(`hold ledger flip refused: ${thrownText(err)}`, "discarded");
}
return { ok: true, holdId, ...(thirdWriterStrandedAt !== undefined ? { thirdWriterStrandedAt } : {}) };
}
export async function reconcileHolds(store, input) {
const discloseStranded = (holdId, scope, rel, at) => {
input.onStranded(scope, `instruction hold ${holdId}: a concurrent writer's bytes for ${JSON.stringify(rel)} could not be restored onto the plane — they are preserved at ${at} for host recovery`);
};
const finishRemoval = async (row, plane) => {
const refused = input.actRefused(plane, "removing a held file from the plane");
if (refused !== undefined)
throw new Error(refused);
const stagingName = mintStagingName(row.holdId, input.now);
renameSync(plane, stagingPathBeside(plane, stagingName));
const staging = claimStaging(stagingPathBeside(plane, stagingName));
if (sha256(readFileSync(staging)) === row.contentDigest) {
dropStaging(staging);
return;
}
const restore = noReplaceRestore(staging, plane);
if (restore === "restored")
return;
const retired = await retireStagingToObject(store, staging, "hold", stagingName, () => input.actRefused(staging, "removing a hold's staged copy"));
if (restore === "stranded" || !retired.settled)
discloseStranded(row.holdId, row.scope, row.rel, retired.at);
};
const seatListing = new Map();
const listSeat = (seatDir) => {
const cached = seatListing.get(seatDir);
if (cached !== undefined)
return cached;
let names;
try {
names = readdirSync(seatDir);
}
catch {
names = [];
}
seatListing.set(seatDir, names);
return names;
};
const sweepStagingGenerations = async (row, plane, custody) => {
const seatDir = dirname(plane);
const pattern = stagingNamePattern(row.holdId);
let seat;
try {
seat = lstatSync(plane);
}
catch {
seat = undefined;
}
for (const name of listSeat(seatDir)) {
if (!pattern.test(name))
continue;
if (input.actRefused(join(seatDir, name), "recovering a hold's staged copy") !== undefined)
continue;
const staged = claimStaging(join(seatDir, name));
let bytes;
try {
if (!lstatSync(staged).isFile())
continue;
bytes = readFileSync(staged);
}
catch {
continue;
}
if (sha256(bytes) === row.contentDigest) {
if (custody === "holds") {
dropStaging(staged);
continue;
}
if (custody === "absent" && (await holdCustodyVerified(store, row.captureName, bytes))) {
if (input.actRefused(staged, "recovering a hold's staged copy") === undefined)
dropStaging(staged);
continue;
}
}
const onSeat = seat !== undefined && isSameFile(staged, seat);
const retired = await retireStagingToObject(store, staged, "hold", name, () => input.actRefused(staged, "removing a hold's staged copy"));
if (!(onSeat && retired.settled && isSameFile(plane, seat)))
discloseStranded(row.holdId, row.scope, row.rel, retired.at);
}
};
const ledger = await readHolds(store);
const rows = ledger.filter((r) => r.status === "capturing");
for (const row of rows) {
let custodyState = await heldBytesAt(store, "hold", row.captureName, row.contentDigest);
try {
await sweepStagingGenerations(row, join(input.homeOf(row.scope), row.rel), custodyState);
}
catch {
}
if (custodyState === "absent")
custodyState = await heldBytesAt(store, "hold", row.captureName, row.contentDigest);
let terminalLost = false;
if (custodyState === "other") {
terminalLost = true;
}
else if (custodyState === "holds") {
const plane = join(input.homeOf(row.scope), row.rel);
if (existsSync(plane)) {
try {
await finishRemoval(row, plane);
}
catch {
}
}
}
else {
const plane = join(input.homeOf(row.scope), row.rel);
if (existsSync(plane)) {
const bytes = readFileSync(plane);
if (sha256(bytes) === row.contentDigest) {
try {
if (!(await holdCustodyVerified(store, row.captureName, bytes)))
throw new Error("the custody copy could not be written or read back");
await finishRemoval(row, plane);
}
catch {
terminalLost = true;
}
}
else {
terminalLost = true;
}
}
else {
terminalLost = true;
}
}
await store.updateDoc("holds", coerceHolds, (rec) => {
const r = rec.rows.find((x) => x.holdId === row.holdId);
if (r === undefined || r.status !== "capturing")
return { result: undefined };
if (terminalLost) {
r.status = "disposed";
r.disposition = { terminal: "capture_lost" };
}
else {
r.status = "held";
}
return { next: rec, result: undefined };
});
}
let custodyNames;
try {
custodyNames = new Set(await store.listObjects("hold"));
}
catch {
custodyNames = new Set();
}
for (const row of ledger) {
const quarantineName = row.disposition?.quarantineName;
if (row.status !== "disposed" || quarantineName === undefined || !custodyNames.has(row.captureName))
continue;
try {
const moved = await moveCustodyToSeat(store, row, quarantineName);
if (moved.at === "custody") {
input.onStranded(row.scope, `instruction hold ${row.holdId} (disposed, ${row.disposition.terminal}): its custody bytes could not be moved to the quarantine seat ${quarantineName} (${moved.code}) — they stay at the custody seat (hold object ${row.captureName} in the memory control plane) for host recovery, and the move is retried at every harvest`);
}
}
catch (err) {
input.onStranded(row.scope, `instruction hold ${row.holdId} (disposed, ${row.disposition.terminal}): ${thrownText(err)}`);
}
}
await adoptOrphanedQuarantineBytes(store, ledger);
}
async function adoptOrphanedQuarantineBytes(store, snapshot) {
let listing;
try {
listing = (await store.listObjects("quarantine")).filter((n) => n.includes("-hold-") && safeBasename(n));
}
catch {
return;
}
const seats = new Set();
for (const r of snapshot)
if (r.disposition?.quarantineName !== undefined)
seats.add(r.disposition.quarantineName);
if (listing.every((n) => seats.has(n)))
return;
const standsAt = async (kind, name) => {
try {
return (await store.getObject(kind, name)) !== undefined;
}
catch {
return true;
}
};
const digests = new Map();
for (const n of listing) {
if (seats.has(n))
continue;
try {
const bytes = await store.getObject("quarantine", n);
digests.set(n, bytes === undefined ? undefined : sha256(Buffer.from(bytes)));
}
catch {
digests.set(n, undefined);
}
}
const custodyStands = new Map();
const seatStands = new Map();
for (const r of snapshot) {
custodyStands.set(r.holdId, await standsAt("hold", r.captureName));
const seat = r.disposition?.quarantineName;
if (seat !== undefined && !seatStands.has(seat))
seatStands.set(seat, await standsAt("quarantine", seat));
}
const moves = await store.updateDoc("holds", coerceHolds, (rec) => {
const claimed = new Set();
for (const r of rec.rows)
if (r.disposition?.quarantineName !== undefined)
claimed.add(r.disposition.quarantineName);
const digestOf = (name) => digests.get(name);
const wants = (r) => {
const custody = custodyStands.get(r.holdId);
if (custody !== false)
return false;
if (r.status === "held")
return true;
if (r.status !== "disposed")
return false;
const seat = r.disposition?.quarantineName;
return seat === undefined || seatStands.get(seat) === false;
};
const endsWithCapture = (name, r) => name.endsWith(`-hold-${r.captureName}`);
const reservedForOther = (name) => rec.rows.some((r) => endsWithCapture(name, r));
const wanting = rec.rows.filter(wants);
const found = new Map();
for (const r of wanting) {
const f = listing.find((n) => !claimed.has(n) && endsWithCapture(n, r) && digestOf(n) === r.contentDigest);
if (f !== undefined) {
found.set(r, f);
claimed.add(f);
}
}
for (const r of wanting) {
if (found.has(r))
continue;
const f = listing.find((n) => !claimed.has(n) && !reservedForOther(n) && digestOf(n) === r.contentDigest);
if (f !== undefined) {
found.set(r, f);
claimed.add(f);
}
}
let changed = false;
const back = [];
for (const [r, f] of found) {
if (r.status === "disposed") {
r.disposition = { ...r.disposition, quarantineName: f };
changed = true;
continue;
}
back.push({ file: f, captureName: r.captureName });
}
return changed ? { next: rec, result: back } : { result: back };
});
for (const m of moves) {
try {
await store.moveObject({ kind: "quarantine", name: m.file }, { kind: "hold", name: m.captureName });
}
catch {
}
}
}
export function holdQuarantineNameOf(row) {
return quarantineObjectNameOf({ sha256: row.contentDigest }, `hold-${row.captureName}`);
}
function foreignSeatRefusal(holdId, seatName) {
return new ControlPlaneCorruptError(`memory instruction hold ${holdId}: the quarantine seat ${seatName} is occupied by something that is not the hold's captured bytes — refusing to replace or adopt it (fail-closed; inspect or remove it, and the next harvest converges)`);
}
async function moveCustodyToSeat(objects, row, seatName) {
if ((await heldBytesAt(objects, "quarantine", seatName, row.contentDigest)) === "other")
throw foreignSeatRefusal(row.holdId, seatName);
try {
await objects.moveObject({ kind: "hold", name: row.captureName }, { kind: "quarantine", name: seatName });
return { at: "seat" };
}
catch (err) {
const seat = await heldBytesAt(objects, "quarantine", seatName, row.contentDigest);
if (seat === "other")
throw foreignSeatRefusal(row.holdId, seatName);
const custody = await heldBytesAt(objects, "hold", row.captureName, row.contentDigest);
if (custody === "absent")
return seat === "holds" ? { at: "seat" } : { at: "none" };
if (seat === "holds" && custody === "other")
return { at: "seat" };
return { at: "custody", code: fileControlObjectFaultCode(err) ?? "move refused" };
}
}
export async function disposeHold(store, input) {
const row = (await readHolds(store)).find((r) => r.holdId === input.holdId);
if (row === undefined || row.status === "disposed" || row.status === "released")
return { ok: false };
const quarantineName = holdQuarantineNameOf(row);
if (!safeBasename(quarantineName)) {
throw new ControlPlaneCorruptError(`memory instruction hold ${row.holdId}: its digest and capture name do not make a safe quarantine file name — refusing (fail-closed)`);
}
const custodyHere = (await heldBytesAt(store, "hold", row.captureName, row.contentDigest)) !== "absent";
const seatState = await heldBytesAt(store, "quarantine", quarantineName, row.contentDigest);
const verdict = await store.updateDoc("holds", coerceHolds, (rec) => {
const r = rec.rows.find((x) => x.holdId === input.holdId);
if (r === undefined || r.status === "disposed" || r.status === "released")
return { result: undefined };
const named = seatState === "holds" || (custodyHere && seatState === "absent");
r.status = "disposed";
r.disposition = { terminal: input.terminal, ...(named ? { quarantineName } : {}) };
return { next: rec, result: { named, refused: custodyHere && seatState === "other" } };
});
if (verdict === undefined)
return { ok: false };
if (verdict.refused)
throw foreignSeatRefusal(row.holdId, quarantineName);
if (!verdict.named)
return { ok: true };
const moved = await moveCustodyToSeat(store, row, quarantineName);
return { ok: true, ...(moved.at === "seat" ? { quarantineName } : {}) };
}
export async function markHoldReleased(store, input) {
const captureName = await store.updateDoc("holds", coerceHolds, (rec) => {
const r = rec.rows.find((x) => x.holdId === input.holdId);
if (r === undefined || (r.status !== "held" && !(r.status === "disposed" && r.disposition?.terminal === "expired")))
return { result: undefined };
r.status = "released";
delete r.resolved;
delete r.resolvedAt;
return { next: rec, result: r.captureName };
});
if (captureName === undefined)
return;
try {
await store.deleteObject("hold", captureName);
}
catch {
}
}
export async function resolveHoldRecord(docs, input) {
if (typeof input.requestId !== "string" || input.requestId.length === 0) {
const e = new Error("resolveHold requires a non-empty requestId (the audit attribution of who resolved) — refused, never defaulted.");
e.code = "memory.hold_resolve_unattributed";
throw e;
}
if (input.action !== "release" && input.action !== "discard") {
const e = new Error(`resolveHold action must be "release" or "discard" (got ${describeRejectedValue(input.action)}) — refused loudly, never folded.`);
e.code = "memory.hold_resolve_invalid";
throw e;
}
await docs.updateDoc("holds", coerceHolds, (rec) => {
const r = rec.rows.find((x) => x.holdId === input.holdId);
if (r === undefined) {
const e = new Error(`This hold resolution is refused: unknown holdId ${JSON.stringify(input.holdId)}`);
e.code = "memory.hold_resolve_unknown";
throw e;
}
if (r.status !== "held" && !(r.status === "disposed" && r.disposition?.terminal === "expired" && input.action === "release")) {
const e = new Error(`This hold resolution is refused: hold ${JSON.stringify(input.holdId)} is ${r.status}${r.disposition !== undefined ? ` (${r.disposition.terminal})` : ""} — only a held row, or an expired disposition (release), can be resolved`);
e.code = "memory.hold_resolve_invalid_state";
throw e;
}
r.resolved = input.action;
const nextGeneration = Math.max(input.now(), 0, (r.resolvedAt ?? 0) + 1);
if (!Number.isSafeInteger(nextGeneration) || nextGeneration < 0 || nextGeneration >= 2 ** 50) {
const e = new Error(`This hold resolution is refused: hold ${JSON.stringify(input.holdId)} cannot mint a fresh verdict generation (${String(nextGeneration)} — an exhausted window, a deranged clock, or a corrupt ledger row) — refused, never written.`);
e.code = "memory.hold_resolve_invalid_state";
throw e;
}
r.resolvedAt = nextGeneration;
return { next: rec, result: undefined };
});
}
export async function clearHoldResolution(docs, input) {
await docs.updateDoc("holds", coerceHolds, (rec) => {
const r = rec.rows.find((x) => x.holdId === input.holdId);
if (r === undefined || r.resolved === undefined || r.resolvedAt !== input.ifResolvedAt)
return { result: undefined };
delete r.resolved;
delete r.resolvedAt;
return { next: rec, result: undefined };
});
}
export async function readHoldCustody(objects, row) {
const seats = [["hold", row.captureName], ...(row.disposition?.quarantineName !== undefined ? [["quarantine", row.disposition.quarantineName]] : [])];
for (const [kind, name] of seats) {
try {
const bytes = await objects.getObject(kind, name);
if (bytes !== undefined && sha256(Buffer.from(bytes)) === row.contentDigest)
return Buffer.from(bytes).toString("utf8");
}
catch {
}
}
return undefined;
}
export async function sessionBlocksCleanRelease(docs, sessionId) {
if ((await readSessionPollution(docs, sessionId)) !== undefined)
return true;
return (await sessionSettlements(docs, sessionId)).some((s) => s.effective !== "clean" && s.effective !== "void");
}