@sema-agent/core
Version:
Stateless, task-oriented AI agent core
427 lines (426 loc) • 30.5 kB
JavaScript
import { strict as assert } from "node:assert";
import { randomUUID } from "node:crypto";
import { peerSessionBoxHandle } from "../../agents/peer-directory.js";
import { SessionError } from "../../internal/harness.js";
import { thrownText } from "../thrown-value.js";
import { fileHistoryScopeOf } from "../../engine/session/repo-utils.js";
import { RETENTION_CASCADE, RETENTION_SESSION_TREE_STEPS } from "../retention.js";
import { beginContract } from "./contract-harness.js";
const endOf = (call) => call.end ?? Number.POSITIVE_INFINITY;
const lastEnd = (calls) => Math.max(...calls.map(endOf));
const firstStart = (calls) => Math.min(...calls.map((call) => call.start));
const HEALTHY = { adopt: "ok" };
const tokenOf = (era) => (era === "address" ? `${randomUUID()}.2` : randomUUID());
function freshScene(era = "address") {
const id = (what) => `kit-cascade-${what}-${randomUUID()}`;
return {
sessionId: id("session"),
owner: "kit-owner",
scope: "kit-scope",
occupant: tokenOf(era),
fork: id("fork"),
forkOccupant: tokenOf(era),
lateFork: id("late-fork"),
lateForkOccupant: tokenOf(era),
strayFork: id("stray-fork"),
strayForkOccupant: tokenOf("address"),
strayOrigin: tokenOf("address"),
other: id("other"),
run: id("run"),
otherRun: id("other-run"),
agent: id("agent"),
rosterAgent: id("roster-agent"),
rosterRootAgent: id("roster-root-agent"),
otherRosterAgent: id("other-roster-agent"),
otherRosterRootAgent: id("other-roster-root-agent"),
};
}
const READS = {
workflowRunStore: ["listByScope"],
backgroundAgentStore: ["listBySession"],
rosterStore: ["list"],
sessionStore: ["list", "headOf"],
};
const FENCE_PARTNERS = { retireRecipient: ["listRetiredRecipients"] };
function filtered(rows, opts, sessionOf) {
const query = typeof opts === "object" && opts !== null ? opts : {};
const kept = rows.filter((row) => (query.status === undefined || row.status === query.status) && (query.session === undefined || sessionOf === undefined || sessionOf(row) === query.session));
return typeof query.limit === "number" ? kept.slice(0, query.limit) : kept;
}
const GUARDED = new Set(RETENTION_SESSION_TREE_STEPS.flatMap((leg) => (leg.unreadable === undefined ? [] : [`${leg.store}.${leg.verb}`])));
const UNREADABLE_VERBS = new Set(RETENTION_SESSION_TREE_STEPS.flatMap((leg) => (leg.unreadable === undefined ? [] : [`${leg.store}.${leg.unreadable}`])));
const unreadableHead = (sessionId, form = "no_header") => {
const said = `kit: the head of session "${sessionId}" cannot be read in this case`;
return form === "bad_entry" ? new SessionError("corrupt_session", said, undefined, "bad_entry") : new SessionError("corrupt_session", said, undefined, "no_header");
};
function answer(call, scene, variant) {
const { seat, verb, args } = call;
if (variant.failing === `${seat}.${verb}`)
throw new Error(`kit: ${seat}.${verb} fails in this case`);
if (variant.unreadable === true && args[0] === scene.sessionId && (GUARDED.has(`${seat}.${verb}`) || `${seat}.${verb}` === "sessionStore.headOf"))
throw unreadableHead(scene.sessionId, variant.headForm);
if (UNREADABLE_VERBS.has(`${seat}.${verb}`)) {
if (variant.unreadable !== true || args[0] !== scene.sessionId)
return seat === "sessionStore" ? false : 0;
return seat === "sessionStore" ? true : 1;
}
switch (`${seat}.${verb}`) {
case "workflowRunStore.listByScope": {
const runs = [
{ id: scene.run, scope: scene.scope, originatingSessionId: scene.sessionId, status: "completed", phaseCount: 1, createdAt: 2 },
{ id: scene.otherRun, scope: scene.scope, originatingSessionId: scene.other, status: "completed", phaseCount: 1, createdAt: 1 },
];
return filtered(runs, args[1], (run) => run.originatingSessionId);
}
case "workflowRunStore.deleteBySession":
return args[0] === scene.sessionId ? [scene.run] : [];
case "backgroundAgentStore.deleteBySession":
return args[0] === scene.scope && args[1] === scene.sessionId ? [scene.agent] : [];
case "peerTaskStore.deleteBySession":
return [];
case "workflowJournalStore.deleteRun":
case "workflowScriptStore.deleteRun":
case "mailboxStore.retireRecipient":
case "sessionStore.delete":
return true;
case "backgroundAgentStore.listBySession":
return args[1] === scene.sessionId
? filtered([{ handle: scene.agent, owner: scene.owner, sessionScoped: false, parentSessionId: scene.sessionId, rootSessionId: scene.sessionId, name: "kit-agent", status: "completed", spawnedAt: 1, updatedAt: 2, settledAt: 2, rev: 1 }], args[2])
: [];
case "mailboxStore.listRetiredRecipients":
return [];
case "rosterStore.list":
return [
{ name: "kit-agent", agentId: scene.rosterAgent, sessionId: scene.sessionId, createdAt: 1 },
{ name: "kit-bg-agent", agentId: scene.rosterRootAgent, rootSessionId: scene.sessionId, createdAt: 1 },
{ name: "kit-other", agentId: scene.otherRosterAgent, sessionId: scene.other, createdAt: 1 },
{ name: "kit-other-bg-agent", agentId: scene.otherRosterRootAgent, rootSessionId: scene.other, createdAt: 1 },
];
case "checkpointStore.deleteSessionCheckpoints":
case "fileHistoryStore.deleteBySession":
return 1;
case "toolResultStore.deleteBySession":
return { deleted: 1, unattributable: 0 };
case "fileHistoryStore.adoptScope":
if (variant.adopt === "throws")
throw new Error("kit: the file-history carry throws in this case");
if (variant.adopt === "ok")
return { ok: true };
return { ok: false, error: { code: variant.adopt === "conflict" ? "conflict" : "adopt_failed", message: `kit: the carry answers ${variant.adopt}` } };
case "sessionStore.list": {
const after = args[0]?.after;
if (after !== undefined)
return [];
const occupants = (incarnation, forkedFromIncarnation) => (variant.listWithoutOccupants === true ? {} : { incarnation, forkedFromIncarnation });
return [
{ sessionId: scene.fork, lastActiveAt: 5, forkedFrom: scene.sessionId, ...occupants(scene.forkOccupant, scene.occupant) },
{ sessionId: scene.lateFork, lastActiveAt: 4, forkedFrom: scene.sessionId, ...occupants(scene.lateForkOccupant, null) },
{ sessionId: scene.strayFork, lastActiveAt: 3, forkedFrom: scene.sessionId, ...occupants(scene.strayForkOccupant, scene.strayOrigin) },
...(variant.unreadable === true ? [] : [{ sessionId: scene.sessionId, lastActiveAt: 2, ...occupants(scene.occupant, null) }]),
{ sessionId: scene.other, lastActiveAt: 1, ...occupants(tokenOf("address"), null) },
];
}
case "sessionStore.headOf":
if (args[0] === scene.sessionId)
return { owner: scene.owner, incarnation: scene.occupant, leafId: null };
return [scene.fork, scene.lateFork, scene.strayFork, scene.other].includes(String(args[0])) ? { owner: scene.owner, leafId: null } : undefined;
default:
return undefined;
}
}
function recorder(seat, verb, journal, clock, scene, variant) {
return async (...args) => {
const call = { seat, verb, args, start: ++clock.ticks, end: undefined };
journal.push(call);
await new Promise((resolve) => setImmediate(resolve));
try {
return answer(call, scene, variant);
}
finally {
call.end = ++clock.ticks;
}
};
}
function exemptSeat(seat, journal, clock) {
return new Proxy({}, {
get: (_target, key) => typeof key !== "string" || key === "then" || key === "retention"
? undefined
: (...args) => void journal.push({ seat, verb: key, args, start: ++clock.ticks, end: ++clock.ticks }),
});
}
function storeRowOf(seat) {
return RETENTION_CASCADE[seat];
}
const SEATS = Object.entries(RETENTION_CASCADE).flatMap(([key, row]) => ("heldBy" in row ? [] : [key]));
function recordingStores(journal, clock, scene, variant) {
const entries = SEATS.map((seat) => {
const row = storeRowOf(seat);
if ("exempt" in row)
return [seat, exemptSeat(seat, journal, clock)];
const verbs = new Set(READS[seat] ?? []);
for (const leg of RETENTION_SESSION_TREE_STEPS) {
if (leg.store !== seat)
continue;
verbs.add(leg.verb);
if (leg.unreadable !== undefined)
verbs.add(leg.unreadable);
if (leg.fence !== undefined && variant.withoutFence !== true)
for (const v of [leg.fence, ...(FENCE_PARTNERS[leg.fence] ?? [])])
verbs.add(v);
}
const members = Object.fromEntries([...verbs].filter((verb) => variant.without !== `${seat}.${verb}`).map((verb) => [verb, recorder(seat, verb, journal, clock, scene, variant)]));
return [seat, Object.assign({}, members)];
});
return Object.assign({}, Object.fromEntries(entries));
}
function labelsOf(legs) {
const seen = new Map();
return legs.map((leg) => {
const key = `${leg.store}.${leg.verb}`;
const n = seen.get(key) ?? 0;
seen.set(key, n + 1);
return `${key}#${n}`;
});
}
function names(value, key) {
if (typeof value === "string")
return value === key;
if (Array.isArray(value))
return value.some((v) => names(v, key));
if (typeof value === "object" && value !== null)
return Object.values(value).some((v) => names(v, key));
return false;
}
const ownerOf = (guard) => (typeof guard === "object" && guard !== null ? guard.owner : undefined);
const historyOf = (scene) => fileHistoryScopeOf(scene.sessionId, scene.occupant);
const forkScopeOf = (scene) => fileHistoryScopeOf(scene.fork, scene.forkOccupant);
const untouchedScopesOf = (scene) => [fileHistoryScopeOf(scene.lateFork, scene.lateForkOccupant), fileHistoryScopeOf(scene.strayFork, scene.strayForkOccupant)];
function legReadings(scene) {
const s = scene.sessionId;
const box = peerSessionBoxHandle(s);
return {
"workflowJournalStore.deleteRun#0": (c) => c.args[0] === scene.run && c.args[1] === scene.scope,
"workflowScriptStore.deleteRun#0": (c) => c.args[0] === scene.run && c.args[1] === scene.scope,
"workflowRunStore.deleteBySession#0": (c) => c.args[0] === s && c.args[1] === scene.scope,
"mailboxStore.drop#0": (c) => c.args[0] === scene.scope && c.args[1] === scene.agent,
"backgroundAgentStore.deleteBySession#0": (c) => c.args[0] === scene.scope && c.args[1] === s,
"rosterStore.releaseAgent#0": (c) => c.args[0] === scene.rosterAgent || c.args[0] === scene.rosterRootAgent,
"checkpointStore.deleteSessionCheckpoints#0": (c) => c.args[0] === s && ownerOf(c.args[1]) === scene.owner,
"toolResultStore.deleteBySession#0": (c) => c.args[0] === s,
"sessionPolicyStore.deleteBySession#0": (c) => c.args[0] === s,
"fileHistoryStore.adoptScope#0": (c) => c.args[0] === historyOf(scene) && c.args[1] === forkScopeOf(scene),
"fileHistoryStore.deleteBySession#0": (c) => c.args[0] === historyOf(scene),
"mailboxStore.drop#1": (c) => c.args[0] === scene.scope && c.args[1] === box,
"taskListStore.drop#0": () => true,
"peerTaskStore.deleteBySession#0": (c) => c.args[0] === scene.scope && c.args[1] === s,
"sessionStore.delete#0": (c) => c.args[0] === s && ownerOf(c.args[1]) === scene.owner,
};
}
function legCalls(journal, scene) {
const readings = legReadings(scene);
const labels = labelsOf(RETENTION_SESSION_TREE_STEPS);
return RETENTION_SESSION_TREE_STEPS.map((leg, i) => {
const label = labels[i];
const reads = readings[label];
assert.ok(reads !== undefined, `the kit has no reading of the table's session-tree leg ${label} (step ${leg.step}) — the kit is older than the table`);
const at = journal.flatMap((call, k) => (call.seat === leg.store && call.verb === leg.verb && reads(call) ? [k] : []));
return { label, leg, at, calls: at.map((k) => journal[k]) };
});
}
function fenceCalls(journal) {
return RETENTION_SESSION_TREE_STEPS.flatMap((leg) => (leg.fence === undefined ? [] : journal.filter((call) => call.seat === leg.store && call.verb === leg.fence)));
}
async function drive(coordinator, variant, scene = freshScene()) {
const journal = [];
const del = coordinator(recordingStores(journal, { ticks: 0 }, scene, variant));
try {
await del({ sessionId: scene.sessionId, owner: scene.owner, scope: scene.scope });
return { journal, scene, rejected: undefined, ok: true };
}
catch (rejected) {
return { journal, scene, rejected, ok: false };
}
}
const describeJournal = (journal) => journal.map((c, k) => `${k}:${c.seat}.${c.verb}@${c.start}-${c.end ?? "open"}`).join(", ");
export async function sessionDeletionCascadeContract(coordinator, runAssertion) {
const { run, settle } = beginContract(runAssertion);
const destructive = new Set(RETENTION_SESSION_TREE_STEPS.flatMap((leg) => [
`${leg.store}.${leg.verb}`,
...(leg.fence === undefined ? [] : [`${leg.store}.${leg.fence}`]),
...(leg.unreadable === undefined ? [] : [`${leg.store}.${leg.unreadable}`]),
]));
run("every session-tree leg of the table is called, with the keys the leg selects", async () => {
const { journal, scene, rejected, ok } = await drive(coordinator, HEALTHY);
assert.ok(ok, `the deletion rejected over healthy stores: ${String(rejected)}`);
for (const { label, leg, at } of legCalls(journal, scene)) {
assert.ok(at.length > 0, `leg ${label} (step ${leg.step}: ${leg.selects}) was never called — calls: ${describeJournal(journal)}`);
}
});
run("the roster leg releases the agent whose entry names the session as its session and the agent whose entry names it as its root session", async () => {
const variants = [HEALTHY, { adopt: "ok", unreadable: true }];
for (const variant of variants) {
const { journal, scene, rejected, ok } = await drive(coordinator, variant);
if (variant.unreadable === true && !journal.some((c) => destructive.has(`${c.seat}.${c.verb}`)))
continue;
assert.ok(ok, `the deletion rejected: ${String(rejected)}`);
const released = journal.filter((c) => c.seat === "rosterStore" && c.verb === "releaseAgent").map((c) => c.args[0]);
assert.ok(released.includes(scene.rosterAgent), `the roster agent whose entry names the session as its session was never released — calls: ${describeJournal(journal)}`);
assert.ok(released.includes(scene.rosterRootAgent), `the roster agent whose entry names the session as its root session (the only session a plain background agent's entry names) was never released — calls: ${describeJournal(journal)}`);
}
});
run("every fence settles before the first step, each leg settles before the next begins, and the session row's leg is last — with the carry answering `ok` and `conflict`", async () => {
for (const carryAnswer of ["ok", "conflict"]) {
const { journal, scene, rejected, ok } = await drive(coordinator, { adopt: carryAnswer });
assert.ok(ok, `the deletion rejected when the carry answered ${carryAnswer}: ${String(rejected)}`);
const legs = legCalls(journal, scene);
const first = firstStart(legs.flatMap((l) => l.calls));
const fences = fenceCalls(journal);
const fenced = RETENTION_SESSION_TREE_STEPS.filter((leg) => leg.fence !== undefined);
assert.ok(fenced.length === 0 || fences.length > 0, `a store carrying the fence ${fenced.map((l) => `${l.store}.${l.fence}`).join(", ")} was never fenced — calls: ${describeJournal(journal)}`);
for (const fence of fences) {
assert.ok(endOf(fence) < first, `the fence ${fence.seat}.${fence.verb} had not settled when the first step began at tick ${first} (carry answering ${carryAnswer}) — calls: ${describeJournal(journal)}`);
assert.ok(fence.args[0] === scene.scope && fence.args[1] === peerSessionBoxHandle(scene.sessionId), `the fence ${fence.seat}.${fence.verb} names another box than the session's`);
}
for (let i = 1; i < legs.length; i++) {
const before = legs[i - 1];
const after = legs[i];
assert.ok(lastEnd(before.calls) < firstStart(after.calls), `leg ${before.label} (step ${before.leg.step}) had a call open after leg ${after.label} (step ${after.leg.step}) began (carry answering ${carryAnswer}) — calls: ${describeJournal(journal)}`);
}
}
});
run("an exempt store seat receives no call, and no destructive call names another session's rows or the fork beyond its carry", async () => {
const { journal, scene, rejected, ok } = await drive(coordinator, HEALTHY);
assert.ok(ok, `the deletion rejected over healthy stores: ${String(rejected)}`);
for (const call of journal) {
const row = storeRowOf(call.seat);
assert.ok("legs" in row, `${call.seat} is exempt (${"exempt" in row ? row.exempt : ""}) and received ${call.verb}`);
if (!destructive.has(`${call.seat}.${call.verb}`))
continue;
for (const key of [scene.other, scene.otherRun, scene.otherRosterAgent, scene.otherRosterRootAgent, scene.lateFork, scene.strayFork, ...untouchedScopesOf(scene)]) {
assert.ok(!names(call.args, key), `${call.seat}.${call.verb} named another session's row ${key}`);
}
const forkScope = forkScopeOf(scene);
const carry = call.seat === "fileHistoryStore" && call.verb === "adoptScope" && call.args[1] === forkScope && !names(call.args[0], forkScope) && !names(call.args[0], scene.fork);
assert.ok(carry || (!names(call.args, scene.fork) && !names(call.args, forkScope)), `${call.seat}.${call.verb} named the fork ${scene.fork} — a fork is named only as the file-history carry's target, by its own scope`);
}
});
run("history is named by its address: a session born before the address epoch has its bare-id scope carried and deleted, and the forks that recorded no source occupant or another occupant receive nothing", async () => {
for (const era of ["address", "pre-address"]) {
const { journal, scene, rejected, ok } = await drive(coordinator, HEALTHY, freshScene(era));
assert.ok(ok, `the deletion rejected over healthy stores (${era} session): ${String(rejected)}`);
const carries = journal.filter((c) => c.seat === "fileHistoryStore" && c.verb === "adoptScope");
const erases = journal.filter((c) => c.seat === "fileHistoryStore" && c.verb === "deleteBySession");
assert.deepEqual(carries.map((c) => c.args.slice(0, 2)), [[historyOf(scene), forkScopeOf(scene)]], `the carry is the session's scope into the one fork that recorded its occupant (${era} session) — calls: ${describeJournal(journal)}`);
assert.deepEqual(erases.map((c) => c.args[0]), [historyOf(scene)], `step 11 deletes the session's one scope (${era} session) — calls: ${describeJournal(journal)}`);
}
});
run("a session list whose rows lack the occupant keys fails the deletion before any history is carried or deleted, and the row stays", async () => {
const { journal, ok } = await drive(coordinator, { adopt: "ok", listWithoutOccupants: true });
assert.ok(!ok, `the deletion completed over list rows without incarnation / forkedFromIncarnation — calls: ${describeJournal(journal)}`);
const touched = journal.filter((c) => (c.seat === "fileHistoryStore" && (c.verb === "adoptScope" || c.verb === "deleteBySession")) || (c.seat === "sessionStore" && c.verb === "delete"));
assert.equal(touched.length, 0, `history or the row was touched though the list could not name the forks' scopes — calls: ${describeJournal(journal)}`);
});
run("the session's file history is carried into its fork before it is deleted; a carry refused `conflict` counts as done", async () => {
for (const adopt of ["ok", "conflict"]) {
const { journal, scene, rejected, ok } = await drive(coordinator, { adopt });
assert.ok(ok, `the deletion rejected when the carry answered ${adopt}: ${String(rejected)}`);
const legs = legCalls(journal, scene);
const carried = legs.find((l) => l.leg.store === "fileHistoryStore" && l.leg.verb === "adoptScope");
const erased = legs.find((l) => l.leg.store === "fileHistoryStore" && l.leg.verb === "deleteBySession");
const row = legs.find((l) => l.leg.store === "sessionStore" && l.leg.verb === "delete");
assert.ok(carried !== undefined && carried.at.length > 0, `the session's history was never carried into its fork (carry answering ${adopt}) — calls: ${describeJournal(journal)}`);
assert.ok(erased !== undefined && erased.calls.length > 0 && lastEnd(carried.calls) < firstStart(erased.calls), `the session's history was not deleted after its carry settled (carry answering ${adopt}) — calls: ${describeJournal(journal)}`);
assert.ok(row !== undefined && row.at.length > 0, `the session row was not deleted when the carry answered ${adopt} — calls: ${describeJournal(journal)}`);
}
});
run("a carry that fails any other way leaves the session's history and its row in place", async () => {
for (const adopt of ["failed", "throws"]) {
const { journal, scene } = await drive(coordinator, { adopt });
const left = journal.filter((c) => (c.seat === "fileHistoryStore" && c.verb === "deleteBySession" && c.args[0] === historyOf(scene)) || (c.seat === "sessionStore" && c.verb === "delete" && c.args[0] === scene.sessionId));
assert.equal(left.length, 0, `the carry ${adopt === "failed" ? "answered a failure" : "threw"} and the session's ${left.map((c) => `${c.seat}.${c.verb}`).join(" and ")} still ran — calls: ${describeJournal(journal)}`);
}
});
run("every call the coordinator makes, made to fail, leaves the session row — with the carry answering `ok` and `conflict` — and a repeat over healthy stores completes the cascade", async () => {
for (const adopt of ["ok", "conflict"]) {
const healthy = await drive(coordinator, { adopt });
assert.ok(healthy.ok, `the deletion rejected when the carry answered ${adopt}: ${String(healthy.rejected)}`);
const points = [...new Set(healthy.journal.map((c) => `${c.seat}.${c.verb}`))].filter((p) => p !== "sessionStore.delete");
for (const failing of points) {
const failed = await drive(coordinator, { adopt, failing }, healthy.scene);
const rowDeletes = failed.journal.filter((c) => c.seat === "sessionStore" && c.verb === "delete").length;
assert.ok(rowDeletes === 0, `${failing} failed (carry answering ${adopt}) and the session row was still deleted — calls: ${describeJournal(failed.journal)}`);
}
const repeat = await drive(coordinator, { adopt }, healthy.scene);
assert.ok(repeat.ok, `the repeat over healthy stores rejected (carry answering ${adopt}): ${String(repeat.rejected)}`);
for (const { label, at } of legCalls(repeat.journal, repeat.scene))
assert.ok(at.length > 0, `the repeat never called leg ${label} — calls: ${describeJournal(repeat.journal)}`);
}
});
run("a mailbox without the recipient-lifecycle pair still has the session's box dropped", async () => {
const { journal, scene, rejected, ok } = await drive(coordinator, { adopt: "ok", withoutFence: true });
assert.ok(ok, `the deletion rejected over a mailbox without the pair: ${String(rejected)}`);
for (const { label, at } of legCalls(journal, scene))
assert.ok(at.length > 0, `leg ${label} was never called over a mailbox without the pair — calls: ${describeJournal(journal)}`);
});
run("a session whose head cannot be read is never half-deleted: refused before any destructive call, or every leg called — a leg with an `unreadable` verb through it, never through its own — the session row's last", async () => {
const { journal, scene, rejected, ok } = await drive(coordinator, { adopt: "ok", unreadable: true });
const destroyed = journal.filter((c) => destructive.has(`${c.seat}.${c.verb}`));
if (destroyed.length === 0)
return;
assert.ok(ok, `the coordinator began deleting a session whose head cannot be read and then rejected — it is half-deleted: ${String(rejected)} — calls: ${describeJournal(journal)}`);
const readings = legReadings(scene);
const labels = labelsOf(RETENTION_SESSION_TREE_STEPS);
const spans = [];
RETENTION_SESSION_TREE_STEPS.forEach((leg, i) => {
const label = labels[i];
if (leg.unreadable !== undefined) {
const own = journal.filter((c) => c.seat === leg.store && c.verb === leg.verb);
assert.equal(own.length, 0, `leg ${label} was called through its own verb on a session whose head cannot be read — calls: ${describeJournal(journal)}`);
const twin = journal.filter((c) => c.seat === leg.store && c.verb === leg.unreadable && c.args[0] === scene.sessionId);
assert.ok(twin.length > 0, `leg ${label} was never called through ${leg.store}.${leg.unreadable} — calls: ${describeJournal(journal)}`);
spans.push(twin);
return;
}
const reads = readings[label];
assert.ok(reads !== undefined, `the kit has no reading of the table's session-tree leg ${label} (step ${leg.step}) — the kit is older than the table`);
const calls = journal.filter((c) => c.seat === leg.store && c.verb === leg.verb && reads(c));
assert.ok(calls.length > 0, `leg ${label} was never called on a session whose head cannot be read — calls: ${describeJournal(journal)}`);
spans.push(calls);
});
const row = spans[spans.length - 1];
for (const other of spans.slice(0, -1)) {
assert.ok(lastEnd(other) < firstStart(row), `the session row's leg began before every other leg had settled on a session whose head cannot be read — calls: ${describeJournal(journal)}`);
}
});
run("a session whose head cannot be read, over a store without its leg's `unreadable` verb, is refused before any destructive call, naming the store and the verb", async () => {
const offered = (await drive(coordinator, { adopt: "ok", unreadable: true })).journal.some((c) => destructive.has(`${c.seat}.${c.verb}`));
for (const leg of RETENTION_SESSION_TREE_STEPS) {
if (leg.unreadable === undefined)
continue;
const missing = `${leg.store}.${leg.unreadable}`;
const { journal, rejected, ok } = await drive(coordinator, { adopt: "ok", unreadable: true, without: missing });
const destroyed = journal.filter((c) => destructive.has(`${c.seat}.${c.verb}`));
assert.equal(destroyed.length, 0, `the store carries no ${missing} and the coordinator still made destructive calls on a session whose head cannot be read — the check comes before the first one — calls: ${describeJournal(journal)}`);
assert.ok(!ok, `the store carries no ${missing} and the deletion of a session whose head cannot be read completed — calls: ${describeJournal(journal)}`);
const said = thrownText(rejected);
if (offered)
assert.ok(said.includes(leg.store) && said.includes(leg.unreadable), `the refusal does not name ${leg.store} and ${leg.unreadable}: ${said}`);
}
});
run("a session whose head reads, over a session store without `delete`, is refused before any destructive call, naming the store and the verb", async () => {
const { journal, rejected, ok } = await drive(coordinator, { adopt: "ok", without: "sessionStore.delete" });
const destroyed = journal.filter((c) => destructive.has(`${c.seat}.${c.verb}`));
assert.equal(destroyed.length, 0, `the session store carries no delete and the coordinator still made destructive calls over a readable session — the check comes before the first one, not at the row's own step after every other leg has run — calls: ${describeJournal(journal)}`);
assert.ok(!ok, `the session store carries no delete and the deletion completed — calls: ${describeJournal(journal)}`);
const said = thrownText(rejected);
assert.ok(said.includes("sessionStore") && said.includes("delete"), `the refusal does not name sessionStore and delete: ${said}`);
});
run("a head refusal is judged by its code, never by its form: one stating `bad_entry` (an entry of the log cannot be read) ends as one stating `no_header` does", async () => {
const shape = (journal) => journal.map((c) => `${c.seat}.${c.verb}`).sort();
const header = await drive(coordinator, { adopt: "ok", unreadable: true, headForm: "no_header" });
const entry = await drive(coordinator, { adopt: "ok", unreadable: true, headForm: "bad_entry" });
assert.equal(entry.ok, header.ok, `a refusal stating bad_entry ${entry.ok ? "completed" : `rejected (${String(entry.rejected)})`} where one stating no_header ${header.ok ? "completed" : `rejected (${String(header.rejected)})`}`);
assert.deepEqual(shape(entry.journal), shape(header.journal), "the same calls are made whichever form the head refusal states");
});
await settle();
}