@sema-agent/core
Version:
Stateless, task-oriented AI agent core
360 lines (359 loc) • 29.1 kB
JavaScript
import { strict as assert } from "node:assert";
import { JOURNAL_INCOMPATIBLE_ERROR_CODE, JOURNAL_OVERSIZE_ERROR_CODE, MAX_JOURNAL_RESULT_BYTES, RESUME_CLAIM_REMAINING_MS_MAX, WORKFLOW_LAUNCH_CONFLICT_CODE, } from "../workflow-journal-store.js";
import { ANONYMOUS_SCOPE } from "../isolation-scope.js";
import { beginContract } from "./contract-harness.js";
const key = (ordinal) => `${ordinal}:h`;
const completed = (ordinal, over = {}) => ({
taskId: `t-${ordinal}`,
sessionId: `s-${ordinal}`,
terminal: { kind: "completed" },
result: `r${ordinal}`,
structuredOutput: { ordinal, nested: { ok: true } },
stats: { turns: 1, tokens: 1, costMicroUsd: 0, nested: { tokens: 0, turns: 0, tasks: 0, costMicroUsd: 0 } },
...over,
});
const parked = (ordinal, over = {}) => ({
taskId: `t-${ordinal}`,
sessionId: `s-${ordinal}`,
terminal: { kind: "paused", token: `tok-${ordinal}`, checkpointId: `cp-${ordinal}`, gate: { kind: "human", reason: "approve", toolName: "Write" } },
result: "",
structuredOutput: { partial: ordinal },
stats: { turns: 1, tokens: 1, costMicroUsd: 0, nested: { tokens: 3, turns: 2, tasks: 1, costMicroUsd: 1 } },
...over,
});
const OVER_CAP = "x".repeat(MAX_JOURNAL_RESULT_BYTES + 1024);
const isOversizeRefusal = (e) => e instanceof Error && e.code === JOURNAL_OVERSIZE_ERROR_CODE;
const isIncompatibleRefusal = (e) => e instanceof Error && e.code === JOURNAL_INCOMPATIBLE_ERROR_CODE;
export async function workflowJournalStoreContract(make, runAssertion, hooks) {
const { run, settle } = beginContract(runAssertion);
run("append → load returns entries ASCENDING by ordinal, both arms verbatim; a re-append per ordinal OVERWRITES", async () => {
const store = make();
await store.append("run-1", "tenant-a", { callKey: key(10), result: completed(10) });
await store.append("run-1", "tenant-a", { callKey: key(1), parked: parked(1) });
await store.append("run-1", "tenant-a", { callKey: key(0), result: completed(0) });
await store.append("run-1", "tenant-a", { callKey: key(2), result: completed(2) });
await store.append("run-1", "tenant-a", { callKey: key(0), result: completed(0, { result: "overwritten" }) });
const entries = await store.load("run-1", "tenant-a");
assert.deepEqual(entries.map((e) => e.callKey), [key(0), key(1), key(2), key(10)]);
assert.deepEqual(entries[0], { callKey: key(0), result: completed(0, { result: "overwritten" }) });
assert.deepEqual(entries[1], { callKey: key(1), parked: parked(1) });
});
run("the STOPPED arm (since 7.71.0: a member a stop of its own ended) round-trips verbatim — the leg's whole result and who stopped it; a re-append per ordinal overwrites it like any arm", async () => {
const store = make();
const stoppedLeg = completed(1, { terminal: { kind: "failed", message: "workflow agent stopped by user" }, result: "partial" });
await store.append("run-1", "tenant-a", { callKey: key(0), result: completed(0) });
await store.append("run-1", "tenant-a", { callKey: key(1), stopped: { result: stoppedLeg, stoppedBy: "user" } });
await store.append("run-1", "tenant-a", { callKey: key(2), stopped: { result: stoppedLeg, stoppedBy: "parent" } });
await store.append("run-1", "tenant-a", { callKey: key(2), result: completed(2) });
const entries = await store.load("run-1", "tenant-a");
assert.deepEqual(entries[1], { callKey: key(1), stopped: { result: stoppedLeg, stoppedBy: "user" } });
assert.deepEqual(entries[2], { callKey: key(2), result: completed(2) });
});
run("scope wall: a cross-scope load is EMPTY — before and after the owner's own load, and after a refused cross-scope append — on both arms", async () => {
const store = make();
await store.append("run-1", "alice", { callKey: key(0), result: completed(0) });
await store.append("run-1", "alice", { callKey: key(1), parked: parked(1) });
assert.deepEqual(await store.load("run-1", "mallory"), []);
assert.equal((await store.load("run-1", "alice")).length, 2);
assert.deepEqual(await store.load("run-1", "mallory"), []);
await assert.rejects(store.append("run-1", "mallory", { callKey: key(2), result: completed(2) }));
await assert.rejects(store.append("run-1", "mallory", { callKey: key(3), parked: parked(3) }));
assert.deepEqual(await store.load("run-1", "mallory"), []);
assert.deepEqual((await store.load("run-1", "alice")).map((e) => e.callKey), [key(0), key(1)]);
});
run("the anonymous working scope is a scope like any other: a run journaled under ANONYMOUS_SCOPE loads under no other name, and a run of a named scope does not load under it", async () => {
const store = make();
await store.append("run-anon", ANONYMOUS_SCOPE, { callKey: key(0), result: completed(0) });
await store.append("run-named", "alice", { callKey: key(0), result: completed(0) });
assert.deepEqual(await store.load("run-anon", "alice"), []);
assert.deepEqual(await store.load("run-named", ANONYMOUS_SCOPE), []);
assert.equal((await store.load("run-anon", ANONYMOUS_SCOPE)).length, 1);
assert.equal((await store.load("run-named", "alice")).length, 1);
});
run(`oversize RESULT arm ⇒ append rejects with code "${JOURNAL_OVERSIZE_ERROR_CODE}"; nothing journaled; the store stays usable`, async () => {
const store = make();
await store.append("run-1", "tenant-a", { callKey: key(0), result: completed(0) });
await assert.rejects(store.append("run-1", "tenant-a", { callKey: key(1), result: completed(1, { result: OVER_CAP }) }), isOversizeRefusal);
assert.deepEqual((await store.load("run-1", "tenant-a")).map((e) => e.callKey), [key(0)]);
await store.append("run-1", "tenant-a", { callKey: key(2), result: completed(2) });
assert.deepEqual((await store.load("run-1", "tenant-a")).map((e) => e.callKey), [key(0), key(2)]);
});
run(`oversize PARKED arm ⇒ append rejects with code "${JOURNAL_OVERSIZE_ERROR_CODE}"; nothing journaled (never a silent skip — a lost park is a resume running the ordinal live)`, async () => {
const store = make();
await store.append("run-1", "tenant-a", { callKey: key(0), result: completed(0) });
await assert.rejects(store.append("run-1", "tenant-a", { callKey: key(1), parked: parked(1, { result: OVER_CAP }) }), isOversizeRefusal);
assert.deepEqual((await store.load("run-1", "tenant-a")).map((e) => e.callKey), [key(0)]);
await store.append("run-1", "tenant-a", { callKey: key(1), parked: parked(1) });
assert.equal((await store.load("run-1", "tenant-a"))[1].parked?.terminal.kind, "paused");
});
run("a PARKED row whose payload is not a paused result is refused — at append, or by the whole load — never read back as an entry, never dropped", async () => {
const bad = [
["terminal completed", { ...parked(1), terminal: { kind: "completed" } }],
["paused terminal without a checkpoint token", { ...parked(1), terminal: { kind: "paused", gate: { kind: "human", reason: "approve", toolName: "Write" } } }],
["parked arm a string", "paused"],
];
for (const [what, payload] of bad) {
const store = make();
await store.append("run-1", "tenant-a", { callKey: key(0), result: completed(0) });
let appended = true;
try {
await store.append("run-1", "tenant-a", { callKey: key(1), parked: payload });
}
catch {
appended = false;
}
if (appended) {
await assert.rejects(store.load("run-1", "tenant-a"), isIncompatibleRefusal, `${what}: the row was journaled, so the load must refuse — with code "${JOURNAL_INCOMPATIBLE_ERROR_CODE}" — rather than answer around it`);
}
else {
assert.deepEqual((await store.load("run-1", "tenant-a")).map((e) => e.callKey), [key(0)], `${what}: an append that refused must have journaled nothing`);
}
}
});
run("the cap is inclusive: a payload of EXACTLY the cap's byte count is accepted on both arms", async () => {
const store = make();
const fit = (payload) => {
const base = Buffer.byteLength(JSON.stringify({ ...payload, result: "" }), "utf8");
return { ...payload, result: "y".repeat(MAX_JOURNAL_RESULT_BYTES - base) };
};
const r = fit(completed(0));
const p = fit(parked(1));
assert.equal(Buffer.byteLength(JSON.stringify(r), "utf8"), MAX_JOURNAL_RESULT_BYTES);
assert.equal(Buffer.byteLength(JSON.stringify(p), "utf8"), MAX_JOURNAL_RESULT_BYTES);
await store.append("run-1", "tenant-a", { callKey: key(0), result: r });
await store.append("run-1", "tenant-a", { callKey: key(1), parked: p });
const entries = await store.load("run-1", "tenant-a");
assert.deepEqual(entries.map((e) => e.callKey), [key(0), key(1)]);
assert.deepEqual(entries[0].result, r);
assert.deepEqual(entries[1].parked, p);
});
run("launch records: both verbs or neither; loadLaunch answers exactly what recordLaunch wrote, once, behind the scope wall, erased with the run", async () => {
const store = make();
const hasRecord = typeof store.recordLaunch === "function";
assert.equal(typeof store.loadLaunch === "function", hasRecord, "recordLaunch and loadLaunch come as a pair");
if (!hasRecord)
return;
const launch = {
script: "export const meta = { name: \"m\", description: \"d\" };\nreturn 1;",
effectiveArgs: { topic: "t", n: [1, 2] },
callArgs: { script: "s", args: { topic: "t" } },
host: { model: "m1", modelPinned: true, thinking: "high" },
face: { deferTools: ["tool-b", "tool-a"], alwaysLoadTools: ["tool-c"], restoreGatedTools: true, promptLean: false },
};
await store.recordLaunch("run-1", "tenant-a", launch);
assert.deepEqual(await store.loadLaunch("run-1", "tenant-a"), launch);
assert.equal(await store.loadLaunch("run-1", "mallory"), undefined);
await store.recordLaunch("run-1", "tenant-a", structuredClone(launch));
assert.deepEqual(await store.loadLaunch("run-1", "tenant-a"), launch);
await assert.rejects(store.recordLaunch("run-1", "tenant-a", { ...launch, script: "return 2;" }), (e) => e.code === WORKFLOW_LAUNCH_CONFLICT_CODE);
await assert.rejects(store.recordLaunch("run-1", "tenant-a", { ...launch, face: { deferTools: ["tool-a"] } }), (e) => e.code === WORKFLOW_LAUNCH_CONFLICT_CODE);
await assert.rejects(store.recordLaunch("run-1", "tenant-b", launch), (e) => e.code === WORKFLOW_LAUNCH_CONFLICT_CODE);
assert.deepEqual(await store.loadLaunch("run-1", "tenant-a"), launch);
assert.equal(await store.loadLaunch("run-1", "tenant-b"), undefined);
await store.recordLaunch("run-2", "tenant-a", { script: "return 3;", callArgs: {} });
assert.deepEqual(await store.loadLaunch("run-2", "tenant-a"), { script: "return 3;", callArgs: {} });
await store.recordLaunch("run-3", "tenant-a", { script: "return 4;", callArgs: {}, host: { model: "m1" } });
const sparse = await store.loadLaunch("run-2", "tenant-a");
const sparseHost = await store.loadLaunch("run-3", "tenant-a");
assert.deepEqual(Object.keys(sparse ?? {}).sort(), ["callArgs", "script"], `only the members written read back (read: ${JSON.stringify(sparse)})`);
assert.deepEqual(Object.keys(sparseHost ?? {}).sort(), ["callArgs", "host", "script"], `only the members written read back (read: ${JSON.stringify(sparseHost)})`);
assert.deepEqual(Object.keys(sparseHost?.host ?? {}), ["model"], `only the host members written read back (read: ${JSON.stringify(sparseHost?.host)})`);
assert.equal(await store.loadLaunch("never", "tenant-a"), undefined);
if (store.deleteRun !== undefined) {
await store.deleteRun("run-1", "tenant-a");
assert.equal(await store.loadLaunch("run-1", "tenant-a"), undefined);
}
});
run("a launch record lives as long as the run, not as the journal's entries: rewriting or erasing the entries leaves it; the cascade's deleteRun takes it", async () => {
const store = make();
if (typeof store.recordLaunch !== "function" || typeof store.loadLaunch !== "function")
return;
const launch = { script: "return 1;", callArgs: { script: "return 1;" } };
await store.recordLaunch("run-1", "tenant-a", launch);
await store.append("run-1", "tenant-a", { callKey: key(0), result: completed(0) });
await store.append("run-1", "tenant-a", { callKey: key(0), result: completed(0, { result: "overwritten" }) });
await store.append("run-1", "tenant-a", { callKey: key(1), parked: parked(1) });
assert.deepEqual(await store.loadLaunch("run-1", "tenant-a"), launch);
await store.recordLaunch("run-2", "tenant-a", launch);
assert.deepEqual(await store.loadLaunch("run-2", "tenant-a"), launch);
if (store.deleteRun !== undefined) {
assert.equal(await store.deleteRun("run-2", "tenant-a"), true);
assert.equal(await store.loadLaunch("run-2", "tenant-a"), undefined);
assert.equal(await store.deleteRun("run-1", "mallory"), false);
assert.deepEqual(await store.loadLaunch("run-1", "tenant-a"), launch);
}
});
run("a launch record over the journal's per-entry cap is refused with the journal's oversize code, and nothing is kept", async () => {
const store = make();
if (typeof store.recordLaunch !== "function" || typeof store.loadLaunch !== "function")
return;
const big = { script: "return 1;", effectiveArgs: { blob: "x".repeat(MAX_JOURNAL_RESULT_BYTES) }, callArgs: {} };
await assert.rejects(store.recordLaunch("run-big", "tenant-a", big), (e) => e.code === JOURNAL_OVERSIZE_ERROR_CODE);
assert.equal(await store.loadLaunch("run-big", "tenant-a"), undefined);
const frame = JSON.stringify({ script: "return 1;", effectiveArgs: { blob: "" }, callArgs: {} });
const fits = { script: "return 1;", effectiveArgs: { blob: "y".repeat(MAX_JOURNAL_RESULT_BYTES - Buffer.byteLength(frame, "utf8")) }, callArgs: {} };
await store.recordLaunch("run-fits", "tenant-a", fits);
assert.deepEqual(await store.loadLaunch("run-fits", "tenant-a"), fits);
});
run("a launch record holding values a JSON round trip changes is kept and answered in its storage form, and the same record written again is no conflict; one holding a value JSON cannot keep is refused and nothing is kept", async () => {
const store = make();
if (typeof store.recordLaunch !== "function" || typeof store.loadLaunch !== "function")
return;
const launch = { script: "return 1;", effectiveArgs: { topic: "t", note: undefined, zero: -0, list: [1, { gone: undefined }] }, callArgs: { name: "n", flag: undefined } };
const stored = { script: "return 1;", effectiveArgs: { topic: "t", zero: 0, list: [1, {}] }, callArgs: { name: "n" } };
await store.recordLaunch("run-1", "tenant-a", launch);
assert.deepEqual(await store.loadLaunch("run-1", "tenant-a"), stored, "the record is answered in its storage form: a member holding undefined absent, -0 as 0");
await store.recordLaunch("run-1", "tenant-a", structuredClone(launch));
await store.recordLaunch("run-1", "tenant-a", stored);
assert.deepEqual(await store.loadLaunch("run-1", "tenant-a"), stored);
await assert.rejects(store.recordLaunch("run-1", "tenant-a", { ...stored, effectiveArgs: { topic: "u" } }), (e) => e.code === WORKFLOW_LAUNCH_CONFLICT_CODE);
const scalar = { script: "return 1;", effectiveArgs: "just text", callArgs: {} };
await store.recordLaunch("run-2", "tenant-a", scalar);
assert.deepEqual(await store.loadLaunch("run-2", "tenant-a"), scalar);
const unkeepable = [["a number that is not finite", Number.NaN], ["an infinite number", Number.POSITIVE_INFINITY], ["a Date", new Date(0)], ["an undefined list element", [1, undefined]]];
for (const [i, [what, value]] of unkeepable.entries()) {
await assert.rejects(store.recordLaunch(`run-bad-${i}`, "tenant-a", { script: "return 1;", effectiveArgs: { v: value }, callArgs: {} }), `a launch record whose args hold ${what} is refused`);
assert.equal(await store.loadLaunch(`run-bad-${i}`, "tenant-a"), undefined, `nothing is kept for a launch record whose args hold ${what}`);
await assert.rejects(store.recordLaunch(`run-bad-c${i}`, "tenant-a", { script: "return 1;", callArgs: { v: value } }), `a launch record whose call arguments hold ${what} is refused`);
assert.equal(await store.loadLaunch(`run-bad-c${i}`, "tenant-a"), undefined, `nothing is kept for a launch record whose call arguments hold ${what}`);
}
});
run("resume claims: a second run is refused while the first holds the claim (naming it, and how long it has left, where the store answers them); the holder's re-claim is granted; released, the claim is free", async () => {
const store = make();
if (typeof store.resumeClaim !== "function")
return;
assert.equal(typeof store.releaseResumeClaim, "function", "a store that takes resume claims gives them back (releaseResumeClaim)");
const a = { sourceRunId: "root-1", newRunId: "run-a", scope: "tenant-a" };
const b = { ...a, newRunId: "run-b" };
const remainingReads = (answer, what) => {
const r = answer.remainingMs;
if (r === undefined)
return;
assert.ok(typeof r === "number" && Number.isSafeInteger(r) && r >= 1 && r <= RESUME_CLAIM_REMAINING_MS_MAX, `${what}: remainingMs is a whole number of milliseconds from 1 to ${RESUME_CLAIM_REMAINING_MS_MAX} (read: ${String(r)})`);
};
const granted = await store.resumeClaim(a);
assert.equal(granted.granted, true);
remainingReads(granted, "a grant");
const refused = await store.resumeClaim(b);
assert.equal(refused.granted, false, "a second run's claim on a held key is refused");
if (refused.holder !== undefined)
assert.equal(refused.holder, "run-a", "a refusal that names a holder names the run that holds the claim");
remainingReads(refused, "a refusal");
assert.ok(!Object.hasOwn(refused, "expiresAt") && !Object.hasOwn(granted, "expiresAt"), "an answer carries no expiresAt (retired in 7.71.0: a remaining time, never an instant of the store's clock)");
const again = await store.resumeClaim(a);
assert.equal(again.granted, true, "the holder's own re-claim is granted");
remainingReads(again, "the holder's re-claim");
await store.releaseResumeClaim(a);
assert.equal((await store.resumeClaim(b)).granted, true, "released, the claim is free");
await store.releaseResumeClaim(b);
});
run("resume claims: a key holding ':', '/' or a space is a claim like any other — a second run is refused, another such key is another claim, released it is free", async () => {
const store = make();
if (typeof store.resumeClaim !== "function")
return;
for (const key of ["team:run-1", "team/run-1", "team run-1"]) {
const a = { sourceRunId: key, newRunId: "run-a", scope: "tenant-a" };
const b = { ...a, newRunId: "run-b" };
assert.equal((await store.resumeClaim(a)).granted, true, `${key}: the first claim is granted`);
assert.equal((await store.resumeClaim(b)).granted, false, `${key}: a second run's claim is refused while the first holds it`);
await store.releaseResumeClaim(a);
assert.equal((await store.resumeClaim(b)).granted, true, `${key}: released, the claim is free`);
await store.releaseResumeClaim(b);
}
const one = { sourceRunId: "team:run-1", newRunId: "run-a", scope: "tenant-a" };
const other = { sourceRunId: "team:run-2", newRunId: "run-b", scope: "tenant-a" };
assert.equal((await store.resumeClaim(one)).granted, true);
assert.equal((await store.resumeClaim(other)).granted, true, "another such key is another claim");
await store.releaseResumeClaim(one);
await store.releaseResumeClaim(other);
});
run("stopResumeClaim tombstone: absent (a), given holder (c), already tombstone (d), held by another (non-writing), stopped.by on resumeClaim, permanence and scope wall", async () => {
const store = make();
if (typeof store.stopResumeClaim !== "function")
return;
assert.equal(typeof store.resumeClaim, "function", "a store that implements stopResumeClaim also implements resumeClaim");
assert.equal(typeof store.releaseResumeClaim, "function", "a store that implements stopResumeClaim also implements releaseResumeClaim");
assert.deepEqual(await store.stopResumeClaim({ sourceRunId: "stop-a", scope: "tenant-a", stoppedBy: "user" }), { stopped: true });
const refusedA = await store.resumeClaim({ sourceRunId: "stop-a", newRunId: "run-1", scope: "tenant-a" });
assert.equal(refusedA.granted, false, "arm (a): resumeClaim on a tombstone is refused");
assert.deepEqual(refusedA.stopped, { by: "user" }, "arm (a): resumeClaim reports explicit stopped.by");
assert.equal(refusedA.remainingMs, undefined, "arm (a): a tombstone has no remainingMs");
assert.equal((await store.resumeClaim({ sourceRunId: "stop-a", newRunId: "run-b", scope: "tenant-b" })).granted, true, "tombstone is isolated to its scope");
await store.releaseResumeClaim({ sourceRunId: "stop-a", newRunId: "run-b", scope: "tenant-b" });
for (const candidate of ["run-1", "user", "workflow:stopped", "", ...(refusedA.holder !== undefined ? [refusedA.holder] : [])]) {
await store.releaseResumeClaim({ sourceRunId: "stop-a", newRunId: candidate, scope: "tenant-a" });
const check = await store.resumeClaim({ sourceRunId: "stop-a", newRunId: candidate, scope: "tenant-a" });
assert.equal(check.granted, false, `release by ${JSON.stringify(candidate)} must never delete a tombstone`);
assert.deepEqual(check.stopped, { by: "user" });
}
if (store.deleteRun !== undefined) {
await store.append("stop-a", "tenant-a", { callKey: key(0), result: completed(0) });
await store.deleteRun("stop-a", "tenant-a");
const afterDelete = await store.resumeClaim({ sourceRunId: "stop-a", newRunId: "run-after-del", scope: "tenant-a" });
assert.equal(afterDelete.granted, false, "deleteRun must not touch tombstones");
assert.deepEqual(afterDelete.stopped, { by: "user" });
}
assert.deepEqual(await store.stopResumeClaim({ sourceRunId: "stop-a", scope: "tenant-a", stoppedBy: "second" }), { stopped: true }, "arm (d): re-stop without holder is idempotent");
assert.deepEqual(await store.stopResumeClaim({ sourceRunId: "stop-a", scope: "tenant-a", stoppedBy: "third", holder: "foreign" }), { stopped: true }, "arm (d): re-stop with foreign holder is idempotent");
const afterIdem = await store.resumeClaim({ sourceRunId: "stop-a", newRunId: "run-2", scope: "tenant-a" });
assert.equal(afterIdem.granted, false);
assert.deepEqual(afterIdem.stopped, { by: "user" }, "arm (d): original stoppedBy is preserved");
assert.equal((await store.resumeClaim({ sourceRunId: "stop-c", newRunId: "run-h1", scope: "tenant-a" })).granted, true);
assert.deepEqual(await store.stopResumeClaim({ sourceRunId: "stop-c", scope: "tenant-a", stoppedBy: "operator", holder: "run-h1" }), { stopped: true }, "arm (c): matching holder rewrites claim into tombstone");
const formerHolderClaim = await store.resumeClaim({ sourceRunId: "stop-c", newRunId: "run-h1", scope: "tenant-a" });
assert.equal(formerHolderClaim.granted, false, "arm (c): former holder can no longer re-claim");
assert.deepEqual(formerHolderClaim.stopped, { by: "operator" });
await store.releaseResumeClaim({ sourceRunId: "stop-c", newRunId: "run-h1", scope: "tenant-a" });
const afterFormerRelease = await store.resumeClaim({ sourceRunId: "stop-c", newRunId: "run-h2", scope: "tenant-a" });
assert.equal(afterFormerRelease.granted, false, "arm (c): former holder's release never deletes the tombstone");
assert.deepEqual(afterFormerRelease.stopped, { by: "operator" });
assert.equal((await store.resumeClaim({ sourceRunId: "stop-held", newRunId: "run-live", scope: "tenant-a" })).granted, true);
assert.deepEqual(await store.stopResumeClaim({ sourceRunId: "stop-held", scope: "tenant-a", stoppedBy: "user" }), { stopped: false, holder: "run-live" }, "non-writing arm (no holder) refuses naming holder");
assert.deepEqual(await store.stopResumeClaim({ sourceRunId: "stop-held", scope: "tenant-a", stoppedBy: "user", holder: "run-wrong" }), { stopped: false, holder: "run-live" }, "non-writing arm (wrong holder) refuses naming holder");
assert.equal((await store.resumeClaim({ sourceRunId: "stop-held", newRunId: "run-live", scope: "tenant-a" })).granted, true, "non-writing arm leaves holder's claim intact");
const stillHeld = await store.resumeClaim({ sourceRunId: "stop-held", newRunId: "run-other", scope: "tenant-a" });
assert.equal(stillHeld.granted, false);
assert.equal(stillHeld.stopped, undefined, "non-writing arm wrote no tombstone");
await store.releaseResumeClaim({ sourceRunId: "stop-held", newRunId: "run-live", scope: "tenant-a" });
assert.equal((await store.resumeClaim({ sourceRunId: "stop-held", newRunId: "run-other", scope: "tenant-a" })).granted, true, "once released, the untouched claim is free");
await store.releaseResumeClaim({ sourceRunId: "stop-held", newRunId: "run-other", scope: "tenant-a" });
assert.deepEqual(await store.stopResumeClaim({ sourceRunId: "team:stop-1", scope: "tenant-a", stoppedBy: "user" }), { stopped: true });
const oddRefused = await store.resumeClaim({ sourceRunId: "team:stop-1", newRunId: "run-odd", scope: "tenant-a" });
assert.equal(oddRefused.granted, false);
assert.deepEqual(oddRefused.stopped, { by: "user" });
});
if (hooks?.expireClaim !== undefined) {
const expireClaim = hooks.expireClaim;
run("stopResumeClaim tombstone arm (b): an expired claim no longer binds and is replaced with a tombstone", async () => {
const store = make();
if (typeof store.stopResumeClaim !== "function")
return;
assert.equal((await store.resumeClaim({ sourceRunId: "stop-expired", newRunId: "run-old", scope: "tenant-a" })).granted, true);
const restore = await expireClaim(store, { sourceRunId: "stop-expired", scope: "tenant-a" });
try {
assert.deepEqual(await store.stopResumeClaim({ sourceRunId: "stop-expired", scope: "tenant-a", stoppedBy: "expiry-stop" }), { stopped: true }, "arm (b) expired: replaces non-binding claim with tombstone");
}
finally {
restore?.();
}
const refused = await store.resumeClaim({ sourceRunId: "stop-expired", newRunId: "run-new", scope: "tenant-a" });
assert.equal(refused.granted, false);
assert.deepEqual(refused.stopped, { by: "expiry-stop" });
});
}
if (hooks?.markClaimHolderGone !== undefined) {
const markClaimHolderGone = hooks.markClaimHolderGone;
run("stopResumeClaim tombstone arm (b): a claim whose holder process is proven gone no longer binds and is replaced with a tombstone", async () => {
const store = make();
if (typeof store.stopResumeClaim !== "function")
return;
assert.equal((await store.resumeClaim({ sourceRunId: "stop-gone", newRunId: "run-dead-proc", scope: "tenant-a" })).granted, true);
await markClaimHolderGone(store, { sourceRunId: "stop-gone", scope: "tenant-a" });
assert.deepEqual(await store.stopResumeClaim({ sourceRunId: "stop-gone", scope: "tenant-a", stoppedBy: "crash-stop" }), { stopped: true }, "arm (b) holder gone: replaces non-binding claim with tombstone");
const refused = await store.resumeClaim({ sourceRunId: "stop-gone", newRunId: "run-new", scope: "tenant-a" });
assert.equal(refused.granted, false);
assert.deepEqual(refused.stopped, { by: "crash-stop" });
});
}
await settle();
}