@sema-agent/core
Version:
Stateless, task-oriented AI agent core
584 lines (583 loc) • 37.8 kB
JavaScript
import { randomBytes } from "node:crypto";
import { isMemberOutcome, isRegistryMemberKind, MEMBER_OUTCOMES, memberCoverageOf, memberCountsOf, memberOutcomeText, sealMemberOutcome } from "./member-outcome.js";
import { isSubagentActions, subagentActionsLine } from "./actions-digest.js";
import { inlineUntrusted } from "./untrusted-text.js";
import { egressText } from "./untrusted-egress.js";
import { describeRejectedValue } from "./tool-search-setting.js";
import { strayMembersOf } from "./own-property-receipt.js";
export const RUN_LEDGER_VERSION = 1;
export const RUN_LEDGER_WIRE_KEY = "_sema_run_ledger";
export const RUN_LEDGER_SELF_REPORT_MAX_CHARS = 400;
export const RUN_LEDGER_CHECKS = Object.freeze(["verified", "evidence", "unverified", "n/a"]);
export function assertRunLedgerDeclaration(v) {
if (v === undefined || v === true)
return;
throw Object.assign(new Error(`TaskSpec.runLedger must be true or absent (got ${describeRejectedValue(v)}) — declare it to carry a member ledger; leave it out otherwise.`), { code: "config.invalid_argument" });
}
export function assertManagerApprovesDeclaration(spec) {
const v = spec.managerApproves;
if (v === undefined)
return;
if (v !== true)
throw Object.assign(new Error(`TaskSpec.managerApproves must be true or absent (got ${describeRejectedValue(v)}) — declare it to have the manager judge its workers' plain cards; leave it out otherwise.`), { code: "config.invalid_argument" });
if (spec.runLedger !== true && spec.team === undefined)
throw Object.assign(new Error("TaskSpec.managerApproves needs runLedger: true (or team, whose run keeps one) on the same spec — the manager approves its workers' cards only on a run that keeps a member ledger (a resume that keeps the manager restates its declaration)."), { code: "config.invalid_argument" });
}
export const RUN_LEDGER_NOT_KEPT_SENTENCE = "This task's first leg kept no member ledger, so this leg keeps none either: whether a task keeps one is fixed when the task starts (declare runLedger on its first leg).";
export function runLedgerIdentityOf(spec, resumed, rowTaskId) {
if (resumed === undefined && spec.runLedger !== true)
return undefined;
if (resumed !== undefined && resumed.section === undefined)
return spec.runLedger === true ? { notKept: RUN_LEDGER_NOT_KEPT_SENTENCE } : undefined;
const parked = resumed !== undefined ? readRunLedgerParked(resumed.section) : undefined;
if (resumed !== undefined && parked === undefined) {
throw Object.assign(new Error("the parked row's member ledger section does not read as a book this engine froze"), { code: "config.invalid_argument" });
}
if (resumed === undefined && rowTaskId !== undefined)
return { taskId: rowTaskId };
const named = spec.taskId;
if (named !== undefined && (typeof named !== "string" || named === "")) {
throw Object.assign(new Error(`TaskSpec.taskId must be a non-empty string on a run that keeps a member ledger (got ${describeRejectedValue(named)}) — name the task, or leave it out and the engine mints one.`), { code: "config.invalid_argument" });
}
if (parked !== undefined) {
if (named !== undefined && named !== parked.taskId) {
throw Object.assign(new Error(`this resume names task "${inlineUntrusted(named, 80)}", but the row it resumes is a leg of task "${inlineUntrusted(parked.taskId, 80)}" (the task its member ledger belongs to) — resume it under its own task id, or name none.`), { code: "config.invalid_argument" });
}
return { taskId: parked.taskId, parked };
}
return { taskId: named !== undefined && named !== spec.sessionId ? named : `rl-${randomBytes(8).toString("hex")}` };
}
export function runLedgerBookFor(spec, resumed, rowTaskId, now = Date.now) {
const id = runLedgerIdentityOf(spec, resumed, rowTaskId);
return id === undefined || "notKept" in id ? undefined : new RunLedgerBook(now, id.parked, id.taskId);
}
export function withRunLedgerTask(spec, book) {
if (book !== undefined)
return { ...spec, taskId: book.taskId, runLedger: true };
if (spec.runLedger === undefined)
return spec;
const { runLedger: _dropped, ...rest } = spec;
return rest;
}
const selfReportOf = (text) => {
if (text === undefined || text.trim() === "")
return undefined;
return inlineUntrusted(egressText("same-principal", text), RUN_LEDGER_SELF_REPORT_MAX_CHARS);
};
const labelOf = (text, fallback) => (text === undefined || text.trim() === "" ? fallback : inlineUntrusted(egressText("same-principal", text), 120));
const PARK_MAX_LISTED = 512;
const PARK_MAX_SYNC_ROWS = 64;
const PARK_MAX_ARRIVALS = 256;
const PARK_MAX_CALLS = 256;
const PARK_MAX_CLAIMS = 64;
const keepTail = (items, max) => items.length <= max ? { kept: [...items], dropped: 0 } : { kept: items.slice(items.length - max), dropped: items.length - max };
const isRec = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
const isNat = (x) => typeof x === "number" && Number.isSafeInteger(x) && x >= 0;
const isPos = (x) => typeof x === "number" && Number.isSafeInteger(x) && x >= 1;
const isOpt = (x, is) => x === undefined || is(x);
const isStr = (x) => typeof x === "string";
const isIn = (words) => (x) => typeof x === "string" && words.includes(x);
const isClaim = (c) => isRec(c) && isStr(c["about"]) && isStr(c["text"]) && isIn(["verified", "relayed", "inferred"])(c["basis"]) && isOpt(c["verdict"], isIn(["confirms", "refutes", "partial"])) && isOpt(c["evidence"], (e) => Array.isArray(e) && e.every(isStr));
const isSyncRow = (r) => isRec(r) && isStr(r["taskId"]) && isStr(r["kind"]) && isMemberOutcome(r["outcome"]) && isNat(r["settledAt"]) && isNat(r["order"]) &&
["label", "name", "selfReport", "call"].every((k) => isOpt(r[k], isStr)) && isOpt(r["began"], isNat) && isOpt(r["actions"], isSubagentActions);
const isArrivalMark = (a) => isRec(a) && isStr(a["taskId"]) && isPos(a["cycle"]) && isNat(a["order"]) && isNat(a["settledAt"]) && isOpt(a["began"], isNat);
const isHeardCall = (c) => isRec(c) && isStr(c["id"]) && isNat(c["at"]) && isNat(c["started"]) && isNat(c["turn"]) && isOpt(c["ended"], isNat) && isOpt(c["duplicate"], (d) => d === true);
const isReport = (r) => isRec(r) && isIn(["normal", "proactive"])(r["status"]) && isStr(r["message"]) && isOpt(r["kind"], isIn(["start", "interim", "final"])) && isOpt(r["claims"], (cs) => Array.isArray(cs) && cs.every(isClaim));
const TRUNCATED_KEYS = ["listed", "syncRows", "arrivals", "calls", "claims"];
const TRUNCATED_WORDS = { subject: "a parked member ledger's truncated section", unit: "member", moment: "when the row is read" };
const isTruncated = (t) => {
if (!isRec(t))
return false;
const keys = Object.keys(t);
return keys.length > 0 && strayMembersOf(t, TRUNCATED_WORDS, TRUNCATED_KEYS) === undefined && keys.every((k) => isPos(t[k]));
};
const isListOf = (x, is) => Array.isArray(x) && x.every(is);
const isReading = (p) => Array.isArray(p) && p.length === 2 && isStr(p[0]) && isNat(p[1]);
const isParked = (v) => isRec(v) && v["v"] === 1 && isStr(v["taskId"]) && v["taskId"] !== "" && isListOf(v["listed"], isStr) && isNat(v["tick"]) && isNat(v["turn"]) && isNat(v["seq"]) && isNat(v["reports"]) &&
isListOf(v["syncRows"], isSyncRow) && isListOf(v["arrivals"], isArrivalMark) && isListOf(v["calls"], isHeardCall) && isListOf(v["claims"], (c) => isClaim(c) && isRec(c) && isListOf(c["readings"], isReading)) &&
isOpt(v["lastReport"], isReport) && isOpt(v["truncated"], isTruncated) && isOpt(v["team"], (t) => isRec(t) && isStr(t["name"]) && isStr(t["source"]) && isStr(t["contentHash"]));
export function readRunLedgerParked(v) {
return isParked(v) ? v : undefined;
}
export class RunLedgerBook {
taskId;
#listed = new Set();
#syncRows = new Map();
#arrivals = new Map();
#liveFrames = new Map();
#calls = new Map();
#dispatched = new Map();
#truncated = { listed: 0, syncRows: 0, arrivals: 0, calls: 0, claims: 0 };
#tick = 0;
#turn = 0;
#isMember = () => undefined;
#claims = [];
#reports = 0;
#lastReport;
#launch;
#team;
#registry = () => [];
#registryBound = false;
#runId;
#seq = 0;
#now;
constructor(now = Date.now, parked, taskId) {
this.#now = now;
this.taskId = parked?.taskId ?? taskId;
if (parked === undefined)
return;
if (readRunLedgerParked(parked) === undefined)
throw Object.assign(new Error("the parked row's member ledger section does not read as a book this engine froze"), { code: "config.invalid_argument" });
if (taskId !== undefined && taskId !== parked.taskId)
throw Object.assign(new Error(`the parked row's member ledger is task "${parked.taskId}"'s, not "${taskId}"'s`), { code: "config.invalid_argument" });
for (const row of parked.syncRows)
this.#syncRows.set(row.taskId, structuredClone(row));
for (const mark of parked.arrivals)
this.#arrivals.set(mark.taskId, { ...mark });
for (const { id, ...call } of parked.calls)
this.#calls.set(id, { ...call });
for (const id of parked.listed)
this.#listed.add(id);
this.#claims.push(...parked.claims.map((c) => ({ ...c, readings: c.readings.map(([t, o]) => [t, o]), ...(c.evidence !== undefined ? { evidence: [...c.evidence] } : {}) })));
this.#tick = parked.tick;
this.#turn = parked.turn;
this.#seq = parked.seq;
this.#reports = parked.reports;
if (parked.lastReport !== undefined)
this.#lastReport = structuredClone(parked.lastReport);
if (parked.team !== undefined)
this.setTeam(parked.team);
if (parked.truncated !== undefined) {
this.#truncated.listed = parked.truncated.listed ?? 0;
this.#truncated.syncRows = parked.truncated.syncRows ?? 0;
this.#truncated.arrivals = parked.truncated.arrivals ?? 0;
this.#truncated.calls = parked.truncated.calls ?? 0;
this.#truncated.claims = parked.truncated.claims ?? 0;
}
}
parkSection() {
if (this.taskId === undefined)
throw Object.assign(new Error("a member ledger book no leg minted cannot be parked: it belongs to no task"), { code: "internal.run_ledger_unbound" });
this.#listing();
const listedCut = keepTail([...this.#listed], PARK_MAX_LISTED);
const syncCut = keepTail([...this.#syncRows.values()].sort((a, b) => a.order - b.order), PARK_MAX_SYNC_ROWS);
const arrivalCut = keepTail([...this.#arrivals.values()].sort((a, b) => a.order - b.order), PARK_MAX_ARRIVALS);
const callCut = keepTail([...this.#calls.entries()].sort((a, b) => a[1].started - b[1].started), PARK_MAX_CALLS);
const claimCut = keepTail(this.#claims, PARK_MAX_CLAIMS);
const totals = {
listed: this.#truncated.listed + listedCut.dropped,
syncRows: this.#truncated.syncRows + syncCut.dropped,
arrivals: this.#truncated.arrivals + arrivalCut.dropped,
calls: this.#truncated.calls + callCut.dropped,
claims: this.#truncated.claims + claimCut.dropped,
};
const truncatedEntries = TRUNCATED_KEYS.flatMap((k) => (totals[k] > 0 ? [[k, totals[k]]] : []));
const truncated = truncatedEntries.length > 0 ? Object.fromEntries(truncatedEntries) : undefined;
return {
v: 1,
taskId: this.taskId,
listed: listedCut.kept,
tick: this.#tick,
turn: this.#turn,
seq: this.#seq + 1,
reports: this.#reports,
syncRows: syncCut.kept.map((row) => structuredClone(row)),
arrivals: arrivalCut.kept.map((mark) => ({ ...mark })),
calls: callCut.kept.map(([id, call]) => ({ id, ...call })),
claims: claimCut.kept.map((c) => structuredClone(c)),
...(this.#lastReport !== undefined ? { lastReport: structuredClone(this.#lastReport) } : {}),
...(truncated !== undefined ? { truncated } : {}),
...(this.#team !== undefined ? { team: { ...this.#team } } : {}),
};
}
bind(runId, read, member) {
this.#runId = runId;
this.#registry = read;
this.#isMember = member ?? ((taskId) => read().find((r) => r.taskId === taskId));
this.#registryBound = true;
}
turnStarted() {
this.#turn = ++this.#tick;
}
setLaunch(launch) {
this.#launch = launch;
}
setTeam(team) {
this.#team = { name: team.name, source: team.source, contentHash: team.contentHash };
}
observeFrame(n, terminal) {
if (!terminal || !isRegistryMemberKind(n.task_type))
return;
const member = this.#registryBound ? this.#isMember(n.task_id) : undefined;
if (this.#registryBound && member === undefined)
return;
const frameCycle = n.task_type === "background_agent" ? n.seq : undefined;
const prior = this.#arrivals.get(n.task_id);
if (prior !== undefined && !(frameCycle !== undefined && frameCycle > prior.cycle))
return;
this.#arrive(n.task_id, frameCycle ?? 1, member?.toolUseId, ++this.#tick);
if (n.task_type === "peer_task")
return;
const selfReport = selfReportOf(n.result);
this.#liveFrames.set(n.task_id, {
kind: n.task_type,
...(n.spawnName !== undefined ? { name: n.spawnName } : {}),
...(selfReport !== undefined ? { selfReport } : {}),
...(n.actions !== undefined && isSubagentActions(n.actions) ? { actions: n.actions } : {}),
});
}
#arrive(taskId, cycle, dispatchCall, order) {
const dispatch = this.#dispatchOf(dispatchCall, order);
this.#arrivals.set(taskId, { taskId, cycle, order, settledAt: this.#now(), ...(dispatch.began !== undefined ? { began: dispatch.began } : {}) });
}
memberDispatched(taskId, toolCallId) {
this.#dispatched.set(toolCallId, taskId);
}
memberSettled(m) {
if (this.#syncRows.has(m.taskId))
return;
const selfReport = selfReportOf(m.selfReport);
const order = ++this.#tick;
this.#syncRows.set(m.taskId, {
taskId: m.taskId,
kind: m.kind,
label: labelOf(m.label, m.kind),
...(m.name !== undefined ? { name: m.name } : {}),
outcome: sealMemberOutcome(m.outcome),
...(selfReport !== undefined ? { selfReport } : {}),
...(m.actions !== undefined ? { actions: m.actions } : {}),
settledAt: this.#now(),
order,
...this.#dispatchOf(m.toolCallId, order),
});
}
#dispatchOf(callId, fallbackOrder) {
if (callId === undefined)
return this.#truncated.calls === 0 ? { began: fallbackOrder } : {};
const rec = this.#calls.get(callId);
const began = rec !== undefined && rec.duplicate !== true ? rec.started : undefined;
return { call: callId, ...(began !== undefined ? { began } : {}) };
}
callStarted(toolCallId) {
const dup = this.#calls.has(toolCallId);
this.#calls.set(toolCallId, { at: this.#now(), started: ++this.#tick, turn: this.#turn, ...(dup ? { duplicate: true } : {}) });
}
callResumed(toolCallId) {
const prior = this.#calls.get(toolCallId);
if (prior !== undefined && prior.ended === undefined && prior.duplicate !== true) {
prior.at = this.#now();
prior.started = ++this.#tick;
return;
}
this.callStarted(toolCallId);
}
callEnded(toolCallId, details) {
const c = this.#calls.get(toolCallId);
const dispatched = this.#dispatched.get(toolCallId);
this.#dispatched.delete(toolCallId);
if (c === undefined || c.ended !== undefined)
return;
c.ended = ++this.#tick;
if (dispatched === undefined || !this.#registryBound || !isRec(details) || details["task_id"] !== dispatched)
return;
const status = details["status"];
const member = this.#isMember(dispatched);
if (member === undefined || member.running || member.toolUseId !== toolCallId || !isStr(status) || member.outcome?.outcome !== status)
return;
const cycle = member.cycle ?? 1;
const prior = this.#arrivals.get(dispatched);
if (prior !== undefined && prior.cycle >= cycle)
return;
this.#arrive(dispatched, cycle, toolCallId, c.ended);
}
acceptReport(input) {
const claims = input.report?.claims ?? [];
const issued = input.toolCallId !== undefined ? (this.#calls.get(input.toolCallId)?.turn ?? this.#turn) : this.#tick + 1;
for (const [i, c] of claims.entries()) {
const n = i + 1;
const row = this.#rowNow(c.about);
if (row === undefined) {
if (this.#truncated.syncRows > 0 && this.#listed.has(c.about)) {
return { ok: false, why: `claim ${n} is about "${inlineUntrusted(c.about, 80)}", whose synchronous member row was truncated when the run parked (${this.#truncated.syncRows} earlier synchronous rows cut) — mark the claim "relayed" or "inferred".` };
}
return { ok: false, why: `claim ${n} is about "${inlineUntrusted(c.about, 80)}", which is not a member this run dispatched — name a row's task id, as the ledger lists it.` };
}
if (c.basis !== "verified")
continue;
const about = `${row.kind === "workflow" ? "workflow" : row.kind === "peer_task" ? "peer task" : "agent"} ${row.name !== undefined ? `"${inlineUntrusted(row.name, 60)}"` : row.taskId}`;
if (row.reclaimed)
return { ok: false, why: `claim ${n} is marked "verified", but ${about} can no longer be read from its holder — mark the claim "relayed" or "inferred".` };
if (row.running) {
const cycleLabel = row.cycleExplicit ? ` (round ${row.cycle})` : "";
return { ok: false, why: `claim ${n} is marked "verified", but ${about} is still running${cycleLabel} and has not reported yet — wait until it finishes before verifying, or mark the claim "relayed" or "inferred".` };
}
if (row.arrival === undefined) {
if (row.cycleExplicit && (row.cycle > 1 || row.hasEarlierArrival)) {
return { ok: false, why: `claim ${n} is marked "verified", but ${about}'s result for round ${row.cycle} has not arrived yet — wait until you receive it before verifying, or mark the claim "relayed".` };
}
if (this.#truncated.arrivals > 0) {
return { ok: false, why: `claim ${n} is marked "verified", but ${about}'s arrival mark is not in this book (${this.#truncated.arrivals} earlier arrival ${this.#truncated.arrivals === 1 ? "mark was" : "marks were"} truncated when the run parked) — wait for a new result or mark the claim "relayed".` };
}
return { ok: false, why: `claim ${n} is marked "verified", but ${about} has not reported yet — its result has not arrived yet. Mark it "relayed" or "inferred", or report again once it has.` };
}
if (c.verdict === undefined)
return { ok: false, why: `claim ${n} is marked "verified" but states no verdict — say whether the check confirms, refutes or partly confirms what ${about} reported.` };
const evidence = c.evidence ?? [];
if (evidence.length === 0)
return { ok: false, why: `claim ${n} is marked "verified" but cites no evidence — cite the call id of the check you ran, or another member's task id, or mark the claim "relayed".` };
for (const e of evidence) {
if (e === c.about)
return { ok: false, why: `claim ${n} cites ${about} as evidence for itself — a member's own result cannot verify it. Cite your own check, or another member that checked it.` };
if (e === input.toolCallId)
return { ok: false, why: `claim ${n} cites this report call itself as evidence — cite the check you ran before it.` };
const call = this.#calls.get(e);
if (call?.duplicate === true) {
return { ok: false, why: `claim ${n} cites "${inlineUntrusted(e, 80)}", a call id that was used more than once in this run (non-unique) — its timing cannot be verified. Run a fresh check with a unique call id, or mark the claim "relayed".` };
}
const other = call === undefined ? this.#rowNow(e) : undefined;
if (other !== undefined && other.running) {
const cycleLabel = other.cycleExplicit ? ` (round ${other.cycle})` : "";
return { ok: false, why: `claim ${n} cites ${e}, a member that is still running${cycleLabel} (a member that has not reported yet) — a check that has no result cannot verify anything.` };
}
const at = call?.at ?? other?.arrival?.settledAt;
const began = call?.started ?? other?.arrival?.began;
const done = call !== undefined ? call.ended : other?.arrival?.order;
if (other !== undefined && other.arrival !== undefined && other.arrival.began === undefined) {
if (this.#truncated.calls > 0) {
return { ok: false, why: `claim ${n} cites ${e}, whose dispatch call record was truncated when the run parked (${this.#truncated.calls} earlier call ${this.#truncated.calls === 1 ? "record was" : "records were"} cut) — cannot verify when it started. Run a fresh check, or mark the claim "relayed".` };
}
return { ok: false, why: `claim ${n} cites ${e}, whose dispatch start was not recorded by this book — cannot verify when it started. Run a fresh check, or mark the claim "relayed".` };
}
if (at === undefined || began === undefined) {
if (other !== undefined) {
const cutNote = this.#truncated.arrivals > 0 ? ` (${this.#truncated.arrivals} earlier arrival marks were truncated when the run parked)` : other.cycleExplicit && other.cycle > 1 ? ` (round ${other.cycle} has not arrived)` : "";
return { ok: false, why: `claim ${n} cites ${e}, a member that has not reported yet${cutNote} — a check that has no result cannot verify anything.` };
}
if (this.#truncated.calls > 0) {
return { ok: false, why: `claim ${n} cites "${inlineUntrusted(e, 80)}", which is not in this book's call records (${this.#truncated.calls} earlier call ${this.#truncated.calls === 1 ? "record was" : "records were"} truncated when the run parked) — run a fresh check, or mark the claim "relayed".` };
}
return { ok: false, why: `claim ${n} cites "${inlineUntrusted(e, 80)}", which is neither a call you made in this run nor a member it dispatched — cite a call id from your own tool calls or a member's task id.` };
}
if (done === undefined || !(done < issued)) {
return { ok: false, why: `claim ${n} cites "${inlineUntrusted(e, 80)}", which had not finished when this report was sent — cite a check whose result you read before reporting.` };
}
if (!(began > row.arrival.order)) {
return { ok: false, why: `claim ${n} is marked "verified" but its evidence "${inlineUntrusted(e, 80)}" ran at ${isoTime(at)}, before ${about} reported at ${isoTime(row.arrival.settledAt)} — a check made before the claim cannot verify it. Check again, or mark the claim "relayed".` };
}
if (other?.reclaimed) {
return { ok: false, why: `claim ${n} cites ${e}, a member that can no longer be read from its holder — run a fresh check, or mark the claim "relayed".` };
}
}
}
const readingsOf = (c) => [...new Set([c.about, ...(c.evidence ?? [])])].flatMap((id) => {
const view = this.#rowNow(id);
return view !== undefined && !view.running && view.arrival !== undefined ? [[id, view.cycle]] : [];
});
this.#claims.push(...claims.map((c) => ({ ...c, ...(c.evidence !== undefined ? { evidence: [...c.evidence] } : {}), readings: readingsOf(c) })));
if (input.report !== undefined)
this.#reports += 1;
this.#lastReport = {
status: input.status,
message: input.message,
...(input.report?.kind !== undefined ? { kind: input.report.kind } : {}),
...(claims.length > 0 ? { claims: claims.map((c) => ({ ...c })) } : {}),
};
return { ok: true };
}
#rowNow(taskId, regHint) {
const sync = this.#syncRows.get(taskId);
const mark = this.#arrivals.get(taskId);
const live = this.#liveFrames.get(taskId);
const reg = regHint ??
(this.#registryBound
? (this.#isMember(taskId) ?? (sync !== undefined ? { taskId, kind: sync.kind, running: false, outcome: sync.outcome, cycle: 1 } : undefined))
: sync !== undefined
? { taskId, kind: sync.kind, running: false, outcome: sync.outcome, cycle: 1 }
: mark !== undefined
? { taskId, kind: live?.kind ?? "background_agent", running: false, cycle: mark.cycle }
: undefined);
if (reg === undefined) {
if (mark === undefined)
return undefined;
return {
taskId,
kind: live?.kind ?? "background_agent",
...(live?.name !== undefined ? { name: live.name } : {}),
running: false,
cycle: mark.cycle,
cycleExplicit: false,
arrival: { order: mark.order, settledAt: mark.settledAt, ...(mark.began !== undefined ? { began: mark.began } : {}) },
hasEarlierArrival: false,
...(live?.selfReport !== undefined ? { selfReport: live.selfReport } : {}),
...(live?.actions !== undefined ? { actions: live.actions } : {}),
reclaimed: true,
};
}
const isSync = sync !== undefined && reg.outcome === sync.outcome;
const isWorkflow = reg.kind === "workflow";
const cycleExplicit = reg.cycle !== undefined;
const cycle = isSync ? 1 : (reg.cycle ?? (isWorkflow ? 1 : (mark?.cycle ?? 1)));
const name = reg.name ?? (isSync ? sync.name : live?.name);
const label = isSync ? sync.label : reg.label;
const selfReport = isSync ? sync.selfReport : live?.selfReport;
const actions = isSync ? sync.actions : live?.actions;
if (reg.running) {
return {
taskId,
kind: reg.kind,
...(name !== undefined ? { name } : {}),
...(label !== undefined ? { label } : {}),
running: true,
cycle,
cycleExplicit,
hasEarlierArrival: mark !== undefined,
...(selfReport !== undefined ? { selfReport } : {}),
...(actions !== undefined ? { actions } : {}),
};
}
const arrival = isSync
? { order: sync.order, settledAt: sync.settledAt, ...(sync.began !== undefined ? { began: sync.began } : {}) }
: mark !== undefined && mark.cycle === cycle
? { order: mark.order, settledAt: mark.settledAt, ...(mark.began !== undefined ? { began: mark.began } : {}) }
: undefined;
return {
taskId,
kind: reg.kind,
...(name !== undefined ? { name } : {}),
...(label !== undefined ? { label } : {}),
running: false,
...(reg.outcome !== undefined ? { outcome: reg.outcome } : {}),
...(reg.members !== undefined ? { members: reg.members } : {}),
cycle,
cycleExplicit,
...(arrival !== undefined ? { arrival } : {}),
hasEarlierArrival: mark !== undefined,
...(selfReport !== undefined ? { selfReport } : {}),
...(actions !== undefined ? { actions } : {}),
};
}
#listing() {
const rows = this.#registry();
const held = new Set(rows.map((r) => r.taskId));
const own = [...this.#syncRows.values()].filter((s) => !held.has(s.taskId));
const now = [...rows.map((r) => r.taskId), ...own.map((s) => s.taskId)];
for (const id of now)
this.#listed.add(id);
const handed = new Set(now);
const unreadable = new Set([...this.#listed, ...this.#arrivals.keys(), ...this.#syncRows.keys()].filter((id) => !handed.has(id))).size;
return { rows: [...rows, ...own.map((s) => ({ taskId: s.taskId, kind: s.kind, running: false, outcome: s.outcome, cycle: 1 }))], unreadable };
}
snapshot(trigger) {
const listing = this.#listing();
const views = listing.rows.map((reg) => this.#rowNow(reg.taskId, reg));
const viewById = new Map(views.map((v) => [v.taskId, v]));
const covers = (c, taskId) => {
const view = viewById.get(taskId);
return view !== undefined && !view.running && c.readings.some(([id, cycle]) => id === taskId && cycle === view.cycle);
};
const verdictOf = new Map();
const cited = new Set();
for (const c of this.#claims) {
if (c.basis !== "verified")
continue;
if (covers(c, c.about))
verdictOf.set(c.about, c.verdict);
for (const e of c.evidence ?? [])
if (covers(c, e))
cited.add(e);
}
const verifiedAbout = new Set(verdictOf.keys());
const rows = views.map((view) => {
const outcome = view.running ? undefined : view.outcome;
const settled = outcome !== undefined;
const check = outcome?.outcome !== "completed" ? "n/a" : verifiedAbout.has(view.taskId) ? "verified" : cited.has(view.taskId) ? "evidence" : "unverified";
const verdict = check === "verified" ? verdictOf.get(view.taskId) : undefined;
return {
taskId: view.taskId,
kind: view.kind,
label: labelOf(view.label, view.kind),
...(view.name !== undefined ? { name: view.name } : {}),
state: settled ? "settled" : "running",
...(outcome !== undefined ? { outcome } : {}),
...(view.selfReport !== undefined ? { selfReport: view.selfReport } : {}),
...(view.actions !== undefined ? { actions: view.actions } : {}),
check,
...(verdict !== undefined ? { verdict } : {}),
...(view.members !== undefined ? { members: view.members } : {}),
...(view.arrival !== undefined && settled ? { settledAt: view.arrival.settledAt } : {}),
};
});
this.#seq += 1;
return runLedgerOf(rows, {
...(this.#runId !== undefined ? { runId: this.#runId } : {}),
seq: this.#seq,
trigger,
...(listing.unreadable > 0 ? { unreadable: listing.unreadable } : {}),
reports: this.#reports,
...(this.#lastReport !== undefined ? { lastReport: this.#lastReport } : {}),
...(this.#launch !== undefined ? { launch: this.#launch } : {}),
...(this.#team !== undefined ? { team: this.#team } : {}),
});
}
}
const isoTime = (ms) => new Date(ms).toISOString().slice(11, 23);
export function runLedgerOf(rows, at) {
const final = at.trigger.kind === "run_end";
const outcomes = rows.map((r) => r.outcome);
const unreadable = at.unreadable !== undefined && at.unreadable > 0 ? at.unreadable : undefined;
const rowCoverage = memberCoverageOf(outcomes) === "complete" && rows.some((r) => r.members !== undefined && r.members.coverage !== "complete") ? "partial" : memberCoverageOf(outcomes);
const coverage = unreadable !== undefined ? "incomplete" : rowCoverage;
const open = rows.filter((r) => r.state === "running").length;
const unverified = rows.filter((r) => r.check === "unverified").length;
const contradicted = rows.filter((r) => r.verdict !== undefined && r.verdict !== "confirms").length;
const base = { v: RUN_LEDGER_VERSION, ...(at.runId !== undefined ? { runId: at.runId } : {}), seq: at.seq, trigger: at.trigger, final, open, coverage, counts: memberCountsOf(outcomes), ...(unreadable !== undefined ? { unreadable } : {}), unverified, contradicted, reports: at.reports, rows };
const headline = runLedgerHeadline(base);
const ledger = { ...base, headline, ...(at.lastReport !== undefined ? { lastReport: at.lastReport } : {}), ...(at.launch !== undefined ? { launch: at.launch } : {}), ...(at.team !== undefined ? { team: at.team } : {}) };
return Object.freeze({ ...ledger, text: runLedgerText(ledger) });
}
export function runLedgerHeadline(l) {
const contradicted = l.contradicted > 0 ? ` · ${l.contradicted} contradicted by a check` : "";
const noReport = l.final && l.reports === 0 ? " · the manager submitted no structured conclusions" : "";
const unreadable = l.unreadable !== undefined && l.unreadable > 0 ? `${l.unreadable} ${l.unreadable === 1 ? "member" : "members"} no longer readable` : "";
if (l.rows.length === 0 && unreadable === "")
return `Settled · no members were dispatched${noReport}`;
const short = l.rows.filter((r) => r.members !== undefined && r.members.coverage !== "complete").length;
const fails = [...endingsOf(l.counts), unreadable, short > 0 ? `${short} ${short === 1 ? "workflow short of its members" : "workflows short of their members"}` : ""].filter((s) => s !== "").join(", ");
const completed = l.rows.some((r) => r.outcome?.outcome === "completed");
if (l.open > 0)
return `Not finished: ${l.open} ${l.open === 1 ? "row" : "rows"} still running${fails !== "" ? ` · ${fails}` : ""}${contradicted}${l.unverified > 0 ? ` · ${l.unverified} unverified` : ""}${noReport}`;
const coverage = `coverage ${l.coverage}${fails !== "" ? ` (${fails})` : ""}`;
const checks = l.unverified > 0 ? `${l.unverified} unverified` : !completed ? "none completed" : l.contradicted > 0 ? "none unverified" : "all verified";
return `Settled · ${coverage}${contradicted} · ${checks}${noReport}`;
}
const endingsOf = (counts) => MEMBER_OUTCOMES.filter((w) => w !== "completed" && (counts[w] ?? 0) > 0).map((w) => `${counts[w]} ${w}`);
const CHECK_WORDS = { verified: "verified", evidence: "used as evidence", unverified: "not verified", "n/a": "—" };
const VERDICT_WORDS = { confirms: "confirmed", refutes: "refuted", partial: "partly confirmed" };
export function runLedgerText(l) {
const lines = [l.headline];
const withResult = l.rows.filter((r) => r.state === "settled").length;
const endings = endingsOf(l.counts);
lines.push(`${l.rows.length} ${l.rows.length === 1 ? "member" : "members"} dispatched: ${withResult} with an ending${endings.length > 0 ? ` (${endings.join(", ")} of them not completed)` : ""}, ${l.open} still running; ${l.unverified} completed without a check, ${l.contradicted} contradicted by one.`);
if (l.unreadable !== undefined && l.unreadable > 0)
lines.push(`${l.unreadable} ${l.unreadable === 1 ? "member" : "members"} this task dispatched can no longer be read from ${l.unreadable === 1 ? "its holder" : "their holder"} (reclaimed, or held by another process): the coverage is not complete.`);
for (const r of l.rows) {
const who = `${r.label}${r.name !== undefined ? ` [${inlineUntrusted(r.name, 60)}]` : ""} (${r.kind} ${r.taskId})`;
const ending = r.outcome !== undefined ? memberOutcomeText(r.outcome) : "still running";
lines.push(`- ${who}: ${ending}${r.check !== "n/a" ? ` · ${CHECK_WORDS[r.check]}` : ""}${r.verdict !== undefined ? ` (${VERDICT_WORDS[r.verdict]})` : ""}`);
if (r.members !== undefined)
lines.push(` its members: coverage ${r.members.coverage}; ${Object.entries(r.members.counts).map(([w, c]) => `${c} ${w}`).join(", ")}`);
if (r.selfReport !== undefined)
lines.push(` said: ${r.selfReport}`);
if (r.actions !== undefined)
lines.push(` did: ${subagentActionsLine(r.actions)}`);
}
if (l.lastReport !== undefined) {
lines.push(`Last report (${l.lastReport.status}${l.lastReport.kind !== undefined ? `, ${l.lastReport.kind}` : ""}): ${inlineUntrusted(l.lastReport.message, 600)}`);
for (const c of l.lastReport.claims ?? [])
lines.push(` ${c.basis}${c.verdict !== undefined ? ` (${c.verdict})` : ""} · ${inlineUntrusted(c.about, 60)}: ${inlineUntrusted(c.text, 200)}`);
}
if (l.launch !== undefined && l.launch.verdict !== "ready") {
lines.push(`Launch check: ${l.launch.verdict} — ${l.launch.items.filter((i) => i.state !== "ok").map((i) => `${i.item} ${i.state}`).join("; ")}`);
}
return lines.join("\n");
}