@sema-agent/core
Version:
Stateless, task-oriented AI agent core
540 lines (539 loc) • 38.9 kB
JavaScript
import { strict as assert } from "node:assert";
import { readSessionRepoRowCells, sessionLogMarkOf } from "../../internal/harness.js";
import { isSessionConflict } from "../session.js";
import { TtlSessionStore } from "../session-store.js";
import { beginContract } from "./contract-harness.js";
const SESSION_ENTRY = (id, parentId) => ({
id,
parentId,
type: "message",
timestamp: "2026-07-30T00:00:00.000Z",
message: { role: "user", content: [{ type: "text", text: `t-${id}` }], timestamp: 1785340800000 },
});
export async function sessionRepoContract(make, runAssertion) {
const { run, settle } = beginContract(runAssertion);
const A = "0198fa00-0000-7000-8000-00000000000a";
const cellsOf = (repo) => readSessionRepoRowCells("the repo under the session repo contract", repo.rowCells);
run("create({id}) on an id that ALREADY has history is an idempotent REOPEN — never a wipe", async () => {
const repo = make();
const sess = await repo.create({ id: A });
await sess.getStorage().appendEntry(SESSION_ENTRY("e1", null));
await sess.getStorage().appendEntry(SESSION_ENTRY("e2", "e1"));
const again = await repo.create({ id: A });
const entries = await again.getStorage().getEntries();
assert.deepEqual(entries.map((e) => e.id), ["e1", "e2"]);
const exported = (await repo.exportEntries?.(A)) ?? [];
assert.deepEqual(exported.map((e) => e.id), ["e1", "e2"]);
});
run("create({id}) fresh → open() sees appended entries (round-trip floor)", async () => {
const repo = make();
const sess = await repo.create({ id: A });
await sess.getStorage().appendEntry(SESSION_ENTRY("e1", null));
const opened = await repo.open({ id: A, createdAt: "" });
assert.deepEqual((await opened.getStorage().getEntries()).map((e) => e.id), ["e1"]);
});
run("open(missing) throws not_found — never a silent create", async () => {
const repo = make();
await assert.rejects(repo.open({ id: "0198fa00-0000-7000-8000-0000000000ff", createdAt: "" }), /not.?found/i);
});
run("delete() makes the id not_found — the history is gone, not merely hidden from open()", async () => {
const repo = make();
const sess = await repo.create({ id: A });
await sess.getStorage().appendEntry(SESSION_ENTRY("e1", null));
await repo.delete({ id: A, createdAt: "" });
await assert.rejects(repo.open({ id: A, createdAt: "" }), /not.?found/i);
const fresh = await repo.create({ id: A });
assert.deepEqual((await fresh.getStorage().getEntries()).map((e) => e.id), []);
});
run("fork() copies the log, stamps forkedFrom, and leaves the SOURCE untouched", async () => {
const repo = make();
const src = await repo.create({ id: A });
await src.getStorage().appendEntry(SESSION_ENTRY("e1", null));
await src.getStorage().appendEntry(SESSION_ENTRY("e2", "e1"));
const B = "0198fa00-0000-7000-8000-00000000000b";
const forked = await repo.fork({ id: A, createdAt: "" }, { id: B });
assert.deepEqual((await forked.getStorage().getEntries()).map((e) => e.id), ["e1", "e2"]);
assert.equal((await forked.getMetadata()).forkedFrom, A, "fork lineage must be stamped (a reap walks it)");
await src.getStorage().appendEntry(SESSION_ENTRY("e3", "e2"));
assert.deepEqual((await (await repo.open({ id: A, createdAt: "" })).getStorage().getEntries()).map((e) => e.id), ["e1", "e2", "e3"]);
assert.deepEqual((await (await repo.open({ id: B, createdAt: "" })).getStorage().getEntries()).map((e) => e.id), ["e1", "e2"]);
});
run("fork() onto an id another row stands on writes nothing and is refused conflict: the standing row keeps its owner, occupant, creation time, lineage and log, and the source is untouched; onto the source's own id it stays invalid_fork_target; two forks onto one free id at once: one lands, the other is refused conflict", async () => {
const repo = make();
const C = "0198fa00-0000-7000-8000-00000000000c";
const D = "0198fa00-0000-7000-8000-00000000000d";
const src = await repo.create({ id: A, owner: "kit-alice" });
await src.getStorage().appendEntry(SESSION_ENTRY("e1", null));
const withTurns = await repo.create({ id: C, owner: "kit-bob" });
await withTurns.getStorage().appendEntry(SESSION_ENTRY("c1", null));
await withTurns.getStorage().appendEntry(SESSION_ENTRY("c2", "c1"));
await repo.create({ id: D, owner: "kit-bob" });
const rowOf = async (id) => {
const s = await repo.open({ id, createdAt: "" });
const m = await s.getMetadata();
return [m.createdAt, m.owner ?? null, m.incarnation ?? null, m.forkedFrom ?? null, m.forkedFromIncarnation ?? null, structuredClone(m.placement ?? null), structuredClone(await s.getStorage().getEntries())];
};
const source = await rowOf(A);
for (const occupied of [C, D]) {
const before = await rowOf(occupied);
await assert.rejects(() => repo.fork({ id: A, createdAt: "" }, { id: occupied }), (err) => isSessionConflict(err), `a fork onto ${occupied === C ? "a row with turns" : "a row with none"} must be refused SessionError("conflict")`);
assert.deepEqual(await rowOf(occupied), before, "the refused fork wrote nothing: the standing row keeps every cell and its log");
}
await assert.rejects(() => repo.fork({ id: A, createdAt: "" }, { id: A }), (err) => err?.code === "invalid_fork_target", "a fork onto its own source's id is the caller's mistake (invalid_fork_target), not another writer's conflict");
assert.deepEqual(await rowOf(A), source, "the source is untouched");
const B = "0198fa00-0000-7000-8000-00000000000b";
const E = "0198fa00-0000-7000-8000-00000000000e";
await (await repo.create({ id: B, owner: "kit-bob" })).getStorage().appendEntry(SESSION_ENTRY("b1", null));
const settled = await Promise.allSettled([repo.fork({ id: A, createdAt: "" }, { id: E }), repo.fork({ id: B, createdAt: "" }, { id: E })]);
const landed = settled.flatMap((s, i) => (s.status === "fulfilled" ? [i] : []));
assert.equal(landed.length, 1, "two forks onto one free id at once: exactly one lands");
const loser = settled[1 - landed[0]];
assert.ok(loser.status === "rejected" && isSessionConflict(loser.reason), "and the other is refused SessionError(\"conflict\")");
const row = await rowOf(E);
assert.equal(row[3], landed[0] === 0 ? A : B, "the row is the one fork that landed");
const log = JSON.stringify(row[6]);
assert.ok(log.includes(landed[0] === 0 ? "t-e1" : "t-b1") && !log.includes(landed[0] === 0 ? "t-b1" : "t-e1"), "and holds that fork's log alone");
});
run("exportEntries → importEntries round-trips the log verbatim, and the imported session REPLACES what was there", async () => {
const repo = make();
if (repo.exportEntries === undefined || repo.importEntries === undefined)
return;
const src = await repo.create({ id: A });
await src.getStorage().appendEntry(SESSION_ENTRY("e1", null));
await src.getStorage().appendEntry(SESSION_ENTRY("e2", "e1"));
const donor = await repo.exportEntries(A);
assert.deepEqual(donor.map((e) => e.id), ["e1", "e2"]);
const C = "0198fa00-0000-7000-8000-00000000000c";
const target = await repo.create({ id: C });
await target.getStorage().appendEntry(SESSION_ENTRY("old", null));
await repo.importEntries(C, undefined, donor);
const after = await repo.exportEntries(C);
assert.deepEqual(after.map((e) => e.id), ["e1", "e2"]);
assert.deepEqual(after.map((e) => e.parentId), [null, "e1"]);
assert.equal((await repo.exportEntries(A)).length, 2, "importing into C must not disturb the donor session");
});
run("list answers each row once, with its owner cell; a row's lastActiveAt, where the repo records it, is a finite time that a later write or touch never moves back", async () => {
const repo = make();
const B = "0198fa00-0000-7000-8000-00000000000b";
await (await repo.create({ id: A, owner: "kit-alice" })).getStorage().appendEntry(SESSION_ENTRY("e1", null));
await new Promise((resolve) => setTimeout(resolve, 20));
await (await repo.create({ id: B })).getStorage().appendEntry(SESSION_ENTRY("e1", null));
let rows = await repo.list();
for (const id of [A, B])
assert.equal(rows.filter((r) => r.id === id).length, 1, `row ${id} is listed once`);
const rowA = rows.find((r) => r.id === A);
const rowB = rows.find((r) => r.id === B);
assert.equal(rowA.owner ?? null, "kit-alice", "a listed row carries its owner cell");
assert.equal(rowB.owner ?? null, null);
const timeOf = (id) => {
const row = rows.find((r) => r.id === id);
return row.lastActiveAt ?? Date.parse(row.createdAt);
};
if (rowA.lastActiveAt !== undefined && rowB.lastActiveAt !== undefined) {
assert.ok(Number.isFinite(rowA.lastActiveAt) && Number.isFinite(rowB.lastActiveAt), "a recorded activity time is a finite epoch-ms number");
assert.ok(rowB.lastActiveAt >= rowA.lastActiveAt, "the row written later is not listed as older");
const before = rowA.lastActiveAt;
await new Promise((resolve) => setTimeout(resolve, 20));
await (await repo.open({ id: A, createdAt: "" })).getStorage().appendEntry(SESSION_ENTRY("e2", "e1"));
rows = await repo.list();
assert.ok(timeOf(A) >= before && timeOf(A) >= rowB.lastActiveAt, "a write moves its row's time forward, past the rows written before it");
}
if (repo.touch === undefined)
return;
const latest = Math.max(timeOf(A), timeOf(B));
const older = timeOf(A) <= timeOf(B) ? A : B;
await new Promise((resolve) => setTimeout(resolve, 20));
await repo.touch(older);
rows = await repo.list();
const touched = rows.find((r) => r.id === older).lastActiveAt;
assert.ok(touched !== undefined && Number.isFinite(touched), "a touched row lists a recorded time");
assert.ok(touched >= latest, "a touch moves its row's time forward, past the rows active before it");
await repo.touch("0198fa00-0000-7000-8000-0000000000ff");
});
run("the owner cell round-trips: create({id, owner}) records it and open() reads it back; a create naming no owner records null", async () => {
const repo = make();
const owned = await repo.create({ id: A, owner: "kit-alice" });
assert.equal((await owned.getMetadata()).owner, "kit-alice");
assert.equal((await (await repo.open({ id: A, createdAt: "" })).getMetadata()).owner, "kit-alice", "the owner is in the row, not in the handle");
const B = "0198fa00-0000-7000-8000-00000000000b";
await repo.create({ id: B });
assert.equal((await (await repo.open({ id: B, createdAt: "" })).getMetadata()).owner ?? null, null, "no owner named ⇒ anonymous");
});
run("a create or fork whose owner is no principal name (the empty string, a blank string, a string holding a control or invisible character) is refused and leaves no row", async () => {
const repo = make();
for (const owner of ["", " \t ", "ali\u0000ce", "\u200b"])
await assert.rejects(() => repo.create({ id: A, owner }), `create with owner ${JSON.stringify(owner)}`);
await assert.rejects(() => repo.open({ id: A, createdAt: "" }), "the refused creates stored nothing");
const src = await repo.create({ id: A, owner: "kit-alice" });
await src.getStorage().appendEntry(SESSION_ENTRY("e1", null));
const B = "0198fa00-0000-7000-8000-00000000000b";
for (const owner of ["", " \t ", "ali\u0000ce", "\u200b"])
await assert.rejects(() => repo.fork({ id: A, createdAt: "" }, { id: B, owner }), `fork with owner ${JSON.stringify(owner)}`);
await assert.rejects(() => repo.open({ id: B, createdAt: "" }), "the refused forks stored nothing");
assert.equal((await (await repo.open({ id: A, createdAt: "" })).getMetadata()).owner, "kit-alice", "the source row is untouched");
});
run("create({id, owner: Y}) onto an existing row owned by X reopens it untouched: the row keeps X, and the session it returns carries X", async () => {
const repo = make();
const first = await repo.create({ id: A, owner: "kit-x" });
const token = (await first.getMetadata()).incarnation;
const again = await repo.create({ id: A, owner: "kit-y" });
assert.equal((await again.getMetadata()).owner, "kit-x", "a caller whose create met an existing row reads that row's owner, never its own");
assert.equal((await again.getMetadata()).incarnation, token, "and the same occupant");
assert.equal((await (await repo.open({ id: A, createdAt: "" })).getMetadata()).owner, "kit-x");
});
run("fork records the owner its options name in the fork row, else (absent or null) the source row's; importEntries onto an existing row keeps its metadata whole and lands only when the row is the importer's (another owner's, or an owned row by an anonymous import, is refused conflict with nothing written), onto an absent id records the importer", async () => {
const repo = make();
const src = await repo.create({ id: A, owner: "kit-alice" });
await src.getStorage().appendEntry(SESSION_ENTRY("e1", null));
const B = "0198fa00-0000-7000-8000-00000000000b";
const C = "0198fa00-0000-7000-8000-00000000000c";
const D = "0198fa00-0000-7000-8000-00000000000d";
assert.equal((await (await repo.fork({ id: A, createdAt: "" }, { id: B, owner: "kit-bob" })).getMetadata()).owner, "kit-bob");
assert.equal((await (await repo.fork({ id: A, createdAt: "" }, { id: C })).getMetadata()).owner, "kit-alice", "a fork whose options name no owner records the source row's — a copy of an owned history is never anonymous");
assert.equal((await (await repo.fork({ id: A, createdAt: "" }, { id: D, owner: null })).getMetadata()).owner, "kit-alice", "an explicit null never downgrades the copy either");
if (repo.importEntries === undefined)
return;
const token = (await src.getMetadata()).incarnation;
const logOf = async (id) => (await (await repo.open({ id, createdAt: "" })).getStorage().getEntries()).map((e) => e.id);
const refusedAsConflict = async (owner, what) => {
let code;
try {
await repo.importEntries(A, owner, [SESSION_ENTRY("x1", null)]);
}
catch (err) {
code = err?.code;
}
assert.equal(code, "conflict", `${what}: an import lands only on the importer's row`);
assert.deepEqual(await logOf(A), ["e1"], `${what}: a refused import writes nothing`);
};
await refusedAsConflict("kit-carol", "an import by another principal");
await refusedAsConflict(undefined, "an import with no principal onto an owned row");
await repo.importEntries(A, "kit-alice", [SESSION_ENTRY("n1", null)]);
const imported = await (await repo.open({ id: A, createdAt: "" })).getMetadata();
assert.deepEqual(await logOf(A), ["n1"], "the owner's import replaces the log");
assert.equal(imported.owner, "kit-alice", "the owner is recorded only by the write that creates the row: an import never re-stamps it");
assert.equal(imported.incarnation, token, "the log is replaced, not the occupant");
const cells = (m) => [m.createdAt, m.forkedFrom, m.forkedFromIncarnation, m.incarnation, m.owner, JSON.stringify(m.placement)];
const forkRow = await (await repo.open({ id: B, createdAt: "" })).getMetadata();
await repo.importEntries(B, "kit-bob", [SESSION_ENTRY("e1", null)]);
assert.deepEqual(cells(await (await repo.open({ id: B, createdAt: "" })).getMetadata()), cells(forkRow), "the log is replaced, never the row: a fork row keeps its creation time and its lineage");
const E = "0198fa00-0000-7000-8000-00000000000e";
await repo.importEntries(E, "kit-carol", [SESSION_ENTRY("e1", null)]);
assert.equal((await (await repo.open({ id: E, createdAt: "" })).getMetadata()).owner, "kit-carol", "an import onto an absent id is a new row of the importer");
});
run("the metadata a repo hands out is not the row: writing to it (from open() or list()) changes no identity cell the row answers", async () => {
const repo = make();
const sess = await repo.create({ id: A, owner: "kit-alice" });
const token = (await sess.getMetadata()).incarnation;
for (const meta of [await sess.getMetadata(), await (await repo.open({ id: A, createdAt: "" })).getMetadata(), ...(await repo.list()).filter((m) => m.id === A)]) {
try {
Object.assign(meta, { owner: "kit-mallory", incarnation: "kit-forged" });
}
catch {
}
}
const again = await (await repo.open({ id: A, createdAt: "" })).getMetadata();
assert.equal(again.owner, "kit-alice", "the owner changes only through a write of the row");
assert.equal(again.incarnation, token);
if (repo.headOf !== undefined)
assert.deepEqual(await repo.headOf(A), { owner: "kit-alice", ...(token === undefined ? {} : { incarnation: token }), leafId: null });
});
run("headOf (where the repo answers it): no row ⇒ undefined; a row ⇒ its owner, occupant and active leaf, as open() reads them", async () => {
const repo = make();
if (repo.headOf === undefined)
return;
assert.equal(await repo.headOf(A), undefined);
const sess = await repo.create({ id: A, owner: "kit-alice" });
await sess.getStorage().appendEntry(SESSION_ENTRY("e1", null));
await sess.getStorage().appendEntry(SESSION_ENTRY("e2", "e1"));
await sess.getStorage().setLeafId("e1");
const opened = await repo.open({ id: A, createdAt: "" });
{
const inc = (await opened.getMetadata()).incarnation;
assert.deepEqual(await repo.headOf(A), { owner: "kit-alice", ...(inc === undefined ? {} : { incarnation: inc }), leafId: await opened.getStorage().getLeafId() });
}
await repo.delete({ id: A, createdAt: "" });
assert.equal(await repo.headOf(A), undefined, "a deleted row has no head");
});
run("the store over a repo: a row replaced behind a cached session (deleted, then created again naming another owner) — the store's next acquire serves the new row, never the cached transcript", async () => {
const repo = make();
if (cellsOf(repo) === "host")
return;
const store = new TtlSessionStore({ repo });
try {
if (store.headOf === undefined)
return;
await store.register(A, "kit-alice");
await (await store.acquire(A)).session.getStorage().appendEntry(SESSION_ENTRY("alice-only", null));
await repo.delete({ id: A, createdAt: "" });
await repo.create({ id: A, owner: "kit-bob" });
const served = (await store.acquire(A)).session;
assert.equal((await served.getMetadata()).owner, "kit-bob", "the session handed out is the row the owner is read from");
assert.deepEqual((await served.getStorage().getEntries()).map((e) => e.id), [], "the previous owner's transcript is not served under the new owner");
}
finally {
store.dispose();
}
});
const conflictOf = async (write) => {
try {
await write();
}
catch (err) {
return err?.code;
}
return "resolved";
};
const logIds = async (repo, id) => {
try {
return (await (await repo.open({ id, createdAt: "" })).getStorage().getEntries()).map((e) => e.id);
}
catch {
return undefined;
}
};
run("importEntries answers the head its write committed — the same head a head read answers right after it", async () => {
const repo = make();
if (repo.importEntries === undefined || repo.headOf === undefined)
return;
const fresh = await repo.importEntries(A, "kit-alice", [SESSION_ENTRY("e1", null), SESSION_ENTRY("e2", "e1")]);
assert.deepEqual(fresh, await repo.headOf(A), "an import onto an absent id answers the new row's head");
assert.equal(fresh.leafId, "e2");
const again = await repo.importEntries(A, "kit-alice", [SESSION_ENTRY("n1", null)]);
assert.deepEqual(again, await repo.headOf(A), "an import onto the importer's row answers that row's head after the write");
assert.equal(again.incarnation, fresh.incarnation, "the same occupant");
});
run("readRow (where the repo answers it): no row ⇒ undefined; a row ⇒ its metadata, its whole log oldest-first and the head a head read answers, of one row", async () => {
const repo = make();
if (repo.readRow === undefined)
return;
assert.equal(await repo.readRow(A), undefined);
const sess = await repo.create({ id: A, owner: "kit-alice" });
await sess.getStorage().appendEntry(SESSION_ENTRY("e1", null));
await sess.getStorage().appendEntry(SESSION_ENTRY("e2", "e1"));
const row = await repo.readRow(A);
assert.ok(row !== undefined);
assert.equal(row.metadata.owner, "kit-alice");
assert.deepEqual(row.entries.map((e) => e.id), ["e1", "e2"]);
if (repo.headOf !== undefined)
assert.deepEqual(row.head, await repo.headOf(A), "the head of the row read is the head read's");
if (repo.exportEntries !== undefined)
assert.deepEqual(row.entries, await repo.exportEntries(A), "the log of the row read is the export's");
});
run("a conditional import lands only on the row it expects: the row and log as read ⇒ written; after an append, a delete, a delete and create again, or with no row expected while one stands ⇒ conflict, nothing written", async () => {
const repo = make();
if (repo.readRow === undefined || repo.importEntries === undefined)
return;
const sess = await repo.create({ id: A, owner: "kit-alice" });
await sess.getStorage().appendEntry(SESSION_ENTRY("e1", null));
const read = (await repo.readRow(A));
const asRead = { row: read.head, log: sessionLogMarkOf(read.entries) };
await sess.getStorage().appendEntry(SESSION_ENTRY("e2", "e1"));
assert.equal(await conflictOf(() => repo.importEntries(A, "kit-alice", [SESSION_ENTRY("x1", null)], { expect: asRead })), "conflict", "an append since the read: the log is not the one read");
assert.deepEqual(await logIds(repo, A), ["e1", "e2"], "the refused import wrote nothing");
assert.equal(await conflictOf(() => repo.importEntries(A, "kit-alice", [SESSION_ENTRY("x1", null)], { expect: { row: null } })), "conflict", "no row expected, a row stands");
const now = (await repo.readRow(A));
await repo.importEntries(A, "kit-alice", [SESSION_ENTRY("n1", null)], { expect: { row: now.head, log: sessionLogMarkOf(now.entries) } });
assert.deepEqual(await logIds(repo, A), ["n1"], "the row and log as read: written");
const before = (await repo.readRow(A));
await repo.delete({ id: A, createdAt: "" });
assert.equal(await conflictOf(() => repo.importEntries(A, "kit-alice", [SESSION_ENTRY("x1", null)], { expect: { row: before.head } })), "conflict", "the row was deleted since the read");
assert.equal(await logIds(repo, A), undefined, "and no row was created");
await repo.create({ id: A, owner: "kit-alice" });
if (cellsOf(repo) === "engine") {
assert.equal(await conflictOf(() => repo.importEntries(A, "kit-alice", [SESSION_ENTRY("x1", null)], { expect: { row: before.head } })), "conflict", "the row was created again: another occupant, same owner");
}
else {
assert.equal(await conflictOf(() => repo.importEntries(A, "kit-alice", [SESSION_ENTRY("x1", null)], { expect: { row: before.head, log: sessionLogMarkOf(before.entries) } })), "conflict", "the row was created again: its log is not the one read");
await assert.rejects(() => repo.importEntries(A, "kit-alice", [SESSION_ENTRY("x1", null)], { expect: { row: { owner: "kit-alice", incarnation: "kit-occupant" } } }), TypeError, "an expectation naming an occupant, to a repo that holds none");
}
assert.deepEqual(await logIds(repo, A), [], "the new row's log is untouched");
const noShape = { row: before.head, log: "a mark of no shape" };
await assert.rejects(() => repo.importEntries(A, "kit-alice", [SESSION_ENTRY("x1", null)], { expect: noShape }), TypeError, "an expectation of no shape is refused, never read as none");
assert.deepEqual(await logIds(repo, A), [], "and wrote nothing");
});
run("a conditional delete removes only the row it expects: another occupant or no row ⇒ conflict, nothing removed; an occupant-only expectation survives an append, an expectation binding the log does not", async () => {
const repo = make();
if (repo.readRow === undefined)
return;
const sess = await repo.create({ id: A, owner: "kit-alice" });
await sess.getStorage().appendEntry(SESSION_ENTRY("e1", null));
const read = (await repo.readRow(A));
await sess.getStorage().appendEntry(SESSION_ENTRY("e2", "e1"));
assert.equal(await conflictOf(() => repo.delete({ id: A, createdAt: "" }, { row: read.head, log: sessionLogMarkOf(read.entries) })), "conflict", "the log bound and appended to since: not deleted");
assert.deepEqual(await logIds(repo, A), ["e1", "e2"]);
await repo.delete({ id: A, createdAt: "" });
await repo.create({ id: A, owner: "kit-alice" });
if (cellsOf(repo) === "engine") {
assert.equal(await conflictOf(() => repo.delete({ id: A, createdAt: "" }, { row: read.head })), "conflict", "another occupant under the id: not deleted");
}
else {
assert.equal(await conflictOf(() => repo.delete({ id: A, createdAt: "" }, { row: read.head, log: sessionLogMarkOf(read.entries) })), "conflict", "the row created again under the id: its log is not the one read, not deleted");
await assert.rejects(() => repo.delete({ id: A, createdAt: "" }, { row: { owner: "kit-alice", incarnation: "kit-occupant" } }), TypeError, "an expectation naming an occupant, to a repo that holds none");
}
assert.deepEqual(await logIds(repo, A), [], "the new occupant stands");
const current = (await repo.readRow(A));
await (await repo.open({ id: A, createdAt: "" })).getStorage().appendEntry(SESSION_ENTRY("f1", null));
await repo.delete({ id: A, createdAt: "" }, { row: current.head });
assert.equal(await logIds(repo, A), undefined, "the occupant expected, appended to since: deleted (an append does not make it another row)");
assert.equal(await conflictOf(() => repo.delete({ id: A, createdAt: "" }, { row: current.head })), "conflict", "no row: an occupant expected is not there");
const noShape = { row: undefined };
await assert.rejects(() => repo.delete({ id: A, createdAt: "" }, noShape), TypeError, "an expectation of no shape is refused, never read as none");
});
run("the store over a repo answers headOf exactly when the repo does: present ⇒ the repo's own answer; absent ⇒ no headOf on the store, which still works", async () => {
const repo = make();
if (cellsOf(repo) === "host")
return;
const store = new TtlSessionStore({ repo });
try {
assert.equal(typeof store.headOf, typeof repo.headOf === "function" ? "function" : "undefined");
const { sessionId } = await store.acquire(A);
if (store.headOf !== undefined)
assert.deepEqual(await store.headOf(sessionId), await repo.headOf(sessionId), "the store's head is the repo's, verbatim");
}
finally {
store.dispose();
}
const bare = {
create: (o) => repo.create(o),
open: (m) => repo.open(m),
list: () => repo.list(),
delete: (m) => repo.delete(m),
fork: (s, o) => repo.fork(s, o),
};
const over = new TtlSessionStore({ repo: bare });
try {
assert.equal(over.headOf, undefined, "no head read on the repo ⇒ none on the store (an authorizer takes its fail-closed arm)");
const B = "0198fa00-0000-7000-8000-00000000000b";
await over.acquire(B);
await over.register(B, "kit-alice");
}
finally {
over.dispose();
}
});
run("the occupant cells by mode: an engine repo writes a row's occupant on create, fork (the source's as forkedFromIncarnation) and an import onto an absent id, and every read hands it out; a host repo writes neither cell and no read hands either out", async () => {
const repo = make();
const B = "0198fa00-0000-7000-8000-00000000000b";
const C = "0198fa00-0000-7000-8000-00000000000c";
const src = await repo.create({ id: A, owner: "kit-alice" });
await src.getStorage().appendEntry(SESSION_ENTRY("e1", null));
const forked = await repo.fork({ id: A, createdAt: "" }, { id: B });
const createdMeta = await src.getMetadata();
const forkedMeta = await forked.getMetadata();
const created = [["the session create returned", createdMeta], ["the session fork returned", forkedMeta]];
assert.equal(forkedMeta.forkedFrom, A, "the lineage's id is the repo's in either mode");
const imported = repo.importEntries === undefined ? undefined : await repo.importEntries(C, "kit-alice", [SESSION_ENTRY("e1", null)]);
const ids = imported === undefined ? [A, B] : [A, B, C];
const metasOf = async (id) => {
const out = [[`open(${id})`, await (await repo.open({ id, createdAt: "" })).getMetadata()]];
const listed = (await repo.list()).find((m) => m.id === id);
assert.ok(listed !== undefined, `list() answers row ${id}`);
out.push([`list() row ${id}`, listed]);
if (repo.readRow !== undefined)
out.push([`readRow(${id}).metadata`, (await repo.readRow(id)).metadata]);
return out;
};
const headsOf = async (id) => {
const out = [];
if (repo.headOf !== undefined)
out.push([`headOf(${id})`, (await repo.headOf(id))]);
if (repo.readRow !== undefined)
out.push([`readRow(${id}).head`, (await repo.readRow(id)).head]);
if (imported !== undefined && id === C)
out.push(["the head the import answered", imported]);
return out;
};
if (cellsOf(repo) === "engine") {
const tokenA = createdMeta.incarnation;
const tokenB = forkedMeta.incarnation;
assert.ok(typeof tokenA === "string" && tokenA !== "", "create writes the row's occupant");
assert.ok(typeof tokenB === "string" && tokenB !== "" && tokenB !== tokenA, "a fork row is an occupant of its own");
assert.equal(forkedMeta.forkedFromIncarnation, tokenA, "and records the source's occupant as its lineage");
const want = new Map([[A, tokenA], [B, tokenB]]);
if (imported !== undefined) {
assert.ok(typeof imported.incarnation === "string" && imported.incarnation !== "" && imported.incarnation !== tokenA && imported.incarnation !== tokenB, "an import onto an absent id writes an occupant of its own");
want.set(C, imported.incarnation);
}
for (const id of ids) {
for (const [what, meta] of await metasOf(id))
assert.equal(meta.incarnation, want.get(id), `${what} hands out the row's occupant`);
for (const [what, head] of await headsOf(id))
assert.equal(head.incarnation, want.get(id), `${what} hands out the row's occupant`);
}
for (const [what, meta] of await metasOf(B))
assert.equal(meta.forkedFromIncarnation, tokenA, `${what} hands out the fork's lineage occupant`);
return;
}
for (const [what, meta] of created) {
assert.equal(meta.incarnation, undefined, `${what}: no occupant`);
assert.equal(meta.forkedFromIncarnation, undefined, `${what}: no lineage occupant`);
}
for (const id of ids) {
for (const [what, meta] of await metasOf(id)) {
assert.equal(meta.incarnation, undefined, `${what}: no occupant handed out`);
assert.equal(meta.forkedFromIncarnation, undefined, `${what}: no lineage occupant handed out`);
}
for (const [what, head] of await headsOf(id))
assert.equal(head.incarnation, undefined, `${what}: no occupant handed out`);
}
});
run("a conditional write by mode: an engine repo judges the occupant an expectation names (another ⇒ conflict); a host repo judges the owner and the log and refuses an expectation naming any occupant (a TypeError, nothing written); in either mode the row as read is written", async () => {
const repo = make();
if (repo.readRow === undefined)
return;
const sess = await repo.create({ id: A, owner: "kit-alice" });
await sess.getStorage().appendEntry(SESSION_ENTRY("e1", null));
const read = (await repo.readRow(A));
const named = { row: { owner: "kit-alice", incarnation: "kit-occupant" } };
if (cellsOf(repo) === "engine") {
assert.equal(await conflictOf(() => repo.delete({ id: A, createdAt: "" }, named)), "conflict", "an occupant that is not the row's: not deleted");
if (repo.importEntries !== undefined)
assert.equal(await conflictOf(() => repo.importEntries(A, "kit-alice", [SESSION_ENTRY("x1", null)], { expect: named })), "conflict", "an occupant that is not the row's: not written");
}
else {
assert.equal(read.head.incarnation, undefined, "the head this repo reads names no occupant");
await assert.rejects(() => repo.delete({ id: A, createdAt: "" }, named), TypeError, "a delete naming an occupant");
if (repo.importEntries !== undefined)
await assert.rejects(() => repo.importEntries(A, "kit-alice", [SESSION_ENTRY("x1", null)], { expect: named }), TypeError, "an import naming an occupant");
const otherOwner = { row: { owner: "kit-bob", incarnation: undefined } };
assert.equal(await conflictOf(() => repo.delete({ id: A, createdAt: "" }, otherOwner)), "conflict", "another owner: not deleted");
const moved = { row: read.head, log: { length: read.entries.length + 1, lastEntryId: "kit-other" } };
assert.equal(await conflictOf(() => repo.delete({ id: A, createdAt: "" }, moved)), "conflict", "another log: not deleted");
}
assert.deepEqual(await logIds(repo, A), ["e1"], "the refused writes wrote nothing");
if (repo.importEntries !== undefined) {
await repo.importEntries(A, "kit-alice", [SESSION_ENTRY("n1", null)], { expect: { row: read.head, log: sessionLogMarkOf(read.entries) } });
assert.deepEqual(await logIds(repo, A), ["n1"], "the row and log as read: written");
}
const now = (await repo.readRow(A));
await repo.delete({ id: A, createdAt: "" }, { row: now.head, log: sessionLogMarkOf(now.entries) });
assert.equal(await logIds(repo, A), undefined, "the row and log as read: deleted");
});
run("recordOwner (where the repo has it): a row recording no owner takes the name on the occupant its caller read, and nothing else of the row changes; a row recording a name is answered as read, unwritten; another occupant is refused conflict; a session opened before the write keeps appending to the row", async () => {
const repo = make();
if (repo.recordOwner === undefined || repo.headOf === undefined || cellsOf(repo) !== "engine")
return;
const sess = await repo.create({ id: A });
await sess.getStorage().appendEntry(SESSION_ENTRY("e1", null));
const before = (await repo.headOf(A));
assert.equal(before.owner, null, "a create naming no owner records none");
const otherOccupant = { row: { owner: null, incarnation: "kit-occupant" } };
assert.equal(await conflictOf(() => repo.recordOwner(A, "kit-alice", otherOccupant)), "conflict", "another occupant: not written");
assert.equal((await repo.headOf(A)).owner, null, "the refused write wrote nothing");
const claimed = await repo.recordOwner(A, "kit-alice", { row: { owner: null, ...(before.incarnation !== undefined ? { incarnation: before.incarnation } : {}) } });
assert.deepEqual(claimed, { ...before, owner: "kit-alice" }, "the head the write committed");
assert.deepEqual(await repo.recordOwner(A, "kit-bob", { row: { owner: null, ...(before.incarnation !== undefined ? { incarnation: before.incarnation } : {}) } }), claimed, "a row recording a name: answered as read");
await sess.getStorage().appendEntry(SESSION_ENTRY("e2", "e1"));
assert.deepEqual(await logIds(repo, A), ["e1", "e2"], "the session opened before the write appends to the row");
assert.deepEqual(await repo.headOf(A), { ...claimed, leafId: "e2" }, "the owner stays, the leaf follows the append");
});
run("TtlSessionStore over a repo whose host holds the occupant cells is refused at construction, coded config.invalid_argument and naming the missing occupant source — never a store whose every occupant comparison reads \"same\"", async () => {
const repo = make();
if (cellsOf(repo) === "engine")
return;
assert.throws(() => new TtlSessionStore({ repo }).dispose(), /this layer has no occupant source/);
assert.equal(await conflictOf(async () => new TtlSessionStore({ repo }).dispose()), "config.invalid_argument");
});
await settle();
}