@sema-agent/core
Version:
Stateless, task-oriented AI agent core
270 lines (269 loc) • 11.2 kB
JavaScript
import { closeSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { join } from "node:path";
import { MEMORY_CONTROL_OBJECT_KINDS } from "./types.js";
import { CONTROL_OBJECT_NAME_MAX_BYTES, CONTROL_OBJECT_STAGE_DIR, ControlPlaneCorruptError, FILE_CONTROL_OBJECT_DIRS, LINK_PROBE_PREFIX, controlPlaneLinksRefusal, ensureControlPlaneDir, quarantineCaptureName, quarantineObjectNameOf, rememberStoreWrite } from "./layout.js";
import { thrownText } from "../thrown-value.js";
export { CONTROL_OBJECT_STAGE_DIR };
function unknownObject(what) {
const e = new Error(`memory governance store: ${what} (a control object is one of ${MEMORY_CONTROL_OBJECT_KINDS.join(", ")}, named by one opaque segment)`);
e.code = "memory.control_object_unknown";
return e;
}
export function fileControlObjectDirOf(kind) {
if (typeof kind !== "string" || !Object.prototype.hasOwnProperty.call(FILE_CONTROL_OBJECT_DIRS, kind))
throw unknownObject(`${JSON.stringify(String(kind))} is not a control-object kind`);
return FILE_CONTROL_OBJECT_DIRS[kind];
}
export function isControlObjectName(name) {
return typeof name === "string" && name !== "" && name !== "." && name !== ".." && !/[/\\\0]/.test(name) && Buffer.byteLength(name, "utf8") <= CONTROL_OBJECT_NAME_MAX_BYTES;
}
function objectPath(controlDir, kind, name) {
const dir = fileControlObjectDirOf(kind);
if (!isControlObjectName(name))
throw unknownObject(`${JSON.stringify(String(name))} is not a control-object name`);
return join(controlDir, dir, name);
}
function errnoOf(err) {
return typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined;
}
export function fileControlObjectFaultCode(err) {
if (err instanceof ControlPlaneCorruptError)
return errnoOf(err.cause);
return errnoOf(err);
}
function unprobeable(path, err) {
return new ControlPlaneCorruptError(`memory control object at ${path} could not be probed (${errnoOf(err) ?? "io error"}) — whether it stands is unknown (fail-closed)`, { cause: err });
}
function entryAt(path) {
let found;
try {
found = lstatSync(path);
}
catch (err) {
if (errnoOf(err) === "ENOENT")
return "absent";
throw unprobeable(path, err);
}
if (found.isFile())
return "object";
if (!found.isSymbolicLink())
return "other";
try {
return statSync(path).isFile() ? "object" : "other";
}
catch (err) {
const code = errnoOf(err);
if (code === "ENOENT" || code === "ELOOP" || code === "ENOTDIR")
return "other";
throw unprobeable(path, err);
}
}
function stands(path) {
return entryAt(path) !== "absent";
}
function notAnObject(kind, name, refusal) {
return new ControlPlaneCorruptError(`memory control object ${kind}/${name} stands but is not a control object (a regular file under a legal name) — ${refusal} (fail-closed)`);
}
function otherBytesStand(kind, name) {
return new ControlPlaneCorruptError(`memory control object put ${kind}/${name}: the name already stands with different bytes — refusing to overwrite it (fail-closed)`);
}
function standingHolds(controlDir, kind, name, bytes) {
const standing = getFileControlObject(controlDir, kind, name);
return standing === undefined ? undefined : Buffer.from(standing).equals(bytes);
}
export function probeControlPlaneLinks(controlDir) {
const source = join(controlDir, `${LINK_PROBE_PREFIX}${randomUUID()}`);
const linked = `${source}.link`;
try {
closeSync(openSync(source, "wx", 0o600));
}
catch {
return;
}
let made = false;
try {
linkSync(source, linked);
made = true;
}
catch (err) {
const fault = errnoOf(err);
if (fault !== "EEXIST")
throw controlPlaneLinksRefusal(controlDir, fault);
}
finally {
for (const path of made ? [linked, source] : [source]) {
try {
rmSync(path, { force: true });
}
catch {
}
}
}
}
export function putFileControlObject(controlDir, kind, name, bytes) {
const path = objectPath(controlDir, kind, name);
const held = standingHolds(controlDir, kind, name, bytes);
if (held === true)
return "existed";
if (held === false)
throw otherBytesStand(kind, name);
ensureControlPlaneDir(controlDir, fileControlObjectDirOf(kind));
const stageDir = join(controlDir, CONTROL_OBJECT_STAGE_DIR);
ensureControlPlaneDir(controlDir, CONTROL_OBJECT_STAGE_DIR);
const staged = join(stageDir, randomUUID());
const fd = openSync(staged, "wx", 0o600);
try {
let written = 0;
while (written < bytes.byteLength) {
const n = writeSync(fd, bytes, written, bytes.byteLength - written);
if (n <= 0)
throw new Error(`memory control object ${kind}/${name}: write made no progress (${written}/${bytes.byteLength} bytes)`);
written += n;
}
fsyncSync(fd);
}
finally {
closeSync(fd);
}
try {
linkSync(staged, path);
rememberStoreWrite(path);
return "created";
}
catch (err) {
if (errnoOf(err) === "EEXIST") {
const held = standingHolds(controlDir, kind, name, bytes);
if (held === true)
return "existed";
if (held === false)
throw otherBytesStand(kind, name);
throw new ControlPlaneCorruptError(`memory control object put ${kind}/${name}: the name stood when the object was published and was gone when its bytes were compared — nothing was written (fail-closed)`);
}
throw err;
}
finally {
rmSync(staged, { force: true });
}
}
export function getFileControlObject(controlDir, kind, name) {
const path = objectPath(controlDir, kind, name);
const state = entryAt(path);
if (state === "absent")
return undefined;
if (state === "other")
throw notAnObject(kind, name, "it is never read as missing");
try {
return new Uint8Array(readFileSync(path));
}
catch (err) {
if ((errnoOf(err) === "ENOENT" || errnoOf(err) === "ENOTDIR") && !stands(path))
return undefined;
throw new ControlPlaneCorruptError(`memory control object ${kind}/${name} stands but cannot be read (${errnoOf(err) ?? "io error"}) — it is never read as missing (fail-closed)`, { cause: err });
}
}
export function standingFileControlObjectNames(controlDir, kind) {
const dir = join(controlDir, fileControlObjectDirOf(kind));
try {
return readdirSync(dir).sort();
}
catch (err) {
if (errnoOf(err) === "ENOENT" && !stands(dir))
return [];
throw new ControlPlaneCorruptError(`memory control objects of kind ${kind} could not be enumerated (${errnoOf(err) ?? "io error"}) at ${dir} — an enumeration failure is not an empty kind (fail-closed)`, { cause: err });
}
}
export function listFileControlObjects(controlDir, kind) {
const dir = join(controlDir, fileControlObjectDirOf(kind));
return standingFileControlObjectNames(controlDir, kind).filter((name) => isControlObjectName(name) && entryAt(join(dir, name)) === "object");
}
function sameBytes(a, b) {
const sa = statSync(a);
const sb = statSync(b);
if (sa.dev === sb.dev && sa.ino === sb.ino)
return true;
return readFileSync(a).equals(readFileSync(b));
}
export function moveFileControlObject(controlDir, from, to) {
const src = objectPath(controlDir, from.kind, from.name);
const dst = objectPath(controlDir, to.kind, to.name);
const neither = () => new ControlPlaneCorruptError(`memory control object move ${from.kind}/${from.name} → ${to.kind}/${to.name}: neither the source nor the target stands — nothing to move or to resume (fail-closed)`);
if (src === dst) {
if (stands(src))
return "already-moved";
throw neither();
}
ensureControlPlaneDir(controlDir, fileControlObjectDirOf(to.kind));
try {
linkSync(src, dst);
}
catch (err) {
const code = errnoOf(err);
if (code === "ENOENT" && !stands(src)) {
if (stands(dst))
return "already-moved";
throw neither();
}
if (code !== "EEXIST")
throw err;
if (!lstatSync(dst).isFile())
throw new ControlPlaneCorruptError(`memory control object move ${from.kind}/${from.name} → ${to.kind}/${to.name}: the target already stands but is not a file of its own (a link, or no file) — refusing to drop the source onto it (fail-closed)`);
if (!sameBytes(src, dst))
throw new ControlPlaneCorruptError(`memory control object move ${from.kind}/${from.name} → ${to.kind}/${to.name}: the target already stands with different bytes — refusing to overwrite it (fail-closed)`);
}
rememberStoreWrite(dst);
unlinkSync(src);
return "moved";
}
export function putFileControlObjectOnce(controlDir, kind, name, bytes) {
try {
return putFileControlObject(controlDir, kind, name, bytes);
}
catch (err) {
let standing;
try {
standing = getFileControlObject(controlDir, kind, name);
}
catch {
throw err;
}
if (standing === undefined)
throw err;
return "existed";
}
}
export function captureIntoFileQuarantine(controlDir, source, content) {
const bytes = new TextEncoder().encode(content);
const base = quarantineObjectNameOf(bytes, source);
try {
for (let attempt = 0; attempt <= 10; attempt++) {
const name = quarantineCaptureName(base, attempt);
if (putFileControlObjectOnce(controlDir, "quarantine", name, bytes) === "created")
return { name };
const standing = getFileControlObject(controlDir, "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 function deleteFileControlObject(controlDir, kind, name) {
const path = objectPath(controlDir, kind, name);
const state = entryAt(path);
if (state === "absent")
return false;
if (state === "other")
throw notAnObject(kind, name, "refusing to delete it");
try {
unlinkSync(path);
return true;
}
catch (err) {
if ((errnoOf(err) === "ENOENT" || errnoOf(err) === "ENOTDIR") && !stands(path))
return false;
throw new ControlPlaneCorruptError(`memory control object ${kind}/${name} stands but could not be deleted (${errnoOf(err) ?? "io error"}) (fail-closed)`, { cause: err });
}
}