@sema-agent/core
Version:
Stateless, task-oriented AI agent core
131 lines (130 loc) • 5.85 kB
JavaScript
import { closeSync, constants as fsConstants, fstatSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync } from "node:fs";
import { dirname, join, relative, sep } from "node:path";
import { thrownText } from "../thrown-value.js";
import { inlineUntrusted } from "../untrusted-text.js";
import { noReplaceRestore } from "./delegation-settlement.js";
import { parseEntryFile, revOfText } from "./frontmatter.js";
import { mintStagingName, RETIRED_STAGING_OWNER } from "./layout.js";
const SEAT_QUOTED_MAX = 36;
export function retireGoneProjections(rows, mount) {
const seat = (scope, rel) => JSON.stringify([scope, rel]);
const read = new Set(mount.entries.map((e) => e.id));
const projected = [...mount.entries.filter((e) => e.frontmatter.provenance?.kind !== "repo_file"), ...mount.headers.filter((h) => !read.has(h.id))];
const occupied = new Set(projected.map((p) => seat(p.scope, `${p.slug}.md`)));
const listed = new Set([...read, ...mount.headers.map((h) => h.id)]);
const out = { judged: [], changed: [], replaced: [], failed: [] };
const judge = (row, text) => {
const parsed = parseEntryFile(text);
if (parsed.id !== row.id)
return "replaced";
return revOfText(text, row.id) === row.rev || (parsed.frontmatter.deleted === true && !listed.has(row.id)) ? "unchanged" : "changed";
};
for (const row of rows) {
const home = mount.homes.get(row.scope);
if (home === undefined || occupied.has(seat(row.scope, row.rel)))
continue;
const path = join(home, ...row.rel.split("/"));
const state = seatState(path);
if (state.kind === "undecidable")
continue;
if (state.kind === "absent") {
out.judged.push(row);
continue;
}
const found = judge(row, state.text);
if (found !== "unchanged") {
out.judged.push(row);
out[found].push(row);
continue;
}
mount.beforeRemove(path);
const staging = join(dirname(path), mintStagingName(RETIRED_STAGING_OWNER, mount.now));
try {
renameSync(path, staging);
}
catch (err) {
out.failed.push({ row, why: thrownText(err) });
continue;
}
const moved = seatState(staging);
const movedFound = moved.kind === "file" ? judge(row, moved.text) : undefined;
if (movedFound === "unchanged") {
try {
unlinkSync(staging);
}
catch {
}
out.judged.push(row);
continue;
}
const back = noReplaceRestore(staging, path);
if (back !== "restored")
out.failed.push({ row, why: `the file changed while it was being removed; its bytes are kept at ${staging}` });
else if (movedFound === undefined)
out.failed.push({ row, why: "what stood there could not be read while it was being removed; it was put back" });
else {
out.judged.push(row);
out[movedFound].push(row);
}
}
return out;
}
export function retirementNotices(r) {
const out = new Map();
const say = (scope, item) => {
out.set(scope, [...(out.get(scope) ?? []), inlineUntrusted(item, 600)]);
};
const q = (s) => {
for (let keep = SEAT_QUOTED_MAX - 3;; keep = Math.floor(keep / 2)) {
const quoted = JSON.stringify(inlineUntrusted(s, keep));
if (keep <= 1 || [...quoted].length <= SEAT_QUOTED_MAX)
return quoted;
}
};
for (const row of r.changed)
say(row.scope, `${q(row.rel)}: gone from the store at this name, changed here since it was placed — kept; not saved back if deleted, else delete the file`);
for (const row of r.replaced)
say(row.scope, `${q(row.rel)}: the store places no entry at this name any more, and this file is now a different note — left as found`);
for (const { row, why } of r.failed)
say(row.scope, `${q(row.rel)}: gone from the store at this name, but this copy was not removed — this session's harvest may save it back (${why})`);
return out;
}
export function ledgerFaultNotice(fault, why) {
const text = fault === "read"
? `memory copy record unreadable — this mount removed no copy, so one whose entry was removed elsewhere may be saved back (${why ?? "unknown"})`
: fault === "rebuilt"
? "memory copy record unreadable — rebuilt from the copies this harvest committed"
: `memory copy record not written — copies placed now are not removed when their entries are removed elsewhere, and may be saved back (${why ?? "unknown"})`;
return inlineUntrusted(text, 600);
}
export function projectionsHeldAt(candidates, scope, home) {
const rows = [];
for (const c of candidates) {
const state = seatState(c.path);
if (state.kind !== "file" || parseEntryFile(state.text).id !== c.id || revOfText(state.text, c.id) !== c.rev)
continue;
rows.push({ scope, rel: relative(home, c.path).split(sep).join("/"), id: c.id, rev: c.rev });
}
return rows;
}
function seatState(path) {
let fd;
try {
const st = lstatSync(path, { throwIfNoEntry: false });
if (st === undefined)
return { kind: "absent" };
if (!st.isFile())
return { kind: "undecidable" };
fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
if (!fstatSync(fd).isFile())
return { kind: "undecidable" };
return { kind: "file", text: readFileSync(fd, "utf8") };
}
catch {
return { kind: "undecidable" };
}
finally {
if (fd !== undefined)
closeSync(fd);
}
}