UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

726 lines • 53.6 kB
import { randomUUID } from "node:crypto";
import { thrownText } from "../../core/thrown-value.js";
import { identityReadVerdict, recordedOwnerIdentityOf } from "../../core/owner-identity.js";
import { ARTIFACT_LIST_SCOPES, ARTIFACT_OWNERSHIP_WORDS, readArtifactHostCapabilities, } from "../../core/artifact-host.js";
const WHO = ["a", "a2", "b", "c", "z"];
class Violation extends Error {
}
const fail = (detail) => {
    throw new Violation(detail);
};
const check = (cond, detail) => {
    if (!cond)
        fail(detail);
};
const enc = new TextEncoder();
const dec = new TextDecoder();
const FOREIGN_URL = "https://conformance.invalid/artifact/none";
const HTML_MEDIA = "text/html";
const CROSS_REFUSALS = ["not_found", "forbidden", "url_foreign"];
const actorOf = (h, who, conversation = 0) => {
    const actor = h.actors.get(`${who}/${conversation}`);
    if ("error" in actor)
        return fail(actor.error);
    return actor;
};
const identityOf = (h, who) => actorOf(h, who).binding.identity;
const ctxOf = (h, who = "a", conversation = 0, attemptId) => {
    const { runId, binding } = actorOf(h, who, conversation);
    return { taskId: `conformance-${runId}`, sessionId: binding.root.sessionId, runId, attemptId: attemptId ?? `${runId}-${++h.seq}`, binding };
};
const bindingHint = (h) => (h.hooks.binding === undefined ? " (if the host needs real identities or real root conversations, supply the `binding` hook)" : "");
const fixtureBudget = (h) => Math.max(1, Math.min(h.caps.maxFileBytes, Math.floor(h.caps.maxTotalBytes / 2)));
const fit = (h, text) => enc.encode(text).slice(0, fixtureBudget(h));
const el = (tag, inner) => `<${tag}>${inner}</${tag}>`;
const page = (h, n, extraFiles = []) => [{ path: "index.html", content: fit(h, `${n}${el("title", `C${n}`)}${el("p", String(n))}`), mediaType: HTML_MEDIA }, ...extraFiles];
const script = (h, n) => ({ path: "assets/app.js", content: fit(h, `${n};console.log(${n})`).slice(0, Math.floor(h.caps.maxTotalBytes / 2)), mediaType: "text/javascript" });
const req = (files, over = {}) => ({ files, publishContext: "plain", ...over });
const same = (a, b) => a.byteLength === b.byteLength && a.every((x, i) => x === b[i]);
const has = (h, a) => h.caps.actions.includes(a);
const sameIdentity = (record, identity) => {
    if (record === null || typeof record !== "object")
        return false;
    const read = recordedOwnerIdentityOf(record);
    return typeof read === "object" && read.principal === identity.principal && read.isolationScope === identity.isolationScope;
};
const show = (x) => {
    try {
        return JSON.stringify(x) ?? String(x);
    }
    catch {
        return String(x);
    }
};
async function call(what, fn) {
    try {
        return await fn();
    }
    catch (err) {
        return fail(`${what} threw: ${thrownText(err)}`);
    }
}
async function publish(h, r, attemptId, who = "a", conversation = 0) {
    return call("publish", () => h.host.publish(r, ctxOf(h, who, conversation, attemptId)));
}
async function publishOk(h, r, what, attemptId, who = "a", conversation = 0) {
    const out = await publish(h, r, attemptId, who, conversation);
    if (!out.ok)
        return fail(`${what}: expected ok, got ${out.code}${"message" in out ? ` (${out.message})` : ""}`);
    check(typeof out.ref.url === "string" && out.ref.url.length > 0 && typeof out.ref.slug === "string" && typeof out.ref.version === "string", `${what}: the ref must carry url, slug and version strings`);
    return out.ref;
}
async function listAs(h, who, scope, conversation = 0, limit = 1000) {
    const out = await call(`list ${scope} as ${who}`, () => h.host.list({ scope, limit }, ctxOf(h, who, conversation)));
    if (out.ok && h.caps.ownership.sharing === "none")
        check(out.rows.every((r) => r.owner === undefined), `list ${scope} as ${who}: a row carries the share marker though the host declares sharing: "none"`);
    return out;
}
async function readAs(h, who, url, conversation = 0) {
    const out = await call(`read as ${who}`, () => h.host.read({ url }, ctxOf(h, who, conversation)));
    if (out.ok && h.caps.ownership.sharing === "none")
        check(out.isolatedSummary === false, `read as ${who}: the answer is marked an isolated summary though the host declares sharing: "none"`);
    return out;
}
async function listMine(h) {
    const out = await listAs(h, "a", "mine");
    if (!out.ok)
        return fail(`list mine refused: ${out.message}`);
    return out.rows;
}
async function updatesRefused(h, who, url, base, label) {
    const texts = [];
    const stale = `${base}-not-current`;
    const arms = [
        ["no base", { url }],
        ["the current base", { url, baseVersion: base }],
        ["force", { url, baseVersion: base, force: true }],
        ["a stale base", { url, baseVersion: stale }],
        ["force over a stale base", { url, baseVersion: stale, force: true }],
    ];
    for (const [arm, over] of arms) {
        const out = await publish(h, req(page(h, 90), over), undefined, who);
        check(!out.ok && CROSS_REFUSALS.includes(out.code), `${who} updating ${label} (${arm}) answered ${out.ok ? "ok" : out.code}, expected one of ${CROSS_REFUSALS.join(" / ")}${bindingHint(h)}`);
        if (!out.ok && "message" in out)
            texts.push(out.message);
    }
    return texts;
}
async function readRefused(h, who, url, label) {
    const out = await readAs(h, who, url);
    check(!out.ok && (out.code === "not_found" || out.code === "forbidden"), `${who} reading ${label} answered ${out.ok ? "ok" : out.code}, expected not_found / forbidden${bindingHint(h)}`);
    return out.ok ? "" : out.message;
}
async function listsNone(h, who, urls, label) {
    const refusedHere = who === "z" && h.caps.ownership.people === "many";
    for (const scope of ["mine", "shared", "all"]) {
        const out = await listAs(h, who, scope);
        check(out.ok || refusedHere, `list ${scope} as ${who} refused`);
        if (!out.ok)
            return;
        check(!out.rows.some((r) => urls.includes(r.url)), `${who} lists ${label} under scope ${scope}${bindingHint(h)}`);
    }
}
const vectorTable = [];
const define = (v, run) => void vectorTable.push({ ...v, run });
define({ id: "publish.fresh_mints_distinct_pages", describe: "two publishes without `url` mint two pages with distinct urls (fresh never touches an existing page)", requiresActions: ["publish"] }, async (h) => {
    const a = await publishOk(h, req(page(h, 1)), "first fresh");
    const b = await publishOk(h, req(page(h, 2)), "second fresh");
    check(a.url !== b.url, `both fresh publishes answered the same url ${a.url}`);
    return `two pages: ${a.url}, ${b.url}`;
});
define({ id: "publish.update_by_url_advances_same_page", describe: "a publish with `url` and the current `baseVersion` advances that page's version on the same url and slug (update never mints a page); where read / read_file are declared, the NEW bytes are what reads back", requiresActions: ["publish"] }, async (h) => {
    const a = await publishOk(h, req(page(h, 1)), "fresh");
    const next = page(h, 2);
    const b = await publishOk(h, req(next, { url: a.url, baseVersion: a.version }), "update");
    check(b.url === a.url && b.slug === a.slug, `the update answered url ${b.url} / slug ${b.slug}, expected ${a.url} / ${a.slug}`);
    check(b.version !== a.version, `the update left the version at ${a.version}`);
    const persisted = [];
    if (has(h, "read")) {
        const r = await readAs(h, "a", a.url);
        check(r.ok && r.content === dec.decode(next[0].content) && r.ref.version === b.version, "read after the update returns the PREVIOUS content or version: the update was acknowledged but not persisted");
        persisted.push("read");
    }
    if (has(h, "read_file")) {
        const f = await call("read_file", () => h.host.readFile({ url: a.url, path: next[0].path }, ctxOf(h)));
        check(f.ok && same(f.file.content, next[0].content), "read_file after the update returns the PREVIOUS bytes: the update was acknowledged but not persisted");
        persisted.push("read_file");
    }
    return `version ${a.version} → ${b.version} on ${a.url}${persisted.length > 0 ? `; new bytes read back via ${persisted.join(", ")}` : ""}`;
});
define({ id: "publish.no_base_version_is_last_write_wins", describe: "`url` present and `baseVersion` absent ⇒ the write applies (last-write-wins is a defined behaviour, never a conflict)", requiresActions: ["publish"] }, async (h) => {
    const a = await publishOk(h, req(page(h, 1)), "fresh");
    const b = await publishOk(h, req(page(h, 2), { url: a.url }), "first update without baseVersion");
    const c = await publishOk(h, req(page(h, 3), { url: a.url }), "second update without baseVersion");
    check(b.version !== a.version && c.version !== b.version, `versions did not advance: ${a.version}, ${b.version}, ${c.version}`);
    return `three versions on ${a.url}`;
});
define({ id: "publish.stale_base_conflicts", describe: "a stale `baseVersion` ⇒ `conflict` carrying the CURRENT version and either a full snapshot or the explicit `\"reread\"` word; nothing is written", requiresActions: ["publish"] }, async (h) => {
    const a = await publishOk(h, req(page(h, 1)), "fresh");
    const b = await publishOk(h, req(page(h, 2), { url: a.url, baseVersion: a.version }), "update to v2");
    const out = await publish(h, req(page(h, 3), { url: a.url, baseVersion: a.version }));
    check(!out.ok && out.code === "conflict", `a stale base answered ${out.ok ? "ok" : out.code}, expected conflict`);
    if (out.ok || out.code !== "conflict")
        return "";
    check(out.currentVersion === b.version, `conflict names currentVersion ${out.currentVersion}, expected ${b.version}`);
    check(out.current === "reread" || (typeof out.current === "object" && Array.isArray(out.current.files)), "conflict.current must be a snapshot object or the string \"reread\"");
    const after = await publishOk(h, req(page(h, 4), { url: a.url, baseVersion: b.version }), "update on the true current version after the conflict");
    check(after.version !== b.version, "the conflict wrote a version: the base the host itself named was stale one call later");
    return `conflict at ${b.version}, current: ${out.current === "reread" ? "reread" : "snapshot"}`;
});
for (const action of ["read", "read_file"]) {
    define({ id: `publish.conflict_preserves_${action}`, describe: `a stale-base rejection leaves readable bytes unchanged through ${action}, even if the host preserves the version number and returns a correct pre-write snapshot`, requiresActions: ["publish", action] }, async (h) => {
        const a = await publishOk(h, req(page(h, 1)), "fresh");
        const b = await publishOk(h, req(page(h, 2), { url: a.url, baseVersion: a.version }), "update");
        const observe = async () => {
            if (action === "read") {
                const out = await readAs(h, "a", a.url);
                if (!out.ok)
                    return fail(`read refused: ${out.code}`);
                return JSON.stringify([out.ref.url, out.ref.slug, out.ref.version, out.ref.title, out.content, out.isolatedSummary]);
            }
            const out = await call("read_file", () => h.host.readFile({ url: a.url, path: "index.html" }, ctxOf(h)));
            if (!out.ok)
                return fail(`read_file refused: ${out.code}`);
            return JSON.stringify([out.file.path, out.file.mediaType, Array.from(out.file.content)]);
        };
        const before = await observe();
        const rejected = await publish(h, req(page(h, 3), { url: a.url, baseVersion: a.version }));
        check(!rejected.ok && rejected.code === "conflict" && rejected.currentVersion === b.version, "a stale base must conflict at the current version");
        check(await observe() === before, `${action} changed after a rejected publish`);
        return `${action} unchanged after conflict`;
    });
}
define({ id: "publish.conflict_snapshot_is_complete", describe: "when the conflict hands back a snapshot it is the WHOLE current version: every published path with its bytes and the media type sent, plus the metadata and the page's owner record", requiresActions: ["publish"] }, async (h) => {
    const extra = h.caps.multiFile ? [script(h, 1)] : [];
    const a = await publishOk(h, req(page(h, 1, extra), { title: "Conformance title" }), "fresh");
    const current = page(h, 2, extra);
    const b = await publishOk(h, req(current, { url: a.url, baseVersion: a.version, title: "Conformance title" }), "update to v2");
    const out = await publish(h, req(page(h, 3, extra), { url: a.url, baseVersion: a.version }));
    check(!out.ok && out.code === "conflict", "a stale base must conflict");
    if (out.ok || out.code !== "conflict")
        return "";
    if (out.current === "reread")
        return `host answers "reread" (explicit; snapshot completeness not claimed) at ${b.version}`;
    for (const f of current) {
        const got = out.current.files.find((x) => x.path === f.path);
        check(got !== undefined, `snapshot lacks published path ${f.path}`);
        check(got !== undefined && same(got.content, f.content), `snapshot bytes differ for ${f.path}`);
        check(got !== undefined && got.mediaType === f.mediaType, `snapshot media type for ${f.path} is ${got?.mediaType}, expected ${f.mediaType}`);
    }
    check(out.current.files.length === current.length, `snapshot carries ${out.current.files.length} files, the current version has ${current.length}`);
    check(out.current.title === "Conformance title", `snapshot title is ${out.current.title}, expected the current title`);
    check(sameIdentity(out.current.ownerIdentity, identityOf(h, "a")), `snapshot owner record is ${show(out.current.ownerIdentity)}, expected the page's ${show(identityOf(h, "a"))}`);
    return `snapshot complete: ${current.length} file(s) + metadata + owner record`;
});
define({ id: "publish.force_overrides_stale_base", describe: "`force: true` over a stale `baseVersion` applies (a plain published version is overwritable)", requiresActions: ["publish"] }, async (h) => {
    const a = await publishOk(h, req(page(h, 1)), "fresh");
    const b = await publishOk(h, req(page(h, 2), { url: a.url, baseVersion: a.version }), "update to v2");
    const forced = await publishOk(h, req(page(h, 3), { url: a.url, baseVersion: a.version, force: true }), "forced publish over a stale base");
    check(forced.version !== b.version, "force answered ok but the version did not advance");
    return `forced ${b.version} → ${forced.version}`;
});
define({ id: "publish.force_refused_over_page_saved_version", describe: "`force: true` over a version saved from inside the page ⇒ `force_refused` (the one version force must not discard)", requiresActions: ["publish"], requiresHook: "pageSavedVersion" }, async (h) => {
    const a = await publishOk(h, req(page(h, 1)), "fresh");
    await h.hooks.pageSavedVersion(a);
    const out = await publish(h, req(page(h, 2), { url: a.url, baseVersion: a.version, force: true }));
    check(!out.ok && out.code === "force_refused", `force over a page-saved version answered ${out.ok ? "ok" : out.code}, expected force_refused`);
    return "force_refused";
});
define({ id: "publish.attempt_replay_is_idempotent", describe: "the same `attemptId` replays the first outcome: a fresh publish never mints a second page, an update never advances twice", requiresActions: ["publish"] }, async (h) => {
    const before = has(h, "list") ? (await listMine(h)).length : undefined;
    const key = `${h.runId}-replay-fresh`;
    const a = await publishOk(h, req(page(h, 1), { title: "first" }), "fresh under key", key);
    const again = await publishOk(h, req(page(h, 9), { title: "changed" }), "replay under the same key", key);
    check(again.url === a.url && again.version === a.version, `the replay answered ${again.url} @ ${again.version}, expected ${a.url} @ ${a.version}`);
    if (before !== undefined) {
        const after = (await listMine(h)).length;
        check(after === before + 1, `two fresh calls under one key left ${after - before} new page(s) in the listing, expected 1`);
    }
    const key2 = `${h.runId}-replay-update`;
    const u1 = await publishOk(h, req(page(h, 2), { url: a.url, baseVersion: a.version }), "update under key2", key2);
    const u2 = await publishOk(h, req(page(h, 3), { url: a.url, baseVersion: a.version }), "replayed update under key2", key2);
    check(u2.version === u1.version, `the replayed update answered version ${u2.version}, expected ${u1.version}`);
    await publishOk(h, req(page(h, 4), { url: a.url, baseVersion: u1.version }), "an update on the replayed version (proves the version did not advance twice)");
    return `fresh and update each replayed once on ${a.url}`;
});
define({ id: "publish.attempt_replay_of_refusal", describe: "a typed refusal is replayed under the same `attemptId` too: a later call under that key with a request that would otherwise SUCCEED still gets the first refusal (the host does not re-decide)", requiresActions: ["publish"] }, async (h) => {
    const key = `${h.runId}-replay-refusal`;
    const a = await publish(h, req(page(h, 1), { url: FOREIGN_URL }), key);
    check(!a.ok && a.code === "url_foreign", `a foreign url answered ${a.ok ? "ok" : a.code}, expected url_foreign`);
    const b = await publish(h, req(page(h, 2)), key);
    check(!b.ok && b.code === "url_foreign", `the replay re-decided: a fresh request under the refused key answered ${b.ok ? "ok" : b.code}, expected the replayed url_foreign`);
    return "the refusal replayed over a request that would otherwise succeed";
});
define({ id: "publish.url_foreign_refused", describe: "a `url` this host never minted ⇒ `url_foreign` (a typed refusal, never a throw, never a page)", requiresActions: ["publish"] }, async (h) => {
    const out = await publish(h, req(page(h, 1), { url: FOREIGN_URL }));
    check(!out.ok && out.code === "url_foreign", `a foreign url answered ${out.ok ? "ok" : out.code}, expected url_foreign`);
    return "url_foreign";
});
define({ id: "publish.atomic_under_precommit_fault", describe: "a failure injected BEFORE the commit point leaves no observable change: no phantom version (the same base still applies) and, when list is declared, no new page", requiresActions: ["publish"], requiresHook: "precommitFault" }, async (h) => {
    const a = await publishOk(h, req(page(h, 1)), "fresh");
    const before = has(h, "list") ? (await listMine(h)).length : undefined;
    const contentBefore = has(h, "read") ? await readAs(h, "a", a.url) : undefined;
    await h.hooks.precommitFault.arm();
    let faulted;
    try {
        const out = await h.host.publish(req(page(h, 2), { url: a.url, baseVersion: a.version }), ctxOf(h));
        faulted = out.ok ? "ok" : "typed";
    }
    catch {
        faulted = "threw";
    }
    finally {
        await h.hooks.precommitFault.disarm();
    }
    check(faulted !== "ok", "the armed fault did not fail the publish — the hook is not reaching the host's write path");
    if (contentBefore !== undefined) {
        const contentAfter = await readAs(h, "a", a.url);
        check(contentBefore.ok && contentAfter.ok && contentAfter.content === contentBefore.content && contentAfter.ref.version === contentBefore.ref.version, "the faulted publish changed the readable content or version before any commit");
    }
    const after = await publishOk(h, req(page(h, 3), { url: a.url, baseVersion: a.version }), "update on the pre-fault base");
    check(after.version !== a.version, "the update after the fault did not advance");
    if (before !== undefined)
        check((await listMine(h)).length === before, "the faulted publish left a new page in the listing");
    return `fault ${faulted}; base ${a.version} still applied → ${after.version}`;
});
define({ id: "publish.byte_limits_enforced", describe: "one file over `maxFileBytes` ⇒ `payload_too_large`; with multiFile, files each within the per-file limit but summing past `maxTotalBytes` ⇒ `payload_too_large`", requiresActions: ["publish"] }, async (h) => {
    const big = await publish(h, req([{ path: "index.html", content: new Uint8Array(h.caps.maxFileBytes + 1), mediaType: HTML_MEDIA }]));
    check(!big.ok && big.code === "payload_too_large", `a file of maxFileBytes+1 answered ${big.ok ? "ok" : big.code}`);
    if (!h.caps.multiFile)
        return "per-file limit enforced (single-file host)";
    const files = [];
    let left = h.caps.maxTotalBytes + 1;
    for (let i = 0; left > 0; i++) {
        const size = Math.min(left, h.caps.maxFileBytes);
        files.push({ path: i === 0 ? "index.html" : `part${i}.bin`, content: new Uint8Array(size), mediaType: i === 0 ? HTML_MEDIA : "application/octet-stream" });
        left -= size;
    }
    const total = await publish(h, req(files));
    check(!total.ok && total.code === "payload_too_large", `${files.length} files summing to maxTotalBytes+1 answered ${total.ok ? "ok" : total.code}`);
    return `per-file and total limits enforced (${files.length} files)`;
});
define({ id: "publish.at_limit_accepted", describe: "a file of exactly `maxFileBytes` (within the total) is accepted; with multiFile, files summing to exactly `maxTotalBytes` are accepted", requiresActions: ["publish"], requiresLargePayloads: true }, async (h) => {
    const fileSize = Math.min(h.caps.maxFileBytes, h.caps.maxTotalBytes);
    await publishOk(h, req([{ path: "index.html", content: new Uint8Array(fileSize), mediaType: HTML_MEDIA }]), `a file of exactly ${fileSize} bytes`);
    if (!h.caps.multiFile)
        return `${fileSize} bytes accepted`;
    const files = [];
    let left = h.caps.maxTotalBytes;
    for (let i = 0; left > 0; i++) {
        const size = Math.min(left, h.caps.maxFileBytes);
        files.push({ path: i === 0 ? "index.html" : `part${i}.bin`, content: new Uint8Array(size), mediaType: i === 0 ? HTML_MEDIA : "application/octet-stream" });
        left -= size;
    }
    await publishOk(h, req(files), `${files.length} files summing to exactly maxTotalBytes`);
    return `at-limit file and at-limit total accepted`;
});
define({ id: "list.scope_words", describe: "the caller is the call's `binding.identity`: `mine` lists only pages whose owner record is the caller's (including the ones just published), `shared` only other identities' pages marked shared, `all` both; `truncated` is a boolean on every answer", requiresActions: ["publish", "list"] }, async (h) => {
    const a = await publishOk(h, req(page(h, 1)), "fresh");
    const b = await publishOk(h, req(page(h, 2)), "fresh");
    const me = identityOf(h, "a");
    const mine = await listAs(h, "a", "mine");
    const shared = await listAs(h, "a", "shared");
    const all = await listAs(h, "a", "all");
    for (const [scope, out] of [["mine", mine], ["shared", shared], ["all", all]]) {
        check(out.ok, `list ${scope} refused`);
        check(out.ok && typeof out.truncated === "boolean", `list ${scope}: truncated is not a boolean`);
    }
    if (!mine.ok || !shared.ok || !all.ok)
        return "";
    check(mine.rows.every((r) => identityReadVerdict(r.ownerIdentity, me) === "readable" && r.owner === undefined), "a `mine` row is not the caller's (its owner record does not name the caller, or it carries the share marker)");
    check(shared.rows.every((r) => r.owner === "shared" && identityReadVerdict(r.ownerIdentity, me) === "other_identity"), "a `shared` row is the caller's own, or carries no share marker");
    check([a.url, b.url].every((u) => mine.rows.some((r) => r.url === u)), "the pages just published are missing from `mine`");
    check([a.url, b.url].every((u) => all.rows.some((r) => r.url === u)), "the pages just published are missing from `all`");
    check(all.rows.length >= mine.rows.length, "`all` lists fewer rows than `mine`");
    return `mine ${mine.rows.length}, shared ${shared.rows.length}, all ${all.rows.length}`;
});
define({ id: "list.limit_and_truncated", describe: "`limit` bounds the rows and `truncated` says so when more exist", requiresActions: ["publish", "list"] }, async (h) => {
    await publishOk(h, req(page(h, 1)), "fresh");
    await publishOk(h, req(page(h, 2)), "fresh");
    const out = await listAs(h, "a", "mine", 0, 1);
    check(out.ok, "list refused");
    if (!out.ok)
        return "";
    check(out.rows.length <= 1, `limit 1 answered ${out.rows.length} rows`);
    check(out.truncated === true, "two pages exist but `truncated` is not true at limit 1");
    return "limit honoured, truncated true";
});
define({ id: "read.own_page_full_content", describe: "`read` of the caller's own single-file page returns its full text with `isolatedSummary: false` and the page's ref", requiresActions: ["publish", "read"] }, async (h) => {
    const files = page(h, 1);
    const a = await publishOk(h, req(files), "fresh");
    const out = await readAs(h, "a", a.url);
    check(out.ok, `read refused: ${out.ok ? "" : out.code}`);
    if (!out.ok)
        return "";
    check(out.isolatedSummary === false, "the caller's own page came back as an isolated summary");
    check(out.content === dec.decode(files[0].content), "the content differs from the published text");
    check(out.ref.url === a.url, `read.ref.url is ${out.ref.url}, expected ${a.url}`);
    return "full text, own page";
});
define({ id: "read.unknown_url_typed", describe: "`read` of a url this host never minted ⇒ a typed `not_found` / `forbidden`, never a throw", requiresActions: ["read"] }, async (h) => {
    const out = await readAs(h, "a", FOREIGN_URL);
    check(!out.ok && (out.code === "not_found" || out.code === "forbidden"), `an unknown url answered ${out.ok ? "ok" : out.code}`);
    return out.ok ? "" : out.code;
});
define({ id: "files.list_and_read_file", describe: "`list_files` names every published path with its byte count; `read_file` returns each file's bytes and media type; an unknown path ⇒ `not_found`; both answers carry the page's owner record", requiresActions: ["publish", "list_files", "read_file"] }, async (h) => {
    const files = page(h, 1, h.caps.multiFile ? [script(h, 2)] : []);
    const a = await publishOk(h, req(files), "fresh");
    const listed = await call("list_files", () => h.host.listFiles({ url: a.url }, ctxOf(h)));
    check(listed.ok, `list_files refused: ${listed.ok ? "" : listed.code}`);
    if (!listed.ok)
        return "";
    check(sameIdentity(listed.ownerIdentity, identityOf(h, "a")), `list_files answered owner record ${show(listed.ownerIdentity)}, expected ${show(identityOf(h, "a"))}`);
    for (const f of files) {
        const e = listed.entries.find((x) => x.path === f.path);
        check(e !== undefined && e.bytes === f.content.byteLength, `list_files lacks ${f.path} at ${f.content.byteLength} bytes`);
        const got = await call("read_file", () => h.host.readFile({ url: a.url, path: f.path }, ctxOf(h)));
        check(got.ok, `read_file ${f.path} refused: ${got.ok ? "" : got.code}`);
        if (!got.ok)
            return "";
        check(same(got.file.content, f.content) && got.file.mediaType === f.mediaType, `read_file ${f.path}: bytes or media type differ`);
        check(sameIdentity(got.ownerIdentity, identityOf(h, "a")), `read_file ${f.path} answered owner record ${show(got.ownerIdentity)}`);
    }
    const missing = await call("read_file", () => h.host.readFile({ url: a.url, path: "no/such/file.txt" }, ctxOf(h)));
    check(!missing.ok && missing.code === "not_found", `an unknown path answered ${missing.ok ? "ok" : missing.code}`);
    return `${files.length} file(s) listed and read`;
});
define({ id: "ownership.declared", describe: "`capabilities().ownership` names a word of each closed set (by / people / unrecorded / sharing); each word picks one arm below", requiresActions: ["publish"] }, async (h) => {
    const o = h.caps.ownership;
    for (const member of Object.keys(ARTIFACT_OWNERSHIP_WORDS)) {
        check(ARTIFACT_OWNERSHIP_WORDS[member].includes(o[member]), `ownership.${member} is ${show(o[member])}, outside ${ARTIFACT_OWNERSHIP_WORDS[member].join(" | ")}`);
    }
    return `by ${o.by}, people ${o.people}, unrecorded ${o.unrecorded}, sharing ${o.sharing}`;
});
define({ id: "binding.identities_are_distinct", describe: "the five identities the kit acts as (its own, or the `binding` hook's) are pairwise different identities; `a` / `a2` are one person in two scopes; `a` / `b` are two people with one scope name; `z` is anonymous; each identity's two conversations have two roots", requiresActions: ["publish"] }, async (h) => {
    const ids = WHO.map((w) => [w, identityOf(h, w)]);
    for (const [w, id] of ids)
        check(identityReadVerdict(id, id) === "readable", `identity ${w} (${show(id)}) is not an identity the judge reads`);
    for (const [w1, x] of ids)
        for (const [w2, y] of ids)
            if (w1 < w2)
                check(identityReadVerdict(x, y) !== "readable", `identities ${w1} and ${w2} are one identity (${show(x)} / ${show(y)})`);
    const [a, a2, b] = [identityOf(h, "a"), identityOf(h, "a2"), identityOf(h, "b")];
    check(a.principal === a2.principal, "a and a2 must be one person");
    check(a.principal !== b.principal && (a.isolationScope ?? a.principal) === (b.isolationScope ?? b.principal), "a and b must be two people with one scope name");
    check(identityOf(h, "z").principal === null, "z must be the anonymous identity (principal null)");
    for (const w of WHO)
        check(actorOf(h, w, 0).binding.root.sessionId !== actorOf(h, w, 1).binding.root.sessionId, `identity ${w}'s two conversations share a root`);
    return `five identities, ten runs${h.hooks.binding !== undefined ? " (from the binding hook)" : ""}`;
});
define({ id: "binding.owner_round_trips", describe: "every page records the creating call's `binding.identity` as given and hands it back as `ownerIdentity`, member for member (no scope ⇒ no member; `isolationScope: null` fails), on the publish answer and, where declared, on the list row and the read answer", requiresActions: ["publish"] }, async (h) => {
    const whos = WHO.filter((w) => w !== "z" || h.caps.ownership.people === "one");
    for (const w of whos) {
        const id = identityOf(h, w);
        const ref = await publishOk(h, req(page(h, 1)), `fresh as ${w}`, undefined, w);
        check(sameIdentity(ref.ownerIdentity, id), `publish as ${w} answered owner record ${show(ref.ownerIdentity)}, expected ${show(id)}${bindingHint(h)}`);
        if (has(h, "list")) {
            const out = await listAs(h, w, "mine");
            const row = out.ok ? out.rows.find((r) => r.url === ref.url) : undefined;
            check(row !== undefined && sameIdentity(row.ownerIdentity, id), `list mine as ${w}: the page is missing or its row's owner record is ${show(row?.ownerIdentity)}`);
        }
        if (has(h, "read")) {
            const out = await readAs(h, w, ref.url);
            check(out.ok && sameIdentity(out.ref.ownerIdentity, id), `read as ${w}: ${out.ok ? `owner record ${show(out.ref.ownerIdentity)}` : `refused ${out.code}`}`);
        }
    }
    return `${whos.length} identities round-trip their owner record`;
});
define({ id: "binding.same_identity_across_runs", describe: "`by: \"identity\"` (which declares read): another run of the same identity (another conversation) updates, reads and lists the page an earlier run published", requiresActions: ["publish", "read"], requiresOwnership: { by: "identity" } }, async (h) => {
    const files = page(h, 2);
    const a = await publishOk(h, req(page(h, 1)), "fresh in a's first run");
    const b = await publishOk(h, req(files, { url: a.url, baseVersion: a.version }), "update from a's second run", undefined, "a", 1);
    check(b.url === a.url && b.version !== a.version, `the second run's update answered ${b.url} @ ${b.version}`);
    const read = await readAs(h, "a", a.url, 1);
    check(read.ok && read.isolatedSummary === false && read.content === dec.decode(files[0].content), "the second run does not read its own page in full");
    if (has(h, "list")) {
        const out = await listAs(h, "a", "mine", 1);
        check(out.ok && out.rows.some((r) => r.url === a.url), "the second run does not list its own page under mine");
    }
    return `one identity, two runs, one page (${a.url})`;
});
define({ id: "binding.run_mints_only", describe: "`by: \"run\"`: another run of the same identity naming the page's url ⇒ `url_foreign` / `not_found`, and (where list is declared) that run's `mine` listing does not hold the page (only what a run minted is the caller's)", requiresActions: ["publish"], requiresOwnership: { by: "run" } }, async (h) => {
    const a = await publishOk(h, req(page(h, 1)), "fresh in a's first run");
    if (has(h, "list")) {
        const listed = await listAs(h, "a", "mine", 1);
        check(listed.ok && !listed.rows.some((r) => r.url === a.url), listed.ok ? "another run of the same identity lists the page under mine" : `another run's list mine refused: ${listed.message}`);
    }
    const out = await publish(h, req(page(h, 2), { url: a.url, baseVersion: a.version }), undefined, "a", 1);
    check(!out.ok && (out.code === "url_foreign" || out.code === "not_found"), `another run naming the page answered ${out.ok ? "ok" : out.code}, expected url_foreign / not_found`);
    return out.ok ? "" : out.code;
});
define({ id: "binding.anonymous_refused_everywhere", describe: "`people: \"many\"`: every call the anonymous identity makes is refused — publish (fresh and by url), list, read, list_files, read_file — and nothing is minted for it", requiresActions: ["publish"], requiresOwnership: { people: "many" } }, async (h) => {
    const target = await publishOk(h, req(page(h, 1)), "a's page");
    const fresh = await publish(h, req(page(h, 2)), undefined, "z");
    check(!fresh.ok, `an anonymous fresh publish answered ok (${fresh.ok ? fresh.ref.url : ""})`);
    const byUrl = await publish(h, req(page(h, 3), { url: target.url }), undefined, "z");
    check(!byUrl.ok && byUrl.code !== "conflict", `an anonymous update answered ${byUrl.ok ? "ok" : byUrl.code}`);
    const refused = ["publish"];
    if (has(h, "list")) {
        for (const scope of ["mine", "shared", "all"])
            check(!(await listAs(h, "z", scope)).ok, `an anonymous list ${scope} answered ok`);
        refused.push("list");
    }
    if (has(h, "read")) {
        check(!(await readAs(h, "z", target.url)).ok, "an anonymous read answered ok");
        refused.push("read");
    }
    if (has(h, "list_files")) {
        check(!(await call("list_files", () => h.host.listFiles({ url: target.url }, ctxOf(h, "z")))).ok, "an anonymous list_files answered ok");
        refused.push("list_files");
    }
    if (has(h, "read_file")) {
        check(!(await call("read_file", () => h.host.readFile({ url: target.url, path: "index.html" }, ctxOf(h, "z")))).ok, "an anonymous read_file answered ok");
        refused.push("read_file");
    }
    return `anonymous refused: ${refused.join(", ")}`;
});
define({ id: "binding.anonymous_is_one_identity", describe: "`people: \"one\"`: the anonymous identity is one identity — its page is not a named identity's (not listed, read or updated by `a`), a named identity's page is not its, and (by identity) another anonymous run reaches its page", requiresActions: ["publish"], requiresOwnership: { people: "one" } }, async (h) => {
    const zPage = await publishOk(h, req(page(h, 1)), "z's page", undefined, "z");
    const aPage = await publishOk(h, req(page(h, 2)), "a's page");
    await updatesRefused(h, "a", zPage.url, zPage.version, "z's page");
    await updatesRefused(h, "z", aPage.url, aPage.version, "a's page");
    if (has(h, "list")) {
        await listsNone(h, "a", [zPage.url], "z's page");
        await listsNone(h, "z", [aPage.url], "a's page");
    }
    if (has(h, "read")) {
        await readRefused(h, "a", zPage.url, "z's page");
        await readRefused(h, "z", aPage.url, "a's page");
    }
    if (h.caps.ownership.by === "identity") {
        const again = await publishOk(h, req(page(h, 3), { url: zPage.url, baseVersion: zPage.version }), "another anonymous run updating z's page", undefined, "z", 1);
        check(again.url === zPage.url, "another anonymous run did not reach the anonymous page");
    }
    return "anonymous is one identity, apart from every named one";
});
define({ id: "binding.unrecorded_publish_refused", describe: "`unrecorded: \"never\"`: a call whose binding names no identity — an identity with no `principal` member (with or without a scope), or no binding at all (a direct call) — is refused, never stored", requiresActions: ["publish"], requiresOwnership: { unrecorded: "never" } }, async (h) => {
    const base = ctxOf(h);
    const scopeOnly = { isolationScope: "conformance-scope" };
    const arms = [
        ["an identity with no principal member", { ...base, attemptId: `${h.runId}-unrecorded-1`, binding: { ...base.binding, identity: {} } }],
        ["an identity with a scope and no principal member", { ...base, attemptId: `${h.runId}-unrecorded-2`, binding: { ...base.binding, identity: scopeOnly } }],
        ["no binding", (({ binding: _b, ...rest }) => ({ ...rest, attemptId: `${h.runId}-unrecorded-3` }))(base)],
    ];
    for (const [arm, ctx] of arms) {
        const out = await call(`publish with ${arm}`, () => h.host.publish(req(page(h, 1)), ctx));
        check(!out.ok, `a publish with ${arm} answered ok (${out.ok ? out.ref.url : ""}): a page with no owner identity`);
    }
    return "every identity-less call refused";
});
define({ id: "binding.unrecorded_is_nobodys", describe: "`unrecorded: \"possible\"`: a page whose owner record names no identity (seeded through the `seedUnrecordedPage` hook) is nobody's — neither `a` nor the anonymous identity lists, reads or updates it", requiresActions: ["publish"], requiresOwnership: { unrecorded: "possible" } }, async (h) => {
    if (h.hooks.seedUnrecordedPage === undefined)
        return fail("the host declares unrecorded: \"possible\" but the `seedUnrecordedPage` hook is not supplied: supply it");
    const url = await call("seedUnrecordedPage", async () => h.hooks.seedUnrecordedPage());
    for (const w of ["a", "z"]) {
        const out = await publish(h, req(page(h, 1), { url }), undefined, w);
        check(!out.ok && out.code !== "conflict", `${w} updating the unrecorded page answered ${out.ok ? "ok" : out.code}`);
        if (has(h, "list"))
            await listsNone(h, w, [url], "the unrecorded page");
        if (has(h, "read")) {
            const r = await readAs(h, w, url);
            check(!r.ok, `${w} reading the unrecorded page answered ok`);
        }
    }
    return "the unrecorded page is nobody's";
});
define({ id: "binding.share_marks_never_set", describe: "`sharing: \"none\"`: no answer the kit reads carries a share marker — no list row `owner: \"shared\"`, no read answer `isolatedSummary: true` — across identities", requiresActions: ["publish"], requiresOwnership: { sharing: "none" } }, async (h) => {
    const aPage = await publishOk(h, req(page(h, 1)), "a's page");
    await publishOk(h, req(page(h, 2)), "b's page", undefined, "b");
    for (const w of ["a", "a2", "b", "c"]) {
        if (has(h, "list"))
            for (const scope of ["mine", "shared", "all"])
                await listAs(h, w, scope);
        if (has(h, "read"))
            await readAs(h, w, aPage.url);
    }
    return "no share marker set";
});
define({ id: "binding.shared_is_read_only", describe: "`sharing: \"marked\"`: a page `a` owns, shared with `b` through the `share` hook, is listed to `b` as shared (owner record `a`'s) and read as an isolated summary, never updated by `b`; `c`, not granted, neither lists nor reads it; `a` still reads it in full", requiresActions: ["publish"], requiresOwnership: { sharing: "marked" } }, async (h) => {
    if (h.hooks.share === undefined)
        return fail("the host declares sharing: \"marked\" but the `share` hook is not supplied: supply it");
    const files = page(h, 1);
    const p = await publishOk(h, req(files), "a's page");
    await call("share", async () => h.hooks.share(p.url, identityOf(h, "a"), identityOf(h, "b")));
    if (has(h, "list")) {
        for (const scope of ["shared", "all"]) {
            const out = await listAs(h, "b", scope);
            const row = out.ok ? out.rows.find((r) => r.url === p.url) : undefined;
            check(row !== undefined && row.owner === "shared" && sameIdentity(row.ownerIdentity, identityOf(h, "a")), `b's ${scope} listing: the shared page is missing, unmarked, or its owner record is not a's`);
        }
        const mine = await listAs(h, "b", "mine");
        check(mine.ok && !mine.rows.some((r) => r.url === p.url), "b lists a's shared page under mine");
        await listsNone(h, "c", [p.url], "a page shared with b only");
    }
    if (has(h, "read")) {
        const out = await readAs(h, "b", p.url);
        check(out.ok && out.isolatedSummary === true, `b reading the shared page answered ${out.ok ? "full content" : out.code}, expected an isolated summary`);
        await readRefused(h, "c", p.url, "a page shared with b only");
        const own = await readAs(h, "a", p.url);
        check(own.ok && own.isolatedSummary === false && own.content === dec.decode(files[0].content), "a no longer reads its own page in full");
    }
    await updatesRefused(h, "b", p.url, p.version, "a page shared with it");
    return "shared: listed and summarized to b, read-only, invisible to c";
});
define({ id: "binding.list_does_not_cross", describe: "a page is listed to no other identity under any scope (no grant: `shared` is empty too): `a2` (same person, other scope), `b` (other person, same scope name), `c` (other person); and `c` does not list `b`'s; under every scope, a limit that holds every row the caller sees answers `truncated: false` (it counts only what the caller may see)", requiresActions: ["publish", "list"] }, async (h) => {
    const p1 = await publishOk(h, req(page(h, 1)), "a's first page");
    const p2 = await publishOk(h, req(page(h, 2)), "a's second page");
    for (const w of ["a2", "b", "c"])
        await listsNone(h, w, [p1.url, p2.url], "a's pages");
    const q = await publishOk(h, req(page(h, 3)), "b's page", undefined, "b");
    await listsNone(h, "c", [q.url], "b's page");
    for (const w of ["a2", "b", "c"]) {
        const mine = await listAs(h, w, "mine");
        check(mine.ok && mine.rows.every((r) => identityReadVerdict(r.ownerIdentity, identityOf(h, w)) === "readable"), `${w}'s mine listing carries a row whose owner record is not ${w}'s`);
        for (const scope of ARTIFACT_LIST_SCOPES) {
            const wide = await listAs(h, w, scope);
            const seen = wide.ok ? wide.rows.length : 0;
            const tight = await listAs(h, w, scope, 0, Math.max(1, seen));
            check(tight.ok && tight.truncated === false, `${w}'s ${scope} listing at limit ${Math.max(1, seen)} (every row it sees) says more artifacts exist: \`truncated\` counts pages ${w} may not see`);
        }
    }
    return "no listing crosses identities";
});
define({ id: "binding.read_does_not_cross", describe: "`a2`, `b` and `c` reading `a`'s page ⇒ `not_found` / `forbidden`, no content; `c` reading `b`'s likewise", requiresActions: ["publish", "read"] }, async (h) => {
    const p = await publishOk(h, req(page(h, 1)), "a's page");
    for (const w of ["a2", "b", "c"])
        await readRefused(h, w, p.url, "a's page");
    const q = await publishOk(h, req(page(h, 2)), "b's page", undefined, "b");
    await readRefused(h, "c", q.url, "b's page");
    return "no read crosses identities";
});
define({ id: "binding.update_does_not_cross", describe: "`a2`, `b` and `c` updating `a`'s page — no base, `a`'s current base, force — ⇒ only `not_found` / `forbidden` / `url_foreign` (never ok, never conflict); `a`'s page keeps its version and bytes; `c` updating `b`'s likewise", requiresActions: ["publish"] }, async (h) => {
    const files = page(h, 1);
    const p = await publishOk(h, req(files), "a's page");
    for (const w of ["a2", "b", "c"])
        await updatesRefused(h, w, p.url, p.version, "a's page");
    const q = await publishOk(h, req(page(h, 2)), "b's page", undefined, "b");
    await updatesRefused(h, "c", q.url, q.version, "b's page");
    if (has(h, "read")) {
        const out = await readAs(h, "a", p.url);
        check(out.ok && out.ref.version === p.version && out.content === dec.decode(files[0].content), "a's page changed under another identity's update");
    }
    const after = await publishOk(h, req(page(h, 3), { url: p.url, baseVersion: p.version }), "a's own update on its unchanged base");
    check(after.version !== p.version, "a's own update did not advance");
    return "no update crosses identities; the page kept its version";
});
define({ id: "binding.refusal_names_no_owner", describe: "the text of every refusal another identity gets for `a`'s page (update arms; read, list_files and read_file where declared) names neither `a`'s principal nor `a`'s isolation scope", requiresActions: ["publish"] }, async (h) => {
    const files = page(h, 1);
    const p = await publishOk(h, req(files), "a's page");
    const a = identityOf(h, "a");
    const names = [a.principal, a.isolationScope].filter((x) => typeof x === "string" && x.length > 0);
    const texts = [];
    const refusalOf = (out) => void (!out.ok && typeof out.message === "string" && texts.push(out.message));
    for (const w of ["a2", "b", "c"]) {
        texts.push(...(await updatesRefused(h, w, p.url, p.version, "a's page")));
        if (has(h, "read"))
            texts.push(await readRefused(h, w, p.url, "a's page"));
        if (has(h, "list_files"))
            refusalOf(await call("list_files", () => h.host.listFiles({ url: p.url }, ctxOf(h, w))));
        if (has(h, "read_file"))
            refusalOf(await call("read_file", () => h.host.readFile({ url: p.url, path: files[0].path }, ctxOf(h, w))));
    }
    for (const t of texts)
        for (const n of names)
            check(!t.includes(n), `a refusal text names the page owner (${show(n)}): ${show(t.slice(0, 200))}`);
    return `${texts.length} refusal texts name no owner`;
});
define({ id: "binding.foreign_page_answers_as_absent", describe: "another identity's page that is not shared with the caller is answered exactly as a url with no page: on every declared face (an update, read, list_files, read_file) the same code and the same message (the url itself aside), and the message names nothing of the page (its title)", requiresActions: ["publish"] }, async (h) => {
    const title = `conformance-title-${h.runId}`;
    const p = await publishOk(h, req(page(h, 1), { title }), "a's titled page");
    const absent = h.hooks.absentUrl !== undefined ? await call("absentUrl", async () => h.hooks.absentUrl()) : `${p.url}-conformance-absent`;
    const hint = h.hooks.absentUrl === undefined ? " (if the host's urls carry a checked form, supply the `absentUrl` hook)" : "";
    const faces = [["update", (url) => publish(h, req(page(h, 2), { url }), undefined, "b")]];
    if (has(h, "read"))
        faces.push(["read", (url) => readAs(h, "b", url)]);
    if (has(h, "list_files"))
        faces.push(["list_files", (url) => call("list_files", () => h.host.listFiles({ url }, ctxOf(h, "b")))]);
    if (has(h, "read_file"))
        faces.push(["read_file", (url) => call("read_file", () => h.host.readFile({ url, path: "index.html" }, ctxOf(h, "b")))]);
    const said = (out, url) => (typeof out.message === "string" ? out.message.split(url).join("<url>") : "");
    for (const [face, ask] of faces) {
        const theirs = await ask(p.url);
        const none = await ask(absent);
        check(!theirs.ok && !none.ok, `${face} as b: a's page answered ${theirs.ok ? "ok" : theirs.code}, a url with no page ${none.ok ? "ok" : none.code} — both must be refused${bindingHint(h)}`);
        check(theirs.code === none.code, `${face} as b: a's page is refused with ${show(theirs.code)}, a url with no page with ${show(none.code)} — another identity's page must read as no page${hint}`);
        check(said(theirs, p.url) === said(none, absent), `${face} as b: a's page and a url with no page are refused in different words (${show(said(theirs, p.url).slice(0, 160))} / ${show(said(none, absent).slice(0, 160))})${hint}`);
        check(!said(theirs, p.url).includes(title), `${face} as b: the refusal names the page's title`);
    }
    return `${faces.length} face(s): another identity's page reads as no page`;
});
for (const action of ["list_files", "read_file"]) {
    define({ id: `binding.files_do_not_cross.${action}`, describe: `\`a2\`, \`b\` and \`c\` asking ${action} of \`a\`'s page ⇒ \`not_found\` / \`forbidden\`; \`c\` of \`b\`'s likewise`, requiresActions: ["publish", action] }, async (h) => {
        const ask = async (w, url, label) => {
            const out = action === "list_files" ? await call(action, () => h.host.listFiles({ url }, ctxOf(h, w))) : await call(action, () => h.host.readFile({ url, path: "index.html" }, ctxOf(h, w)));
            check(!out.ok && (out.code === "not_found" || out.code === "forbidden"), `${w} asking ${action} of ${label} answered ${out.ok ? "ok" : out.code}${bindingHint(h)}`);
        };
        const p = await publishOk(h, req(page(h, 1)), "a's page");
        for (const w of ["a2", "b", "c"])
            await ask(w, p.url, "a's page");
        const q = await publishOk(h, req(page(h, 2)), "b's page", undefined, "b");
        await ask("c", q.url, "b's page");
        return `no ${action} crosses identities`;
    });
}
export const ARTIFACT_CONFORMANCE_VECTORS = vectorTable.map(({ run: _run, ...v }) => Object.freeze(v));
const applies = (v, caps) => v.requiresActions.every((a) => caps.actions.includes(a)) &&
    (v.requiresMultiFile !== true || caps.multiFile) &&
    Object.entries(v.requiresOwnership ?? {}).every(([k, word]) => caps.ownership[k] === word);
