@sema-agent/core
Version:
Stateless, task-oriented AI agent core
548 lines (547 loc) • 42.9 kB
JavaScript
import { strict as assert } from "node:assert";
import { isDeepStrictEqual } from "node:util";
import { WORKFLOW_RUN_ROW_MALFORMED_CODE, WORKFLOW_RUN_UPDATE_CAUSES, readStoredWorkflowRun, summarizeWorkflowRun } from "./workflow-run-store.js";
import { thrownText } from "./thrown-value.js";
import { adoptHostPromise } from "./host-promise.js";
import { ANONYMOUS_SCOPE } from "./isolation-scope.js";
function readableRows(rows) {
const out = [];
for (const s of rows) {
if ("rowVerdict" in s)
assert.fail(`run ${s.id} was listed as unreadable (${s.rowVerdict.member}) though the case wrote it readable`);
out.push(s);
}
return out;
}
export function createWorkflowRun(over = {}) {
const createdAt = over.createdAt ?? 1_000;
return {
id: over.id ?? "run-1",
scope: "tenant-a",
status: "completed",
phases: [{ title: "build", status: "completed", startedAt: createdAt, endedAt: createdAt + 5 }],
agents: [
{ label: "agent-1", callKey: "0:abc", phase: "build", status: "completed", taskStatus: "completed", queuedAt: createdAt, startedAt: createdAt, endedAt: createdAt + 4, stats: { tokens: 100, turns: 1, costMicroUsd: 10 } },
],
groups: [],
stats: { tokens: 100, turns: 1, costMicroUsd: 10, nested: { tokens: 50, turns: 1, tasks: 1, costMicroUsd: 5 } },
startedAt: createdAt,
endedAt: createdAt + 10,
createdAt,
...over,
};
}
export async function workflowRunStoreContract(make, runAssertion = defaultSequentialRunner, hooks) {
if (hooks !== undefined && hooks.plantRow === undefined && (hooks.unplantable === undefined || hooks.unplantable.trim() === "")) {
throw new TypeError("workflowRunStoreContract: pass plantRow, or declare unplantable with the reason this backend keeps no bytes a foreign writer could damage");
}
const pending = [];
const run = (name, fn) => {
const result = runAssertion(name, fn);
const resultAsync = adoptHostPromise(result);
if (resultAsync !== undefined)
pending.push(resultAsync);
};
run("put create-once → already_exists", async () => {
const store = make();
const r = createWorkflowRun();
await store.put(r.id, r);
await assert.rejects(store.put(r.id, r), (e) => e.code === "workflow_run.already_exists");
});
run("a resume's row names the run it resumed (resumedFrom) in every listing; listByScope({ resumedFrom }) lists its direct successors, or — a store that does not filter — every run of the scope, never a successor whose row lacks the member", async () => {
const store = make();
await store.put("src", createWorkflowRun({ id: "src", createdAt: 1_000 }));
await store.put("next-1", createWorkflowRun({ id: "next-1", createdAt: 2_000, resume: { fromRunId: "src", journalEntries: 1, replayed: 1 } }));
await store.put("next-2", createWorkflowRun({ id: "next-2", createdAt: 3_000, resume: { fromRunId: "next-1", journalEntries: 1, replayed: 1 } }));
const rows = (listed) => readableRows(listed).map((s) => [s.id, s.resumedFrom]);
const all = rows(await store.listByScope("tenant-a"));
assert.deepEqual(all, [["next-2", "next-1"], ["next-1", "src"], ["src", undefined]]);
const successors = rows(await store.listByScope("tenant-a", { resumedFrom: "src" }));
assert.ok(isDeepStrictEqual(successors, [["next-1", "src"]]) || isDeepStrictEqual(successors, all), `listByScope("tenant-a", { resumedFrom: "src" }) answered ${JSON.stringify(successors)}: the direct successors with their resumedFrom ([["next-1","src"]]), or the scope unfiltered (${JSON.stringify(all)})`);
assert.deepEqual(await store.listByScope("tenant-b", { resumedFrom: "src" }), []);
});
run("get returns a deep copy (mutating the result must not corrupt the store)", async () => {
const store = make();
const r = createWorkflowRun();
await store.put(r.id, r);
const got = await store.get(r.id);
assert.ok(got);
got.agents.push({ label: "x", callKey: "0:x", status: "running", queuedAt: 0, startedAt: 0 });
const again = await store.get(r.id);
assert.equal(again.agents.length, 1);
assert.equal(await store.get("nope"), null);
});
run("update CAS: bumps rev, scope-mismatch loses, stale-rev loses, current-rev wins", async () => {
const store = make();
const r = createWorkflowRun({ status: "running" });
await store.put(r.id, r);
assert.equal(await store.update(r.id, r.scope, { ...r, status: "running", stats: { ...r.stats, tokens: 200 } }), true);
assert.equal((await store.get(r.id)).rev, 1);
assert.equal((await store.get(r.id)).stats.tokens, 200);
assert.equal(await store.update(r.id, "tenant-b", { ...r, status: "completed" }), false);
assert.equal(await store.update(r.id, r.scope, { ...r, status: "completed" }, { rev: 0 }), false);
assert.equal(await store.update(r.id, r.scope, { ...r, status: "completed" }, { rev: 1 }), true);
assert.equal((await store.get(r.id)).rev, 2);
assert.equal((await store.get(r.id)).status, "completed");
assert.equal(await store.update("ghost", r.scope, createWorkflowRun({ id: "ghost" })), false);
});
run("a record's creationId, treeId and resume.fromCreationId come back from get as put, and survive writing back what get returned", async () => {
const store = make();
const r = createWorkflowRun({ id: "ident", creationId: "c-ident", treeId: "root-run", resume: { fromRunId: "root-run", fromCreationId: "c-root", journalEntries: 1, replayed: 1 } });
await store.put(r.id, r);
const got = await store.get("ident");
assert.ok(got);
assert.equal(got.creationId, "c-ident", "creationId comes back as put");
assert.equal(got.treeId, "root-run", "treeId comes back as put");
assert.equal(got.resume?.fromCreationId, "c-root", "resume.fromCreationId comes back as put");
assert.equal(await store.update("ident", "tenant-a", got, { rev: got.rev ?? 0, creationId: "c-ident" }), true);
const again = (await store.get("ident"));
assert.deepEqual([again.creationId, again.treeId, again.resume?.fromCreationId], ["c-ident", "root-run", "c-root"], "writing back what get returned keeps the three members");
});
{
const cells = [
["a: row c-1, given c-1, wins", "c-1", "c-1", true],
["b: row c-1, given c-2 — another creation of the same id loses", "c-1", "c-2", false],
["c: row c-1, given null — another creation of the same id loses", "c-1", null, false],
["d: row c-1, given none, wins (not compared)", "c-1", undefined, true],
["e: row without the member, given c-1 — another creation of the same id loses", "absent", "c-1", false],
["f: row without the member, given null, wins", "absent", null, true],
["g: row without the member, given none, wins", "absent", undefined, true],
["h: a stored JSON null, given null, wins", "json-null", null, true],
["i: a stored JSON null, given c-1 — another creation of the same id loses", "json-null", "c-1", false],
["j: a stored JSON null, given none, wins", "json-null", undefined, true],
];
for (const [name, live, given, wins] of cells) {
run(`update compares the creation it read (expect.creationId), the rev matching — ${name}`, async () => {
const store = make();
const base = createWorkflowRun({ id: "cid", status: "failed", error: "parked" });
const stored = live === "c-1" ? { ...base, creationId: "c-1" } : live === "json-null" ? readStoredWorkflowRun(JSON.parse(JSON.stringify({ ...base, creationId: null })), { key: "cid" }) : base;
await store.put("cid", stored);
const before = (await store.get("cid"));
const expect = given === undefined ? { rev: before.rev ?? 0 } : { rev: before.rev ?? 0, creationId: given };
const written = { ...before, result: "written" };
assert.equal(await store.update("cid", "tenant-a", written, expect), wins, `${name}: the write ${wins ? "wins" : "loses"}`);
const after = (await store.get("cid"));
if (wins) {
assert.equal(after.rev, (before.rev ?? 0) + 1, `${name}: the winning write bumps rev`);
assert.equal(after.result, "written", `${name}: the winning write is persisted`);
}
else {
assert.deepEqual(after, before, `${name}: the losing write changes nothing (rev and the whole row as they were)`);
}
});
}
}
run("update with the creation matching and a stale rev loses — the creation id never stands in for the rev — and changes nothing", async () => {
const store = make();
await store.put("cid-rev", createWorkflowRun({ id: "cid-rev", status: "running", creationId: "c-1" }));
const before = (await store.get("cid-rev"));
assert.equal(await store.update("cid-rev", "tenant-a", { ...before, status: "completed" }, { rev: (before.rev ?? 0) + 1, creationId: "c-1" }), false, "a rev ahead loses though the creation matches");
assert.deepEqual(await store.get("cid-rev"), before, "the losing write changes nothing");
assert.equal(await store.update("cid-rev", "tenant-a", { ...before, status: "completed" }, { rev: before.rev ?? 0, creationId: "c-1" }), true, "the current rev and creation win");
});
run("update of a FINISHED run compares and sets on rev like any other: the current rev wins and bumps, a stale one loses", async () => {
const store = make();
const entry = { callKey: "1:g", sessionId: "child-1", token: "tok-1", originRunId: "fin", parkedBy: "fin", generation: 1 };
const finished = createWorkflowRun({ id: "fin", status: "failed", error: "parked", errorCode: "workflow.agent_parked", parks: [entry] });
await store.put(finished.id, finished);
const got = await store.get("fin");
assert.ok(got);
const passed = { ...got, parks: [{ ...entry, passedTo: "fin-next" }] };
assert.equal(await store.update("fin", "tenant-a", passed, { rev: got.rev ?? 0 }), true, "the current rev wins on a finished row");
const after = await store.get("fin");
assert.equal(after.rev, (got.rev ?? 0) + 1, "the write bumps rev");
assert.equal(after.status, "failed");
assert.equal(after.errorCode, "workflow.agent_parked");
assert.deepEqual(after.parks, [{ ...entry, passedTo: "fin-next" }], "the park entry keeps the member written on it");
assert.equal(await store.update("fin", "tenant-a", { ...passed, parks: [{ ...entry, passedTo: "fin-other" }] }, { rev: got.rev ?? 0 }), false, "the same expectation loses once the row moved");
assert.deepEqual((await store.get("fin")).parks, [{ ...entry, passedTo: "fin-next" }], "a lost write changes nothing");
});
run("update never moves a terminal run (completed, failed or killed) back to running: the write loses and changes nothing", async () => {
const store = make();
for (const status of ["completed", "failed", "killed"]) {
const id = `term-${status}`;
await store.put(id, createWorkflowRun({ id, status, creationId: `c-${status}`, ...(status === "killed" ? { stoppedBy: "ops" } : {}) }));
const before = (await store.get(id));
const backToRunning = { ...before, status: "running", endedAt: undefined };
assert.equal(await store.update(id, "tenant-a", backToRunning, { rev: before.rev ?? 0 }), false, `${status} -> running loses with matching rev`);
assert.equal(await store.update(id, "tenant-a", backToRunning, { rev: before.rev ?? 0, creationId: `c-${status}` }), false, `${status} -> running loses with matching rev and creationId`);
assert.equal(await store.update(id, "tenant-a", backToRunning), false, `${status} -> running loses without expect`);
for (const cause of WORKFLOW_RUN_UPDATE_CAUSES) {
assert.equal(await store.update(id, "tenant-a", backToRunning, { rev: before.rev ?? 0, creationId: `c-${status}` }, { cause }), false, `${status} -> running loses with cause ${cause}`);
}
assert.deepEqual(await store.get(id), before, `${status} row is untouched after refused writes`);
}
});
run("an update stating a cause persists the same row as one stating none, and wins and loses on rev, scope and a missing row the same way", async () => {
const store = make();
for (const cause of WORKFLOW_RUN_UPDATE_CAUSES) {
for (const order of ["passed first", "passed second"]) {
const tag = `${cause}-${order === "passed first" ? "a" : "b"}`;
const entryPassed = { callKey: "1:g", sessionId: "child-1", token: `tok-${tag}-1`, originRunId: "origin-run", parkedBy: "holder-run", generation: 1 };
const entryOther = { callKey: "2:h", sessionId: "child-2", token: `tok-${tag}-2`, originRunId: "origin-run", parkedBy: "holder-run", generation: 1 };
const entries = order === "passed first" ? [entryPassed, entryOther] : [entryOther, entryPassed];
const fixture = (id) => createWorkflowRun({ id, status: "failed", error: "parked", errorCode: "workflow.agent_parked", parks: entries.map((e) => ({ ...e })) });
const [plainId, markedId] = [`plain-${tag}`, `marked-${tag}`];
await store.put(plainId, fixture(plainId));
await store.put(markedId, fixture(markedId));
const [plain, marked] = [(await store.get(plainId)), (await store.get(markedId))];
const passed = (got) => ({ ...got, parks: got.parks.map((p) => (p.callKey === entryPassed.callKey ? { ...p, passedTo: "fin-next" } : p)) });
const asWritten = entries.map((e) => (e === entryPassed ? { ...e, passedTo: "fin-next" } : { ...e }));
assert.equal(await store.update(plainId, "tenant-a", passed(plain), { rev: plain.rev ?? 0 }), true, `the write without a cause wins (${order})`);
assert.equal(await store.update(markedId, "tenant-a", passed(marked), { rev: marked.rev ?? 0 }, { cause }), true, `the same write stating ${cause} wins (${order})`);
const [afterPlain, afterMarked] = [(await store.get(plainId)), (await store.get(markedId))];
assert.deepEqual({ ...afterMarked, id: plainId }, afterPlain, `the row written with ${cause} is the row written without it, rev included (${order})`);
assert.deepEqual(afterPlain.parks, asWritten, `the write without a cause leaves the passed entry with the member and the other entry as it was (${order})`);
assert.deepEqual(afterMarked.parks, asWritten, `the entry the write passed carries the member it added and every member it had, as written, and the other entry carries none of it — a write stating ${cause} puts the member on no other entry (${order})`);
assert.equal(await store.update(markedId, "tenant-a", passed(marked), { rev: marked.rev ?? 0 }, { cause }), false, `a stale rev loses with a cause (${order})`);
assert.equal(await store.update(markedId, "tenant-b", passed(afterMarked), { rev: afterMarked.rev ?? 0 }, { cause }), false, `another scope loses with a cause (${order})`);
assert.equal(await store.update(`ghost-${tag}`, "tenant-a", createWorkflowRun({ id: `ghost-${tag}` }), undefined, { cause }), false, `a missing row is not created by a write stating a cause (${order})`);
assert.deepEqual(await store.get(markedId), afterMarked, `the lost writes changed nothing (${order})`);
assert.equal(await store.get(`ghost-${tag}`), null);
}
}
});
run("get answers every stored member — a park entry's unknown member included — and writing back what get returned loses nothing (a store whose get answers less loses those members on that write-back)", async () => {
const store = make();
const entry = { callKey: "1:g", sessionId: "child-1", token: "tok-1", originRunId: "full", parkedBy: "full", generation: 2, futureMember: { kept: true } };
const full = createWorkflowRun({
id: "full",
status: "failed",
error: "workflow agent \"g\" is parked",
errorCode: "workflow.agent_parked",
result: "partial",
completionId: "completion-1",
originatingSessionId: "sess-1",
resume: { fromRunId: "earlier", journalEntries: 2, replayed: 1 },
parks: [entry],
});
await store.put(full.id, full);
const got = await store.get("full");
assert.ok(got);
assert.deepEqual(got, { ...full, rev: got.rev }, "get answers what put stored, every member");
assert.equal(await store.update("full", "tenant-a", got, { rev: got.rev ?? 0 }), true);
const again = await store.get("full");
assert.deepEqual(again, { ...full, rev: (got.rev ?? 0) + 1 }, "writing back what get returned keeps every member");
});
run("a park entry's settledDecisions written on a FINISHED run (cause park_decision_settled) comes back from get as written, on that entry alone, and survives the next write of the record", async () => {
const store = make();
const held = { callKey: "1:g", sessionId: "child-1", token: "tok-held", originRunId: "fin-s", parkedBy: "fin-s", generation: 1 };
const other = { callKey: "2:h", sessionId: "child-2", token: "tok-other", originRunId: "fin-s", parkedBy: "fin-s", generation: 1 };
const finished = createWorkflowRun({ id: "fin-s", status: "failed", error: "parked", errorCode: "workflow.agent_parked", parks: [held, other] });
await store.put(finished.id, finished);
const got = (await store.get("fin-s"));
const settled = [
{ decisionId: "dec-a", reason: "denied", code: "persisted_rule" },
{ decisionId: "dec-b", reason: "launch_unreadable" },
];
const written = { ...got, parks: got.parks.map((p) => (p.token === held.token ? { ...p, settledDecisions: settled.map((s) => ({ ...s })) } : p)) };
assert.equal(await store.update("fin-s", "tenant-a", written, { rev: got.rev ?? 0 }, { cause: "park_decision_settled" }), true, "the current rev wins on a finished row");
const after = (await store.get("fin-s"));
assert.deepEqual(after.parks, [{ ...held, settledDecisions: settled }, other], "the entry carries the member as written (order, each member, an absent code absent), and the other entry carries none of it");
assert.equal(after.status, "failed");
assert.equal(after.errorCode, "workflow.agent_parked");
assert.equal(after.rev, (got.rev ?? 0) + 1, "the write bumps rev");
const passed = { ...after, parks: after.parks.map((p) => (p.token === other.token ? { ...p, passedTo: "fin-s-next" } : p)) };
assert.equal(await store.update("fin-s", "tenant-a", passed, { rev: after.rev ?? 0 }, { cause: "park_pass" }), true);
assert.deepEqual((await store.get("fin-s")).parks, [{ ...held, settledDecisions: settled }, { ...other, passedTo: "fin-s-next" }], "a later write of what get returned keeps the member");
});
run("a recoverable mark's condition and inputs on a park entry's settledDecisions come back from get as written, and a mark replaced in a later write is replaced", async () => {
const store = make();
const held = { callKey: "1:g", sessionId: "child-1", token: "tok-held", originRunId: "fin-c", parkedBy: "fin-c", generation: 1 };
const finished = createWorkflowRun({ id: "fin-c", status: "failed", error: "parked", errorCode: "workflow.agent_parked", parks: [held] });
await store.put(finished.id, finished);
const got = (await store.get("fin-c"));
const first = [{ decisionId: "dec-a", reason: "host_changed", inputs: ["model", "tools"], condition: "0123456789abcdef0123456789abcdef" }];
const written = { ...got, parks: got.parks.map((p) => ({ ...p, settledDecisions: first.map((s) => ({ ...s, inputs: [...s.inputs] })) })) };
assert.equal(await store.update("fin-c", "tenant-a", written, { rev: got.rev ?? 0 }, { cause: "park_decision_settled" }), true);
const after = (await store.get("fin-c"));
assert.deepEqual(after.parks, [{ ...held, settledDecisions: first }], "condition and inputs come back as written");
const replaced = [{ decisionId: "dec-a", reason: "launch_unrecorded", condition: "fedcba9876543210fedcba9876543210" }];
const next = { ...after, parks: after.parks.map((p) => ({ ...p, settledDecisions: replaced.map((s) => ({ ...s })) })) };
assert.equal(await store.update("fin-c", "tenant-a", next, { rev: after.rev ?? 0 }, { cause: "park_decision_settled" }), true);
assert.deepEqual((await store.get("fin-c")).parks, [{ ...held, settledDecisions: replaced }], "the replaced mark alone, with no inputs left over");
});
run("a run's decision account (decisions) comes back from get as written through put and update, an absent code absent", async () => {
const store = make();
const decisions = [
{ ordinal: 1, callKey: "1:g", decisionId: "dec-a", result: "refused", code: "checkpoint.gate_mismatch" },
{ ordinal: 2, callKey: "2:h", decisionId: "dec-b", result: "driven" },
];
const run = createWorkflowRun({ id: "acct", status: "running" });
await store.put(run.id, { ...run, decisions: [decisions[0]] });
const got = (await store.get("acct"));
assert.deepEqual(got.decisions, [decisions[0]], "put keeps it");
assert.equal(await store.update("acct", "tenant-a", { ...got, status: "completed", decisions: decisions.map((d) => ({ ...d })) }, { rev: got.rev ?? 0 }), true);
assert.deepEqual((await store.get("acct")).decisions, decisions, "update keeps it, in order, an absent code absent");
});
run("a member row's ending object and the roster-full refusal count come back as written through put, get and update, and an absent one stays absent", async () => {
const store = make();
const createdAt = 1_000;
const row = (label, status, outcome) => ({ label, callKey: `0:${label}`, phase: "build", status, queuedAt: createdAt, startedAt: createdAt, endedAt: createdAt + 4, ...(outcome !== undefined ? { outcome } : {}) });
const ledgered = createWorkflowRun({
id: "ledgered",
status: "failed",
errorCode: "workflow.max_agents",
refusedAtMemberCap: 2,
agents: [
row("done", "completed", { kind: "workflow_member", outcome: "completed", provenance: "live" }),
row("refused", "failed", { kind: "workflow_member", outcome: "budget_refused", code: "workflow.budget_exceeded", provenance: "live" }),
row("stopped", "failed", { kind: "workflow_member", outcome: "killed", stoppedBy: "parent", provenance: "replayed", refused: { haltedByPerson: true } }),
row("older", "completed"),
],
});
const bare = createWorkflowRun({ id: "bare" });
await store.put(ledgered.id, ledgered);
await store.put(bare.id, bare);
const got = await store.get("ledgered");
assert.ok(got);
assert.deepEqual(got, { ...ledgered, rev: got.rev }, "get answers each row's ending object and the refusal count as put wrote them");
assert.equal(Object.hasOwn(got.agents[3], "outcome"), false, "a row written without an ending object comes back without the member");
const bareGot = await store.get("bare");
assert.ok(bareGot);
assert.equal(Object.hasOwn(bareGot, "refusedAtMemberCap"), false, "a run written without the refusal count comes back without the member");
assert.ok(bareGot.agents.every((a) => !Object.hasOwn(a, "outcome")), "rows written without an ending object come back without the member");
const next = { ...got, refusedAtMemberCap: 3, agents: got.agents.map((a) => (a.label === "older" ? { ...a, outcome: { kind: "workflow_member", outcome: "completed", provenance: "live" } } : a)) };
assert.equal(await store.update("ledgered", "tenant-a", next, { rev: got.rev ?? 0 }), true);
assert.deepEqual(await store.get("ledgered"), { ...next, rev: (got.rev ?? 0) + 1 }, "an update's ending objects and refusal count come back as written");
assert.equal(await store.update("bare", "tenant-a", bareGot, { rev: bareGot.rev ?? 0 }), true);
const bareAgain = await store.get("bare");
assert.equal(Object.hasOwn(bareAgain, "refusedAtMemberCap"), false, "writing back a run without the refusal count keeps it absent");
assert.ok(bareAgain.agents.every((a) => !Object.hasOwn(a, "outcome")), "writing back rows without an ending object keeps it absent");
});
run("the key id is authoritative — a payload with a mismatched id never poisons the projection", async () => {
const store = make();
const r = createWorkflowRun({ id: "real", status: "running" });
await store.put("real", { ...r, id: "spoofed" });
assert.equal((await store.get("real")).id, "real");
assert.equal(await store.get("spoofed"), null);
await store.update("real", r.scope, { ...r, id: "spoofed-again", status: "completed" });
assert.equal((await store.get("real")).id, "real");
const listed = await store.listByScope(r.scope);
assert.ok(listed.every((s) => s.id === "real"));
});
run("the anonymous working scope is a scope like any other: a run filed under ANONYMOUS_SCOPE lists and updates under no other name, and a named scope's run never lists under it", async () => {
const store = make();
const anon = createWorkflowRun({ id: "r-anon", scope: ANONYMOUS_SCOPE, createdAt: 2_000 });
const named = createWorkflowRun({ id: "r-named", scope: "tenant-a", createdAt: 1_000 });
for (const r of [anon, named])
await store.put(r.id, r);
assert.deepEqual(readableRows(await store.listByScope(ANONYMOUS_SCOPE)).map((s) => s.id), ["r-anon"]);
assert.deepEqual(readableRows(await store.listByScope("tenant-a")).map((s) => s.id), ["r-named"]);
assert.equal(await store.update("r-anon", "tenant-a", { ...anon, status: "failed" }), false, "another scope never writes an anonymous run");
assert.equal(await store.update("r-named", ANONYMOUS_SCOPE, { ...named, status: "failed" }), false, "the anonymous scope never writes a named scope's run");
assert.equal(await store.update("r-anon", ANONYMOUS_SCOPE, { ...anon, status: "failed" }), true);
});
run("listByScope: history included (completed + failed + running), createdAt DESC, status filter + limit", async () => {
const store = make();
assert.deepEqual(await store.listByScope("tenant-a"), []);
const running = createWorkflowRun({ id: "r-run", status: "running", createdAt: 3_000, endedAt: undefined });
const done = createWorkflowRun({ id: "r-done", status: "completed", createdAt: 2_000 });
const failed = createWorkflowRun({ id: "r-fail", status: "failed", createdAt: 1_000 });
const other = createWorkflowRun({ id: "r-other", scope: "tenant-b", createdAt: 9_000 });
for (const r of [running, done, failed, other])
await store.put(r.id, r);
const all = readableRows(await store.listByScope("tenant-a"));
assert.deepEqual(all.map((s) => s.id), ["r-run", "r-done", "r-fail"]);
assert.deepEqual(all.map((s) => s.status), ["running", "completed", "failed"]);
assert.deepEqual((await store.listByScope("tenant-a", { status: "completed" })).map((s) => s.id), ["r-done"]);
assert.deepEqual((await store.listByScope("tenant-a", { status: "failed" })).map((s) => s.id), ["r-fail"]);
assert.deepEqual((await store.listByScope("tenant-a", { limit: 2 })).map((s) => s.id), ["r-run", "r-done"]);
assert.deepEqual(all.find((s) => s.id === "r-done"), summarizeWorkflowRun(done));
assert.equal(all.find((s) => s.id === "r-done").tokens, done.stats.tokens + done.stats.nested.tokens);
const doneSummary = all.find((s) => s.id === "r-done");
assert.equal(doneSummary.currentPhase, "build");
assert.equal(doneSummary.name, undefined);
assert.equal(doneSummary.description, undefined);
const named = createWorkflowRun({
id: "r-named", name: "find-flaky", description: "find flaky tests", createdAt: 4_000,
phases: [
{ title: "scan", status: "completed", startedAt: 4_000, endedAt: 4_001 },
{ title: "fix", status: "running", startedAt: 4_001 },
],
});
await store.put(named.id, named);
const namedSummary = readableRows(await store.listByScope("tenant-a")).find((s) => s.id === "r-named");
assert.equal(namedSummary.name, "find-flaky");
assert.equal(namedSummary.description, "find flaky tests");
assert.equal(namedSummary.currentPhase, "fix");
});
run("the ADDITIVE terminal disclosures reach the LIST row: agentFailures + budgetOvershoot project, and a clean run keeps both keys ABSENT", async () => {
const store = make();
const over = createWorkflowRun({ id: "d-over", createdAt: 5_000, agentFailures: 2, budgetOvershoot: { budgetTokens: 150, spentTokens: 1_200 } });
const unsettled = createWorkflowRun({ id: "d-unsettled", createdAt: 6_000, budgetOvershoot: { budgetTokens: 100, spentTokens: 0, unsettledTokens: 500 } });
const clean = createWorkflowRun({ id: "d-clean", createdAt: 7_000 });
for (const r of [over, unsettled, clean])
await store.put(r.id, r);
const byId = new Map(readableRows(await store.listByScope("tenant-a")).map((s) => [s.id, s]));
assert.equal(byId.get("d-over").agentFailures, 2);
assert.deepEqual(byId.get("d-over").budgetOvershoot, { budgetTokens: 150, spentTokens: 1_200 });
assert.deepEqual(byId.get("d-unsettled").budgetOvershoot, { budgetTokens: 100, spentTokens: 0, unsettledTokens: 500 });
assert.equal("agentFailures" in byId.get("d-clean"), false, "no failures ⇒ the key is OMITTED, not 0/null");
assert.equal("budgetOvershoot" in byId.get("d-clean"), false, "within (or without) a ceiling ⇒ the key is OMITTED, not null/zeroed");
assert.equal(byId.get("d-over").tokens, over.stats.tokens + over.stats.nested.tokens);
byId.get("d-over").budgetOvershoot.spentTokens = 7;
assert.equal((await store.get("d-over")).budgetOvershoot.spentTokens, 1_200);
});
run("the failure CODE reaches the LIST row verbatim, and a run without one keeps the key ABSENT", async () => {
const store = make();
const coded = createWorkflowRun({ id: "f-coded", status: "failed", createdAt: 5_000, error: "the body gave up", errorCode: "workflow.agent_blocked" });
const codeless = createWorkflowRun({ id: "f-codeless", status: "failed", createdAt: 6_000, error: "the body gave up" });
const ok = createWorkflowRun({ id: "f-ok", status: "completed", createdAt: 7_000 });
for (const r of [coded, codeless, ok])
await store.put(r.id, r);
const byId = new Map(readableRows(await store.listByScope("tenant-a")).map((s) => [s.id, s]));
assert.equal(byId.get("f-coded").errorCode, "workflow.agent_blocked");
assert.equal("errorCode" in byId.get("f-codeless"), false, "a failed run with no code ⇒ the key is OMITTED, not an `unknown` stand-in");
assert.equal("errorCode" in byId.get("f-ok"), false, "a completed run never carries one ⇒ the key is OMITTED");
assert.deepEqual(byId.get("f-coded"), summarizeWorkflowRun(coded));
});
run("the TOTAL-TIMEOUT disclosure reaches the LIST row: timeoutInterruption projects (de-aliased), and a run without it keeps the key ABSENT", async () => {
const store = make();
const seat = { timeoutMs: 600_000, agentsCompleted: 3, agentsFailed: 1, agentsInFlight: 2, approvalWaitedMs: 540_000 };
const cut = createWorkflowRun({ id: "d-timeout", createdAt: 8_000, status: "failed", error: "workflow total timeout", timeoutInterruption: seat });
const noWait = { timeoutMs: 600_000, agentsCompleted: 1, agentsFailed: 0, agentsInFlight: 1 };
const slow = createWorkflowRun({ id: "d-slow", createdAt: 8_050, status: "failed", error: "workflow total timeout", timeoutInterruption: noWait });
const threw = createWorkflowRun({ id: "d-threw", createdAt: 8_100, status: "failed", error: "script blew up" });
for (const r of [cut, slow, threw])
await store.put(r.id, r);
const byId = new Map(readableRows(await store.listByScope("tenant-a")).map((s) => [s.id, s]));
assert.deepEqual(byId.get("d-timeout").timeoutInterruption, seat);
assert.deepEqual(byId.get("d-slow").timeoutInterruption, noWait);
assert.equal("approvalWaitedMs" in byId.get("d-slow").timeoutInterruption, false, "a run nobody reported a wait for ⇒ the member is OMITTED, never stored as 0 (absence is 'not supplied', not 'nobody waited')");
assert.equal("timeoutInterruption" in byId.get("d-threw"), false, "a run its own error ended ⇒ the key is OMITTED, not null/zeroed");
byId.get("d-timeout").timeoutInterruption.agentsCompleted = 7;
assert.equal((await store.get("d-timeout")).timeoutInterruption.agentsCompleted, 3);
});
run("reap: only terminal runs, NEVER running; maxAgeMs + keep retention; no policy → no-op", async () => {
const store = make();
const running = createWorkflowRun({ id: "k-run", status: "running", createdAt: 100, endedAt: undefined });
const oldDone = createWorkflowRun({ id: "k-old", status: "completed", createdAt: 100, endedAt: 100 });
const newDone = createWorkflowRun({ id: "k-new", status: "completed", createdAt: 9_000, endedAt: 9_000 });
const oldFail = createWorkflowRun({ id: "k-fail", status: "failed", createdAt: 200, endedAt: 200 });
for (const r of [running, oldDone, newDone, oldFail])
await store.put(r.id, r);
assert.equal(await store.reap("tenant-a", 1_000_000), 0);
assert.equal(store2size(store) >= -1, true);
const reaped = await store.reap("tenant-a", 10_000, { maxAgeMs: 5_000 });
assert.equal(reaped, 2);
assert.equal(await store.get("k-old"), null);
assert.equal(await store.get("k-fail"), null);
assert.ok(await store.get("k-new"));
assert.ok(await store.get("k-run"));
});
run("reap keep-newest-N: deletes all but the newest N terminal runs; running excluded from the count", async () => {
const store = make();
const running = createWorkflowRun({ id: "p-run", status: "running", createdAt: 50, endedAt: undefined });
const t1 = createWorkflowRun({ id: "p-1", status: "completed", createdAt: 1_000 });
const t2 = createWorkflowRun({ id: "p-2", status: "completed", createdAt: 2_000 });
const t3 = createWorkflowRun({ id: "p-3", status: "failed", createdAt: 3_000 });
for (const r of [running, t1, t2, t3])
await store.put(r.id, r);
assert.equal(await store.reap("tenant-a", 99_999, { keep: 1 }), 2);
assert.equal(await store.get("p-1"), null);
assert.equal(await store.get("p-2"), null);
assert.ok(await store.get("p-3"));
assert.ok(await store.get("p-run"));
});
run("deleteRun deletes one terminal run of the scope and answers true; a running run, another scope's and a missing one answer false and stay", async () => {
const store = make();
if (store.deleteRun === undefined)
return;
const done = createWorkflowRun({ id: "d-done" });
const failed = createWorkflowRun({ id: "d-failed", status: "failed" });
const running = createWorkflowRun({ id: "d-run", status: "running", endedAt: undefined });
const other = createWorkflowRun({ id: "d-other", scope: "tenant-b" });
for (const r of [done, failed, running, other])
await store.put(r.id, r);
assert.equal(await store.deleteRun("d-done", "tenant-a"), true);
assert.equal(await store.get("d-done"), null);
assert.equal(await store.deleteRun("d-failed", "tenant-a"), true);
assert.equal(await store.deleteRun("d-run", "tenant-a"), false, "a running run is never deleted");
assert.ok(await store.get("d-run"));
assert.equal(await store.deleteRun("d-other", "tenant-a"), false, "another scope's run is not this call's");
assert.ok(await store.get("d-other"));
assert.equal(await store.deleteRun("d-done", "tenant-a"), false, "a repeat answers false");
assert.equal(await store.deleteRun("never", "tenant-a"), false);
assert.deepEqual(readableRows(await store.listByScope("tenant-a")).map((s) => s.id), ["d-run"]);
await store.settleErasure?.();
await store.settleErasure?.();
assert.deepEqual(readableRows(await store.listByScope("tenant-a")).map((s) => s.id), ["d-run"]);
assert.ok(await store.get("d-other"), "the batch's end deletes nothing of its own");
});
run("a killed run is terminal: the status filter finds it, it never moves back to running, and reap, deleteRun and deleteBySession take it", async () => {
const store = make();
const killed = (id, over = {}) => createWorkflowRun({ id, status: "killed", stoppedBy: "ops", error: "stopped", ...over });
await store.put("kd-old", killed("kd-old", { createdAt: 100, endedAt: 100 }));
await store.put("kd-new", killed("kd-new", { createdAt: 9_000, endedAt: 9_000 }));
await store.put("kd-run", createWorkflowRun({ id: "kd-run", status: "running", createdAt: 100, endedAt: undefined }));
assert.deepEqual(readableRows(await store.listByScope("tenant-a", { status: "killed" })).map((s) => s.id), ["kd-new", "kd-old"]);
const before = (await store.get("kd-new"));
assert.equal(before.stoppedBy, "ops");
assert.equal(await store.update("kd-new", "tenant-a", { ...before, status: "running", endedAt: undefined, stoppedBy: undefined }, { rev: before.rev ?? 0 }), false, "killed -> running loses");
assert.deepEqual(await store.get("kd-new"), before);
assert.equal(await store.reap("tenant-a", 10_000, { maxAgeMs: 5_000 }), 1);
assert.equal(await store.get("kd-old"), null);
if (store.deleteRun !== undefined) {
assert.equal(await store.deleteRun("kd-new", "tenant-a"), true);
await store.settleErasure?.();
assert.equal(await store.get("kd-new"), null);
}
if (store.deleteBySession !== undefined) {
await store.put("kd-sess", killed("kd-sess", { originatingSessionId: "sess-k" }));
assert.deepEqual(await store.deleteBySession("sess-k", "tenant-a"), ["kd-sess"]);
await store.settleErasure?.();
assert.equal(await store.get("kd-sess"), null);
}
assert.ok(await store.get("kd-run"), "a running run stays");
});
const plantRow = hooks?.plantRow;
if (plantRow !== undefined) {
const SENTINEL = "planted-marker-1023";
const forged = (over) => ({ ...JSON.parse(JSON.stringify(createWorkflowRun({ id: "bad", createdAt: 1_000, originatingSessionId: "sess-1", description: SENTINEL }))), ...over });
const damaged = [
["phases not a list", { phases: 42 }],
["stats without the nested tally", { stats: { tokens: 1, turns: 1, costMicroUsd: 1 } }],
["rev not a count", { rev: "7" }],
["agents' status outside the set", { agents: [{ status: "paused-later" }] }],
];
const codeOf = (e) => (typeof e === "object" && e !== null ? Reflect.get(e, "code") : undefined);
const refused = (e) => codeOf(e) === WORKFLOW_RUN_ROW_MALFORMED_CODE && !thrownText(e).includes(SENTINEL);
for (const [what, over] of damaged) {
run(`damaged run (${what}): listed as its id and verdict, the other run intact; get and update refuse in the family code quoting nothing planted; deletion by its session, and retention over its readable stamps, remove it`, async () => {
const seeded = make();
const good = createWorkflowRun({ id: "good", createdAt: 2_000 });
await seeded.put(good.id, good);
const store = await plantRow(seeded, "bad", forged(over));
try {
const listed = await store.listByScope("tenant-a");
assert.deepEqual(listed.map((s) => s.id), ["good", "bad"]);
const bad = listed[1];
assert.ok("rowVerdict" in bad && bad.rowVerdict.code === WORKFLOW_RUN_ROW_MALFORMED_CODE, "the planted run is listed as damaged");
assert.ok(!JSON.stringify(listed).includes(SENTINEL), "the listing carries no planted value");
await assert.rejects(store.get("bad"), refused, "get refuses in the family code");
await assert.rejects(store.update("bad", "tenant-a", createWorkflowRun({ id: "bad", status: "failed" })), refused, "update refuses in the family code");
if (store.deleteBySession !== undefined) {
assert.deepEqual(await store.deleteBySession("sess-1", "tenant-a"), ["bad"], "deletion by its session goes on");
assert.deepEqual((await store.listByScope("tenant-a")).map((s) => s.id), ["good"]);
}
else {
assert.equal(await store.reap("tenant-a", 1e12, { keep: 0 }), 2, "retention over readable stamps deletes it with the readable run");
}
}
finally {
store.close?.();
}
});
}
}
await Promise.all(pending);
}
function defaultSequentialRunner(_name, fn) {
return fn();
}
function store2size(store) {
const s = store.size;
return typeof s === "number" ? s : -1;
}