@sema-agent/core
Version:
Stateless, task-oriented AI agent core
235 lines (234 loc) • 13.6 kB
JavaScript
import { existsSync } from "node:fs";
import { join } from "node:path";
import { MemoryEngine } from "./engine.js";
import { derivePersonalControlDir, derivePersonalMemoryDir, judgeMemoryStoreSeat, memoryPlaneStore, memoryScopePlaneOf, mergeErasureAttestations, refuseAbsentPlaneStores, refuseMemoryStoreInput } from "./dual-root.js";
import { acquireStoreTxnLock, assertRootNotSensitive, assertStoreTxnLockOwnership, controlPlanePinOf, ControlPlaneCorruptError, directoryPinOf, refuseAbsentStore, renewStoreTxnLock, resolveMemoryEngineRoot, storeAbsence, storeHoldsRecord, storeOpenArtifactFault, TXN_LOCK_STALE_MS } from "./layout.js";
import { captureErasureInput, ERASURE_REFUSED, erasureRequestInvalid, erasureSelectHash } from "./file-backend.js";
import { canonicalExpectedScopes } from "./export-bundle.js";
import { isEngineCodeShape, thrownLabel, thrownText } from "../thrown-value.js";
import { chooseSessionWriteHome } from "./session-write-home.js";
const FACE = "createMemoryDeployment";
export const MEMORY_DEPLOYMENT_ERASURE_LOCK_DIR = ".memory-erasure-judge";
const STATUS_KEYS_DECIDED = true;
void STATUS_KEYS_DECIDED;
export function foldSessionMemoryStatuses(statuses) {
const sum = (key) => {
let n = 0;
for (const s of statuses) {
const v = s[key];
if (v === undefined)
return undefined;
n += v;
}
return n;
};
const committedCount = sum("committedCount");
const foldedCount = sum("foldedCount");
const captures = statuses.flatMap((s) => (s.lastCaptureAt !== undefined ? [s.lastCaptureAt] : []));
const lastCaptureAt = committedCount !== undefined && captures.length > 0 ? Math.max(...captures) : undefined;
const capture = statuses.some((s) => s.captureOptedOut === true)
? { captureOptedOut: true, optOutSource: "record" }
: statuses.every((s) => s.captureOptedOut === false)
? { captureOptedOut: false }
: { optOutSource: "fault" };
return {
...capture,
...(committedCount !== undefined ? { committedCount } : {}),
...(foldedCount !== undefined ? { foldedCount } : {}),
...(lastCaptureAt !== undefined ? { lastCaptureAt } : {}),
};
}
export function createMemoryDeployment(input) {
judgeMemoryStoreSeat(FACE, input);
const { backend, scopeContract, onIncident, memoryCaptureRecordStore } = input;
if (controlPlanePinOf(backend) === undefined) {
refuseMemoryStoreInput(FACE, "the backend publishes no control plane (controlPlaneRoot) — a session's memory facts then live in per-project control planes no deployment-wide reading can name", backend);
}
const engineRoot = resolveMemoryEngineRoot(input.memoryEngineDir);
assertRootNotSensitive("engine_root", engineRoot);
const pinned = directoryPinOf(backend) !== undefined;
const seatOf = (plane, store) => {
const controlDir = controlPlanePinOf(store);
const engine = new MemoryEngine({
backend: store,
memoryDir: directoryPinOf(store) ?? engineRoot,
...(onIncident !== undefined ? { onIncident } : {}),
...(memoryCaptureRecordStore !== undefined && controlDir !== undefined ? { captureRecordStore: memoryCaptureRecordStore({ controlDir }) } : {}),
});
return Object.freeze({ plane, backend: store, engine });
};
const project = seatOf("project", backend);
let personal;
const personalStore = () => {
try {
const fault = storeOpenArtifactFault(derivePersonalMemoryDir(engineRoot), derivePersonalControlDir(engineRoot));
if (fault !== undefined)
throw fault;
refuseAbsentStore(derivePersonalMemoryDir(engineRoot), derivePersonalControlDir(engineRoot));
if (personal !== undefined)
return personal;
personal = seatOf("personal", memoryPlaneStore("personal", backend, engineRoot, onIncident));
}
catch (err) {
throw personalOpenFault(err, derivePersonalMemoryDir(engineRoot));
}
return personal;
};
const hasPersonalStore = () => pinned && (storeHoldsRecord(derivePersonalMemoryDir(engineRoot), derivePersonalControlDir(engineRoot)) || storeAbsence(derivePersonalControlDir(engineRoot)) !== undefined);
const stores = () => (hasPersonalStore() ? [project, personalStore()] : [project]);
const planeOf = (scope) => memoryScopePlaneOf(FACE, scope, scopeContract);
const planesOf = (req, personalInSet) => {
const seat = (scope) => (pinned ? planeOf(scope) : "project");
const select = req.select;
if ("scope" in select)
return [seat(select.scope)];
if (req.expectedScopes !== undefined) {
const seats = new Set(canonicalExpectedScopes(req.expectedScopes).map(seat));
if (seats.size > 1) {
throw coded(`${ERASURE_REFUSED} the request's expectedScopes name scopes kept in two of this deployment's memory stores, and one request is judged in one store's lock — send one request per store (nothing was deleted, nothing was recorded; no scope is reported)`, "config.memory_erasure_scope");
}
return [[...seats][0] ?? "project"];
}
return personalInSet ? ["project", "personal"] : ["project"];
};
const reachOf = (req, personalInSet) => planesOf(req, personalInSet).map((plane) => (plane === "personal" ? personalStore() : project));
return {
stores: () => stores(),
async eraseMemoryEntries(raw) {
const req = captureErasureInput(raw);
const bad = erasureRequestInvalid(req);
if (bad !== undefined)
throw coded(`${ERASURE_REFUSED} ${bad}`, "config.memory_erasure_request");
refuseAbsentPlaneStores(backend, engineRoot, planesOf(req, hasPersonalStore()).includes("personal") || !existsSync(engineRoot));
const lockDir = join(engineRoot, MEMORY_DEPLOYMENT_ERASURE_LOCK_DIR);
const lock = await acquireStoreTxnLock(lockDir, { now: Date.now });
let lost;
const heartbeat = setInterval(() => {
try {
renewStoreTxnLock(lockDir, lock.token);
}
catch (err) {
lost ??= err;
}
}, TXN_LOCK_STALE_MS / 3);
heartbeat.unref?.();
const fence = (when) => {
if (lost === undefined) {
try {
assertStoreTxnLockOwnership(lockDir, lock.token);
return;
}
catch (err) {
lost = err;
}
}
throw new ControlPlaneCorruptError(`This erasure request lost the deployment's erasure lock ${when} (the holder stalled past its stale line and another erasure took it) — the stores this request executed keep their anchors; a replay of the same requestId converges them`, { cause: lost, facet: "lock-ownership" });
};
try {
const personalInSet = hasPersonalStore();
const reach = reachOf(req, personalInSet);
const all = personalInSet && storeAbsence(derivePersonalControlDir(engineRoot)) === undefined ? [project, personalStore()] : [project];
const grant = req.expectedScopes !== undefined ? canonicalExpectedScopes(req.expectedScopes) : undefined;
const selectHash = erasureSelectHash(req.select);
for (const store of new Set([...all, ...reach])) {
const anchor = await anchorOf(store.backend, req.requestId);
if (anchor === undefined)
continue;
const recorded = anchor.expectedScopes;
const sameGrant = recorded === undefined || grant === undefined ? recorded === grant : recorded.length === grant.length && recorded.every((s, i) => grant[i] === s);
if (!sameGrant) {
throw coded(`${ERASURE_REFUSED} requestId ${JSON.stringify(req.requestId)} was first executed under a different expectedScopes set — a requestId names one request under one authorization; nothing is reported`, "config.memory_erasure_scope");
}
if (anchor.selectHash === selectHash && reach.includes(store))
continue;
throw coded(`${ERASURE_REFUSED} requestId ${JSON.stringify(req.requestId)} was first executed ${anchor.selectHash === selectHash ? "in another of this deployment's memory stores" : "with a DIFFERENT selector"} — a requestId names ONE request in the deployment; use a new requestId for a new selector (nothing was deleted, nothing was recorded)`, "memory.erasure_selector_mismatch");
}
let receipt;
const executed = [];
for (const store of reach) {
fence(receipt === undefined ? "before any store executed" : "between two stores' executions");
let part;
try {
part = await store.engine.eraseMemoryEntries(req);
}
catch (err) {
throw receipt === undefined ? err : refusedAfterExecuting(err, executed, store.plane, receipt.erased.length);
}
executed.push(store.plane);
receipt = receipt === undefined ? part : mergeErasureAttestations(receipt, part);
}
fence("while a store executed");
if (receipt === undefined)
throw new Error("eraseMemoryEntries: no store reached (unreachable — a request reaches at least the project store)");
return receipt;
}
finally {
clearInterval(heartbeat);
lock.release();
}
},
async sessionMemoryStatus(sessionId, given) {
let incarnation;
let onSeparated;
try {
incarnation = given?.incarnation;
onSeparated = given?.onSeparated?.bind(given);
}
catch {
}
const identity = given === undefined ? undefined : { ...(incarnation !== undefined ? { incarnation } : {}), ...(onSeparated !== undefined ? { onSeparated } : {}) };
const rows = [{ plane: "project", ...(await project.engine.sessionMemoryStatusRead(sessionId, identity)) }];
const inSet = hasPersonalStore();
if (inSet || (pinned && memoryCaptureRecordStore !== undefined)) {
let seat;
try {
seat = personalStore();
}
catch {
seat = undefined;
}
const read = seat !== undefined ? await seat.engine.sessionMemoryStatusRead(sessionId, identity) : { status: { optOutSource: "fault" }, writeHome: { state: "unreadable" } };
if (inSet || read.status.optOutSource !== undefined)
rows.push({ plane: "personal", ...read });
}
const planes = rows.map(({ plane, status }) => ({ plane, status }));
const writeHome = chooseSessionWriteHome(rows.map((r) => r.writeHome));
return { ...foldSessionMemoryStatuses(planes.map((p) => p.status)), ...(writeHome !== undefined ? { writeHome } : {}), planes };
},
};
}
function refusedAfterExecuting(err, executed, refusing, erased) {
if (!(err instanceof Error))
return err;
const done = executed.map((plane) => `the ${plane} store`).join(" and ");
const sentence = `This erasure request had already executed in ${done} (${erased} ${erased === 1 ? "entry" : "entries"} erased there; each keeps its anchor and a replay of the same requestId converges every store) when the ${refusing} store refused it — what follows describes the refusing store alone: ${err.message}`;
try {
const copy = Object.create(Object.getPrototypeOf(err), Object.getOwnPropertyDescriptors(err));
Object.defineProperty(copy, "message", { value: sentence, writable: true, configurable: true, enumerable: false });
return copy;
}
catch {
return err;
}
}
async function anchorOf(store, requestId) {
const face = store;
if (typeof face.erasureAnchorOf === "function")
return face.erasureAnchorOf.call(store, requestId);
if (typeof face.eraseWithEvidence !== "function")
return undefined;
throw coded(`${ERASURE_REFUSED} another store of this deployment has an erasure-evidence face but no anchor read (erasureAnchorOf), so whether it already executed this requestId cannot be judged — nothing was deleted`, "memory.erasure_evidence_unavailable");
}
function personalOpenFault(err, mount) {
if (err instanceof ControlPlaneCorruptError)
return err;
const code = err?.code;
if (typeof code === "string" && isEngineCodeShape(code))
return err;
return new ControlPlaneCorruptError(`the personal plane's memory store at ${mount} could not be opened (${typeof code === "string" ? code : thrownLabel(err)}): ${thrownText(err)}`, { cause: err });
}
function coded(message, code) {
const e = new Error(message);
e.code = code;
return e;
}