export function artifactConformanceVectors(host) {
    const verdict = readArtifactHostCapabilities(host);
    if (!verdict.ok)
        throw new Error(`artifactConformanceVectors: the host's declaration is invalid — ${verdict.problem}`);
    return ARTIFACT_CONFORMANCE_VECTORS.filter((v) => applies(v, verdict.capabilities));
}
function syntheticBinding(nonce, who, conversation) {
    const p = `conformance-person-p-${nonce}`;
    const q = `conformance-person-q-${nonce}`;
    const identity = { a: { principal: p, isolationScope: `conformance-scope-s1-${nonce}` }, a2: { principal: p, isolationScope: `conformance-scope-s2-${nonce}` }, b: { principal: q, isolationScope: `conformance-scope-s1-${nonce}` }, c: { principal: q }, z: { principal: null } }[who];
    return { identity, root: { sessionId: `conformance-${who}-${conversation}-${nonce}` } };
}
export async function runArtifactConformance(host, opts = {}) {
    const verdict = readArtifactHostCapabilities(host);
    if (!verdict.ok)
        throw new Error(`runArtifactConformance: the host's declaration is invalid — ${verdict.problem}`);
    const h = { host, caps: verdict.capabilities, runId: opts.runId ?? randomUUID(), hooks: opts.hooks ?? {}, largePayloads: opts.largePayloads === true, actors: new Map(), seq: 0 };
    const nonce = randomUUID().slice(0, 8);
    for (const who of WHO) {
        for (const conversation of [0, 1]) {
            const runId = who === "a" && conversation === 0 ? h.runId : randomUUID();
            try {
                const binding = h.hooks.binding !== undefined ? await h.hooks.binding(who, conversation) : syntheticBinding(nonce, who, conversation);
                host.onMount?.(runId);
                h.actors.set(`${who}/${conversation}`, { runId, binding });
            }
            catch (err) {
                h.actors.set(`${who}/${conversation}`, { error: `the binding hook (or onMount) failed for ${who} in conversation ${conversation}: ${thrownText(err)}` });
            }
        }
    }
    const results = [];
    for (const v of vectorTable) {
        if (!applies(v, h.caps)) {
            const ownership = Object.entries(v.requiresOwnership ?? {}).map(([k, w]) => `ownership.${k} ${w}`);
            results.push({ id: v.id, status: "not_applicable", detail: `requires ${[...v.requiresActions, ...(v.requiresMultiFile ? ["multiFile"] : []), ...ownership].join(" + ")}; not declared` });
            continue;
        }
        if (v.requiresHook !== undefined && h.hooks[v.requiresHook] === undefined) {
            results.push({ id: v.id, status: "skipped", detail: `hook ${v.requiresHook} not supplied` });
            continue;
        }
        if (v.requiresLargePayloads === true && !h.largePayloads) {
            results.push({ id: v.id, status: "skipped", detail: "largePayloads not enabled" });
            continue;
        }
        let row;
        try {
            row = { id: v.id, status: "pass", detail: await v.run(h) };
        }
        catch (err) {
            row = { id: v.id, status: "fail", detail: err instanceof Violation ? err.message : `threw: ${thrownText(err)}` };
        }
        results.push(row);
    }
    const count = (s) => results.filter((r) => r.status === s).length;
    return { capabilities: h.caps, runId: h.runId, results, passed: count("pass"), failed: count("fail"), notApplicable: count("not_applicable"), skipped: count("skipped") };
}