@sema-agent/core
Version:
Stateless, task-oriented AI agent core
256 lines (255 loc) • 12.3 kB
JavaScript
import { createHash } from "node:crypto";
import { ControlPlaneCorruptError } from "./layout.js";
import { MEMORY_ORIGIN_CAUSES } from "./types.js";
export function clearanceCustodyName(clearanceId) {
return `${clearanceId}.md`;
}
function sha256Hex(bytes) {
return createHash("sha256").update(bytes).digest("hex");
}
async function readClearanceRecord(store) {
return coerceClearances(await store.readDoc("origin-clearances"));
}
async function custodyTextOf(store, row) {
if (row.custodyErased === true)
return "";
if (row.entryText !== undefined)
return row.entryText;
const name = clearanceCustodyName(row.clearanceId);
const bytes = await store.getObject("clearance-custody", name);
if (bytes === undefined)
throw new ControlPlaneCorruptError(`memory origin-clearance ledger: clearance ${JSON.stringify(row.clearanceId)} names custody ${JSON.stringify(name)} that is not there (fail-closed)`);
if (sha256Hex(bytes) !== row.custodyDigest)
throw new ControlPlaneCorruptError(`memory origin-clearance ledger: clearance ${JSON.stringify(row.clearanceId)}'s custody does not match the digest its row records (fail-closed)`);
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
}
async function keepCustody(store, clearanceId, text) {
const bytes = new TextEncoder().encode(text);
await store.putObject("clearance-custody", clearanceCustodyName(clearanceId), bytes);
return sha256Hex(bytes);
}
async function clearanceUpdate(store, fn) {
const kept = new Map();
let seen;
let landed = false;
try {
for (const row of (await readClearanceRecord(store)).rows) {
if (row.entryText !== undefined)
kept.set(row.clearanceId, await keepCustody(store, row.clearanceId, row.entryText));
}
const answer = await store.updateDoc("origin-clearances", coerceClearances, (rec) => {
seen = [...rec.rows];
let moved = false;
for (const row of rec.rows) {
if (row.entryText === undefined)
continue;
const digest = kept.get(row.clearanceId);
if (digest === undefined || digest !== sha256Hex(new TextEncoder().encode(row.entryText)))
continue;
const r = row;
delete r.entryText;
r.custodyDigest = digest;
moved = true;
}
const out = fn(rec);
return out.next === undefined && moved ? { next: rec, result: out.result } : out;
});
landed = true;
return answer;
}
finally {
const rows = seen ?? (await readClearanceRecord(store).then((rec) => rec.rows, () => undefined));
const deleteFailures = [];
for (const row of rows ?? []) {
if (row.custodyErased !== true)
continue;
try {
await store.deleteObject("clearance-custody", clearanceCustodyName(row.clearanceId));
}
catch (err) {
deleteFailures.push(err);
}
}
if (deleteFailures.length > 0 && landed)
throw deleteFailures[0];
}
}
function reqStr(v) {
return typeof v === "string" && v.length > 0;
}
function coerceOrigin(v, what) {
const o = v;
if (typeof o !== "object" || o === null || o.taint !== "external" || typeof o.at !== "number" || !Number.isFinite(o.at)) {
throw new ControlPlaneCorruptError(`${what}: clearance row carries a malformed origin member`);
}
if (o.cause !== undefined && !MEMORY_ORIGIN_CAUSES.includes(o.cause)) {
throw new ControlPlaneCorruptError(`${what}: clearance row carries an out-of-vocabulary origin cause (${JSON.stringify(o.cause)})`);
}
return { taint: "external", ...(o.cause !== undefined ? { cause: o.cause } : {}), at: o.at };
}
function coerceClearances(raw) {
if (raw === undefined)
return { version: 1, rows: [] };
const rec = raw;
if (typeof rec !== "object" || rec === null || !Array.isArray(rec.rows)) {
throw new ControlPlaneCorruptError("memory origin-clearance ledger has the wrong shape");
}
if (rec.version !== 1)
throw new ControlPlaneCorruptError(`memory origin-clearance ledger has an unrecognized version (${String(rec.version)}) — refusing (fail-closed)`);
if (rec.erasures !== undefined && !(Number.isSafeInteger(rec.erasures) && rec.erasures >= 0)) {
throw new ControlPlaneCorruptError("memory origin-clearance ledger carries a malformed erasure count (fail-closed)");
}
for (const r of rec.rows) {
const notErased = r?.custodyErased === undefined && r?.custodyErasedAt === undefined;
const custodyInline = typeof r?.entryText === "string" && r.entryText.length > 0 && r.custodyDigest === undefined && notErased;
const custodyKept = r?.entryText === undefined && typeof r?.custodyDigest === "string" && /^[0-9a-f]{64}$/.test(r.custodyDigest) && notErased;
const custodyGone = r?.custodyErased === true && typeof r.custodyErasedAt === "number" && Number.isFinite(r.custodyErasedAt) && r.entryText === undefined && r.custodyDigest === undefined;
if (typeof r !== "object" ||
r === null ||
!reqStr(r.clearanceId) ||
!reqStr(r.entryId) ||
!reqStr(r.scope) ||
!reqStr(r.slug) ||
!reqStr(r.baseRev) ||
!reqStr(r.requestId) ||
!reqStr(r.reason) ||
typeof r.at !== "number" ||
!Number.isFinite(r.at) ||
!(custodyInline || custodyKept || custodyGone) ||
(r.tombstonedAt !== undefined && (typeof r.tombstonedAt !== "number" || !Number.isFinite(r.tombstonedAt))) ||
(r.status !== "pending" && r.status !== "done" && r.status !== "failed") ||
!Array.isArray(r.events)) {
throw new ControlPlaneCorruptError("memory origin-clearance ledger row is malformed (fail-closed)");
}
coerceOrigin(r.origin, "memory origin-clearance ledger");
for (const e of r.events) {
if (typeof e !== "object" || e === null || !reqStr(e.eventId) || typeof e.at !== "number" || !Number.isFinite(e.at) || (e.to !== "done" && e.to !== "failed") || !reqStr(e.requestId) || (e.detail !== undefined && typeof e.detail !== "string")) {
throw new ControlPlaneCorruptError("memory origin-clearance ledger event is malformed (fail-closed)");
}
}
}
return rec;
}
export async function moveOriginClearanceCustodyOut(store) {
await clearanceUpdate(store, () => ({ result: undefined }));
}
export async function readOriginClearances(store) {
const out = [];
for (const r of (await readClearanceRecord(store)).rows) {
const { custodyDigest: _digest, entryText: _inline, custodyErased: _erased, custodyErasedAt: _erasedAt, ...row } = r;
out.push({ ...row, entryText: await custodyTextOf(store, r), ...(r.custodyErased === true ? { custodyErased: true } : {}), events: [...r.events] });
}
return out;
}
function pendingClearanceRefusal(entryId) {
const e = new Error(`origin clearance for entry ${JSON.stringify(entryId)} is already pending — resume it (call clearEntryOrigin again) instead of opening a second row.`);
e.code = "memory.origin_clear_pending";
return e;
}
function erasedSinceJudgedRefusal(entryId) {
const e = new Error(`an erasure ran over the memory store while the clearance of entry ${JSON.stringify(entryId.slice(0, 80))} was being opened — nothing was recorded; call clearEntryOrigin again to re-judge (an erased entry then answers unknown).`);
e.code = "memory.origin_clear_conflict";
return e;
}
export async function readClearanceErasureCount(store) {
const raw = await store.readDoc("origin-clearances");
return raw === undefined ? 0 : coerceClearances(raw).erasures ?? 0;
}
export async function openOriginClearance(store, row, judgedUnder) {
const pendingFor = (rec) => rec.rows.some((r) => r.entryId === row.entryId && r.status === "pending");
if (pendingFor(await readClearanceRecord(store)))
throw pendingClearanceRefusal(row.entryId);
const { entryText, ...rest } = row;
const custodyDigest = await keepCustody(store, row.clearanceId, entryText);
let refusedUnderLock = false;
try {
await clearanceUpdate(store, (rec) => {
if (pendingFor(rec)) {
refusedUnderLock = true;
throw pendingClearanceRefusal(row.entryId);
}
if ((rec.erasures ?? 0) !== judgedUnder) {
refusedUnderLock = true;
throw erasedSinceJudgedRefusal(row.entryId);
}
rec.rows.push({ ...rest, custodyDigest, status: "pending", events: [] });
return { next: rec, result: undefined };
});
}
catch (err) {
if (refusedUnderLock)
await Promise.resolve(store.deleteObject("clearance-custody", clearanceCustodyName(row.clearanceId))).catch(() => undefined);
throw err;
}
}
export async function markOriginClearanceTombstoned(store, input) {
await clearanceUpdate(store, (rec) => {
const r = rec.rows.find((x) => x.clearanceId === input.clearanceId);
if (r === undefined || r.status !== "pending" || r.tombstonedAt !== undefined)
return { result: undefined };
r.tombstonedAt = input.now();
return { next: rec, result: undefined };
});
}
export async function settleOriginClearance(store, input) {
await clearanceUpdate(store, (rec) => {
const r = rec.rows.find((x) => x.clearanceId === input.clearanceId);
if (r === undefined) {
const e = new Error(`origin clearance ${JSON.stringify(input.clearanceId)} is unknown`);
e.code = "memory.origin_clear_unknown";
throw e;
}
if (r.status !== "pending")
return { result: undefined };
if (r.events.some((ev) => ev.eventId === input.eventId))
return { result: undefined };
r.events.push({ eventId: input.eventId, at: input.now(), to: input.to, requestId: input.requestId, ...(input.detail !== undefined ? { detail: input.detail } : {}) });
if (input.keepPending !== true)
r.status = input.to;
return { next: rec, result: undefined };
});
}
export async function clearanceCustodyErased(store, clearanceId) {
const row = (await readClearanceRecord(store)).rows.find((r) => r.clearanceId === clearanceId);
return row === undefined || row.custodyErased === true;
}
export async function eraseOriginClearanceCustody(store, entryIds, at) {
if (entryIds.size === 0)
return { removed: 0, remaining: 0 };
const marked = await store.updateDoc("origin-clearances", coerceClearances, (rec) => {
rec.erasures = (rec.erasures ?? 0) + 1;
const objects = [];
let inline = 0;
for (const row of rec.rows) {
if (!entryIds.has(row.entryId))
continue;
if (row.custodyErased === true) {
objects.push({ clearanceId: row.clearanceId, take: "leftover" });
continue;
}
if (row.entryText !== undefined)
inline++;
objects.push({ clearanceId: row.clearanceId, take: row.entryText !== undefined ? "inline" : "kept" });
const r = row;
delete r.entryText;
delete r.custodyDigest;
r.custodyErased = true;
r.custodyErasedAt = at;
}
return { next: rec, result: { objects, inline } };
});
const out = { removed: marked.inline, remaining: 0 };
for (const { clearanceId, take } of marked.objects) {
try {
const deleted = await store.deleteObject("clearance-custody", clearanceCustodyName(clearanceId));
if (deleted !== true && deleted !== false)
out.remaining++;
else if (take === "kept" || (take === "leftover" && deleted === true))
out.removed++;
}
catch {
out.remaining++;
}
}
return out;
}