@sema-agent/core
Version:
Stateless, task-oriented AI agent core
154 lines (153 loc) • 8.45 kB
JavaScript
import assert from "node:assert";
import { matchesPathPrefix, listPrefixArgument } from "./normalize.js";
const CTX = { sessionId: "contract-session", taskId: "contract-task" };
function info(id, description, writable) {
return { id, description, writable };
}
function twoStoreFixture() {
return {
state: "connected",
stores: [
{
info: info("alpha", "the alpha store", true),
documents: [
{ path: "/a/one.md", content: "alpha one", updatedAt: "2026-01-02T03:04:05Z" },
{ path: "/a/nested/two.md", content: "alpha two" },
{ path: "/ab/three.md", content: "alpha three" },
{ path: "/top.md", content: "alpha top" },
],
},
{
info: info("beta", "the beta store", false),
documents: [{ path: "/b/only.md", content: "beta only" }],
},
],
};
}
async function connectedStores(provider) {
const snapshot = await provider.snapshot(CTX, {});
if (snapshot.state !== "connected") {
return assert.fail(`snapshot(connected fixture) reported state "${snapshot.state}" — the fixture state must be reported as-is`);
}
return [...snapshot.stores];
}
async function walkList(reader, prefix) {
const out = [];
let cursor;
for (let round = 0; round < 64; round++) {
const rows = await reader.list(prefix, { ...(cursor !== undefined ? { cursor } : {}), limit: 50 });
if (Array.isArray(rows))
return [...out, ...rows];
out.push(...rows.entries);
if (rows.nextCursor === undefined)
return out;
assert.ok(cursor === undefined || rows.nextCursor > cursor, `paged list nextCursor must strictly advance (got ${JSON.stringify(rows.nextCursor)} after ${JSON.stringify(cursor)})`);
cursor = rows.nextCursor;
}
return assert.fail("paged list did not terminate within 64 windows — nextCursor must eventually be absent");
}
function storeById(stores, id) {
const found = stores.find((s) => s.info.id === id);
if (!found)
return assert.fail(`snapshot did not report the fixture store "${id}"`);
return found;
}
function abortedSignal() {
const controller = new AbortController();
controller.abort();
return controller.signal;
}
export async function sharedMemoryStoreContract(hooks) {
const cases = [];
const defer = (name, fn) => {
cases.push([name, fn]);
};
defer("snapshot(connected) reports every fixture store with id/description/writable verbatim", async () => {
const fixture = twoStoreFixture();
const stores = await connectedStores(await hooks.make(fixture));
assert.deepStrictEqual(stores.map((s) => s.info.id).sort(), fixture.stores.map((s) => s.info.id).sort(), "the snapshot's store id set must equal the fixture's");
for (const expected of fixture.stores) {
const got = storeById(stores, expected.info.id).info;
assert.strictEqual(got.description, expected.info.description, `store "${expected.info.id}" description must be reported as-is`);
assert.strictEqual(got.writable, expected.info.writable, `store "${expected.info.id}" writable bit must be reported as-is`);
}
});
defer("a connecting / unavailable fixture is reported as that state, never as an empty store set", async () => {
for (const state of ["connecting", "unavailable"]) {
const provider = await hooks.make({ state, stores: [] });
const snapshot = await provider.snapshot(CTX, {});
assert.strictEqual(snapshot.state, state, `a "${state}" fixture must snapshot as "${state}"`);
}
});
defer("read of an absent path resolves null — absence is a VALUE, never an exception", async () => {
const stores = await connectedStores(await hooks.make(twoStoreFixture()));
const alpha = storeById(stores, "alpha");
const got = await alpha.reader.read("/a/does-not-exist.md", {});
assert.strictEqual(got, null, "an absent document must resolve null, not throw and not resolve a placeholder body");
});
defer("read returns content/updatedAt code-unit exact — a provider must NOT pre-sanitize", async () => {
const body = "alpha\u0007one\r\ntail";
const fixture = {
state: "connected",
stores: [
{
info: info("alpha", "the alpha store", true),
documents: [{ path: "/a/one.md", content: body, updatedAt: "2026-01-02T03:04:05Z" }],
},
],
};
const stores = await connectedStores(await hooks.make(fixture));
const got = await storeById(stores, "alpha").reader.read("/a/one.md", {});
if (got === null)
return assert.fail("read of a fixture document resolved null");
assert.strictEqual(got.content, body, "content must round-trip code-unit exact (no normalization, no scrubbing)");
assert.strictEqual(got.updatedAt, "2026-01-02T03:04:05Z", "updatedAt must round-trip verbatim");
});
defer("list(prefix) misses nothing under that prefix (a superset is allowed — the engine re-filters)", async () => {
const fixture = twoStoreFixture();
const stores = await connectedStores(await hooks.make(fixture));
const alpha = storeById(stores, "alpha");
const normalizedPrefix = "/a";
const rows = await walkList(alpha.reader, listPrefixArgument(normalizedPrefix));
const listed = new Set(rows.map((r) => r.path));
const expected = fixture.stores[0].documents.filter((d) => matchesPathPrefix(d.path, normalizedPrefix));
assert.ok(expected.length > 0, "the fixture must actually place documents under the probed prefix");
for (const doc of expected) {
assert.ok(listed.has(doc.path), `list("${listPrefixArgument(normalizedPrefix)}") omitted "${doc.path}"`);
}
});
defer("list(undefined) covers the whole store", async () => {
const fixture = twoStoreFixture();
const stores = await connectedStores(await hooks.make(fixture));
const alpha = storeById(stores, "alpha");
const listed = new Set((await walkList(alpha.reader, undefined)).map((r) => r.path));
for (const doc of fixture.stores[0].documents) {
assert.ok(listed.has(doc.path), `list(undefined) omitted "${doc.path}"`);
}
});
defer("every I/O method rejects when handed an already-aborted signal", async () => {
const provider = await hooks.make(twoStoreFixture());
const stores = await connectedStores(provider);
const alpha = storeById(stores, "alpha");
await assert.rejects(async () => provider.snapshot(CTX, { signal: abortedSignal() }), "snapshot must reject on an already-aborted signal (resolving a value hides the cancellation)");
await assert.rejects(async () => alpha.reader.list(undefined, { signal: abortedSignal() }), "list must reject on an already-aborted signal");
await assert.rejects(async () => alpha.reader.read("/a/one.md", { signal: abortedSignal() }), "read must reject on an already-aborted signal");
});
defer("stores are isolated — one store's reader never sees another's documents", async () => {
const stores = await connectedStores(await hooks.make(twoStoreFixture()));
const alpha = storeById(stores, "alpha");
const beta = storeById(stores, "beta");
const alphaPaths = new Set((await walkList(alpha.reader, undefined)).map((r) => r.path));
assert.ok(!alphaPaths.has("/b/only.md"), "store alpha listed a document that belongs to store beta");
assert.strictEqual(await alpha.reader.read("/b/only.md", {}), null, "store alpha read a document that belongs to store beta");
const betaPaths = new Set((await walkList(beta.reader, undefined)).map((r) => r.path));
assert.ok(!betaPaths.has("/a/one.md"), "store beta listed a document that belongs to store alpha");
assert.strictEqual(await beta.reader.read("/a/one.md", {}), null, "store beta read a document that belongs to store alpha");
});
for (const [name, fn] of cases) {
if (hooks.runAssertion)
await hooks.runAssertion(name, fn);
else
await fn();
}
}