@sema-agent/core
Version:
Stateless, task-oriented AI agent core
54 lines (53 loc) • 2.38 kB
JavaScript
import { SessionError } from "../harness/types.js";
import { ParentChainGuard } from "./parent-chain-guard.js";
export function replayLossText(loss) {
return `${loss.dropped} of ${loss.total} records skipped as corrupt`;
}
export class LineageBreak extends SessionError {
missingParentId;
childId;
replayLoss;
constructor(missingParentId, childId, replayLoss) {
super("corrupt_session", `Entry ${missingParentId} not found — ${childId} names it as its parent and the log does not hold it${replayLoss !== undefined ? ` (${replayLossText(replayLoss)})` : ""}`, undefined, "parent_missing");
this.missingParentId = missingParentId;
this.childId = childId;
this.replayLoss = replayLoss;
}
}
export function pathToRoot(start, links, floorId) {
const path = [];
const chain = new ParentChainGuard();
let current = start;
while (current !== undefined) {
const id = links.idOf(current);
chain.stepOnto(id);
path.push(current);
if (id === floorId)
break;
const parentId = links.parentOf(current);
if (parentId === null || parentId === undefined)
break;
const parent = parentId === "" ? undefined : links.read(parentId);
if (parent === undefined) {
throw new LineageBreak(parentId, id);
}
current = parent;
}
return path.reverse();
}
export function selectForkRows(rows, sourceLeafId, point, shape) {
if (point.entryId === undefined)
return { rows: [...rows], leafId: sourceLeafId };
if (point.position !== "at") {
throw new SessionError("invalid_fork_target", `fork point ${point.entryId} comes with a position the copy does not select rows for (${String(point.position)}) — only "at" is`);
}
const byId = new Map();
for (const row of rows)
byId.set(shape.idOf(row), row);
const target = byId.get(point.entryId);
if (target === undefined)
throw new SessionError("invalid_fork_target", `Entry ${point.entryId} not found`);
const links = { read: (id) => byId.get(id), idOf: (row) => shape.idOf(row), parentOf: (row) => shape.parentOf(row) };
const onPath = new Set(pathToRoot(target, links).map((row) => shape.idOf(row)));
return { rows: rows.filter((row) => onPath.has(shape.idOf(row))), leafId: point.entryId };
}