@sema-agent/core
Version:
Stateless, task-oriented AI agent core
187 lines (186 loc) • 9.01 kB
JavaScript
import { createHash } from "node:crypto";
import { lstatSync } from "node:fs";
import { join } from "node:path";
import { isDeepStrictEqual } from "node:util";
import { MEMORY_CONTROL_OBJECT_KINDS, MEMORY_GOVERNANCE_DOC_NAMES } from "./types.js";
import { ControlPlaneCorruptError, fileGovernanceDocOf, lockedStrictRemove, lockedStrictUpdate, readStrictSidecar } from "./layout.js";
import { deleteFileControlObject, getFileControlObject, standingFileControlObjectNames } from "./control-objects.js";
import { fileGovernanceStore, governanceStoreIsFileOver } from "./consolidation.js";
import { moveOriginClearanceCustodyOut } from "./origin-clearance.js";
import { convertV1SessionAccountsAt } from "./delegation-settlement.js";
import { thrownText } from "../thrown-value.js";
export const CONTROL_PLANE_ADOPTION_FILE = "control-plane-adoption.json";
function coerceReceipt(raw) {
if (raw === undefined)
return { version: 1, adopted: [] };
if (typeof raw !== "object" || raw === null || Reflect.get(raw, "version") !== 1 || !Array.isArray(Reflect.get(raw, "adopted"))) {
throw new ControlPlaneCorruptError("memory control-plane adoption receipt has the wrong shape (fail-closed)");
}
return raw;
}
function sha256Hex(bytes) {
return createHash("sha256").update(bytes).digest("hex");
}
function standsAt(path) {
try {
lstatSync(path);
return true;
}
catch (err) {
if (Reflect.get(err, "code") === "ENOENT")
return false;
throw new ControlPlaneCorruptError(`memory control plane: ${path} could not be probed (${String(Reflect.get(err, "code") ?? "io error")}) (fail-closed)`, { cause: err });
}
}
export function replicaControlPlaneStrays(controlDir) {
const docs = MEMORY_GOVERNANCE_DOC_NAMES.filter((name) => {
const file = join(controlDir, fileGovernanceDocOf(name).file);
return standsAt(file) || standsAt(`${file}.journal`);
});
const objects = {};
for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
const n = standingFileControlObjectNames(controlDir, kind).length;
if (n > 0)
objects[kind] = n;
}
return { docs, objects };
}
export async function adoptReplicaControlPlane(controlDir, carrier, opts) {
const now = opts?.now ?? Date.now;
const handed = [];
const refused = [];
if (governanceStoreIsFileOver(carrier, controlDir))
return { adopted: [], refused };
if (!standsAt(controlDir))
throw new ControlPlaneCorruptError(`memory control-plane adoption: ${controlDir} does not exist — a replica control plane to adopt from is a directory that stands (a wrong path hands over nothing and says so) (fail-closed)`);
const receipt = (record, digest) => {
lockedStrictUpdate(controlDir, CONTROL_PLANE_ADOPTION_FILE, "memory control-plane adoption receipt", coerceReceipt, (rec) => {
if (rec.adopted.some((r) => r.record === record && r.digest === digest))
return { result: undefined };
rec.adopted.push({ record, digest, at: now() });
return { next: rec, result: undefined };
});
};
const docStands = (name) => {
const file = join(controlDir, fileGovernanceDocOf(name).file);
return standsAt(file) || standsAt(`${file}.journal`);
};
if (docStands("session-accounts")) {
try {
convertV1SessionAccountsAt(controlDir);
}
catch (err) {
refused.push({ record: "doc:session-accounts", reason: `its v1 key form could not be converted first: ${thrownText(err)}` });
}
}
if (docStands("origin-clearances")) {
try {
await moveOriginClearanceCustodyOut(fileGovernanceStore(controlDir));
}
catch (err) {
refused.push({ record: "doc:origin-clearances", reason: `its inline custody could not be moved out first: ${thrownText(err)}` });
}
}
for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
for (const name of standingFileControlObjectNames(controlDir, kind)) {
const record = `${kind}/${name}`;
try {
const bytes = getFileControlObject(controlDir, kind, name);
if (bytes === undefined)
continue;
const digest = sha256Hex(bytes);
const outcome = (await carrier.putObject(kind, name, bytes)) === "created" ? "written" : "converged";
const held = await carrier.getObject(kind, name);
if (held === undefined || sha256Hex(held) !== digest) {
refused.push({ record, reason: outcome === "converged" ? "the carrier already holds an object of this name with different bytes" : "the carrier's copy does not read back the same" });
continue;
}
const again = getFileControlObject(controlDir, kind, name);
if (again === undefined || sha256Hex(again) !== digest) {
refused.push({ record, reason: "the replica's bytes changed while they were adopted" });
continue;
}
receipt(record, digest);
handed.push({
adopted: { record, outcome, digest },
removeSource: () => {
const current = getFileControlObject(controlDir, kind, name);
if (current === undefined)
return true;
if (sha256Hex(current) !== digest)
return false;
deleteFileControlObject(controlDir, kind, name);
return true;
},
});
}
catch (err) {
refused.push({ record, reason: thrownText(err) });
}
}
}
const before = refused.map((r) => r.record);
if (before.length > 0) {
for (const name of replicaControlPlaneStrays(controlDir).docs) {
if (!before.includes(`doc:${name}`))
refused.push({ record: `doc:${name}`, reason: `left in the replica until every record before it is adopted (refused: ${before.join(", ")})` });
}
return { adopted: handed.map((h) => h.adopted), refused };
}
for (const name of MEMORY_GOVERNANCE_DOC_NAMES) {
const record = `doc:${name}`;
const { file, what } = fileGovernanceDocOf(name);
const path = join(controlDir, file);
try {
if (!standsAt(path) && !standsAt(`${path}.journal`))
continue;
const value = readStrictSidecar(controlDir, file, what);
if (value === undefined)
continue;
const digest = sha256Hex(JSON.stringify(value));
const outcome = await carrier.updateDoc(name, (raw) => raw, (cur) => {
if (cur === undefined)
return { next: value, result: "written" };
return { result: isDeepStrictEqual(cur, value) ? "converged" : "different" };
});
if (outcome === "different") {
refused.push({ record, reason: "the carrier already holds a different document of this name" });
continue;
}
if (!isDeepStrictEqual(await carrier.readDoc(name), value)) {
refused.push({ record, reason: "the carrier's copy does not read back the same" });
continue;
}
if (!isDeepStrictEqual(readStrictSidecar(controlDir, file, what), value)) {
refused.push({ record, reason: "the replica's document changed while it was adopted" });
continue;
}
receipt(record, digest);
handed.push({
adopted: { record, outcome, digest },
removeSource: () => lockedStrictRemove(controlDir, file, what, (committed) => sha256Hex(JSON.stringify(committed)) === digest) !== "kept",
});
}
catch (err) {
refused.push({ record, reason: thrownText(err) });
}
}
if (refused.length > 0)
return { adopted: handed.map((h) => h.adopted), refused };
const adopted = [];
for (const h of handed) {
try {
if (h.removeSource())
adopted.push(h.adopted);
else
refused.push({ record: h.adopted.record, reason: "the carrier holds it; the replica's copy changed after it was adopted and is kept" });
}
catch (err) {
refused.push({ record: h.adopted.record, reason: `the carrier holds it; removing the replica's copy failed: ${thrownText(err)}` });
}
}
return { adopted, refused };
}
export function readControlPlaneAdoptionReceipt(controlDir) {
return coerceReceipt(readStrictSidecar(controlDir, CONTROL_PLANE_ADOPTION_FILE, "memory control-plane adoption receipt")).adopted;
}