@mostra/conformance 0.2.0 → 0.4.0

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/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as SCENARIOS, t as runConformance, y as readBaseline } from "./runner-CvoSJlfk.js";
2
+ import { n as SCENARIOS, t as runConformance, y as readBaseline } from "./runner-BlBQXUFz.js";
3
3
  import { parseArgs } from "node:util";
4
4
  //#region src/cli.ts
5
5
  /**
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as FIXTURES, a as ScenarioFailure, c as Browser, d as parseLink, f as resultOf, g as codeOf, h as InstanceError, i as ScenarioContext, l as OpenError, m as HostUnderTest, n as SCENARIOS, o as check, p as send, r as NotApplicable, s as same, t as runConformance, u as Viewer, v as NO_BASELINE, y as readBaseline } from "./runner-CvoSJlfk.js";
1
+ import { _ as FIXTURES, a as ScenarioFailure, c as Browser, d as parseLink, f as resultOf, g as codeOf, h as InstanceError, i as ScenarioContext, l as OpenError, m as HostUnderTest, n as SCENARIOS, o as check, p as send, r as NotApplicable, s as same, t as runConformance, u as Viewer, v as NO_BASELINE, y as readBaseline } from "./runner-BlBQXUFz.js";
2
2
  import { a as HARNESS_METHODS, o as HARNESS_REVISIONS } from "./protocol-RQ9lbehE.js";
3
3
  import { i as serveHarness, n as ReferenceStore, r as runReferenceHost, t as REFERENCE_FAULTS } from "./reference-host-d6gs3Tal.js";
4
4
  export { Browser, FIXTURES, HARNESS_METHODS, HARNESS_REVISIONS, HostUnderTest, InstanceError, NO_BASELINE, NotApplicable, OpenError, REFERENCE_FAULTS, ReferenceStore, SCENARIOS, ScenarioContext, ScenarioFailure, Viewer, check, codeOf, parseLink, readBaseline, resultOf, runConformance, runReferenceHost, same, send, serveHarness };
@@ -4,8 +4,8 @@ import * as z from "zod";
4
4
  import { spawn } from "node:child_process";
5
5
  import { BROWSER_PROTOCOL_REVISIONS, HOST_PROTOCOL_REVISIONS, LineSplitter, MutationId, RpcError, RpcPeer, createDiagnostic, deserializeAll, encodeLine, serializeAll } from "@mostra/protocol";
6
6
  import { dirname, join } from "node:path";
7
+ import { connectControl, resolveRuntime } from "@mostra/sdk";
7
8
  import { tmpdir } from "node:os";
8
- import { createConnection } from "node:net";
9
9
  import { request } from "node:http";
10
10
  //#region src/baseline.ts
11
11
  /**
@@ -769,11 +769,7 @@ function removeTree(dir) {
769
769
  }
770
770
  /** Connects to an instance's socket and initializes a session as `@mostra/conformance`. */
771
771
  async function connectSocket(path, revisions = HOST_PROTOCOL_REVISIONS) {
772
- const socket = await new Promise((resolve, reject) => {
773
- const connection = createConnection(path);
774
- connection.once("connect", () => resolve(connection));
775
- connection.once("error", reject);
776
- });
772
+ const socket = await connectControl(path, { runtime: process.platform === "win32" ? await resolveRuntime() : void 0 });
777
773
  const peer = new RpcPeer({ send: (message) => {
778
774
  if (!socket.destroyed) socket.write(encodeLine(message));
779
775
  } });
@@ -1937,4 +1933,4 @@ async function runConformance(options) {
1937
1933
  //#endregion
1938
1934
  export { FIXTURES as _, ScenarioFailure as a, Browser as c, parseLink as d, resultOf as f, codeOf as g, InstanceError as h, ScenarioContext as i, OpenError as l, HostUnderTest as m, SCENARIOS as n, check as o, send as p, NotApplicable as r, same as s, runConformance as t, Viewer as u, NO_BASELINE as v, readBaseline as y };
1939
1935
 
1940
- //# sourceMappingURL=runner-CvoSJlfk.js.map
1936
+ //# sourceMappingURL=runner-BlBQXUFz.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner-BlBQXUFz.js","names":["InitializeResultSchema","StartResultSchema","CallResultSchema","StoreResultSchema","EventsResultSchema","httpRequest"],"sources":["../src/baseline.ts","../src/fixtures.ts","../src/harness/client.ts","../src/viewer.ts","../src/scenario.ts","../src/scenarios/delivery.ts","../src/scenarios/interaction.ts","../src/scenarios/ports.ts","../src/scenarios/session.ts","../src/scenarios/viewing.ts","../src/scenarios/index.ts","../src/runner.ts"],"sourcesContent":["/**\n * Expected-failure baselines (HO-05): a host that knows it fails some scenarios today records them,\n * with why, so a run stays green while the gap is known and goes red the moment anything changes:\n * a scenario that newly fails, or one the baseline expects to fail that passes (the baseline is\n * then stale and must shrink). The pattern of the MCP conformance suite and WPT's expectations.\n *\n * ```json\n * { \"schemaVersion\": 1, \"expectedFailures\": { \"delivery.exactly-once\": \"our store isn't idempotent yet (#123)\" } }\n * ```\n */\nimport { readFileSync } from \"node:fs\";\nimport * as z from \"zod\";\n\n/** A baseline: the scenarios a host is expected to fail, each with its reason. */\nexport interface Baseline {\n /** The baseline format's version: 1. */\n readonly schemaVersion: 1;\n /** Each expected failure: the scenario's ID and why it fails. */\n readonly expectedFailures: Readonly<Record<string, string>>;\n}\n\nconst BaselineSchema: z.ZodType<Baseline> = z.strictObject({\n schemaVersion: z.literal(1),\n expectedFailures: z.record(z.string().min(1), z.string().min(1)),\n});\n\n/** An empty baseline: every scenario must pass. */\nexport const NO_BASELINE: Baseline = { schemaVersion: 1, expectedFailures: {} };\n\n/**\n * Reads a baseline file. Throws on a file that isn't one, and on a scenario ID no scenario of\n * `known` has (a typo would otherwise expect nothing, silently).\n */\nexport function readBaseline(path: string, known: readonly string[]): Baseline {\n let data: unknown;\n try {\n data = JSON.parse(readFileSync(path, \"utf8\"));\n } catch (error) {\n throw new Error(`${path} isn't a readable JSON baseline: ${(error as Error).message}`);\n }\n const parsed = BaselineSchema.safeParse(data);\n if (!parsed.success) {\n throw new Error(\n `${path} isn't a conformance baseline: { \"schemaVersion\": 1, \"expectedFailures\": { \"<scenario>\": \"<why>\" } }.`,\n );\n }\n const unknown = Object.keys(parsed.data.expectedFailures).filter((id) => !known.includes(id));\n if (unknown.length > 0)\n throw new Error(`${path} names scenarios the kit doesn't have: ${unknown.join(\", \")}.`);\n return parsed.data;\n}\n","/**\n * The artifacts the scenarios publish, written fresh into the run's authoring directory. They\n * declare their fields with literal IDs, so every answer a scenario writes is covered by the\n * version (D109) and none is orphaned by accident.\n */\n\n/** A fixture: its files by relative path. */\nexport type Fixture = Readonly<Record<string, string>>;\n\n/** A questionnaire with viewer fields, an artifact-scoped counter, a family and a link (H-06). */\nexport const FORM: Fixture = {\n \"index.tsx\": `import { defineArtifact, useField, useSubmitControl } from \"@mostra/react\";\n\nexport const artifact = defineArtifact({\n title: \"Conformance questionnaire\",\n description: \"The form the host conformance kit answers.\",\n family: \"questionnaire\",\n links: [{ rel: \"round-of\", artifact: \"conformance-round-1\" }],\n});\n\nexport default function Page() {\n useSubmitControl({ label: \"Send answers\" });\n const [name, setName] = useField(\"name\", \"\", { label: \"Your name\", required: true });\n const [comment, setComment] = useField(\"comment\", \"\", { label: \"Comment\" });\n const [count, setCount] = useField(\"count\", 0, { label: \"Count\", scope: \"artifact\" });\n const [done, setDone] = useField(\"done\", false, { label: \"Done\", scope: \"artifact\" });\n return (\n <main>\n <h1>Conformance questionnaire</h1>\n <input name=\"name\" aria-label=\"Your name\" value={name} onChange={(e) => setName(e.target.value)} />\n <textarea name=\"comment\" aria-label=\"Comment\" value={comment} onChange={(e) => setComment(e.target.value)} />\n <button type=\"button\" onClick={() => setCount(count + 1)}>Count {count}</button>\n <label><input type=\"checkbox\" checked={done} onChange={(e) => setDone(e.target.checked)} /> Done</label>\n </main>\n );\n}\n`,\n};\n\n/** The same questionnaire with one more question: a second version of {@link FORM}. */\nexport const FORM_V2: Fixture = {\n \"index.tsx\": (FORM[\"index.tsx\"] as string)\n .replace(\"<h1>Conformance questionnaire</h1>\", \"<h1>Conformance questionnaire, round 2</h1>\")\n .replace(\n \" const [done, setDone]\",\n ' const [extra, setExtra] = useField(\"extra\", \"\", { label: \"Extra\" });\\n const [done, setDone]',\n )\n .replace(\n \" <label>\",\n ' <input name=\"extra\" aria-label=\"Extra\" value={extra} onChange={(e) => setExtra(e.target.value)} />\\n <label>',\n ),\n};\n\n/**\n * Server code: an action that raises a signal and emits a host event (AC-05), and one that reads\n * a secret through `secret()` (D131) and returns only its length, never the value.\n */\nexport const ACTIONS: Fixture = {\n \"index.tsx\": `import { defineArtifact } from \"@mostra/react\";\n\nexport const artifact = defineArtifact({ title: \"Conformance actions\" });\n\nexport default function Page() {\n return <main><h1>Conformance actions</h1></main>;\n}\n`,\n \"actions.ts\": `\"use server\";\nimport { emit, secret, signal } from \"@mostra/server\";\n\nexport async function notify(to: string): Promise<string> {\n signal(\"mail.sent\", { to });\n emit(\"host.mail.sent\", { to });\n return \"sent\";\n}\n\nexport async function secretLength(name: string): Promise<number> {\n return secret(name).length;\n}\n`,\n};\n\n/** The bundled fixtures by name. */\nexport const FIXTURES: Readonly<Record<string, Fixture>> = {\n form: FORM,\n \"form-v2\": FORM_V2,\n actions: ACTIONS,\n};\n","/**\n * The kit's side of the harness protocol: starts a host's shim (a command line), speaks to it\n * over its stdio, and gives scenarios typed methods. The shim's stderr is kept (its last lines\n * explain a failure). A shim that exits ends every pending call with\n * `MOSTRA_HOST_CONNECTION_CLOSED`.\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport {\n createDiagnostic,\n type Diagnostic,\n encodeLine,\n LineSplitter,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport { kitVersion } from \"../version.ts\";\nimport {\n type CallError,\n type CallResult,\n CallResult as CallResultSchema,\n type EventsParams,\n type EventsResult,\n EventsResult as EventsResultSchema,\n HARNESS_METHODS,\n HARNESS_REVISIONS,\n type InitializeResult,\n InitializeResult as InitializeResultSchema,\n type ScriptParams,\n type StartParams,\n type StartResult,\n StartResult as StartResultSchema,\n type StoreResult,\n StoreResult as StoreResultSchema,\n} from \"./protocol.ts\";\n\n/** How long one harness request may take before the kit gives up on the host. */\nconst HARNESS_TIMEOUT_MS = 120_000;\n\n/** An instance's error, carried through the host: its diagnostic code and JSON-RPC code. */\nexport class InstanceError extends Error {\n /** The diagnostic code (`MOSTRA_…`). */\n readonly code: string;\n /** The JSON-RPC error code. */\n readonly rpcCode: number;\n /** The diagnostic as it arrived. */\n readonly data: CallError[\"data\"];\n\n constructor(method: string, error: CallError) {\n super(`${method} failed with ${error.data.code}: ${error.data.message ?? \"\"}`);\n this.name = \"InstanceError\";\n this.code = error.data.code;\n this.rpcCode = error.code;\n this.data = error.data;\n }\n}\n\n/** A host under test, reached through its harness shim. */\nexport class HostUnderTest {\n readonly #child: ChildProcess;\n readonly #peer: RpcPeer;\n readonly #stderr: string[] = [];\n readonly #exited: Promise<number | null>;\n /** What the host said about itself. */\n info: InitializeResult | undefined;\n\n private constructor(command: string, env: Readonly<Record<string, string>>) {\n this.#child = spawn(command, {\n shell: true,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: { ...process.env, ...env } as NodeJS.ProcessEnv,\n detached: true,\n });\n this.#exited = new Promise((done) => {\n this.#child.on(\"close\", (code) => done(code));\n this.#child.on(\"error\", () => done(null));\n });\n this.#peer = new RpcPeer({\n send: (message) => {\n if (this.#child.stdin?.writable) this.#child.stdin.write(encodeLine(message));\n },\n });\n const lines = new LineSplitter();\n this.#child.stdout?.setEncoding(\"utf8\");\n this.#child.stdout?.on(\"data\", (chunk: string) => {\n for (const line of lines.push(chunk)) this.#peer.receiveLine(line);\n });\n const errors = new LineSplitter();\n this.#child.stderr?.setEncoding(\"utf8\");\n this.#child.stderr?.on(\"data\", (chunk: string) => {\n for (const line of errors.push(chunk)) {\n this.#stderr.push(line);\n if (this.#stderr.length > 40) this.#stderr.shift();\n }\n });\n this.#child.stdin?.on(\"error\", () => {});\n void this.#exited.then((code) =>\n this.#peer.close(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `The host under test exited (${code ?? \"signal\"}): ${this.#stderr.slice(-3).join(\" | \")}`,\n }),\n ),\n );\n }\n\n /** Starts the shim and asks it who it is. */\n static async start(\n command: string,\n env: Readonly<Record<string, string>> = {},\n ): Promise<HostUnderTest> {\n const host = new HostUnderTest(command, env);\n try {\n const answer = await host.#request(HARNESS_METHODS.initialize, {\n revision: HARNESS_REVISIONS.at(-1),\n kit: { name: \"@mostra/conformance\", version: kitVersion() },\n });\n host.info = InitializeResultSchema.parse(answer);\n } catch (error) {\n await host.close();\n throw error;\n }\n return host;\n }\n\n /** The host's last stderr lines. */\n get stderr(): readonly string[] {\n return this.#stderr;\n }\n\n /** Whether the host serves `port` / supports `feature`. */\n serves(port: string): boolean {\n return this.info?.ports.includes(port) ?? false;\n }\n /** Whether the host supports the harness feature `feature`. */\n supports(feature: string): boolean {\n return this.info?.features.includes(feature) ?? false;\n }\n\n #request(method: string, params: unknown, timeoutMs = HARNESS_TIMEOUT_MS): Promise<unknown> {\n return this.#peer.request(method, params as never, { timeoutMs });\n }\n\n /** `harness/start`: the host starts or attaches to its instance. */\n async startInstance(params: StartParams): Promise<StartResult> {\n return StartResultSchema.parse(await this.#request(HARNESS_METHODS.start, params));\n }\n\n /** `harness/call`, raw: the instance's answer or error as the host received it. */\n async callRaw(method: string, params: unknown, timeoutMs?: number): Promise<CallResult> {\n return CallResultSchema.parse(\n await this.#request(\n HARNESS_METHODS.call,\n { method, params, ...(timeoutMs !== undefined ? { timeoutMs } : {}) },\n (timeoutMs ?? 60_000) + 30_000,\n ),\n );\n }\n\n /** `harness/call`: the answer, or an {@link InstanceError}. */\n async call<T = Record<string, unknown>>(\n method: string,\n params: unknown,\n timeoutMs?: number,\n ): Promise<T> {\n const answer = await this.callRaw(method, params, timeoutMs);\n if (\"error\" in answer) throw new InstanceError(method, answer.error);\n return answer.result as T;\n }\n\n /** `harness/stop`: the host ends its session. */\n async stopInstance(): Promise<void> {\n await this.#request(HARNESS_METHODS.stop, {});\n }\n\n /** `harness/store`. */\n async store(): Promise<StoreResult> {\n return StoreResultSchema.parse(await this.#request(HARNESS_METHODS.store, {}));\n }\n\n /** `harness/script` (feature `faults`). */\n async script(params: ScriptParams): Promise<void> {\n await this.#request(HARNESS_METHODS.script, params);\n }\n\n /** `harness/events` (feature `events`). */\n async events(params: EventsParams): Promise<EventsResult> {\n return EventsResultSchema.parse(\n await this.#request(HARNESS_METHODS.events, params, params.timeoutMs + 30_000),\n );\n }\n\n /** Ends the shim: stdin closes, then SIGTERM to its process group, then SIGKILL. */\n async close(): Promise<void> {\n this.#child.stdin?.end();\n const pid = this.#child.pid;\n const signal = (name: NodeJS.Signals): void => {\n if (pid === undefined) return;\n try {\n process.kill(-pid, name);\n } catch {\n // gone already\n }\n };\n const outcome = await Promise.race([\n this.#exited.then(() => \"exited\" as const),\n new Promise<\"waiting\">((done) => setTimeout(() => done(\"waiting\"), 5000)),\n ]);\n if (outcome === \"waiting\") {\n signal(\"SIGTERM\");\n const later = await Promise.race([\n this.#exited.then(() => \"exited\" as const),\n new Promise<\"waiting\">((done) => setTimeout(() => done(\"waiting\"), 5000)),\n ]);\n if (later === \"waiting\") signal(\"SIGKILL\");\n }\n this.#peer.close();\n }\n}\n\n/** A diagnostic code from an error the kit saw: the instance's, an RPC error's, or none. */\nexport function codeOf(error: unknown): string | undefined {\n if (error instanceof InstanceError) return error.code;\n if (error instanceof RpcError) return (error.diagnostic as Diagnostic).code;\n return undefined;\n}\n","/**\n * A viewer as the kit plays one: it opens a capability link the way the shell does (the token for\n * a shell session, a frame ticket, the frame's entry) and speaks the browser protocol the way a\n * page does, with a per-host cookie jar (browsers keep cookies per host, not per port, D98) and the\n * `Origin`, `Sec-Fetch-*` and CSRF headers a browser sends. It also sends what no browser would,\n * for the hygiene scenarios. It never follows redirects.\n */\nimport { request as httpRequest } from \"node:http\";\nimport {\n BROWSER_PROTOCOL_REVISIONS,\n deserializeAll,\n type Frame,\n type FrameTicket,\n MutationId,\n serializeAll,\n} from \"@mostra/protocol\";\n\n/** The browser-protocol revision the kit speaks: the first, which every gateway serves. */\nconst REVISION: string = BROWSER_PROTOCOL_REVISIONS[0] as string;\n\n/** One HTTP answer. */\nexport interface Answer {\n /** The HTTP status. */\n readonly status: number;\n /** Each header (lowercase name) with every value it was sent with. */\n readonly headers: Readonly<Record<string, readonly string[]>>;\n /** The body as text. */\n readonly body: string;\n /** The body as JSON (`{}` when it isn't). */\n json<T = Record<string, unknown>>(): T;\n}\n\n/** One request. */\nexport interface Ask {\n /** The HTTP method; default `GET`. */\n readonly method?: string;\n /** The full URL. */\n readonly url: string;\n /** The request's headers, exactly as sent. */\n readonly headers?: Readonly<Record<string, string>>;\n /** The body, if any. */\n readonly body?: string;\n /** Leave out the jar's cookies. */\n readonly noCookies?: boolean;\n}\n\n/** Sends one request, never following a redirect. */\nexport function send(ask: Ask): Promise<Answer> {\n const url = new URL(ask.url);\n return new Promise((resolve, reject) => {\n const req = httpRequest(\n {\n host: url.hostname.replace(/^\\[|\\]$/g, \"\"),\n port: url.port,\n method: ask.method ?? \"GET\",\n path: `${url.pathname}${url.search}`,\n headers: ask.headers,\n agent: false,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n res.on(\"end\", () => {\n const headers: Record<string, string[]> = {};\n for (let index = 0; index + 1 < res.rawHeaders.length; index += 2) {\n const name = (res.rawHeaders[index] as string).toLowerCase();\n const values = headers[name] ?? [];\n values.push(res.rawHeaders[index + 1] as string);\n headers[name] = values;\n }\n const body = Buffer.concat(chunks).toString(\"utf8\");\n resolve({\n status: res.statusCode ?? 0,\n headers,\n body,\n json: <T>() => {\n try {\n return JSON.parse(body) as T;\n } catch {\n return {} as T;\n }\n },\n });\n });\n },\n );\n req.setTimeout(60_000, () => req.destroy(new Error(`${ask.url} didn't answer in 60 s`)));\n req.on(\"error\", reject);\n if (ask.body !== undefined) req.write(ask.body);\n req.end();\n });\n}\n\n/** A link's parts: its shell origin, artifact, token secret and pinned version. */\nexport interface ParsedLink {\n /** The shell's origin. */\n readonly origin: string;\n /** The artifact the link opens. */\n readonly artifactId: string;\n /** The token's secret, from the fragment. */\n readonly secret: string;\n /** The version number the link pins, if it pins one. */\n readonly version?: string;\n}\n\n/** Reads a capability link (`http://host:port/a/<artifactId>[/v/<n>]#t=<secret>`). */\nexport function parseLink(link: string): ParsedLink {\n const url = new URL(link);\n const match = /^\\/a\\/(art_[0-9A-Z]{26})(?:\\/v\\/(\\d+))?$/.exec(url.pathname);\n const secret = new URLSearchParams(url.hash.slice(1)).get(\"t\");\n if (!match?.[1] || !secret)\n throw new Error(`${url.origin}${url.pathname} isn't a capability link.`);\n return {\n origin: url.origin,\n artifactId: match[1],\n secret,\n ...(match[2] !== undefined ? { version: match[2] } : {}),\n };\n}\n\n/** A browser-like client with a per-host cookie jar. */\nexport class Browser {\n readonly #jar = new Map<string, { value: string; path: string }>();\n\n /** The cookies the jar sends to `url`: every cookie of the host whose path matches. */\n cookiesFor(url: string): string {\n const { pathname } = new URL(url);\n return [...this.#jar]\n .filter(([, cookie]) => {\n const prefix = cookie.path.endsWith(\"/\") ? cookie.path : `${cookie.path}/`;\n return pathname === cookie.path || pathname.startsWith(prefix);\n })\n .map(([key, cookie]) => `${key.split(\" \")[0]}=${cookie.value}`)\n .join(\"; \");\n }\n\n /** Sends a request with the jar's cookies and keeps the ones that come back. */\n async ask(ask: Ask): Promise<Answer> {\n const cookie = ask.noCookies ? \"\" : this.cookiesFor(ask.url);\n const answer = await send({\n ...ask,\n headers: { ...(cookie ? { cookie } : {}), ...ask.headers },\n });\n for (const line of answer.headers[\"set-cookie\"] ?? []) {\n const [pair = \"\", ...attributes] = line.split(\";\").map((part) => part.trim());\n const at = pair.indexOf(\"=\");\n const path =\n attributes.find((attribute) => attribute.toLowerCase().startsWith(\"path=\"))?.slice(5) ??\n \"/\";\n this.#jar.set(`${pair.slice(0, at)} ${path}`, { value: pair.slice(at + 1), path });\n }\n return answer;\n }\n\n /** A page on `origin` posting or fetching JSON from its own origin. */\n fetchJson(\n origin: string,\n path: string,\n init: { method?: string; body?: unknown; csrf?: string; headers?: Record<string, string> } = {},\n ): Promise<Answer> {\n const method = init.method ?? (init.body === undefined ? \"GET\" : \"POST\");\n return this.ask({\n method,\n url: `${origin}${path}`,\n headers: {\n \"sec-fetch-site\": \"same-origin\",\n \"sec-fetch-mode\": \"cors\",\n \"sec-fetch-dest\": \"empty\",\n ...(method === \"GET\" ? {} : { origin, \"content-type\": \"application/json\" }),\n ...(init.csrf ? { \"x-mostra-csrf\": init.csrf } : {}),\n ...init.headers,\n },\n ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),\n });\n }\n}\n\n/** Why a viewer couldn't open its link: the step and the gateway's answer. */\nexport class OpenError extends Error {\n /** The HTTP status of the refused step. */\n readonly status: number;\n /** The diagnostic code (`MOSTRA_…`). */\n readonly code: string | undefined;\n\n constructor(step: string, answer: Answer) {\n const code = answer.json<{ code?: string }>().code;\n super(`${step}: HTTP ${answer.status}${code ? ` ${code}` : \"\"}`);\n this.name = \"OpenError\";\n this.status = answer.status;\n this.code = code;\n }\n}\n\n/** A run's state, as `runs` and `runs/attach` answer it. */\nexport interface RunState {\n /** The run's ID (`run_…`). */\n readonly runId: string;\n /** `queued`, `running`, `succeeded`, `failed` or `cancelled` (D130). */\n readonly status: string;\n /** Its result, as serializer batches. */\n readonly batches: readonly Frame[][];\n /** The rest of the run's state (progress, log, error). */\n readonly [key: string]: unknown;\n}\n\n/** One opened view: a shell session, a frame session and the view they show. */\nexport class Viewer {\n /** The cookie jar this viewer's requests use. */\n readonly browser: Browser;\n /** The link it opened. */\n readonly link: ParsedLink;\n /** The frame ticket the shell got: the view, its version, channels and controls. */\n readonly ticket: FrameTicket;\n readonly #shellCsrf: string;\n readonly #frameCsrf: string;\n\n private constructor(\n browser: Browser,\n link: ParsedLink,\n ticket: FrameTicket,\n shellCsrf: string,\n frameCsrf: string,\n ) {\n this.browser = browser;\n this.link = link;\n this.ticket = ticket;\n this.#shellCsrf = shellCsrf;\n this.#frameCsrf = frameCsrf;\n }\n\n /**\n * Opens `link` as the shell does. `headers` go with the session exchange (the request the\n * `identity` port judges, D143). Throws an {@link OpenError} for a refused step.\n */\n static async open(\n link: string,\n options: { browser?: Browser; headers?: Record<string, string> } = {},\n ): Promise<Viewer> {\n const browser = options.browser ?? new Browser();\n const parsed = parseLink(link);\n const api = `/a/${parsed.artifactId}/_mostra`;\n const exchange = await browser.fetchJson(parsed.origin, `${api}/session`, {\n body: { token: parsed.secret },\n ...(options.headers ? { headers: options.headers } : {}),\n });\n if (exchange.status !== 200) throw new OpenError(\"exchange\", exchange);\n const shellCsrf = exchange.json<{ csrf: string }>().csrf;\n const ticketAnswer = await browser.fetchJson(parsed.origin, `${api}/ticket`, {\n body: parsed.version !== undefined ? { version: Number(parsed.version) } : {},\n csrf: shellCsrf,\n });\n if (ticketAnswer.status !== 200) throw new OpenError(\"ticket\", ticketAnswer);\n const ticket = ticketAnswer.json<FrameTicket>();\n const enter = await browser.ask({\n url: ticket.src,\n headers: {\n accept: \"text/html\",\n \"sec-fetch-mode\": \"navigate\",\n \"sec-fetch-dest\": \"iframe\",\n \"sec-fetch-site\": \"same-site\",\n },\n });\n if (enter.status !== 303) throw new OpenError(\"enter\", enter);\n const session = await browser.fetchJson(ticket.artifactOrigin, \"/_mostra/session\");\n if (session.status !== 200) throw new OpenError(\"frame session\", session);\n return new Viewer(browser, parsed, ticket, shellCsrf, session.json<{ csrf: string }>().csrf);\n }\n\n /** The view this frame load is (D104). */\n get viewId(): string {\n return this.ticket.viewId;\n }\n\n /** A browser-protocol request from the page. */\n page(path: string, body: unknown): Promise<Answer> {\n return this.browser.fetchJson(this.ticket.artifactOrigin, `/_mostra/v/${REVISION}/${path}`, {\n body,\n csrf: this.#frameCsrf,\n });\n }\n\n /** A request of the shell (its own origin, under `/a/<artifactId>`). */\n shell(path: string, body?: unknown, method?: string): Promise<Answer> {\n return this.browser.fetchJson(this.link.origin, `/a/${this.link.artifactId}/_mostra/${path}`, {\n ...(body === undefined ? {} : { body }),\n ...(method ? { method } : {}),\n csrf: this.#shellCsrf,\n });\n }\n\n /**\n * Writes fields of the viewer's draft (or, with `scope: \"artifact\"`, the artifact state), with\n * the labels a page sends for them (D106).\n */\n write(\n fields: Record<string, unknown>,\n options: {\n baseRevision?: string;\n scope?: \"viewer\" | \"artifact\";\n labels?: Readonly<Record<string, string>>;\n } = {},\n ): Promise<Answer> {\n return this.page(\"fields\", {\n mutationId: MutationId.create(),\n scope: options.scope ?? \"viewer\",\n baseRevision: options.baseRevision ?? \"0\",\n viewId: this.viewId,\n ops: Object.entries(fields).map(([id, value]) => ({\n id,\n value,\n ...(options.labels?.[id] !== undefined ? { label: options.labels[id] } : {}),\n })),\n });\n }\n\n /** Submits on the artifact channel (D40). */\n submit(expectedRevision: string): Promise<Answer> {\n return this.page(\"submit\", { viewId: this.viewId, expectedRevision, channel: \"artifact\" });\n }\n\n /** The trusted Submit, on the shell channel (D40, D108). */\n shellSubmit(expectedRevision: string): Promise<Answer> {\n return this.shell(`v/${REVISION}/submit`, { viewId: this.viewId, expectedRevision });\n }\n\n /** Writes `fields`, then submits on `channel`; answers the submit. */\n async answer(\n fields: Record<string, unknown>,\n channel: \"artifact\" | \"shell\" = \"artifact\",\n labels?: Readonly<Record<string, string>>,\n ): Promise<Answer> {\n const written = await this.write(fields, labels ? { labels } : {});\n if (written.status !== 200) return written;\n const { revision } = written.json<{ revision: string }>();\n return channel === \"artifact\" ? this.submit(revision) : this.shellSubmit(revision);\n }\n\n /** Raises a signal from the page (IN-09). */\n signal(name: string, payload?: unknown): Promise<Answer> {\n return this.page(\"signal\", {\n viewId: this.viewId,\n name,\n ...(payload === undefined ? {} : { payload }),\n });\n }\n\n /** Starts an action run (D130) and follows it until it ends. */\n async run(fnId: string, args: unknown[], timeoutMs = 60_000): Promise<RunState> {\n const started = await this.page(\"runs\", {\n viewId: this.viewId,\n fnId,\n args: await serializeAll(args, { mode: \"argument\" }),\n clientKey: `ck-${MutationId.create()}`,\n });\n if (started.status !== 200) throw new OpenError(\"run\", started);\n const runId = started.json<{ runId: string }>().runId;\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const attached = await this.page(\"runs/attach\", { viewId: this.viewId, runIds: [runId] });\n const state = attached.json<{ runs: RunState[] }>().runs?.[0];\n if (state && [\"succeeded\", \"failed\", \"cancelled\"].includes(state.status)) return state;\n if (Date.now() > deadline) throw new Error(`run ${runId} didn't end in ${timeoutMs} ms`);\n await new Promise((done) => setTimeout(done, 100));\n }\n }\n\n /** The page's long poll: events after `cursor` (D47). */\n poll(cursor?: string): Promise<Answer> {\n const query = `view=${this.viewId}&wait=0${cursor !== undefined ? `&cursor=${cursor}` : \"\"}`;\n return this.browser.fetchJson(\n this.ticket.artifactOrigin,\n `/_mostra/v/${REVISION}/events/poll?${query}`,\n );\n }\n}\n\n/** A run's result, from its stored batches. */\nexport async function resultOf(state: RunState): Promise<unknown> {\n return state.batches.length === 0 ? undefined : deserializeAll([...state.batches]);\n}\n","/**\n * Scenarios and what they get to work with. A scenario is one property a host integration must\n * have, checked through the host's own client and ports (the harness) and a viewer playing the\n * browser. Each runs against a fresh home in its own directory, with a fresh host shim.\n */\nimport {\n chmodSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport {\n createDiagnostic,\n type EventRecord,\n encodeLine,\n HOST_PROTOCOL_REVISIONS,\n LineSplitter,\n type Results,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport { connectControl, resolveRuntime } from \"@mostra/sdk\";\nimport type { Fixture } from \"./fixtures.ts\";\nimport { HostUnderTest } from \"./harness/client.ts\";\nimport type { StartParams, StartResult, StoreResult } from \"./harness/protocol.ts\";\nimport { kitVersion } from \"./version.ts\";\nimport { Viewer } from \"./viewer.ts\";\n\n/** A scenario: one property of a host integration, with the requirements it covers. */\nexport interface Scenario {\n /** A stable ID, `group.name`: baselines name scenarios by it. */\n readonly id: string;\n /** What it proves, in one sentence. */\n readonly title: string;\n /** The requirements and host needs it exercises (`HO-05`, `IN-12`, `H-03` …). */\n readonly covers: readonly string[];\n /** Harness features without which it doesn't apply (it is then skipped, never failed). */\n readonly needs?: readonly string[];\n /** Runs it; throws a {@link ScenarioFailure} (or any error) when the property doesn't hold. */\n run(context: ScenarioContext): Promise<void>;\n}\n\n/** A property that didn't hold. */\nexport class ScenarioFailure extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ScenarioFailure\";\n }\n}\n\n/** Thrown to say a scenario doesn't apply to this host (a port or feature it lacks). */\nexport class NotApplicable extends Error {\n constructor(reason: string) {\n super(reason);\n this.name = \"NotApplicable\";\n }\n}\n\n/** Fails the scenario with `message` unless `condition` holds. */\nexport function check(condition: unknown, message: string): asserts condition {\n if (!condition) throw new ScenarioFailure(message);\n}\n\n/** `value` as JSON with every object's keys sorted, so key order never decides equality. */\nfunction canonical(value: unknown): string {\n return JSON.stringify(value, (_key, inner: unknown) =>\n inner !== null && typeof inner === \"object\" && !Array.isArray(inner)\n ? Object.fromEntries(\n Object.entries(inner as Record<string, unknown>).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n )\n : inner,\n );\n}\n\n/** Fails unless `actual` deep-equals `expected` (JSON comparison, key order aside). */\nexport function same(actual: unknown, expected: unknown, what: string): void {\n const a = canonical(actual);\n const b = canonical(expected);\n if (a !== b) throw new ScenarioFailure(`${what}: expected ${b}, got ${a}`);\n}\n\n/** Options of a run that scenarios see. */\nexport interface RunSettings {\n /** The host shim's command line. */\n readonly host: string;\n /** Variables for the shim's own process (how it finds its runtime). */\n readonly hostEnv: Readonly<Record<string, string>>;\n /** Publish through verify's gate (needs the verify browser); off, publish skips it, loudly. */\n readonly verify: boolean;\n}\n\n/** What a scenario works with: its host, its home, its viewers. */\nexport class ScenarioContext {\n /** The run's settings. */\n readonly settings: RunSettings;\n /** The scenario's directory: the home, the authoring directories, the runtime directory. */\n readonly dir: string;\n /** The home the host is told to use (HO-08). */\n readonly home: string;\n /** The host: its name and version. */\n host!: HostUnderTest;\n readonly #hosts: HostUnderTest[] = [];\n #published = 0;\n\n constructor(settings: RunSettings, dir: string) {\n this.settings = settings;\n this.dir = dir;\n this.home = join(dir, \"home\");\n }\n\n /** Starts the scenario's host shim (the runner does this before `run`). */\n async open(): Promise<void> {\n this.host = await this.anotherHost();\n }\n\n /** A second shim of the same host, for scenarios about two hosts of one home. */\n async anotherHost(): Promise<HostUnderTest> {\n const host = await HostUnderTest.start(this.settings.host, this.settings.hostEnv);\n this.#hosts.push(host);\n return host;\n }\n\n /** The variables every instance of the run gets: its own runtime and config directories. */\n instanceEnv(extra: Readonly<Record<string, string>> = {}): Record<string, string> {\n return {\n MOSTRA_RUNTIME_DIR: join(this.dir, \"run\"),\n MOSTRA_CONFIG_DIR: join(this.dir, \"config\"),\n ...(this.settings.verify ? {} : { MOSTRA_TEST_UNVERIFIED_PUBLISH: \"1\" }),\n ...extra,\n };\n }\n\n /** `harness/start` on this scenario's home. */\n start(\n options: {\n env?: Readonly<Record<string, string>>;\n mode?: StartParams[\"mode\"];\n host?: HostUnderTest;\n } = {},\n ): Promise<StartResult> {\n mkdirSync(join(this.dir, \"run\"), { recursive: true, mode: 0o700 });\n return (options.host ?? this.host).startInstance({\n home: this.home,\n env: this.instanceEnv(options.env),\n ...(options.mode ? { mode: options.mode } : {}),\n });\n }\n\n /** Stops the host's instance and starts it again (the same home). */\n async restart(options: { env?: Readonly<Record<string, string>> } = {}): Promise<StartResult> {\n await this.host.stopInstance();\n return this.start(options);\n }\n\n /** Writes a fixture into a fresh authoring directory and returns the directory. */\n author(fixture: Fixture, name = \"artifact\"): string {\n this.#published += 1;\n const dir = join(this.dir, \"authoring\", `${name}-${this.#published}`);\n for (const [path, text] of Object.entries(fixture)) {\n mkdirSync(dirname(join(dir, path)), { recursive: true });\n writeFileSync(join(dir, path), text);\n }\n return dir;\n }\n\n /** Writes `files` over the authoring directory `dir` (a new version of the same artifact). */\n rewrite(dir: string, fixture: Fixture): void {\n for (const [path, text] of Object.entries(fixture)) writeFileSync(join(dir, path), text);\n }\n\n /** Publishes `dir` through the host (`artifact/publish`). */\n publish(\n dir: string,\n options: { policy?: unknown; requestId?: string } = {},\n ): Promise<{\n artifactId: string;\n versionId: string;\n version: number;\n url?: string;\n tokenId?: string;\n cursor: string;\n }> {\n return this.host.call(\"artifact/publish\", {\n source: { path: dir },\n ...(options.policy !== undefined ? { policy: options.policy } : {}),\n ...(options.requestId ? { requestId: options.requestId } : {}),\n });\n }\n\n /** Authors and publishes a fixture; the receipt with its authoring directory. */\n async published(\n fixture: Fixture,\n options: { policy?: unknown } = {},\n ): Promise<{\n artifactId: string;\n versionId: string;\n version: number;\n url?: string;\n tokenId?: string;\n cursor: string;\n dir: string;\n }> {\n const dir = this.author(fixture);\n return { ...(await this.publish(dir, options)), dir };\n }\n\n /** A new capability link through the host (`view/url`). */\n async link(artifactId: string, params: Record<string, unknown> = {}): Promise<string> {\n const link = await this.host.call<{ url: string }>(\"view/url\", {\n artifact: { artifactId },\n ...params,\n });\n return link.url;\n }\n\n /** Opens a new link as a viewer. */\n async viewer(\n artifactId: string,\n options: { link?: Record<string, unknown>; headers?: Record<string, string> } = {},\n ): Promise<Viewer> {\n return Viewer.open(await this.link(artifactId, options.link ?? {}), {\n ...(options.headers ? { headers: options.headers } : {}),\n });\n }\n\n /** `results/get` through the host. */\n results(artifactId: string, submission?: string): Promise<Results> {\n return this.host.call(\"results/get\", {\n artifact: { artifactId },\n ...(submission ? { submission } : {}),\n });\n }\n\n /** `events/read` through the host. */\n async events(\n filter: { artifacts?: string[]; types?: string[] },\n after?: string,\n ): Promise<{ events: EventRecord[]; cursor: string }> {\n return this.host.call(\"events/read\", { filter, ...(after ? { after } : {}), limit: 100 });\n }\n\n /** The host's store. */\n store(): Promise<StoreResult> {\n return this.host.store();\n }\n\n /** Waits for `condition` to hold, checking every 100 ms; fails with `what` after `timeoutMs`. */\n async eventually<T>(\n what: string,\n condition: () => Promise<T | undefined | false> | T | undefined | false,\n timeoutMs = 30_000,\n ): Promise<T> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const value = await condition();\n if (value !== undefined && value !== false) return value;\n if (Date.now() > deadline) throw new ScenarioFailure(`${what} (waited ${timeoutMs} ms)`);\n await new Promise((done) => setTimeout(done, 100));\n }\n }\n\n /** Skips the scenario unless the host serves `port`. */\n requirePort(port: string): void {\n if (!this.host.serves(port)) throw new NotApplicable(`the host serves no ${port} port`);\n }\n\n /** Skips the scenario unless the host supports `feature`. */\n requireFeature(feature: string): void {\n if (!this.host.supports(feature))\n throw new NotApplicable(`the host lacks the ${feature} feature`);\n }\n\n /** The socket of the home's running instance, from `instance.json` (D81). */\n socket(): string | undefined {\n try {\n const record = JSON.parse(readFileSync(join(this.home, \"instance.json\"), \"utf8\")) as {\n socket?: string;\n };\n return record.socket;\n } catch {\n return undefined;\n }\n }\n\n /** Ends every shim, stops a daemon the scenario left, and removes the directory. */\n async close(): Promise<void> {\n for (const host of this.#hosts) {\n await host.stopInstance().catch(() => undefined);\n await host.close().catch(() => undefined);\n }\n const socket = this.socket();\n if (socket) {\n const session = await connectSocket(socket).catch(() => undefined);\n await session?.peer\n .request(\"mostra/shutdown\", {}, { timeoutMs: 10_000 })\n .catch(() => undefined);\n session?.close();\n }\n removeTree(this.dir);\n }\n}\n\n/**\n * Removes a scenario's directory. A home's versions are sealed read-only (files 0444,\n * directories 0555, DATA_MODEL §1), so directories are made writable first.\n */\nexport function removeTree(dir: string): void {\n const open = (path: string): void => {\n let stats: ReturnType<typeof lstatSync>;\n try {\n stats = lstatSync(path);\n } catch {\n return;\n }\n if (!stats.isDirectory()) return;\n chmodSync(path, 0o700);\n for (const name of readdirSync(path)) open(join(path, name));\n };\n open(dir);\n rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });\n}\n\n/** A raw protocol session over the home's socket, opened by the kit itself. */\nexport interface SocketSession {\n readonly peer: RpcPeer;\n close(): void;\n}\n\n/** Connects to an instance's socket and initializes a session as `@mostra/conformance`. */\nexport async function connectSocket(\n path: string,\n revisions: readonly string[] = HOST_PROTOCOL_REVISIONS,\n): Promise<SocketSession & { initialize: Promise<unknown> }> {\n // As every client reaches an instance: on Windows through the helper beside the runtime, which\n // refuses a pipe another user created under the name (D150 item 4).\n const socket = await connectControl(path, {\n runtime: process.platform === \"win32\" ? await resolveRuntime() : undefined,\n });\n const peer = new RpcPeer({\n send: (message) => {\n if (!socket.destroyed) socket.write(encodeLine(message));\n },\n });\n const lines = new LineSplitter();\n socket.setEncoding(\"utf8\");\n socket.on(\"data\", (chunk: string) => {\n for (const line of lines.push(chunk)) peer.receiveLine(line);\n });\n socket.on(\"error\", () => socket.destroy());\n socket.on(\"close\", () =>\n peer.close(createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", { message: \"socket closed\" })),\n );\n const initialize = peer.request(\n \"mostra/initialize\",\n {\n client: { name: \"mostra-conformance\", version: kitVersion() },\n revisions: [...revisions],\n capabilities: {},\n ports: [],\n },\n { timeoutMs: 10_000 },\n );\n initialize.catch(() => undefined);\n return { peer, initialize, close: () => socket.destroy() };\n}\n\n/** The diagnostic code of a rejected request. */\nexport function rpcCode(error: unknown): string | undefined {\n return error instanceof RpcError ? error.diagnostic.code : undefined;\n}\n","/**\n * Submissions reaching the host: durable first, delivered whole, once in effect across crashes,\n * retried while the host can't take them, replayed in order when it returns, and never confused\n * with draft mirrors (IN-06, IN-12, H-01, H-03, H-04, H-08).\n */\nimport { FORM } from \"../fixtures.ts\";\nimport { check, connectSocket, type Scenario, type ScenarioContext, same } from \"../scenario.ts\";\n\n/** Publishes the form, answers it and submits on the artifact channel; the submission's ID. */\nasync function submitForm(\n context: ScenarioContext,\n fields: Record<string, unknown> = { name: \"Ada\", comment: \"Looks good\" },\n): Promise<{ artifactId: string; submissionId: string }> {\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const answer = await viewer.answer(\n fields,\n viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\",\n );\n same(answer.status, 200, `the submit's status (${answer.body})`);\n return { artifactId: receipt.artifactId, submissionId: answer.json<{ id: string }>().id };\n}\n\n/** H-01, H-08: the host receives the whole submission once, and Mostra's record agrees. */\nexport const delivered: Scenario = {\n id: \"delivery.submission\",\n title:\n \"A submission is durable before delivery, reaches the host's submissions port once with the full results, and is readable through results/get\",\n covers: [\"HO-01\", \"HO-05\", \"IN-12\", \"H-01\", \"H-08\"],\n async run(context) {\n await context.start();\n const { artifactId, submissionId } = await submitForm(context);\n // Durable at commit, whatever the delivery state (FAILURE_MODEL §4).\n const waited = await context.host.call<{ status: string }>(\"wait\", {\n artifact: { artifactId },\n until: \"submitted\",\n timeoutMs: 0,\n });\n same(waited.status, \"satisfied\", \"wait --until submitted right after the submit\");\n if (context.host.serves(\"submissions\")) {\n const stored = await context.eventually(\"the host's store holds the submission\", async () =>\n (await context.store()).deliveries.find((entry) => entry.submissionId === submissionId),\n );\n same(stored.kind, \"submission\", \"the envelope's kind\");\n same(stored.stored, 1, \"copies the host's store holds\");\n check(stored.deliveryId.startsWith(\"dlv_\"), `a delivery ID (${stored.deliveryId})`);\n const results = await context.eventually(\n \"the delivery is recorded as delivered\",\n async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"delivered\" ? read : undefined;\n },\n );\n same(results.submission.id, submissionId, \"the submission results/get reads\");\n same(results.answers, { name: \"Ada\", comment: \"Looks good\" }, \"the answers\");\n } else {\n // Standalone: Mostra's built-in adapter takes it at once (D58, D105).\n const results = await context.eventually(\"the built-in adapter accepts it\", async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"delivered\" ? read : undefined;\n });\n same(results.answers, { name: \"Ada\", comment: \"Looks good\" }, \"the answers\");\n }\n },\n};\n\n/** H-03, IN-12: a crash after the host accepted redelivers the same delivery, stored once. */\nexport const exactlyOnce: Scenario = {\n id: \"delivery.exactly-once\",\n title:\n \"When the instance dies after the host accepted a delivery but before recording it, the restarted instance redelivers the same deliveryId and the host stores it once\",\n covers: [\"HO-05\", \"IN-12\", \"H-03\"],\n async run(context) {\n context.requirePort(\"submissions\");\n // The instance kills itself between the host's answer and its record (FAILURE_MODEL §4).\n await context.start({ env: { MOSTRA_TEST_FAULTS: \"deliver:after-answer:crash\" } });\n const { artifactId, submissionId } = await submitForm(context);\n const first = await context.eventually(\"the host received the first attempt\", async () =>\n (await context.store()).deliveries.find((entry) => entry.submissionId === submissionId),\n );\n await context.host.stopInstance().catch(() => undefined);\n await context.start();\n const after = await context.eventually(\"the restarted instance redelivers it\", async () => {\n const entry = (await context.store()).deliveries.find(\n (candidate) => candidate.submissionId === submissionId,\n );\n return entry && entry.calls >= 2 ? entry : undefined;\n });\n same(after.deliveryId, first.deliveryId, \"the redelivery's deliveryId\");\n same(after.stored, 1, \"copies the host's store holds after the redelivery\");\n check(\n (after.attempts.at(-1) ?? 0) > (after.attempts[0] ?? 0),\n `the redelivery's attempt counts up (${after.attempts.join(\", \")})`,\n );\n const results = await context.eventually(\"the delivery ends delivered\", async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"delivered\" ? read : undefined;\n });\n same(results.submission.id, submissionId, \"the submission\");\n },\n};\n\n/** IN-12, H-04: a host that can't take a delivery gets it again with backoff; terminal is final. */\nexport const retry: Scenario = {\n id: \"delivery.retry\",\n title:\n \"A delivery the host answers retry: true stays pending and arrives when the host can take it; an undeliverable answer is final and never retried\",\n covers: [\"HO-05\", \"IN-12\", \"H-04\"],\n needs: [\"faults\"],\n async run(context) {\n context.requirePort(\"submissions\");\n await context.start();\n await context.host.script({ port: \"submissions\", answer: \"retry\" });\n const { artifactId, submissionId } = await submitForm(context);\n await context.eventually(\"the delivery is pending while the host can't take it\", async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"pending\" ? read : undefined;\n });\n const retrying = await context.events({\n artifacts: [artifactId],\n types: [\"submission.retrying\"],\n });\n check(\n retrying.events.length > 0,\n \"no submission.retrying event while the delivery waits (IN-13)\",\n );\n await context.host.script({ port: \"submissions\", answer: \"accept\" });\n await context.eventually(\n \"the delivery arrives once the host can take it\",\n async () =>\n (await context.store()).deliveries.find((entry) => entry.submissionId === submissionId),\n 45_000,\n );\n await context.eventually(\"the delivery ends delivered\", async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"delivered\" ? read : undefined;\n });\n // A terminal answer: undeliverable, shown, and never retried.\n await context.host.script({ port: \"submissions\", answer: \"undeliverable\" });\n const second = await submitForm(context, { name: \"Grace\" });\n await context.eventually(\"the delivery ends undeliverable\", async () => {\n const read = await context.results(second.artifactId);\n return read.submission.delivery === \"undeliverable\" ? read : undefined;\n });\n await context.host.script({ port: \"submissions\", answer: \"accept\" });\n await new Promise((done) => setTimeout(done, 3000));\n const store = await context.store();\n check(\n !store.deliveries.some((entry) => entry.submissionId === second.submissionId),\n \"an undeliverable delivery was retried\",\n );\n },\n};\n\n/** IN-12, H-04: submissions made while the host is away wait for it and replay in order. */\nexport const outboxReplay: Scenario = {\n id: \"delivery.outbox-replay\",\n title:\n \"Submissions made while the host is away stay pending in the outbox and replay in submission order, each with its deliveryId, when the host attaches again\",\n covers: [\"HO-05\", \"IN-12\", \"H-04\"],\n needs: [\"attach\"],\n async run(context) {\n context.requirePort(\"submissions\");\n await context.start({ mode: \"attach\" });\n const first = await context.published(FORM);\n const second = await context.published(FORM);\n // The viewers open their links while the host is there (a host that serves identity refuses\n // new links while it is away, D143), then the host goes away and its daemon keeps the home,\n // expecting the host back (D105).\n const viewers = [\n await context.viewer(first.artifactId),\n await context.viewer(second.artifactId),\n ];\n await context.host.stopInstance();\n const submissions: string[] = [];\n for (const viewer of viewers) {\n // A host that took the channel policy over gave these views the shell channel (D108).\n const channel = viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\";\n const answer = await viewer.answer({ name: `Ada ${submissions.length + 1}` }, channel);\n same(answer.status, 200, `a submit while the host is away (${answer.body})`);\n submissions.push(answer.json<{ id: string }>().id);\n }\n // A daemon that keeps the home while its host is away records where clients find it: no\n // record is a defect, never a reason to skip (Opus review of WP-12, finding 11).\n const socket = context.socket();\n check(socket, \"the daemon kept the home but left no instance.json to find it by\");\n const kit = await connectSocket(socket);\n await kit.initialize;\n const pending = (await kit.peer.request(\"results/get\", {\n artifact: { artifactId: first.artifactId },\n })) as { submission: { delivery: string } };\n kit.close();\n same(pending.submission.delivery, \"pending\", \"a delivery while its host is away\");\n check(\n (await context.store()).deliveries.length === 0,\n \"the host received a delivery while it was away\",\n );\n await context.start({ mode: \"attach\" });\n const store = await context.eventually(\"both deliveries replay\", async () => {\n const read = await context.store();\n return read.deliveries.length >= 2 ? read : undefined;\n });\n same(\n store.deliveries.map((entry) => entry.submissionId),\n submissions,\n \"the replay's order (submission order)\",\n );\n check(\n store.deliveries.every((entry) => entry.stored === 1),\n \"a replayed delivery stored twice\",\n );\n await context.host.stopInstance();\n },\n};\n\n/** IN-06: drafts reach the host only as mirrors labelled `draft`, never as submissions. */\nexport const draftMirrors: Scenario = {\n id: \"drafts.mirror\",\n title:\n \"Draft revisions reach the host only through drafts.mirror, labelled kind: draft, and never through the submissions port\",\n covers: [\"HO-01\", \"HO-05\", \"IN-06\", \"H-01\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const written = await viewer.write({ name: \"Ada\" });\n same(written.status, 200, \"a draft write\");\n if (context.host.serves(\"drafts\")) {\n const mirror = await context.eventually(\"the host receives the draft's mirror\", async () =>\n (await context.store()).drafts.find((entry) => entry.artifactId === receipt.artifactId),\n );\n same(mirror.kind, \"draft\", \"the mirror's kind\");\n }\n const before = await context.store();\n check(\n before.deliveries.every((entry) => entry.kind === \"submission\") &&\n !before.deliveries.some((entry) => entry.artifactId === receipt.artifactId),\n \"a draft reached the host as a delivery before any submit (IN-06)\",\n );\n const { revision } = written.json<{ revision: string }>();\n const submitted = await (viewer.ticket.submitChannels.includes(\"artifact\")\n ? viewer.submit(revision)\n : viewer.shellSubmit(revision));\n same(submitted.status, 200, \"the submit\");\n if (context.host.serves(\"submissions\")) {\n await context.eventually(\"the submission arrives\", async () =>\n (await context.store()).deliveries.find((entry) => entry.artifactId === receipt.artifactId),\n );\n const after = await context.store();\n const delivered = after.deliveries.filter((entry) => entry.artifactId === receipt.artifactId);\n same(delivered.length, 1, \"deliveries for the artifact\");\n check(\n after.deliveries.every((entry) => entry.kind === \"submission\"),\n \"the host stores something that isn't a submission as one (IN-06)\",\n );\n }\n },\n};\n\n/** The delivery scenarios. */\nexport const DELIVERY_SCENARIOS: readonly Scenario[] = [\n delivered,\n exactlyOnce,\n retry,\n outboxReplay,\n draftMirrors,\n];\n","/**\n * The interaction model a host builds on: submission policies, events with durable cursors,\n * signals, waits, artifact state, complete results, idempotent requests and durability across\n * restarts (IN-07 to IN-10, LL-02, H-02, H-03, H-06 to H-10).\n */\nimport { FORM, FORM_V2 } from \"../fixtures.ts\";\nimport { codeOf } from \"../harness/client.ts\";\nimport { check, type Scenario, same } from \"../scenario.ts\";\nimport type { Viewer } from \"../viewer.ts\";\n\n/** Answers and submits on whichever channel the view allows. */\nasync function answerAndSubmit(viewer: Viewer, fields: Record<string, unknown>) {\n return viewer.answer(\n fields,\n viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\",\n );\n}\n\nasync function code(answer: { json<T>(): T }): Promise<string | undefined> {\n return answer.json<{ code?: string }>().code;\n}\n\n/** IN-07, H-02, LL-02: every submission policy, decided by the host at publish. */\nexport const policies: Scenario = {\n id: \"interaction.policies\",\n title:\n \"once per artifact answers a second submit with MOSTRA_SUBMIT_ALREADY and the existing submission; once per viewer, epochs and none behave as specified\",\n covers: [\"HO-05\", \"IN-07\", \"LL-02\", \"H-02\"],\n async run(context) {\n await context.start();\n // once, per artifact (the default)\n const once = await context.published(FORM, { policy: { policy: \"once\" } });\n const first = await context.viewer(once.artifactId);\n const accepted = await answerAndSubmit(first, { name: \"Ada\" });\n same(accepted.status, 200, \"the first submit under once\");\n const second = await context.viewer(once.artifactId);\n const conflict = await answerAndSubmit(second, { name: \"Grace\" });\n check(conflict.status === 409, `a second submit under once answered ${conflict.status}`);\n same(await code(conflict), \"MOSTRA_SUBMIT_ALREADY\", \"a second submit's code\");\n same(\n conflict.json<{ submission?: { id: string } }>().submission?.id,\n accepted.json<{ id: string }>().id,\n \"the existing submission carried beside the conflict\",\n );\n // once, per viewer: each person once.\n const survey = await context.published(FORM, {\n policy: { policy: \"once\", scope: \"per-viewer\" },\n });\n for (const ref of [\"ada@example.com\", \"grace@example.com\"]) {\n const person = await context.viewer(survey.artifactId, { link: { viewer: { ref } } });\n same((await answerAndSubmit(person, { name: ref })).status, 200, `${ref}'s submit`);\n }\n const again = await context.viewer(survey.artifactId, {\n link: { viewer: { ref: \"ada@example.com\" } },\n });\n same(\n await code(await answerAndSubmit(again, { name: \"again\" })),\n \"MOSTRA_SUBMIT_ALREADY\",\n \"a person's second submit\",\n );\n // epochs: rounds linked to each other.\n const rounds = await context.published(FORM, { policy: { policy: \"epochs\" } });\n const person = await context.viewer(rounds.artifactId, { link: { viewer: { ref: \"ada\" } } });\n const one = (await answerAndSubmit(person, { name: \"round 1\" })).json<{\n id: string;\n epoch: number;\n }>();\n const written = await person.write({ name: \"round 2\" }, { baseRevision: \"1\" });\n const revision = written.json<{ revision: string }>().revision;\n const twoAnswer = await (person.ticket.submitChannels.includes(\"artifact\")\n ? person.submit(revision)\n : person.shellSubmit(revision));\n same(twoAnswer.status, 200, \"the second round's submit\");\n const two = twoAnswer.json<{ id: string; epoch: number }>();\n same([one.epoch, two.epoch], [1, 2], \"the rounds' epochs\");\n const results = await context.results(rounds.artifactId, two.id);\n same(results.submission.previous, one.id, \"the second round's previous submission\");\n // none: no submission at all.\n const board = await context.published(FORM, { policy: { policy: \"none\" } });\n const viewer = await context.viewer(board.artifactId);\n same(viewer.ticket.policy.policy, \"none\", \"the view's policy\");\n same(\n await code(await answerAndSubmit(viewer, { name: \"x\" })),\n \"MOSTRA_SUBMIT_POLICY_NONE\",\n \"a submit under none\",\n );\n const wait = await context.host\n .call(\"wait\", {\n artifact: { artifactId: board.artifactId },\n until: \"submitted\",\n timeoutMs: 0,\n })\n .then(\n () => undefined,\n (error: unknown) => codeOf(error),\n );\n same(wait, \"MOSTRA_SUBMIT_POLICY_NONE\", \"wait --until submitted under none\");\n },\n};\n\n/** IN-08, H-09: a named, filtered subscription resumes after what it acknowledged, restarts included. */\nexport const subscriptions: Scenario = {\n id: \"events.subscription\",\n title:\n \"A host's named, filtered event stream sees only the types it asked for, in cursor order, and resumes after its acknowledged cursor across an instance restart\",\n covers: [\"HO-01\", \"HO-05\", \"IN-08\", \"H-09\"],\n needs: [\"events\"],\n async run(context) {\n await context.start();\n const name = \"conformance-host\";\n const filter = { types: [\"submission.created\"] };\n // A new name starts now: nothing earlier is read.\n same(\n (await context.host.events({ name, filter, pages: 1, timeoutMs: 500 })).pages.length,\n 0,\n \"pages for a new name\",\n );\n const submit = async (who: string): Promise<string> => {\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n return (await answerAndSubmit(viewer, { name: who })).json<{ id: string }>().id;\n };\n const first = await submit(\"Ada\");\n const read = await context.host.events({ name, filter, pages: 1, timeoutMs: 10_000 });\n const events = read.pages.flatMap((page) => page.events);\n same(\n events.map((event) => event.type),\n [\"submission.created\"],\n \"the filtered stream's events\",\n );\n same(\n (events[0]?.[\"payload\"] as { submissionId?: string } | undefined)?.submissionId,\n first,\n \"the submission it names\",\n );\n await context.restart();\n const second = await submit(\"Grace\");\n const resumed = await context.host.events({ name, filter, pages: 1, timeoutMs: 10_000 });\n const after = resumed.pages.flatMap((page) => page.events);\n same(\n after.map((event) => (event[\"payload\"] as { submissionId?: string }).submissionId),\n [second],\n \"the resumed stream: the next submission, no repeat, no gap\",\n );\n const cursors = [...events, ...after].map((event) => BigInt(event.cursor));\n check(\n cursors.every((cursor, i) => i === 0 || cursor > (cursors[i - 1] as bigint)),\n \"cursors in order\",\n );\n },\n};\n\n/** IN-09: signals are events; Mostra wakes nobody. */\nexport const signals: Scenario = {\n id: \"events.signals\",\n title:\n \"A page's signal and every submit appear as signal.raised events the host filters; Mostra calls no port and wakes nobody for them\",\n covers: [\"HO-05\", \"IN-09\", \"H-09\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const before = await context.store();\n same((await viewer.signal(\"ping\", { n: 1 })).status, 200, \"a page's signal\");\n const raised = await context.events({\n artifacts: [receipt.artifactId],\n types: [\"signal.raised\"],\n });\n const ping = raised.events.find((event) => event.payload?.[\"name\"] === \"ping\");\n check(ping, \"no signal.raised for the page's signal\");\n same(ping.payload[\"source\"], \"artifact\", \"the signal's source\");\n same(ping.payload[\"payload\"], { n: 1 }, \"the signal's payload\");\n const after = await context.store();\n same(after.deliveries.length, before.deliveries.length, \"deliveries a signal caused\");\n same(after.drafts.length, before.drafts.length, \"draft mirrors a signal caused\");\n same((await answerAndSubmit(viewer, { name: \"Ada\" })).status, 200, \"the submit\");\n const all = await context.events({ artifacts: [receipt.artifactId], types: [\"signal.*\"] });\n check(\n all.events.some((event) => event.payload?.[\"name\"] === \"submit\"),\n \"a submit raises no signal.raised named submit (D106)\",\n );\n },\n};\n\n/** IN-10: waits are level- or edge-triggered as specified, and a timeout loses nothing. */\nexport const waits: Scenario = {\n id: \"interaction.wait\",\n title:\n \"wait returns still_waiting with a cursor on timeout and loses nothing; signal and state waits are edge-triggered after the cursor; submitted is level-triggered under once\",\n covers: [\"HO-05\", \"IN-10\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const artifact = { artifactId: receipt.artifactId };\n const timedOut = await context.host.call<{ status: string; cursor: string }>(\"wait\", {\n artifact,\n until: \"signal:ping\",\n timeoutMs: 0,\n });\n same(timedOut.status, \"still_waiting\", \"a wait that times out\");\n const viewer = await context.viewer(receipt.artifactId);\n await viewer.signal(\"ping\");\n const caught = await context.host.call<{ status: string; cursor: string }>(\"wait\", {\n artifact,\n until: \"signal:ping\",\n after: timedOut.cursor,\n timeoutMs: 10_000,\n });\n same(caught.status, \"satisfied\", \"a wait after the cursor of a timed-out wait\");\n const edge = await context.host.call<{ status: string }>(\"wait\", {\n artifact,\n until: \"signal:ping\",\n after: caught.cursor,\n timeoutMs: 0,\n });\n same(edge.status, \"still_waiting\", \"the same signal waited for after its own cursor\");\n const state = context.host.call<{ status: string }>(\"wait\", {\n artifact,\n until: \"state:done\",\n after: caught.cursor,\n timeoutMs: 15_000,\n });\n await context.host.call(\"state/patch\", {\n artifact,\n ops: [{ id: \"done\", value: true }],\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XC\",\n as: \"host\",\n });\n same((await state).status, \"satisfied\", \"a state wait when the host sets the field\");\n await answerAndSubmit(viewer, { name: \"Ada\" });\n const level = await context.host.call<{ status: string; cursor: string }>(\"wait\", {\n artifact,\n until: \"submitted\",\n timeoutMs: 0,\n });\n same(level.status, \"satisfied\", \"submitted, after the fact, under once (level-triggered)\");\n const levelAfter = await context.host.call<{ status: string }>(\"wait\", {\n artifact,\n until: \"submitted\",\n after: level.cursor,\n timeoutMs: 0,\n });\n same(levelAfter.status, \"satisfied\", \"submitted after a later cursor, under once per artifact\");\n },\n};\n\n/** LL-02 and D63: artifact state shared by viewers and the host, with conflicts on both sides. */\nexport const longLived: Scenario = {\n id: \"interaction.long-lived-state\",\n title:\n \"Under policy none, viewers and the host share artifact state through compare-and-set: an overlapping write is a conflict on either side, and every change is a state.changed event\",\n covers: [\"HO-05\", \"LL-02\", \"IN-07\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM, { policy: { policy: \"none\" } });\n const artifact = { artifactId: receipt.artifactId };\n const hostWrite = await context.host.call<{ revision: string }>(\"state/patch\", {\n artifact,\n ops: [{ id: \"count\", value: 1 }],\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XD\",\n as: \"host\",\n });\n const viewer = await context.viewer(receipt.artifactId);\n const stale = await viewer.write({ count: 5 }, { scope: \"artifact\", baseRevision: \"0\" });\n same(stale.status, 200, \"a stale viewer write's status\");\n const conflicts = stale.json<{ conflicts: { id: string }[] }>().conflicts;\n same(\n conflicts.map((conflict) => conflict.id),\n [\"count\"],\n \"the viewer's conflicts\",\n );\n const fresh = await viewer.write(\n { count: 2 },\n { scope: \"artifact\", baseRevision: hostWrite.revision },\n );\n const freshRevision = fresh.json<{ revision: string; conflicts: unknown[] }>();\n same(freshRevision.conflicts, [], \"a viewer write on the current revision\");\n const hostStale = await context.host.call<{ conflicts: { id: string }[] }>(\"state/patch\", {\n artifact,\n ops: [{ id: \"count\", value: 9 }],\n baseRevision: hostWrite.revision,\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XE\",\n as: \"host\",\n });\n same(\n hostStale.conflicts.map((conflict) => conflict.id),\n [\"count\"],\n \"the host's conflicts on a field a viewer changed\",\n );\n const state = await context.host.call<{ fields: Record<string, { value: unknown }> }>(\n \"state/get\",\n {\n artifact,\n },\n );\n same(state.fields[\"count\"]?.value, 2, \"the shared state\");\n const changed = await context.events({\n artifacts: [receipt.artifactId],\n types: [\"state.changed\"],\n });\n same(changed.events.length, 2, \"state.changed events (one per applied write)\");\n },\n};\n\n/** H-06, H-08, H-10: results name exactly what the viewer saw, stale views flagged. */\nexport const results: Scenario = {\n id: \"interaction.results\",\n title:\n \"results/get returns the complete submission: metadata, answers with labels, the exact version and view, a stale view flagged with the newer version, and Markdown\",\n covers: [\"HO-05\", \"IN-11\", \"H-06\", \"H-08\", \"H-10\"],\n async run(context) {\n await context.start();\n const v1 = await context.published(FORM);\n const viewer = await context.viewer(v1.artifactId);\n context.rewrite(v1.dir, FORM_V2);\n const v2 = await context.publish(v1.dir);\n same(v2.version, 2, \"the second version's number\");\n const submitted = await viewer.answer(\n { name: \"Ada\", comment: \"on the first version\" },\n viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\",\n { name: \"Your name\", comment: \"Comment\" },\n );\n same(submitted.status, 200, \"a submit from the older view\");\n const read = await context.results(v1.artifactId);\n same(read.artifact.family, \"questionnaire\", \"the artifact's family\");\n same(read.artifact.links, [{ rel: \"round-of\", artifact: \"conformance-round-1\" }], \"its links\");\n const submission = read.submission;\n same(\n [submission.versionId, submission.version],\n [v1.versionId, 1],\n \"the version the viewer saw\",\n );\n same(submission.viewId, viewer.viewId, \"the view\");\n same(\n [submission.staleView, submission.latestVersion],\n [true, 2],\n \"the stale view and the newer version\",\n );\n same(read.answers, { name: \"Ada\", comment: \"on the first version\" }, \"the answers\");\n check(\n read.fields.some((field) => field.id === \"name\" && field.label === \"Your name\"),\n \"the answers' labels\",\n );\n const markdown = await context.host.call<{ markdown: string }>(\"results/get\", {\n artifact: { artifactId: v1.artifactId },\n format: \"md\",\n });\n check(markdown.markdown.includes(\"Your name\"), \"the Markdown results name answers by label\");\n },\n};\n\n/** H-03: request IDs make retries converge; the same ID for another request is refused. */\nexport const idempotency: Scenario = {\n id: \"interaction.request-ids\",\n title:\n \"A retried request with the same requestId or mutationId returns the recorded result; the same ID with other parameters is refused\",\n covers: [\"HO-05\", \"H-03\"],\n async run(context) {\n await context.start();\n const dir = context.author(FORM);\n const first = await context.publish(dir, { requestId: \"req-publish-1\" });\n const retried = await context.publish(dir, { requestId: \"req-publish-1\" });\n same(retried, first, \"a retried publish's receipt\");\n const reused = await context\n .publish(dir, { requestId: \"req-publish-1\", policy: { policy: \"epochs\" } })\n .then(\n () => undefined,\n (error: unknown) => codeOf(error),\n );\n same(reused, \"MOSTRA_HOST_REQUEST_ID_REUSED\", \"a request ID reused with other parameters\");\n const patch = {\n artifact: { artifactId: first.artifactId },\n ops: [{ id: \"count\", value: 3 }],\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XF\",\n as: \"host\",\n };\n const once = await context.host.call(\"state/patch\", patch);\n const twice = await context.host.call(\"state/patch\", patch);\n same(twice, once, \"a retried state/patch\");\n const link = { artifact: { artifactId: first.artifactId }, requestId: \"req-link-1\" };\n same(\n (await context.host.call<{ url: string }>(\"view/url\", link)).url,\n (await context.host.call<{ url: string }>(\"view/url\", link)).url,\n \"a retried view/url\",\n );\n },\n};\n\n/** Durability: what Mostra acknowledged survives the instance stopping and starting again. */\nexport const durability: Scenario = {\n id: \"interaction.durability\",\n title:\n \"Everything acknowledged (versions, drafts, state, submissions, events) survives the instance stopping and starting again\",\n covers: [\"HO-05\", \"IN-12\", \"H-04\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n await viewer.write({ comment: \"a draft only\" });\n await context.host.call(\"state/patch\", {\n artifact: { artifactId: receipt.artifactId },\n ops: [{ id: \"count\", value: 7 }],\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XG\",\n as: \"host\",\n });\n const submitter = await context.viewer(receipt.artifactId, {\n link: { viewer: { ref: \"ada\" } },\n });\n same((await answerAndSubmit(submitter, { name: \"Ada\" })).status, 200, \"the submit\");\n const before = await context.results(receipt.artifactId);\n const eventsBefore = await context.events({ artifacts: [receipt.artifactId] });\n await context.restart();\n const after = await context.results(receipt.artifactId);\n same(\n after.submission.digest,\n before.submission.digest,\n \"the submission's digest after a restart\",\n );\n const state = await context.host.call<{ fields: Record<string, { value: unknown }> }>(\n \"state/get\",\n {\n artifact: { artifactId: receipt.artifactId },\n },\n );\n same(state.fields[\"count\"]?.value, 7, \"artifact state after a restart\");\n const eventsAfter = await context.events({ artifacts: [receipt.artifactId] });\n same(\n eventsAfter.events.slice(0, eventsBefore.events.length).map((event) => event.cursor),\n eventsBefore.events.map((event) => event.cursor),\n \"the event log after a restart\",\n );\n // The viewer's draft is still the canonical one: the same link continues it.\n const poll = await viewer.poll();\n same(\n poll.json<{ snapshot?: { draft?: { fields?: Record<string, { value: unknown }> } } }>()\n .snapshot?.draft?.fields?.[\"comment\"]?.value,\n \"a draft only\",\n \"the viewer's draft after a restart\",\n );\n },\n};\n\n/** The interaction scenarios. */\nexport const INTERACTION_SCENARIOS: readonly Scenario[] = [\n policies,\n subscriptions,\n signals,\n waits,\n longLived,\n results,\n idempotency,\n durability,\n];\n","/**\n * The host's ports, each with and without registration (HO-01): identity, trusted controls,\n * secrets, and what server code raises for the host (D108, D131, D143, AC-05, H-05, H-14).\n */\nimport { ACTIONS, FORM } from \"../fixtures.ts\";\nimport { check, type Scenario, same } from \"../scenario.ts\";\nimport { OpenError, resultOf } from \"../viewer.ts\";\n\n/** D143: the identity port names the person behind a link minted without a viewer. */\nexport const identity: Scenario = {\n id: \"ports.identity\",\n title:\n \"With an identity port, a link minted without a viewer acts as the person the host names from the request's headers (never its cookies); without one, as the home's local user\",\n covers: [\"HO-01\", \"HO-05\", \"H-05\", \"H-14\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM, { policy: { policy: \"epochs\" } });\n // The exchange carries a cookie and a Mostra header, so the filter that keeps them from the\n // host is really tested (Opus review of WP-12, finding 9).\n const headers = {\n \"x-forwarded-user\": \"ada@example.com\",\n cookie: \"elsewhere=1\",\n \"x-mostra-csrf\": \"not-for-the-host\",\n };\n const viewer = await context.viewer(receipt.artifactId, { headers });\n const channel = viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\";\n same((await viewer.answer({ name: \"Ada\" }, channel)).status, 200, \"the submit\");\n const read = await context.results(receipt.artifactId);\n if (!context.host.serves(\"identity\")) {\n same(read.submission.viewer.kind, \"local\", \"the viewer without an identity port\");\n return;\n }\n const calls = (await context.store()).identity;\n const call = calls.at(-1);\n check(call, \"the host's identity port was never asked\");\n // The session acts as whoever the host named, in its own terms (D143 item 2): the kit judges\n // the session by the host's answer, not by any one way of naming people.\n check(\n call.answer !== undefined,\n \"the host's store doesn't report what its identity port answered (harness/store)\",\n );\n same(\n call.answer === null\n ? [read.submission.viewer.kind]\n : [read.submission.viewer.kind, read.submission.viewer.ref],\n call.answer === null ? [\"local\"] : [\"host\", call.answer.ref],\n \"the submission's viewer, by the host's answer\",\n );\n same(call.via, \"local\", \"how the request reached the gateway\");\n check(\n call.headers.includes(\"x-forwarded-user\"),\n \"the port didn't receive the request's headers\",\n );\n check(\n !call.headers.some((name) => name === \"cookie\" || name.startsWith(\"x-mostra-\")),\n `the port received Mostra's credentials (${call.headers.join(\", \")})`,\n );\n // A link minted for a person keeps that person; the port isn't asked (D104).\n const minted = await context.viewer(receipt.artifactId, {\n link: { viewer: { ref: \"grace@example.com\", name: \"Grace\" } },\n headers,\n });\n same(\n (await context.store()).identity.length,\n calls.length,\n \"identity calls for a link with a viewer\",\n );\n same((await minted.answer({ name: \"Grace\" }, channel)).status, 200, \"the minted link's submit\");\n const graces = await context.results(receipt.artifactId);\n same(\n [graces.submission.viewer.kind, graces.submission.viewer.ref],\n [\"token\", \"grace@example.com\"],\n \"the viewer a link was minted for\",\n );\n if (context.host.supports(\"faults\")) {\n // A host that can't answer refuses the link rather than guess (D143).\n await context.host.script({ port: \"identity\", answer: \"fail\" });\n const refused = await context.viewer(receipt.artifactId, { headers }).then(\n () => undefined,\n (error: unknown) => error,\n );\n check(refused instanceof OpenError, \"a failing identity port still opened the link\");\n same(\n [refused.status, refused.code],\n [503, \"MOSTRA_HOST_IDENTITY_UNAVAILABLE\"],\n \"the refusal\",\n );\n await context.host.script({ port: \"identity\", answer: null });\n const local = await context.viewer(receipt.artifactId, { headers });\n same(\n (await local.answer({ name: \"local\" }, channel)).status,\n 200,\n \"a submit as the local user\",\n );\n same(\n (await context.results(receipt.artifactId)).submission.viewer.kind,\n \"local\",\n \"a null answer's viewer\",\n );\n }\n },\n};\n\n/** D108, H-05, SH-02: the host decides the channels; the artifact can't submit where it may not. */\nexport const trustedControls: Scenario = {\n id: \"ports.trusted-controls\",\n title:\n \"The host's trustedControls policy decides each view's channels: the artifact channel is refused with MOSTRA_SUBMIT_CHANNEL_DENIED, the shell's trusted Submit records the shell channel, and the host hears it was used\",\n covers: [\"HO-01\", \"HO-05\", \"SH-02\", \"H-05\"],\n async run(context) {\n await context.start();\n if (!context.host.serves(\"trustedControls\")) {\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n same(\n [...viewer.ticket.submitChannels].sort(),\n [\"artifact\", \"shell\"],\n \"the standalone channels (D40)\",\n );\n same(\n (await viewer.answer({ name: \"Ada\" }, \"artifact\")).status,\n 200,\n \"an artifact-channel submit\",\n );\n same(\n (await context.results(receipt.artifactId)).submission.channel,\n \"artifact\",\n \"the recorded channel\",\n );\n return;\n }\n // A host that can script its policy is asked for shell-only, the case hosts that need\n // provenance use (H-05); any other host is judged by the policy it answered itself.\n const scripted = context.host.supports(\"faults\")\n ? { submitChannels: [\"shell\"], controls: [\"submit\"] }\n : undefined;\n if (scripted) await context.host.script({ port: \"trustedControls\", answer: scripted });\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const asked = (await context.store()).policies.find(\n (entry) => entry.artifactId === receipt.artifactId,\n );\n check(asked, \"the host's policy wasn't asked when the view opened\");\n const policy = scripted ?? asked.answer;\n check(\n policy,\n \"the host's store doesn't report what its trustedControls policy answered (harness/store)\",\n );\n same(\n [...viewer.ticket.submitChannels].sort(),\n [...policy.submitChannels].sort(),\n \"the view's channels under the host's policy\",\n );\n const written = await viewer.write({ name: \"Ada\" });\n const revision = written.json<{ revision: string }>().revision;\n const artifactAllowed = policy.submitChannels.includes(\"artifact\");\n if (!artifactAllowed) {\n const denied = await viewer.submit(revision);\n same(\n [denied.status, denied.json<{ code?: string }>().code],\n [403, \"MOSTRA_SUBMIT_CHANNEL_DENIED\"],\n \"the artifact channel's submit\",\n );\n }\n if (!policy.submitChannels.includes(\"shell\")) {\n // A host that allows the artifact channel alone: the page's submit is recorded as such.\n same((await viewer.submit(revision)).status, 200, \"the artifact channel's submit\");\n same(\n (await context.results(receipt.artifactId)).submission.channel,\n \"artifact\",\n \"the recorded channel\",\n );\n return;\n }\n const trusted = await viewer.shellSubmit(revision);\n same(trusted.status, 200, \"the shell's trusted Submit\");\n same(\n (await context.results(receipt.artifactId)).submission.channel,\n \"shell\",\n \"the recorded channel\",\n );\n const activation = await context.eventually(\n \"the host hears the trusted Submit was used\",\n async () =>\n (await context.store()).activations.find(\n (entry) => entry.artifactId === receipt.artifactId,\n ),\n );\n same([activation.control, activation.viewId], [\"submit\", viewer.viewId], \"the activation\");\n if (context.host.supports(\"faults\")) {\n // A policy that fails narrows the view to the shell channel (D108).\n await context.host.script({ port: \"trustedControls\", answer: \"fail\" });\n const other = await context.published(FORM);\n const narrowed = await context.viewer(other.artifactId);\n same(narrowed.ticket.submitChannels, [\"shell\"], \"the channels when the host's policy fails\");\n }\n },\n};\n\n/** D131: secret() asks the host first; the value never reaches events or results. */\nexport const secrets: Scenario = {\n id: \"ports.secrets\",\n title:\n \"secret() in server code asks the host's secrets port first and falls back to the home's store on null; the value appears in no event\",\n covers: [\"HO-01\", \"HO-05\"],\n async run(context) {\n await context.start();\n await context.host.call(\"secret/set\", { name: \"HOME_ONLY\", value: \"from-the-home-store\" });\n const receipt = await context.published(ACTIONS);\n const viewer = await context.viewer(receipt.artifactId);\n const fromHome = await viewer.run(\"actions.ts#secretLength\", [\"HOME_ONLY\"]);\n same(\n fromHome.status,\n \"succeeded\",\n `a run reading the home's secret (${JSON.stringify(fromHome[\"error\"] ?? \"\")})`,\n );\n same(await resultOf(fromHome), \"from-the-home-store\".length, \"the home secret's length\");\n if (context.host.serves(\"secrets\") && context.host.supports(\"faults\")) {\n await context.host.script({ port: \"secrets\", answer: { API_KEY: \"s3cret-from-the-host\" } });\n const fromHost = await viewer.run(\"actions.ts#secretLength\", [\"API_KEY\"]);\n same(await resultOf(fromHost), \"s3cret-from-the-host\".length, \"the host secret's length\");\n check(\n (await context.store()).secrets.some((entry) => entry.name === \"API_KEY\"),\n \"the host's secrets port wasn't asked\",\n );\n const events = await context.events({ artifacts: [receipt.artifactId] });\n check(\n !JSON.stringify(events).includes(\"s3cret-from-the-host\"),\n \"a secret reached the event log\",\n );\n }\n },\n};\n\n/** AC-05, IN-09: server code's signals and host events reach the host as events, with the run. */\nexport const serverEvents: Scenario = {\n id: \"ports.server-events\",\n title:\n \"An action's signal() and emit() reach the host as signal.raised (source action) and host.* events caused by the run; Mostra wakes nobody for them\",\n covers: [\"HO-05\", \"IN-09\", \"AC-05\", \"H-09\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(ACTIONS);\n const viewer = await context.viewer(receipt.artifactId);\n const before = await context.store();\n const run = await viewer.run(\"actions.ts#notify\", [\"ada@example.com\"]);\n same(run.status, \"succeeded\", `the action run (${JSON.stringify(run[\"error\"] ?? \"\")})`);\n const read = await context.events({\n artifacts: [receipt.artifactId],\n types: [\"signal.raised\", \"host.*\", \"action.*\"],\n });\n const types = read.events.map((event) => event.type as string);\n const signal = read.events.find((event) => event.type === \"signal.raised\");\n const emitted = read.events.find((event) => event.type === \"host.mail.sent\");\n check(signal && emitted, `the run's signal or host event is missing (${types.join(\", \")})`);\n same([signal.payload[\"name\"], signal.payload[\"source\"]], [\"mail.sent\", \"action\"], \"the signal\");\n same(signal.causation?.[\"runId\"], run.runId, \"the signal's causing run\");\n same(emitted.payload[\"data\"], { to: \"ada@example.com\" }, \"the host event's data\");\n const started = types.indexOf(\"action.started\");\n const ended = types.indexOf(\"action.succeeded\");\n check(\n started >= 0 &&\n ended > types.indexOf(\"host.mail.sent\") &&\n started < types.indexOf(\"signal.raised\"),\n `the order of the run's events (${types.join(\", \")})`,\n );\n const after = await context.store();\n same(after.deliveries.length, before.deliveries.length, \"deliveries the run caused\");\n },\n};\n\n/** The port scenarios. */\nexport const PORT_SCENARIOS: readonly Scenario[] = [\n identity,\n trustedControls,\n secrets,\n serverEvents,\n];\n","/**\n * The session, process models, the home and privacy: what every host gets right before anything\n * else (HO-02, HO-08, RT-06, H-11, H-12, H-13, H-16).\n */\nimport { readFileSync, realpathSync, rmSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { HOST_PROTOCOL_REVISIONS } from \"@mostra/protocol\";\nimport { FORM } from \"../fixtures.ts\";\nimport { codeOf } from \"../harness/client.ts\";\nimport { check, connectSocket, rpcCode, type Scenario, same } from \"../scenario.ts\";\nimport { send } from \"../viewer.ts\";\n\n/** The session: a revision both sides speak, every registered port supported, order enforced. */\nexport const negotiation: Scenario = {\n id: \"session.negotiation\",\n title:\n \"The host negotiates a revision the instance speaks, registers only ports it supports, and an instance refuses a client with no common revision\",\n covers: [\"HO-02\", \"HO-05\", \"H-13\", \"H-15\"],\n async run(context) {\n const started = await context.start();\n check(\n (HOST_PROTOCOL_REVISIONS as readonly string[]).includes(started.revision),\n `the negotiated revision ${started.revision} isn't one this kit knows (${HOST_PROTOCOL_REVISIONS.join(\", \")})`,\n );\n const unsupported = started.warnings.filter(\n (warning) => warning.code === \"MOSTRA_HOST_PORT_UNSUPPORTED\",\n );\n check(\n unsupported.length === 0,\n \"the host registers a port the instance doesn't support (MOSTRA_HOST_PORT_UNSUPPORTED)\",\n );\n // mostra/initialize is sent once per connection; the host's client surfaces the refusal.\n const again = await context.host.callRaw(\"mostra/initialize\", {\n client: { name: \"again\", version: \"0\" },\n revisions: [...HOST_PROTOCOL_REVISIONS],\n capabilities: {},\n ports: [],\n });\n check(\"error\" in again, \"a second mostra/initialize on the host's connection was accepted\");\n same(again.error.data.code, \"MOSTRA_HOST_INITIALIZE_ORDER\", \"a second initialize's code\");\n // A client with no revision in common is refused with a typed error; one with any is served.\n const socket = context.socket();\n check(socket, \"the instance's home has no instance.json naming its socket (D81)\");\n const old = await connectSocket(socket, [\"2020-01-01\"]);\n const refused = await old.initialize.then(\n () => undefined,\n (error: unknown) => rpcCode(error),\n );\n old.close();\n same(refused, \"MOSTRA_HOST_REVISION_UNSUPPORTED\", \"a client offering only 2020-01-01\");\n const mixed = await connectSocket(socket, [\"2020-01-01\", ...HOST_PROTOCOL_REVISIONS]);\n const answer = (await mixed.initialize) as { revision: string };\n mixed.close();\n same(\n answer.revision,\n started.revision,\n \"the revision negotiated with an older and a current one\",\n );\n },\n};\n\n/** One supervisor per home: a second host of the same home meets the lock, attached ones share it. */\nexport const processModels: Scenario = {\n id: \"session.process-models\",\n title:\n \"A host spawns its instance over stdio or attaches to the home's daemon; a second spawn of the same home is refused with MOSTRA_HOME_LOCKED\",\n covers: [\"HO-05\", \"RT-06\", \"H-12\"],\n async run(context) {\n const second = await context.anotherHost();\n if (context.host.supports(\"attach\")) {\n const first = await context.start({ mode: \"attach\" });\n same(first.instance.mode, \"daemon\", \"an attached host's instance mode\");\n const other = await context.start({ mode: \"attach\", host: second });\n same(other.instance.pid, first.instance.pid, \"the daemon two attached hosts reach\");\n const third = await context.anotherHost();\n const locked = await context.start({ host: third }).then(\n () => undefined,\n (error: unknown) => codeOf(error),\n );\n same(locked, \"MOSTRA_HOME_LOCKED\", \"a spawn while the daemon owns the home\");\n await second.stopInstance();\n await context.host.stopInstance();\n return;\n }\n const first = await context.start();\n same(first.instance.mode, \"host\", \"a spawned instance's mode\");\n same(first.instance.pid > 0, true, \"the instance reports its PID\");\n const locked = await context.start({ host: second }).then(\n () => undefined,\n (error: unknown) => codeOf(error),\n );\n same(locked, \"MOSTRA_HOME_LOCKED\", \"a second spawn of the same home\");\n },\n};\n\n/**\n * HO-08 and H-11: the host chooses the home, and what was published stays readable after the\n * authoring directory is removed and the instance restarts.\n */\nexport const authoringRemoved: Scenario = {\n id: \"home.authoring-removed\",\n title:\n \"The host chooses the home; artifacts, versions and submissions stay readable after the authoring directory is removed\",\n covers: [\"HO-05\", \"HO-08\", \"H-11\"],\n async run(context) {\n const started = await context.start();\n same(started.instance.home, realpathSync(context.home), \"the home the instance owns\");\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const channel = viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\";\n const submitted = await viewer.answer({ name: \"Ada\", comment: \"kept\" }, channel);\n same(submitted.status, 200, \"the submit's status\");\n const before = await context.results(receipt.artifactId);\n rmSync(receipt.dir, { recursive: true, force: true });\n await context.restart();\n const byId = await context.host.call<{ id: string; versions: { id: string }[] }>(\n \"artifact/get\",\n { artifact: { artifactId: receipt.artifactId } },\n );\n same(byId.versions[0]?.id, receipt.versionId, \"the version, by artifact ID\");\n const byPath = await context.host.call<{ id: string }>(\"artifact/get\", {\n artifact: { path: receipt.dir },\n });\n same(byPath.id, receipt.artifactId, \"the artifact its deleted path still names\");\n const after = await context.results(receipt.artifactId);\n same(after.submission.digest, before.submission.digest, \"the submission's digest\");\n same(after.answers, before.answers, \"the submission's answers\");\n // The version still serves: its files live in the home, not in the authoring directory.\n const again = await context.viewer(receipt.artifactId);\n const page = await again.browser.ask({\n url: `${again.ticket.artifactOrigin}/`,\n headers: { accept: \"text/html\", \"sec-fetch-site\": \"same-origin\", \"sec-fetch-dest\": \"iframe\" },\n });\n same(page.status, 200, \"the version's page after the source is gone\");\n check(\n statSync(join(context.home, \"sources\", receipt.artifactId)).isDirectory(),\n \"the home keeps the version's source snapshot (DATA_MODEL §1)\",\n );\n },\n};\n\n/** H-16: a host-embedded instance sends no telemetry, keeps its home private, binds loopback. */\nexport const privacy: Scenario = {\n id: \"home.privacy\",\n title:\n \"A host's home is marked host-configured (no telemetry), owner-only (0700, secrets 0600), and its gateway binds loopback\",\n covers: [\"HO-05\", \"H-16\", \"EN-08\"],\n async run(context) {\n const started = await context.start();\n const config = JSON.parse(readFileSync(join(context.home, \"config.json\"), \"utf8\")) as {\n hostConfigured?: { client: string };\n };\n check(config.hostConfigured, \"config.json has no hostConfigured mark (D140 item 4)\");\n same(statSync(context.home).mode & 0o777, 0o700, \"the home's mode\");\n await context.host.call(\"secret/set\", { name: \"CONFORMANCE_TOKEN\", value: \"kept-private-123\" });\n same(\n statSync(join(context.home, \"secrets\", \"home\", \"CONFORMANCE_TOKEN\")).mode & 0o777,\n 0o600,\n \"a secret's mode\",\n );\n const status = await context.host.call<{ gateway?: { bind: string; shell: string } }>(\n \"instance/status\",\n {},\n );\n same(status.gateway?.bind, \"127.0.0.1\", \"the gateway's bind address\");\n // Nothing answers on any address but loopback: the shell's port on the machine's name fails.\n const shell = new URL(status.gateway?.shell ?? \"http://127.0.0.1:1\");\n const elsewhere = await send({ url: `http://localhost:${shell.port}/` }).catch(() => undefined);\n check(\n elsewhere === undefined || elsewhere.status === 421,\n `the shell answered a request for another host name (${elsewhere?.status})`,\n );\n same(started.instance.mode === \"host\" || started.instance.mode === \"daemon\", true, \"the mode\");\n },\n};\n\n/** The session scenarios. */\nexport const SESSION_SCENARIOS: readonly Scenario[] = [\n negotiation,\n processModels,\n authoringRemoved,\n privacy,\n];\n","/**\n * Viewing: capability links the host mints, and the gateway's hygiene against strangers (H-07,\n * H-14, HY-01, HY-03), then the shell and its bridge in a real browser (D108, SH-02).\n */\nimport { FORM, FORM_V2 } from \"../fixtures.ts\";\nimport { check, NotApplicable, type Scenario, same } from \"../scenario.ts\";\nimport { OpenError, parseLink, send, Viewer } from \"../viewer.ts\";\n\n/** H-07, H-14: publish answers a durable receipt with a link; links are scoped, revoked, rotated. */\nexport const links: Scenario = {\n id: \"viewing.links\",\n title:\n \"Publish returns a durable receipt with the artifact's link; view/url mints scoped links, a link without submit can't submit, and revoked or rotated links answer 410\",\n covers: [\"HO-05\", \"H-07\", \"H-14\", \"HY-03\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n check(receipt.url && receipt.tokenId, \"the publish receipt has no link (H-07)\");\n check(/^\\d+$/.test(receipt.cursor), `the receipt's cursor (${receipt.cursor})`);\n const viewOnly = await context.viewer(receipt.artifactId, { link: { scopes: [\"view\"] } });\n const written = await viewOnly.write({ name: \"x\" });\n same(\n [written.status, written.json<{ code?: string }>().code],\n [403, \"MOSTRA_HYGIENE_SCOPE_DENIED\"],\n \"a view-only link's write\",\n );\n const minted = await context.host.call<{ url: string; tokenId: string }>(\"view/url\", {\n artifact: { artifactId: receipt.artifactId },\n });\n await context.host.call(\"view/revoke\", { tokenId: minted.tokenId });\n const revoked = await Viewer.open(minted.url).then(\n () => undefined,\n (error: unknown) => error,\n );\n check(revoked instanceof OpenError, \"a revoked link still opened\");\n same([revoked.status, revoked.code], [410, \"MOSTRA_HYGIENE_TOKEN_REVOKED\"], \"a revoked link\");\n const rotated = await context.host.call<{ url: string }>(\"view/rotate\", {\n tokenId: receipt.tokenId,\n });\n const old = await Viewer.open(receipt.url).then(\n () => undefined,\n (error: unknown) => error,\n );\n check(\n old instanceof OpenError && old.status === 410,\n \"the default link still opens after its rotation\",\n );\n await Viewer.open(rotated.url);\n // A link that names a version opens that version, also after a newer one.\n context.rewrite(receipt.dir, FORM_V2);\n await context.publish(receipt.dir);\n const pinned = await context.viewer(receipt.artifactId, { link: { version: 1 } });\n same(pinned.ticket.version.number, 1, \"the version a pinned link opens\");\n same(pinned.ticket.latest.number, 2, \"the latest version it reports\");\n },\n};\n\n/** HY-01: the gateway refuses strangers: wrong Host, wrong Origin, no token, no CSRF token. */\nexport const hygiene: Scenario = {\n id: \"viewing.hygiene\",\n title:\n \"The host's instance refuses requests from strangers: an unknown Host (421), a foreign Origin (403), a wrong token (401), a mutation without its CSRF token (403)\",\n covers: [\"HO-05\", \"HY-01\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const link = parseLink(await context.link(receipt.artifactId));\n const exchange = `${link.origin}/a/${link.artifactId}/_mostra/session`;\n const post = (headers: Record<string, string>, body: unknown) =>\n send({\n method: \"POST\",\n url: exchange,\n headers: {\n \"content-type\": \"application/json\",\n \"sec-fetch-site\": \"same-origin\",\n origin: link.origin,\n ...headers,\n },\n body: JSON.stringify(body),\n });\n const host = await post({ host: \"evil.example\" }, { token: link.secret });\n same(host.status, 421, \"an unknown Host\");\n const origin = await post({ origin: \"http://evil.example\" }, { token: link.secret });\n same(origin.status, 403, \"a foreign Origin\");\n const token = await post({}, { token: \"A\".repeat(26) });\n same(token.status, 401, \"a wrong token\");\n const viewer = await Viewer.open(await context.link(receipt.artifactId));\n const noCsrf = await viewer.browser.ask({\n method: \"POST\",\n url: `${viewer.ticket.artifactOrigin}/_mostra/v/2026-10-15/signal`,\n headers: {\n \"content-type\": \"application/json\",\n origin: viewer.ticket.artifactOrigin,\n \"sec-fetch-site\": \"same-origin\",\n },\n body: JSON.stringify({ viewId: viewer.viewId, name: \"ping\" }),\n });\n same(noCsrf.status, 403, \"a mutation without its CSRF token\");\n for (const answer of [host, origin, token, noCsrf]) {\n check(\n !Object.keys(answer.headers).some((name) => name.startsWith(\"access-control-\")),\n \"a refusal carries a CORS header\",\n );\n }\n },\n};\n\n/**\n * D108, SH-02, SH-04: the shell and the page in a real browser. The trusted Submit carries the\n * label the page asked for (`mostra/controls.request`), lists the required answer by label\n * (`mostra/fields`) and focuses it in the page (`mostra/field.focus`), submits only after the page\n * flushed its saves, the defaults it showed included (`mostra/flush`, D110), and a new version\n * shows the trusted banner (`mostra/version.available`).\n */\nexport const shellBridge: Scenario = {\n id: \"viewing.shell-bridge\",\n title:\n \"In a browser, the shell and the page speak the bridge: a labelled trusted Submit, blockers by label that focus the field, a flush before submit, and the new-version banner\",\n covers: [\"HO-05\", \"SH-02\", \"SH-04\", \"H-05\"],\n async run(context) {\n let chromium: typeof import(\"playwright-core\").chromium;\n try {\n ({ chromium } = await import(\"playwright-core\"));\n } catch {\n throw new NotApplicable(\"playwright-core isn't installed\");\n }\n const browser = await chromium.launch().catch((error: unknown) => {\n throw new NotApplicable(\n `no browser to run the shell in (${(error as Error).message.split(\"\\n\")[0]})`,\n );\n });\n try {\n await context.start();\n const receipt = await context.published(FORM);\n const page = await browser.newPage();\n await page.goto(await context.link(receipt.artifactId));\n await page.waitForSelector('html[data-shell=\"ready\"]', { timeout: 60_000 });\n const frame = page.frameLocator(\"iframe\");\n const submit = page.locator(\"#mostra-submit\");\n await submit.waitFor();\n check(\n (await submit.textContent())?.includes(\"Send answers\"),\n \"the trusted Submit's label isn't the one the page asked for\",\n );\n // The required answer is listed by label, and picking it focuses the field in the page.\n await page.waitForTimeout(600);\n await submit.click();\n const blocker = page.locator(\"[data-mostra-blocker=name]\");\n await blocker.waitFor({ timeout: 10_000 });\n same((await blocker.textContent())?.trim(), \"Your name\", \"the blocker's label\");\n await blocker.click();\n await frame.getByLabel(\"Your name\").waitFor();\n await context.eventually(\n \"picking the blocker focuses the field in the page (mostra/field.focus)\",\n () =>\n frame\n .locator('[name=\"name\"]')\n .evaluate(\n (element: { ownerDocument: { activeElement: unknown } }) =>\n element === element.ownerDocument.activeElement,\n ),\n 10_000,\n );\n await frame.getByLabel(\"Your name\").fill(\"Ada\");\n await context.eventually(\"the trusted Submit submits\", async () => {\n if ((await submit.textContent())?.includes(\"Submitted\")) return true;\n await submit.click().catch(() => undefined);\n return (await submit.textContent())?.includes(\"Submitted\");\n });\n const read = await context.results(receipt.artifactId);\n same(read[\"submission\"].channel, \"shell\", \"the trusted Submit's channel\");\n // The page flushed first: the answer typed, and the default it showed for \"comment\".\n same(read[\"answers\"], { name: \"Ada\", comment: \"\" }, \"the answers, defaults included (D110)\");\n context.rewrite(receipt.dir, FORM_V2);\n await context.publish(receipt.dir);\n await page.locator('[data-mostra-banner=\"2\"]').waitFor({ timeout: 15_000 });\n } finally {\n await browser.close();\n }\n },\n};\n\n/** The viewing scenarios. */\nexport const VIEWING_SCENARIOS: readonly Scenario[] = [links, hygiene, shellBridge];\n","/**\n * Every scenario of the kit, in the order a run takes them. A scenario's ID is stable surface:\n * baselines name it. New scenarios join additively (WP-13 adds addressing, WP-20 reviews and\n * capture, WP-29 remote and WP-31 team scenarios).\n */\nimport type { Scenario } from \"../scenario.ts\";\nimport { DELIVERY_SCENARIOS } from \"./delivery.ts\";\nimport { INTERACTION_SCENARIOS } from \"./interaction.ts\";\nimport { PORT_SCENARIOS } from \"./ports.ts\";\nimport { SESSION_SCENARIOS } from \"./session.ts\";\nimport { VIEWING_SCENARIOS } from \"./viewing.ts\";\n\n/** Every scenario. */\nexport const SCENARIOS: readonly Scenario[] = [\n ...SESSION_SCENARIOS,\n ...DELIVERY_SCENARIOS,\n ...INTERACTION_SCENARIOS,\n ...PORT_SCENARIOS,\n ...VIEWING_SCENARIOS,\n];\n","/**\n * Runs scenarios against a host (HO-05): each in a fresh directory with a fresh shim and home,\n * one at a time, each bounded in time; then judges the run against the host's baseline.\n */\nimport { mkdtempSync, rmdirSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { type Baseline, NO_BASELINE } from \"./baseline.ts\";\nimport type { InitializeResult } from \"./harness/protocol.ts\";\nimport { NotApplicable, type RunSettings, type Scenario, ScenarioContext } from \"./scenario.ts\";\nimport { SCENARIOS } from \"./scenarios/index.ts\";\n\n/** How one scenario went. */\nexport type ScenarioStatus =\n /** The property held. */\n | \"passed\"\n /** It didn't, and the baseline doesn't expect that: the run fails. */\n | \"failed\"\n /** The host lacks a port or feature the scenario needs. */\n | \"skipped\"\n /** It didn't, as the baseline expects. */\n | \"expected-failure\"\n /** It held, though the baseline expects it to fail: the baseline is stale, the run fails. */\n | \"unexpected-pass\";\n\n/** One scenario's outcome. */\nexport interface ScenarioOutcome {\n /** The scenario's ID. */\n readonly id: string;\n /** What the scenario proves. */\n readonly title: string;\n /** The requirements and host needs it exercises. */\n readonly covers: readonly string[];\n /** How it went. */\n readonly status: ScenarioStatus;\n /** Why it failed or was skipped, or what the baseline says. */\n readonly reason?: string;\n /** How long it took. */\n readonly durationMs: number;\n}\n\n/** A run's report. */\nexport interface ConformanceReport {\n /** What the host said about itself. */\n readonly host: InitializeResult | undefined;\n /** Each scenario's outcome, in the order they ran. */\n readonly outcomes: readonly ScenarioOutcome[];\n /** Whether the run passes: nothing `failed` and nothing `unexpected-pass`. */\n readonly ok: boolean;\n}\n\n/** Options of {@link runConformance}. */\nexport interface RunOptions {\n /** The host's harness shim, as a command line (run through the shell). */\n readonly host: string;\n /** Variables for the shim's process, on top of this process's. */\n readonly hostEnv?: Readonly<Record<string, string>>;\n /** Only the scenarios whose ID equals or starts with one of these (`delivery.`). */\n readonly only?: readonly string[];\n /** The host's expected failures. */\n readonly baseline?: Baseline;\n /** Publish through verify's gate (needs the verify browser). Default false. */\n readonly verify?: boolean;\n /** Each scenario's time limit. Default 240 s. */\n readonly timeoutMs?: number;\n /** Where scenario directories go. Default a fresh directory under `/tmp` (short socket paths). */\n readonly workDir?: string;\n /** Each outcome as it is known. */\n readonly onOutcome?: (outcome: ScenarioOutcome) => void;\n /** The scenarios to choose from. Default every scenario of the kit. */\n readonly scenarios?: readonly Scenario[];\n}\n\nfunction selected(scenarios: readonly Scenario[], only: readonly string[] | undefined): Scenario[] {\n if (!only || only.length === 0) return [...scenarios];\n return scenarios.filter((scenario) =>\n only.some((prefix) => scenario.id === prefix || scenario.id.startsWith(prefix)),\n );\n}\n\n/** Runs one scenario: `passed`, `failed` or `skipped`, before the baseline. */\nasync function runOne(\n scenario: Scenario,\n settings: RunSettings,\n dir: string,\n timeoutMs: number,\n): Promise<{ status: \"passed\" | \"failed\" | \"skipped\"; reason?: string; host?: InitializeResult }> {\n const context = new ScenarioContext(settings, dir);\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await context.open();\n for (const feature of scenario.needs ?? []) context.requireFeature(feature);\n await Promise.race([\n scenario.run(context),\n new Promise<never>((_, fail) => {\n timer = setTimeout(\n () => fail(new Error(`the scenario didn't finish within ${timeoutMs / 1000} s`)),\n timeoutMs,\n );\n }),\n ]);\n return { status: \"passed\", ...(context.host.info ? { host: context.host.info } : {}) };\n } catch (error) {\n const host = context.host?.info;\n if (error instanceof NotApplicable)\n return { status: \"skipped\", reason: error.message, ...(host ? { host } : {}) };\n const stderr = context.host?.stderr.slice(-3).join(\" | \");\n const message = (error as Error).message ?? String(error);\n return {\n status: \"failed\",\n reason:\n stderr && !(error as Error).name?.startsWith(\"Scenario\")\n ? `${message} (host: ${stderr})`\n : message,\n ...(host ? { host } : {}),\n };\n } finally {\n clearTimeout(timer);\n await context.close().catch(() => undefined);\n }\n}\n\n/** Runs the kit's scenarios against a host and judges them against its baseline. */\nexport async function runConformance(options: RunOptions): Promise<ConformanceReport> {\n const baseline = options.baseline ?? NO_BASELINE;\n // A baseline naming a scenario the run doesn't know would expect nothing, silently: refused here\n // as `readBaseline` refuses it, whoever built the baseline (GPT review of WP-12, finding 9).\n const catalog = (options.scenarios ?? SCENARIOS).map((scenario) => scenario.id);\n const unknown = Object.keys(baseline.expectedFailures).filter((id) => !catalog.includes(id));\n if (unknown.length > 0) {\n throw new Error(`The baseline names scenarios the kit doesn't have: ${unknown.join(\", \")}.`);\n }\n const settings: RunSettings = {\n host: options.host,\n hostEnv: options.hostEnv ?? {},\n verify: options.verify ?? false,\n };\n const root =\n options.workDir ?? mkdtempSync(join(process.platform === \"darwin\" ? \"/tmp\" : tmpdir(), \"mc-\"));\n const outcomes: ScenarioOutcome[] = [];\n let host: InitializeResult | undefined;\n let index = 0;\n for (const scenario of selected(options.scenarios ?? SCENARIOS, options.only)) {\n index += 1;\n const started = Date.now();\n const result = await runOne(\n scenario,\n settings,\n join(root, `s${index}`),\n options.timeoutMs ?? 240_000,\n );\n host ??= result.host;\n const expected = baseline.expectedFailures[scenario.id];\n let status: ScenarioStatus = result.status;\n let reason = result.reason;\n if (expected !== undefined && result.status === \"failed\") {\n status = \"expected-failure\";\n reason = `${expected} (${result.reason ?? \"failed\"})`;\n } else if (expected !== undefined && result.status === \"passed\") {\n status = \"unexpected-pass\";\n reason = `the baseline expects a failure (${expected}), and it passed: remove it from the baseline`;\n }\n const outcome: ScenarioOutcome = {\n id: scenario.id,\n title: scenario.title,\n covers: scenario.covers,\n status,\n ...(reason !== undefined ? { reason } : {}),\n durationMs: Date.now() - started,\n };\n outcomes.push(outcome);\n options.onOutcome?.(outcome);\n }\n // Each scenario removed its own directory; the run's own is removed when the kit made it.\n if (options.workDir === undefined) {\n try {\n rmdirSync(root);\n } catch {\n // Not empty: something a scenario couldn't remove stays for a look.\n }\n }\n return {\n host,\n outcomes,\n ok: outcomes.every(\n (outcome) => outcome.status !== \"failed\" && outcome.status !== \"unexpected-pass\",\n ),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,iBAAsC,EAAE,aAAa;CACzD,eAAe,EAAE,QAAQ,CAAC;CAC1B,kBAAkB,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC;AACjE,CAAC;;AAGD,MAAa,cAAw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OAAO;CAC7B;CAEA,IAAI,QAAQ,YAAY,KAAA,GACtB,IAAI;EACF,UAAU,IAAI;CAChB,QAAQ,CAER;CAEF,OAAO;EACL;EACA;EACA,IAAI,SAAS,OACV,YAAY,QAAQ,WAAW,YAAY,QAAQ,WAAW,iBACjE;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/conformance",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Prove a host's Mostra integration: conformance scenarios run against your host through a small harness protocol, with expected-failure baselines and reference hosts.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -35,8 +35,8 @@
35
35
  "provenance": true
36
36
  },
37
37
  "dependencies": {
38
- "@mostra/protocol": "0.2.0",
39
- "@mostra/sdk": "0.2.0",
38
+ "@mostra/protocol": "0.4.0",
39
+ "@mostra/sdk": "0.4.0",
40
40
  "playwright-core": "1.64.0",
41
41
  "zod": "4.6.5"
42
42
  },
@@ -46,7 +46,7 @@
46
46
  "tsdown": "0.23.0",
47
47
  "typescript": "7.0.2",
48
48
  "vitest": "5.0.3",
49
- "@mostra/runtime": "0.2.0"
49
+ "@mostra/runtime": "0.4.0"
50
50
  },
51
51
  "keywords": [
52
52
  "mostra",
package/src/scenario.ts CHANGED
@@ -12,7 +12,6 @@ import {
12
12
  rmSync,
13
13
  writeFileSync,
14
14
  } from "node:fs";
15
- import { createConnection } from "node:net";
16
15
  import { dirname, join } from "node:path";
17
16
  import {
18
17
  createDiagnostic,
@@ -24,6 +23,7 @@ import {
24
23
  RpcError,
25
24
  RpcPeer,
26
25
  } from "@mostra/protocol";
26
+ import { connectControl, resolveRuntime } from "@mostra/sdk";
27
27
  import type { Fixture } from "./fixtures.ts";
28
28
  import { HostUnderTest } from "./harness/client.ts";
29
29
  import type { StartParams, StartResult, StoreResult } from "./harness/protocol.ts";
@@ -337,10 +337,10 @@ export async function connectSocket(
337
337
  path: string,
338
338
  revisions: readonly string[] = HOST_PROTOCOL_REVISIONS,
339
339
  ): Promise<SocketSession & { initialize: Promise<unknown> }> {
340
- const socket = await new Promise<ReturnType<typeof createConnection>>((resolve, reject) => {
341
- const connection = createConnection(path);
342
- connection.once("connect", () => resolve(connection));
343
- connection.once("error", reject);
340
+ // As every client reaches an instance: on Windows through the helper beside the runtime, which
341
+ // refuses a pipe another user created under the name (D150 item 4).
342
+ const socket = await connectControl(path, {
343
+ runtime: process.platform === "win32" ? await resolveRuntime() : undefined,
344
344
  });
345
345
  const peer = new RpcPeer({
346
346
  send: (message) => {
@@ -1 +0,0 @@
1
- {"version":3,"file":"runner-CvoSJlfk.js","names":["InitializeResultSchema","StartResultSchema","CallResultSchema","StoreResultSchema","EventsResultSchema","httpRequest"],"sources":["../src/baseline.ts","../src/fixtures.ts","../src/harness/client.ts","../src/viewer.ts","../src/scenario.ts","../src/scenarios/delivery.ts","../src/scenarios/interaction.ts","../src/scenarios/ports.ts","../src/scenarios/session.ts","../src/scenarios/viewing.ts","../src/scenarios/index.ts","../src/runner.ts"],"sourcesContent":["/**\n * Expected-failure baselines (HO-05): a host that knows it fails some scenarios today records them,\n * with why, so a run stays green while the gap is known and goes red the moment anything changes:\n * a scenario that newly fails, or one the baseline expects to fail that passes (the baseline is\n * then stale and must shrink). The pattern of the MCP conformance suite and WPT's expectations.\n *\n * ```json\n * { \"schemaVersion\": 1, \"expectedFailures\": { \"delivery.exactly-once\": \"our store isn't idempotent yet (#123)\" } }\n * ```\n */\nimport { readFileSync } from \"node:fs\";\nimport * as z from \"zod\";\n\n/** A baseline: the scenarios a host is expected to fail, each with its reason. */\nexport interface Baseline {\n /** The baseline format's version: 1. */\n readonly schemaVersion: 1;\n /** Each expected failure: the scenario's ID and why it fails. */\n readonly expectedFailures: Readonly<Record<string, string>>;\n}\n\nconst BaselineSchema: z.ZodType<Baseline> = z.strictObject({\n schemaVersion: z.literal(1),\n expectedFailures: z.record(z.string().min(1), z.string().min(1)),\n});\n\n/** An empty baseline: every scenario must pass. */\nexport const NO_BASELINE: Baseline = { schemaVersion: 1, expectedFailures: {} };\n\n/**\n * Reads a baseline file. Throws on a file that isn't one, and on a scenario ID no scenario of\n * `known` has (a typo would otherwise expect nothing, silently).\n */\nexport function readBaseline(path: string, known: readonly string[]): Baseline {\n let data: unknown;\n try {\n data = JSON.parse(readFileSync(path, \"utf8\"));\n } catch (error) {\n throw new Error(`${path} isn't a readable JSON baseline: ${(error as Error).message}`);\n }\n const parsed = BaselineSchema.safeParse(data);\n if (!parsed.success) {\n throw new Error(\n `${path} isn't a conformance baseline: { \"schemaVersion\": 1, \"expectedFailures\": { \"<scenario>\": \"<why>\" } }.`,\n );\n }\n const unknown = Object.keys(parsed.data.expectedFailures).filter((id) => !known.includes(id));\n if (unknown.length > 0)\n throw new Error(`${path} names scenarios the kit doesn't have: ${unknown.join(\", \")}.`);\n return parsed.data;\n}\n","/**\n * The artifacts the scenarios publish, written fresh into the run's authoring directory. They\n * declare their fields with literal IDs, so every answer a scenario writes is covered by the\n * version (D109) and none is orphaned by accident.\n */\n\n/** A fixture: its files by relative path. */\nexport type Fixture = Readonly<Record<string, string>>;\n\n/** A questionnaire with viewer fields, an artifact-scoped counter, a family and a link (H-06). */\nexport const FORM: Fixture = {\n \"index.tsx\": `import { defineArtifact, useField, useSubmitControl } from \"@mostra/react\";\n\nexport const artifact = defineArtifact({\n title: \"Conformance questionnaire\",\n description: \"The form the host conformance kit answers.\",\n family: \"questionnaire\",\n links: [{ rel: \"round-of\", artifact: \"conformance-round-1\" }],\n});\n\nexport default function Page() {\n useSubmitControl({ label: \"Send answers\" });\n const [name, setName] = useField(\"name\", \"\", { label: \"Your name\", required: true });\n const [comment, setComment] = useField(\"comment\", \"\", { label: \"Comment\" });\n const [count, setCount] = useField(\"count\", 0, { label: \"Count\", scope: \"artifact\" });\n const [done, setDone] = useField(\"done\", false, { label: \"Done\", scope: \"artifact\" });\n return (\n <main>\n <h1>Conformance questionnaire</h1>\n <input name=\"name\" aria-label=\"Your name\" value={name} onChange={(e) => setName(e.target.value)} />\n <textarea name=\"comment\" aria-label=\"Comment\" value={comment} onChange={(e) => setComment(e.target.value)} />\n <button type=\"button\" onClick={() => setCount(count + 1)}>Count {count}</button>\n <label><input type=\"checkbox\" checked={done} onChange={(e) => setDone(e.target.checked)} /> Done</label>\n </main>\n );\n}\n`,\n};\n\n/** The same questionnaire with one more question: a second version of {@link FORM}. */\nexport const FORM_V2: Fixture = {\n \"index.tsx\": (FORM[\"index.tsx\"] as string)\n .replace(\"<h1>Conformance questionnaire</h1>\", \"<h1>Conformance questionnaire, round 2</h1>\")\n .replace(\n \" const [done, setDone]\",\n ' const [extra, setExtra] = useField(\"extra\", \"\", { label: \"Extra\" });\\n const [done, setDone]',\n )\n .replace(\n \" <label>\",\n ' <input name=\"extra\" aria-label=\"Extra\" value={extra} onChange={(e) => setExtra(e.target.value)} />\\n <label>',\n ),\n};\n\n/**\n * Server code: an action that raises a signal and emits a host event (AC-05), and one that reads\n * a secret through `secret()` (D131) and returns only its length, never the value.\n */\nexport const ACTIONS: Fixture = {\n \"index.tsx\": `import { defineArtifact } from \"@mostra/react\";\n\nexport const artifact = defineArtifact({ title: \"Conformance actions\" });\n\nexport default function Page() {\n return <main><h1>Conformance actions</h1></main>;\n}\n`,\n \"actions.ts\": `\"use server\";\nimport { emit, secret, signal } from \"@mostra/server\";\n\nexport async function notify(to: string): Promise<string> {\n signal(\"mail.sent\", { to });\n emit(\"host.mail.sent\", { to });\n return \"sent\";\n}\n\nexport async function secretLength(name: string): Promise<number> {\n return secret(name).length;\n}\n`,\n};\n\n/** The bundled fixtures by name. */\nexport const FIXTURES: Readonly<Record<string, Fixture>> = {\n form: FORM,\n \"form-v2\": FORM_V2,\n actions: ACTIONS,\n};\n","/**\n * The kit's side of the harness protocol: starts a host's shim (a command line), speaks to it\n * over its stdio, and gives scenarios typed methods. The shim's stderr is kept (its last lines\n * explain a failure). A shim that exits ends every pending call with\n * `MOSTRA_HOST_CONNECTION_CLOSED`.\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport {\n createDiagnostic,\n type Diagnostic,\n encodeLine,\n LineSplitter,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport { kitVersion } from \"../version.ts\";\nimport {\n type CallError,\n type CallResult,\n CallResult as CallResultSchema,\n type EventsParams,\n type EventsResult,\n EventsResult as EventsResultSchema,\n HARNESS_METHODS,\n HARNESS_REVISIONS,\n type InitializeResult,\n InitializeResult as InitializeResultSchema,\n type ScriptParams,\n type StartParams,\n type StartResult,\n StartResult as StartResultSchema,\n type StoreResult,\n StoreResult as StoreResultSchema,\n} from \"./protocol.ts\";\n\n/** How long one harness request may take before the kit gives up on the host. */\nconst HARNESS_TIMEOUT_MS = 120_000;\n\n/** An instance's error, carried through the host: its diagnostic code and JSON-RPC code. */\nexport class InstanceError extends Error {\n /** The diagnostic code (`MOSTRA_…`). */\n readonly code: string;\n /** The JSON-RPC error code. */\n readonly rpcCode: number;\n /** The diagnostic as it arrived. */\n readonly data: CallError[\"data\"];\n\n constructor(method: string, error: CallError) {\n super(`${method} failed with ${error.data.code}: ${error.data.message ?? \"\"}`);\n this.name = \"InstanceError\";\n this.code = error.data.code;\n this.rpcCode = error.code;\n this.data = error.data;\n }\n}\n\n/** A host under test, reached through its harness shim. */\nexport class HostUnderTest {\n readonly #child: ChildProcess;\n readonly #peer: RpcPeer;\n readonly #stderr: string[] = [];\n readonly #exited: Promise<number | null>;\n /** What the host said about itself. */\n info: InitializeResult | undefined;\n\n private constructor(command: string, env: Readonly<Record<string, string>>) {\n this.#child = spawn(command, {\n shell: true,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: { ...process.env, ...env } as NodeJS.ProcessEnv,\n detached: true,\n });\n this.#exited = new Promise((done) => {\n this.#child.on(\"close\", (code) => done(code));\n this.#child.on(\"error\", () => done(null));\n });\n this.#peer = new RpcPeer({\n send: (message) => {\n if (this.#child.stdin?.writable) this.#child.stdin.write(encodeLine(message));\n },\n });\n const lines = new LineSplitter();\n this.#child.stdout?.setEncoding(\"utf8\");\n this.#child.stdout?.on(\"data\", (chunk: string) => {\n for (const line of lines.push(chunk)) this.#peer.receiveLine(line);\n });\n const errors = new LineSplitter();\n this.#child.stderr?.setEncoding(\"utf8\");\n this.#child.stderr?.on(\"data\", (chunk: string) => {\n for (const line of errors.push(chunk)) {\n this.#stderr.push(line);\n if (this.#stderr.length > 40) this.#stderr.shift();\n }\n });\n this.#child.stdin?.on(\"error\", () => {});\n void this.#exited.then((code) =>\n this.#peer.close(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `The host under test exited (${code ?? \"signal\"}): ${this.#stderr.slice(-3).join(\" | \")}`,\n }),\n ),\n );\n }\n\n /** Starts the shim and asks it who it is. */\n static async start(\n command: string,\n env: Readonly<Record<string, string>> = {},\n ): Promise<HostUnderTest> {\n const host = new HostUnderTest(command, env);\n try {\n const answer = await host.#request(HARNESS_METHODS.initialize, {\n revision: HARNESS_REVISIONS.at(-1),\n kit: { name: \"@mostra/conformance\", version: kitVersion() },\n });\n host.info = InitializeResultSchema.parse(answer);\n } catch (error) {\n await host.close();\n throw error;\n }\n return host;\n }\n\n /** The host's last stderr lines. */\n get stderr(): readonly string[] {\n return this.#stderr;\n }\n\n /** Whether the host serves `port` / supports `feature`. */\n serves(port: string): boolean {\n return this.info?.ports.includes(port) ?? false;\n }\n /** Whether the host supports the harness feature `feature`. */\n supports(feature: string): boolean {\n return this.info?.features.includes(feature) ?? false;\n }\n\n #request(method: string, params: unknown, timeoutMs = HARNESS_TIMEOUT_MS): Promise<unknown> {\n return this.#peer.request(method, params as never, { timeoutMs });\n }\n\n /** `harness/start`: the host starts or attaches to its instance. */\n async startInstance(params: StartParams): Promise<StartResult> {\n return StartResultSchema.parse(await this.#request(HARNESS_METHODS.start, params));\n }\n\n /** `harness/call`, raw: the instance's answer or error as the host received it. */\n async callRaw(method: string, params: unknown, timeoutMs?: number): Promise<CallResult> {\n return CallResultSchema.parse(\n await this.#request(\n HARNESS_METHODS.call,\n { method, params, ...(timeoutMs !== undefined ? { timeoutMs } : {}) },\n (timeoutMs ?? 60_000) + 30_000,\n ),\n );\n }\n\n /** `harness/call`: the answer, or an {@link InstanceError}. */\n async call<T = Record<string, unknown>>(\n method: string,\n params: unknown,\n timeoutMs?: number,\n ): Promise<T> {\n const answer = await this.callRaw(method, params, timeoutMs);\n if (\"error\" in answer) throw new InstanceError(method, answer.error);\n return answer.result as T;\n }\n\n /** `harness/stop`: the host ends its session. */\n async stopInstance(): Promise<void> {\n await this.#request(HARNESS_METHODS.stop, {});\n }\n\n /** `harness/store`. */\n async store(): Promise<StoreResult> {\n return StoreResultSchema.parse(await this.#request(HARNESS_METHODS.store, {}));\n }\n\n /** `harness/script` (feature `faults`). */\n async script(params: ScriptParams): Promise<void> {\n await this.#request(HARNESS_METHODS.script, params);\n }\n\n /** `harness/events` (feature `events`). */\n async events(params: EventsParams): Promise<EventsResult> {\n return EventsResultSchema.parse(\n await this.#request(HARNESS_METHODS.events, params, params.timeoutMs + 30_000),\n );\n }\n\n /** Ends the shim: stdin closes, then SIGTERM to its process group, then SIGKILL. */\n async close(): Promise<void> {\n this.#child.stdin?.end();\n const pid = this.#child.pid;\n const signal = (name: NodeJS.Signals): void => {\n if (pid === undefined) return;\n try {\n process.kill(-pid, name);\n } catch {\n // gone already\n }\n };\n const outcome = await Promise.race([\n this.#exited.then(() => \"exited\" as const),\n new Promise<\"waiting\">((done) => setTimeout(() => done(\"waiting\"), 5000)),\n ]);\n if (outcome === \"waiting\") {\n signal(\"SIGTERM\");\n const later = await Promise.race([\n this.#exited.then(() => \"exited\" as const),\n new Promise<\"waiting\">((done) => setTimeout(() => done(\"waiting\"), 5000)),\n ]);\n if (later === \"waiting\") signal(\"SIGKILL\");\n }\n this.#peer.close();\n }\n}\n\n/** A diagnostic code from an error the kit saw: the instance's, an RPC error's, or none. */\nexport function codeOf(error: unknown): string | undefined {\n if (error instanceof InstanceError) return error.code;\n if (error instanceof RpcError) return (error.diagnostic as Diagnostic).code;\n return undefined;\n}\n","/**\n * A viewer as the kit plays one: it opens a capability link the way the shell does (the token for\n * a shell session, a frame ticket, the frame's entry) and speaks the browser protocol the way a\n * page does, with a per-host cookie jar (browsers keep cookies per host, not per port, D98) and the\n * `Origin`, `Sec-Fetch-*` and CSRF headers a browser sends. It also sends what no browser would,\n * for the hygiene scenarios. It never follows redirects.\n */\nimport { request as httpRequest } from \"node:http\";\nimport {\n BROWSER_PROTOCOL_REVISIONS,\n deserializeAll,\n type Frame,\n type FrameTicket,\n MutationId,\n serializeAll,\n} from \"@mostra/protocol\";\n\n/** The browser-protocol revision the kit speaks: the first, which every gateway serves. */\nconst REVISION: string = BROWSER_PROTOCOL_REVISIONS[0] as string;\n\n/** One HTTP answer. */\nexport interface Answer {\n /** The HTTP status. */\n readonly status: number;\n /** Each header (lowercase name) with every value it was sent with. */\n readonly headers: Readonly<Record<string, readonly string[]>>;\n /** The body as text. */\n readonly body: string;\n /** The body as JSON (`{}` when it isn't). */\n json<T = Record<string, unknown>>(): T;\n}\n\n/** One request. */\nexport interface Ask {\n /** The HTTP method; default `GET`. */\n readonly method?: string;\n /** The full URL. */\n readonly url: string;\n /** The request's headers, exactly as sent. */\n readonly headers?: Readonly<Record<string, string>>;\n /** The body, if any. */\n readonly body?: string;\n /** Leave out the jar's cookies. */\n readonly noCookies?: boolean;\n}\n\n/** Sends one request, never following a redirect. */\nexport function send(ask: Ask): Promise<Answer> {\n const url = new URL(ask.url);\n return new Promise((resolve, reject) => {\n const req = httpRequest(\n {\n host: url.hostname.replace(/^\\[|\\]$/g, \"\"),\n port: url.port,\n method: ask.method ?? \"GET\",\n path: `${url.pathname}${url.search}`,\n headers: ask.headers,\n agent: false,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n res.on(\"end\", () => {\n const headers: Record<string, string[]> = {};\n for (let index = 0; index + 1 < res.rawHeaders.length; index += 2) {\n const name = (res.rawHeaders[index] as string).toLowerCase();\n const values = headers[name] ?? [];\n values.push(res.rawHeaders[index + 1] as string);\n headers[name] = values;\n }\n const body = Buffer.concat(chunks).toString(\"utf8\");\n resolve({\n status: res.statusCode ?? 0,\n headers,\n body,\n json: <T>() => {\n try {\n return JSON.parse(body) as T;\n } catch {\n return {} as T;\n }\n },\n });\n });\n },\n );\n req.setTimeout(60_000, () => req.destroy(new Error(`${ask.url} didn't answer in 60 s`)));\n req.on(\"error\", reject);\n if (ask.body !== undefined) req.write(ask.body);\n req.end();\n });\n}\n\n/** A link's parts: its shell origin, artifact, token secret and pinned version. */\nexport interface ParsedLink {\n /** The shell's origin. */\n readonly origin: string;\n /** The artifact the link opens. */\n readonly artifactId: string;\n /** The token's secret, from the fragment. */\n readonly secret: string;\n /** The version number the link pins, if it pins one. */\n readonly version?: string;\n}\n\n/** Reads a capability link (`http://host:port/a/<artifactId>[/v/<n>]#t=<secret>`). */\nexport function parseLink(link: string): ParsedLink {\n const url = new URL(link);\n const match = /^\\/a\\/(art_[0-9A-Z]{26})(?:\\/v\\/(\\d+))?$/.exec(url.pathname);\n const secret = new URLSearchParams(url.hash.slice(1)).get(\"t\");\n if (!match?.[1] || !secret)\n throw new Error(`${url.origin}${url.pathname} isn't a capability link.`);\n return {\n origin: url.origin,\n artifactId: match[1],\n secret,\n ...(match[2] !== undefined ? { version: match[2] } : {}),\n };\n}\n\n/** A browser-like client with a per-host cookie jar. */\nexport class Browser {\n readonly #jar = new Map<string, { value: string; path: string }>();\n\n /** The cookies the jar sends to `url`: every cookie of the host whose path matches. */\n cookiesFor(url: string): string {\n const { pathname } = new URL(url);\n return [...this.#jar]\n .filter(([, cookie]) => {\n const prefix = cookie.path.endsWith(\"/\") ? cookie.path : `${cookie.path}/`;\n return pathname === cookie.path || pathname.startsWith(prefix);\n })\n .map(([key, cookie]) => `${key.split(\" \")[0]}=${cookie.value}`)\n .join(\"; \");\n }\n\n /** Sends a request with the jar's cookies and keeps the ones that come back. */\n async ask(ask: Ask): Promise<Answer> {\n const cookie = ask.noCookies ? \"\" : this.cookiesFor(ask.url);\n const answer = await send({\n ...ask,\n headers: { ...(cookie ? { cookie } : {}), ...ask.headers },\n });\n for (const line of answer.headers[\"set-cookie\"] ?? []) {\n const [pair = \"\", ...attributes] = line.split(\";\").map((part) => part.trim());\n const at = pair.indexOf(\"=\");\n const path =\n attributes.find((attribute) => attribute.toLowerCase().startsWith(\"path=\"))?.slice(5) ??\n \"/\";\n this.#jar.set(`${pair.slice(0, at)} ${path}`, { value: pair.slice(at + 1), path });\n }\n return answer;\n }\n\n /** A page on `origin` posting or fetching JSON from its own origin. */\n fetchJson(\n origin: string,\n path: string,\n init: { method?: string; body?: unknown; csrf?: string; headers?: Record<string, string> } = {},\n ): Promise<Answer> {\n const method = init.method ?? (init.body === undefined ? \"GET\" : \"POST\");\n return this.ask({\n method,\n url: `${origin}${path}`,\n headers: {\n \"sec-fetch-site\": \"same-origin\",\n \"sec-fetch-mode\": \"cors\",\n \"sec-fetch-dest\": \"empty\",\n ...(method === \"GET\" ? {} : { origin, \"content-type\": \"application/json\" }),\n ...(init.csrf ? { \"x-mostra-csrf\": init.csrf } : {}),\n ...init.headers,\n },\n ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),\n });\n }\n}\n\n/** Why a viewer couldn't open its link: the step and the gateway's answer. */\nexport class OpenError extends Error {\n /** The HTTP status of the refused step. */\n readonly status: number;\n /** The diagnostic code (`MOSTRA_…`). */\n readonly code: string | undefined;\n\n constructor(step: string, answer: Answer) {\n const code = answer.json<{ code?: string }>().code;\n super(`${step}: HTTP ${answer.status}${code ? ` ${code}` : \"\"}`);\n this.name = \"OpenError\";\n this.status = answer.status;\n this.code = code;\n }\n}\n\n/** A run's state, as `runs` and `runs/attach` answer it. */\nexport interface RunState {\n /** The run's ID (`run_…`). */\n readonly runId: string;\n /** `queued`, `running`, `succeeded`, `failed` or `cancelled` (D130). */\n readonly status: string;\n /** Its result, as serializer batches. */\n readonly batches: readonly Frame[][];\n /** The rest of the run's state (progress, log, error). */\n readonly [key: string]: unknown;\n}\n\n/** One opened view: a shell session, a frame session and the view they show. */\nexport class Viewer {\n /** The cookie jar this viewer's requests use. */\n readonly browser: Browser;\n /** The link it opened. */\n readonly link: ParsedLink;\n /** The frame ticket the shell got: the view, its version, channels and controls. */\n readonly ticket: FrameTicket;\n readonly #shellCsrf: string;\n readonly #frameCsrf: string;\n\n private constructor(\n browser: Browser,\n link: ParsedLink,\n ticket: FrameTicket,\n shellCsrf: string,\n frameCsrf: string,\n ) {\n this.browser = browser;\n this.link = link;\n this.ticket = ticket;\n this.#shellCsrf = shellCsrf;\n this.#frameCsrf = frameCsrf;\n }\n\n /**\n * Opens `link` as the shell does. `headers` go with the session exchange (the request the\n * `identity` port judges, D143). Throws an {@link OpenError} for a refused step.\n */\n static async open(\n link: string,\n options: { browser?: Browser; headers?: Record<string, string> } = {},\n ): Promise<Viewer> {\n const browser = options.browser ?? new Browser();\n const parsed = parseLink(link);\n const api = `/a/${parsed.artifactId}/_mostra`;\n const exchange = await browser.fetchJson(parsed.origin, `${api}/session`, {\n body: { token: parsed.secret },\n ...(options.headers ? { headers: options.headers } : {}),\n });\n if (exchange.status !== 200) throw new OpenError(\"exchange\", exchange);\n const shellCsrf = exchange.json<{ csrf: string }>().csrf;\n const ticketAnswer = await browser.fetchJson(parsed.origin, `${api}/ticket`, {\n body: parsed.version !== undefined ? { version: Number(parsed.version) } : {},\n csrf: shellCsrf,\n });\n if (ticketAnswer.status !== 200) throw new OpenError(\"ticket\", ticketAnswer);\n const ticket = ticketAnswer.json<FrameTicket>();\n const enter = await browser.ask({\n url: ticket.src,\n headers: {\n accept: \"text/html\",\n \"sec-fetch-mode\": \"navigate\",\n \"sec-fetch-dest\": \"iframe\",\n \"sec-fetch-site\": \"same-site\",\n },\n });\n if (enter.status !== 303) throw new OpenError(\"enter\", enter);\n const session = await browser.fetchJson(ticket.artifactOrigin, \"/_mostra/session\");\n if (session.status !== 200) throw new OpenError(\"frame session\", session);\n return new Viewer(browser, parsed, ticket, shellCsrf, session.json<{ csrf: string }>().csrf);\n }\n\n /** The view this frame load is (D104). */\n get viewId(): string {\n return this.ticket.viewId;\n }\n\n /** A browser-protocol request from the page. */\n page(path: string, body: unknown): Promise<Answer> {\n return this.browser.fetchJson(this.ticket.artifactOrigin, `/_mostra/v/${REVISION}/${path}`, {\n body,\n csrf: this.#frameCsrf,\n });\n }\n\n /** A request of the shell (its own origin, under `/a/<artifactId>`). */\n shell(path: string, body?: unknown, method?: string): Promise<Answer> {\n return this.browser.fetchJson(this.link.origin, `/a/${this.link.artifactId}/_mostra/${path}`, {\n ...(body === undefined ? {} : { body }),\n ...(method ? { method } : {}),\n csrf: this.#shellCsrf,\n });\n }\n\n /**\n * Writes fields of the viewer's draft (or, with `scope: \"artifact\"`, the artifact state), with\n * the labels a page sends for them (D106).\n */\n write(\n fields: Record<string, unknown>,\n options: {\n baseRevision?: string;\n scope?: \"viewer\" | \"artifact\";\n labels?: Readonly<Record<string, string>>;\n } = {},\n ): Promise<Answer> {\n return this.page(\"fields\", {\n mutationId: MutationId.create(),\n scope: options.scope ?? \"viewer\",\n baseRevision: options.baseRevision ?? \"0\",\n viewId: this.viewId,\n ops: Object.entries(fields).map(([id, value]) => ({\n id,\n value,\n ...(options.labels?.[id] !== undefined ? { label: options.labels[id] } : {}),\n })),\n });\n }\n\n /** Submits on the artifact channel (D40). */\n submit(expectedRevision: string): Promise<Answer> {\n return this.page(\"submit\", { viewId: this.viewId, expectedRevision, channel: \"artifact\" });\n }\n\n /** The trusted Submit, on the shell channel (D40, D108). */\n shellSubmit(expectedRevision: string): Promise<Answer> {\n return this.shell(`v/${REVISION}/submit`, { viewId: this.viewId, expectedRevision });\n }\n\n /** Writes `fields`, then submits on `channel`; answers the submit. */\n async answer(\n fields: Record<string, unknown>,\n channel: \"artifact\" | \"shell\" = \"artifact\",\n labels?: Readonly<Record<string, string>>,\n ): Promise<Answer> {\n const written = await this.write(fields, labels ? { labels } : {});\n if (written.status !== 200) return written;\n const { revision } = written.json<{ revision: string }>();\n return channel === \"artifact\" ? this.submit(revision) : this.shellSubmit(revision);\n }\n\n /** Raises a signal from the page (IN-09). */\n signal(name: string, payload?: unknown): Promise<Answer> {\n return this.page(\"signal\", {\n viewId: this.viewId,\n name,\n ...(payload === undefined ? {} : { payload }),\n });\n }\n\n /** Starts an action run (D130) and follows it until it ends. */\n async run(fnId: string, args: unknown[], timeoutMs = 60_000): Promise<RunState> {\n const started = await this.page(\"runs\", {\n viewId: this.viewId,\n fnId,\n args: await serializeAll(args, { mode: \"argument\" }),\n clientKey: `ck-${MutationId.create()}`,\n });\n if (started.status !== 200) throw new OpenError(\"run\", started);\n const runId = started.json<{ runId: string }>().runId;\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const attached = await this.page(\"runs/attach\", { viewId: this.viewId, runIds: [runId] });\n const state = attached.json<{ runs: RunState[] }>().runs?.[0];\n if (state && [\"succeeded\", \"failed\", \"cancelled\"].includes(state.status)) return state;\n if (Date.now() > deadline) throw new Error(`run ${runId} didn't end in ${timeoutMs} ms`);\n await new Promise((done) => setTimeout(done, 100));\n }\n }\n\n /** The page's long poll: events after `cursor` (D47). */\n poll(cursor?: string): Promise<Answer> {\n const query = `view=${this.viewId}&wait=0${cursor !== undefined ? `&cursor=${cursor}` : \"\"}`;\n return this.browser.fetchJson(\n this.ticket.artifactOrigin,\n `/_mostra/v/${REVISION}/events/poll?${query}`,\n );\n }\n}\n\n/** A run's result, from its stored batches. */\nexport async function resultOf(state: RunState): Promise<unknown> {\n return state.batches.length === 0 ? undefined : deserializeAll([...state.batches]);\n}\n","/**\n * Scenarios and what they get to work with. A scenario is one property a host integration must\n * have, checked through the host's own client and ports (the harness) and a viewer playing the\n * browser. Each runs against a fresh home in its own directory, with a fresh host shim.\n */\nimport {\n chmodSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createConnection } from \"node:net\";\nimport { dirname, join } from \"node:path\";\nimport {\n createDiagnostic,\n type EventRecord,\n encodeLine,\n HOST_PROTOCOL_REVISIONS,\n LineSplitter,\n type Results,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport type { Fixture } from \"./fixtures.ts\";\nimport { HostUnderTest } from \"./harness/client.ts\";\nimport type { StartParams, StartResult, StoreResult } from \"./harness/protocol.ts\";\nimport { kitVersion } from \"./version.ts\";\nimport { Viewer } from \"./viewer.ts\";\n\n/** A scenario: one property of a host integration, with the requirements it covers. */\nexport interface Scenario {\n /** A stable ID, `group.name`: baselines name scenarios by it. */\n readonly id: string;\n /** What it proves, in one sentence. */\n readonly title: string;\n /** The requirements and host needs it exercises (`HO-05`, `IN-12`, `H-03` …). */\n readonly covers: readonly string[];\n /** Harness features without which it doesn't apply (it is then skipped, never failed). */\n readonly needs?: readonly string[];\n /** Runs it; throws a {@link ScenarioFailure} (or any error) when the property doesn't hold. */\n run(context: ScenarioContext): Promise<void>;\n}\n\n/** A property that didn't hold. */\nexport class ScenarioFailure extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ScenarioFailure\";\n }\n}\n\n/** Thrown to say a scenario doesn't apply to this host (a port or feature it lacks). */\nexport class NotApplicable extends Error {\n constructor(reason: string) {\n super(reason);\n this.name = \"NotApplicable\";\n }\n}\n\n/** Fails the scenario with `message` unless `condition` holds. */\nexport function check(condition: unknown, message: string): asserts condition {\n if (!condition) throw new ScenarioFailure(message);\n}\n\n/** `value` as JSON with every object's keys sorted, so key order never decides equality. */\nfunction canonical(value: unknown): string {\n return JSON.stringify(value, (_key, inner: unknown) =>\n inner !== null && typeof inner === \"object\" && !Array.isArray(inner)\n ? Object.fromEntries(\n Object.entries(inner as Record<string, unknown>).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n )\n : inner,\n );\n}\n\n/** Fails unless `actual` deep-equals `expected` (JSON comparison, key order aside). */\nexport function same(actual: unknown, expected: unknown, what: string): void {\n const a = canonical(actual);\n const b = canonical(expected);\n if (a !== b) throw new ScenarioFailure(`${what}: expected ${b}, got ${a}`);\n}\n\n/** Options of a run that scenarios see. */\nexport interface RunSettings {\n /** The host shim's command line. */\n readonly host: string;\n /** Variables for the shim's own process (how it finds its runtime). */\n readonly hostEnv: Readonly<Record<string, string>>;\n /** Publish through verify's gate (needs the verify browser); off, publish skips it, loudly. */\n readonly verify: boolean;\n}\n\n/** What a scenario works with: its host, its home, its viewers. */\nexport class ScenarioContext {\n /** The run's settings. */\n readonly settings: RunSettings;\n /** The scenario's directory: the home, the authoring directories, the runtime directory. */\n readonly dir: string;\n /** The home the host is told to use (HO-08). */\n readonly home: string;\n /** The host: its name and version. */\n host!: HostUnderTest;\n readonly #hosts: HostUnderTest[] = [];\n #published = 0;\n\n constructor(settings: RunSettings, dir: string) {\n this.settings = settings;\n this.dir = dir;\n this.home = join(dir, \"home\");\n }\n\n /** Starts the scenario's host shim (the runner does this before `run`). */\n async open(): Promise<void> {\n this.host = await this.anotherHost();\n }\n\n /** A second shim of the same host, for scenarios about two hosts of one home. */\n async anotherHost(): Promise<HostUnderTest> {\n const host = await HostUnderTest.start(this.settings.host, this.settings.hostEnv);\n this.#hosts.push(host);\n return host;\n }\n\n /** The variables every instance of the run gets: its own runtime and config directories. */\n instanceEnv(extra: Readonly<Record<string, string>> = {}): Record<string, string> {\n return {\n MOSTRA_RUNTIME_DIR: join(this.dir, \"run\"),\n MOSTRA_CONFIG_DIR: join(this.dir, \"config\"),\n ...(this.settings.verify ? {} : { MOSTRA_TEST_UNVERIFIED_PUBLISH: \"1\" }),\n ...extra,\n };\n }\n\n /** `harness/start` on this scenario's home. */\n start(\n options: {\n env?: Readonly<Record<string, string>>;\n mode?: StartParams[\"mode\"];\n host?: HostUnderTest;\n } = {},\n ): Promise<StartResult> {\n mkdirSync(join(this.dir, \"run\"), { recursive: true, mode: 0o700 });\n return (options.host ?? this.host).startInstance({\n home: this.home,\n env: this.instanceEnv(options.env),\n ...(options.mode ? { mode: options.mode } : {}),\n });\n }\n\n /** Stops the host's instance and starts it again (the same home). */\n async restart(options: { env?: Readonly<Record<string, string>> } = {}): Promise<StartResult> {\n await this.host.stopInstance();\n return this.start(options);\n }\n\n /** Writes a fixture into a fresh authoring directory and returns the directory. */\n author(fixture: Fixture, name = \"artifact\"): string {\n this.#published += 1;\n const dir = join(this.dir, \"authoring\", `${name}-${this.#published}`);\n for (const [path, text] of Object.entries(fixture)) {\n mkdirSync(dirname(join(dir, path)), { recursive: true });\n writeFileSync(join(dir, path), text);\n }\n return dir;\n }\n\n /** Writes `files` over the authoring directory `dir` (a new version of the same artifact). */\n rewrite(dir: string, fixture: Fixture): void {\n for (const [path, text] of Object.entries(fixture)) writeFileSync(join(dir, path), text);\n }\n\n /** Publishes `dir` through the host (`artifact/publish`). */\n publish(\n dir: string,\n options: { policy?: unknown; requestId?: string } = {},\n ): Promise<{\n artifactId: string;\n versionId: string;\n version: number;\n url?: string;\n tokenId?: string;\n cursor: string;\n }> {\n return this.host.call(\"artifact/publish\", {\n source: { path: dir },\n ...(options.policy !== undefined ? { policy: options.policy } : {}),\n ...(options.requestId ? { requestId: options.requestId } : {}),\n });\n }\n\n /** Authors and publishes a fixture; the receipt with its authoring directory. */\n async published(\n fixture: Fixture,\n options: { policy?: unknown } = {},\n ): Promise<{\n artifactId: string;\n versionId: string;\n version: number;\n url?: string;\n tokenId?: string;\n cursor: string;\n dir: string;\n }> {\n const dir = this.author(fixture);\n return { ...(await this.publish(dir, options)), dir };\n }\n\n /** A new capability link through the host (`view/url`). */\n async link(artifactId: string, params: Record<string, unknown> = {}): Promise<string> {\n const link = await this.host.call<{ url: string }>(\"view/url\", {\n artifact: { artifactId },\n ...params,\n });\n return link.url;\n }\n\n /** Opens a new link as a viewer. */\n async viewer(\n artifactId: string,\n options: { link?: Record<string, unknown>; headers?: Record<string, string> } = {},\n ): Promise<Viewer> {\n return Viewer.open(await this.link(artifactId, options.link ?? {}), {\n ...(options.headers ? { headers: options.headers } : {}),\n });\n }\n\n /** `results/get` through the host. */\n results(artifactId: string, submission?: string): Promise<Results> {\n return this.host.call(\"results/get\", {\n artifact: { artifactId },\n ...(submission ? { submission } : {}),\n });\n }\n\n /** `events/read` through the host. */\n async events(\n filter: { artifacts?: string[]; types?: string[] },\n after?: string,\n ): Promise<{ events: EventRecord[]; cursor: string }> {\n return this.host.call(\"events/read\", { filter, ...(after ? { after } : {}), limit: 100 });\n }\n\n /** The host's store. */\n store(): Promise<StoreResult> {\n return this.host.store();\n }\n\n /** Waits for `condition` to hold, checking every 100 ms; fails with `what` after `timeoutMs`. */\n async eventually<T>(\n what: string,\n condition: () => Promise<T | undefined | false> | T | undefined | false,\n timeoutMs = 30_000,\n ): Promise<T> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const value = await condition();\n if (value !== undefined && value !== false) return value;\n if (Date.now() > deadline) throw new ScenarioFailure(`${what} (waited ${timeoutMs} ms)`);\n await new Promise((done) => setTimeout(done, 100));\n }\n }\n\n /** Skips the scenario unless the host serves `port`. */\n requirePort(port: string): void {\n if (!this.host.serves(port)) throw new NotApplicable(`the host serves no ${port} port`);\n }\n\n /** Skips the scenario unless the host supports `feature`. */\n requireFeature(feature: string): void {\n if (!this.host.supports(feature))\n throw new NotApplicable(`the host lacks the ${feature} feature`);\n }\n\n /** The socket of the home's running instance, from `instance.json` (D81). */\n socket(): string | undefined {\n try {\n const record = JSON.parse(readFileSync(join(this.home, \"instance.json\"), \"utf8\")) as {\n socket?: string;\n };\n return record.socket;\n } catch {\n return undefined;\n }\n }\n\n /** Ends every shim, stops a daemon the scenario left, and removes the directory. */\n async close(): Promise<void> {\n for (const host of this.#hosts) {\n await host.stopInstance().catch(() => undefined);\n await host.close().catch(() => undefined);\n }\n const socket = this.socket();\n if (socket) {\n const session = await connectSocket(socket).catch(() => undefined);\n await session?.peer\n .request(\"mostra/shutdown\", {}, { timeoutMs: 10_000 })\n .catch(() => undefined);\n session?.close();\n }\n removeTree(this.dir);\n }\n}\n\n/**\n * Removes a scenario's directory. A home's versions are sealed read-only (files 0444,\n * directories 0555, DATA_MODEL §1), so directories are made writable first.\n */\nexport function removeTree(dir: string): void {\n const open = (path: string): void => {\n let stats: ReturnType<typeof lstatSync>;\n try {\n stats = lstatSync(path);\n } catch {\n return;\n }\n if (!stats.isDirectory()) return;\n chmodSync(path, 0o700);\n for (const name of readdirSync(path)) open(join(path, name));\n };\n open(dir);\n rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });\n}\n\n/** A raw protocol session over the home's socket, opened by the kit itself. */\nexport interface SocketSession {\n readonly peer: RpcPeer;\n close(): void;\n}\n\n/** Connects to an instance's socket and initializes a session as `@mostra/conformance`. */\nexport async function connectSocket(\n path: string,\n revisions: readonly string[] = HOST_PROTOCOL_REVISIONS,\n): Promise<SocketSession & { initialize: Promise<unknown> }> {\n const socket = await new Promise<ReturnType<typeof createConnection>>((resolve, reject) => {\n const connection = createConnection(path);\n connection.once(\"connect\", () => resolve(connection));\n connection.once(\"error\", reject);\n });\n const peer = new RpcPeer({\n send: (message) => {\n if (!socket.destroyed) socket.write(encodeLine(message));\n },\n });\n const lines = new LineSplitter();\n socket.setEncoding(\"utf8\");\n socket.on(\"data\", (chunk: string) => {\n for (const line of lines.push(chunk)) peer.receiveLine(line);\n });\n socket.on(\"error\", () => socket.destroy());\n socket.on(\"close\", () =>\n peer.close(createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", { message: \"socket closed\" })),\n );\n const initialize = peer.request(\n \"mostra/initialize\",\n {\n client: { name: \"mostra-conformance\", version: kitVersion() },\n revisions: [...revisions],\n capabilities: {},\n ports: [],\n },\n { timeoutMs: 10_000 },\n );\n initialize.catch(() => undefined);\n return { peer, initialize, close: () => socket.destroy() };\n}\n\n/** The diagnostic code of a rejected request. */\nexport function rpcCode(error: unknown): string | undefined {\n return error instanceof RpcError ? error.diagnostic.code : undefined;\n}\n","/**\n * Submissions reaching the host: durable first, delivered whole, once in effect across crashes,\n * retried while the host can't take them, replayed in order when it returns, and never confused\n * with draft mirrors (IN-06, IN-12, H-01, H-03, H-04, H-08).\n */\nimport { FORM } from \"../fixtures.ts\";\nimport { check, connectSocket, type Scenario, type ScenarioContext, same } from \"../scenario.ts\";\n\n/** Publishes the form, answers it and submits on the artifact channel; the submission's ID. */\nasync function submitForm(\n context: ScenarioContext,\n fields: Record<string, unknown> = { name: \"Ada\", comment: \"Looks good\" },\n): Promise<{ artifactId: string; submissionId: string }> {\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const answer = await viewer.answer(\n fields,\n viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\",\n );\n same(answer.status, 200, `the submit's status (${answer.body})`);\n return { artifactId: receipt.artifactId, submissionId: answer.json<{ id: string }>().id };\n}\n\n/** H-01, H-08: the host receives the whole submission once, and Mostra's record agrees. */\nexport const delivered: Scenario = {\n id: \"delivery.submission\",\n title:\n \"A submission is durable before delivery, reaches the host's submissions port once with the full results, and is readable through results/get\",\n covers: [\"HO-01\", \"HO-05\", \"IN-12\", \"H-01\", \"H-08\"],\n async run(context) {\n await context.start();\n const { artifactId, submissionId } = await submitForm(context);\n // Durable at commit, whatever the delivery state (FAILURE_MODEL §4).\n const waited = await context.host.call<{ status: string }>(\"wait\", {\n artifact: { artifactId },\n until: \"submitted\",\n timeoutMs: 0,\n });\n same(waited.status, \"satisfied\", \"wait --until submitted right after the submit\");\n if (context.host.serves(\"submissions\")) {\n const stored = await context.eventually(\"the host's store holds the submission\", async () =>\n (await context.store()).deliveries.find((entry) => entry.submissionId === submissionId),\n );\n same(stored.kind, \"submission\", \"the envelope's kind\");\n same(stored.stored, 1, \"copies the host's store holds\");\n check(stored.deliveryId.startsWith(\"dlv_\"), `a delivery ID (${stored.deliveryId})`);\n const results = await context.eventually(\n \"the delivery is recorded as delivered\",\n async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"delivered\" ? read : undefined;\n },\n );\n same(results.submission.id, submissionId, \"the submission results/get reads\");\n same(results.answers, { name: \"Ada\", comment: \"Looks good\" }, \"the answers\");\n } else {\n // Standalone: Mostra's built-in adapter takes it at once (D58, D105).\n const results = await context.eventually(\"the built-in adapter accepts it\", async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"delivered\" ? read : undefined;\n });\n same(results.answers, { name: \"Ada\", comment: \"Looks good\" }, \"the answers\");\n }\n },\n};\n\n/** H-03, IN-12: a crash after the host accepted redelivers the same delivery, stored once. */\nexport const exactlyOnce: Scenario = {\n id: \"delivery.exactly-once\",\n title:\n \"When the instance dies after the host accepted a delivery but before recording it, the restarted instance redelivers the same deliveryId and the host stores it once\",\n covers: [\"HO-05\", \"IN-12\", \"H-03\"],\n async run(context) {\n context.requirePort(\"submissions\");\n // The instance kills itself between the host's answer and its record (FAILURE_MODEL §4).\n await context.start({ env: { MOSTRA_TEST_FAULTS: \"deliver:after-answer:crash\" } });\n const { artifactId, submissionId } = await submitForm(context);\n const first = await context.eventually(\"the host received the first attempt\", async () =>\n (await context.store()).deliveries.find((entry) => entry.submissionId === submissionId),\n );\n await context.host.stopInstance().catch(() => undefined);\n await context.start();\n const after = await context.eventually(\"the restarted instance redelivers it\", async () => {\n const entry = (await context.store()).deliveries.find(\n (candidate) => candidate.submissionId === submissionId,\n );\n return entry && entry.calls >= 2 ? entry : undefined;\n });\n same(after.deliveryId, first.deliveryId, \"the redelivery's deliveryId\");\n same(after.stored, 1, \"copies the host's store holds after the redelivery\");\n check(\n (after.attempts.at(-1) ?? 0) > (after.attempts[0] ?? 0),\n `the redelivery's attempt counts up (${after.attempts.join(\", \")})`,\n );\n const results = await context.eventually(\"the delivery ends delivered\", async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"delivered\" ? read : undefined;\n });\n same(results.submission.id, submissionId, \"the submission\");\n },\n};\n\n/** IN-12, H-04: a host that can't take a delivery gets it again with backoff; terminal is final. */\nexport const retry: Scenario = {\n id: \"delivery.retry\",\n title:\n \"A delivery the host answers retry: true stays pending and arrives when the host can take it; an undeliverable answer is final and never retried\",\n covers: [\"HO-05\", \"IN-12\", \"H-04\"],\n needs: [\"faults\"],\n async run(context) {\n context.requirePort(\"submissions\");\n await context.start();\n await context.host.script({ port: \"submissions\", answer: \"retry\" });\n const { artifactId, submissionId } = await submitForm(context);\n await context.eventually(\"the delivery is pending while the host can't take it\", async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"pending\" ? read : undefined;\n });\n const retrying = await context.events({\n artifacts: [artifactId],\n types: [\"submission.retrying\"],\n });\n check(\n retrying.events.length > 0,\n \"no submission.retrying event while the delivery waits (IN-13)\",\n );\n await context.host.script({ port: \"submissions\", answer: \"accept\" });\n await context.eventually(\n \"the delivery arrives once the host can take it\",\n async () =>\n (await context.store()).deliveries.find((entry) => entry.submissionId === submissionId),\n 45_000,\n );\n await context.eventually(\"the delivery ends delivered\", async () => {\n const read = await context.results(artifactId);\n return read.submission.delivery === \"delivered\" ? read : undefined;\n });\n // A terminal answer: undeliverable, shown, and never retried.\n await context.host.script({ port: \"submissions\", answer: \"undeliverable\" });\n const second = await submitForm(context, { name: \"Grace\" });\n await context.eventually(\"the delivery ends undeliverable\", async () => {\n const read = await context.results(second.artifactId);\n return read.submission.delivery === \"undeliverable\" ? read : undefined;\n });\n await context.host.script({ port: \"submissions\", answer: \"accept\" });\n await new Promise((done) => setTimeout(done, 3000));\n const store = await context.store();\n check(\n !store.deliveries.some((entry) => entry.submissionId === second.submissionId),\n \"an undeliverable delivery was retried\",\n );\n },\n};\n\n/** IN-12, H-04: submissions made while the host is away wait for it and replay in order. */\nexport const outboxReplay: Scenario = {\n id: \"delivery.outbox-replay\",\n title:\n \"Submissions made while the host is away stay pending in the outbox and replay in submission order, each with its deliveryId, when the host attaches again\",\n covers: [\"HO-05\", \"IN-12\", \"H-04\"],\n needs: [\"attach\"],\n async run(context) {\n context.requirePort(\"submissions\");\n await context.start({ mode: \"attach\" });\n const first = await context.published(FORM);\n const second = await context.published(FORM);\n // The viewers open their links while the host is there (a host that serves identity refuses\n // new links while it is away, D143), then the host goes away and its daemon keeps the home,\n // expecting the host back (D105).\n const viewers = [\n await context.viewer(first.artifactId),\n await context.viewer(second.artifactId),\n ];\n await context.host.stopInstance();\n const submissions: string[] = [];\n for (const viewer of viewers) {\n // A host that took the channel policy over gave these views the shell channel (D108).\n const channel = viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\";\n const answer = await viewer.answer({ name: `Ada ${submissions.length + 1}` }, channel);\n same(answer.status, 200, `a submit while the host is away (${answer.body})`);\n submissions.push(answer.json<{ id: string }>().id);\n }\n // A daemon that keeps the home while its host is away records where clients find it: no\n // record is a defect, never a reason to skip (Opus review of WP-12, finding 11).\n const socket = context.socket();\n check(socket, \"the daemon kept the home but left no instance.json to find it by\");\n const kit = await connectSocket(socket);\n await kit.initialize;\n const pending = (await kit.peer.request(\"results/get\", {\n artifact: { artifactId: first.artifactId },\n })) as { submission: { delivery: string } };\n kit.close();\n same(pending.submission.delivery, \"pending\", \"a delivery while its host is away\");\n check(\n (await context.store()).deliveries.length === 0,\n \"the host received a delivery while it was away\",\n );\n await context.start({ mode: \"attach\" });\n const store = await context.eventually(\"both deliveries replay\", async () => {\n const read = await context.store();\n return read.deliveries.length >= 2 ? read : undefined;\n });\n same(\n store.deliveries.map((entry) => entry.submissionId),\n submissions,\n \"the replay's order (submission order)\",\n );\n check(\n store.deliveries.every((entry) => entry.stored === 1),\n \"a replayed delivery stored twice\",\n );\n await context.host.stopInstance();\n },\n};\n\n/** IN-06: drafts reach the host only as mirrors labelled `draft`, never as submissions. */\nexport const draftMirrors: Scenario = {\n id: \"drafts.mirror\",\n title:\n \"Draft revisions reach the host only through drafts.mirror, labelled kind: draft, and never through the submissions port\",\n covers: [\"HO-01\", \"HO-05\", \"IN-06\", \"H-01\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const written = await viewer.write({ name: \"Ada\" });\n same(written.status, 200, \"a draft write\");\n if (context.host.serves(\"drafts\")) {\n const mirror = await context.eventually(\"the host receives the draft's mirror\", async () =>\n (await context.store()).drafts.find((entry) => entry.artifactId === receipt.artifactId),\n );\n same(mirror.kind, \"draft\", \"the mirror's kind\");\n }\n const before = await context.store();\n check(\n before.deliveries.every((entry) => entry.kind === \"submission\") &&\n !before.deliveries.some((entry) => entry.artifactId === receipt.artifactId),\n \"a draft reached the host as a delivery before any submit (IN-06)\",\n );\n const { revision } = written.json<{ revision: string }>();\n const submitted = await (viewer.ticket.submitChannels.includes(\"artifact\")\n ? viewer.submit(revision)\n : viewer.shellSubmit(revision));\n same(submitted.status, 200, \"the submit\");\n if (context.host.serves(\"submissions\")) {\n await context.eventually(\"the submission arrives\", async () =>\n (await context.store()).deliveries.find((entry) => entry.artifactId === receipt.artifactId),\n );\n const after = await context.store();\n const delivered = after.deliveries.filter((entry) => entry.artifactId === receipt.artifactId);\n same(delivered.length, 1, \"deliveries for the artifact\");\n check(\n after.deliveries.every((entry) => entry.kind === \"submission\"),\n \"the host stores something that isn't a submission as one (IN-06)\",\n );\n }\n },\n};\n\n/** The delivery scenarios. */\nexport const DELIVERY_SCENARIOS: readonly Scenario[] = [\n delivered,\n exactlyOnce,\n retry,\n outboxReplay,\n draftMirrors,\n];\n","/**\n * The interaction model a host builds on: submission policies, events with durable cursors,\n * signals, waits, artifact state, complete results, idempotent requests and durability across\n * restarts (IN-07 to IN-10, LL-02, H-02, H-03, H-06 to H-10).\n */\nimport { FORM, FORM_V2 } from \"../fixtures.ts\";\nimport { codeOf } from \"../harness/client.ts\";\nimport { check, type Scenario, same } from \"../scenario.ts\";\nimport type { Viewer } from \"../viewer.ts\";\n\n/** Answers and submits on whichever channel the view allows. */\nasync function answerAndSubmit(viewer: Viewer, fields: Record<string, unknown>) {\n return viewer.answer(\n fields,\n viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\",\n );\n}\n\nasync function code(answer: { json<T>(): T }): Promise<string | undefined> {\n return answer.json<{ code?: string }>().code;\n}\n\n/** IN-07, H-02, LL-02: every submission policy, decided by the host at publish. */\nexport const policies: Scenario = {\n id: \"interaction.policies\",\n title:\n \"once per artifact answers a second submit with MOSTRA_SUBMIT_ALREADY and the existing submission; once per viewer, epochs and none behave as specified\",\n covers: [\"HO-05\", \"IN-07\", \"LL-02\", \"H-02\"],\n async run(context) {\n await context.start();\n // once, per artifact (the default)\n const once = await context.published(FORM, { policy: { policy: \"once\" } });\n const first = await context.viewer(once.artifactId);\n const accepted = await answerAndSubmit(first, { name: \"Ada\" });\n same(accepted.status, 200, \"the first submit under once\");\n const second = await context.viewer(once.artifactId);\n const conflict = await answerAndSubmit(second, { name: \"Grace\" });\n check(conflict.status === 409, `a second submit under once answered ${conflict.status}`);\n same(await code(conflict), \"MOSTRA_SUBMIT_ALREADY\", \"a second submit's code\");\n same(\n conflict.json<{ submission?: { id: string } }>().submission?.id,\n accepted.json<{ id: string }>().id,\n \"the existing submission carried beside the conflict\",\n );\n // once, per viewer: each person once.\n const survey = await context.published(FORM, {\n policy: { policy: \"once\", scope: \"per-viewer\" },\n });\n for (const ref of [\"ada@example.com\", \"grace@example.com\"]) {\n const person = await context.viewer(survey.artifactId, { link: { viewer: { ref } } });\n same((await answerAndSubmit(person, { name: ref })).status, 200, `${ref}'s submit`);\n }\n const again = await context.viewer(survey.artifactId, {\n link: { viewer: { ref: \"ada@example.com\" } },\n });\n same(\n await code(await answerAndSubmit(again, { name: \"again\" })),\n \"MOSTRA_SUBMIT_ALREADY\",\n \"a person's second submit\",\n );\n // epochs: rounds linked to each other.\n const rounds = await context.published(FORM, { policy: { policy: \"epochs\" } });\n const person = await context.viewer(rounds.artifactId, { link: { viewer: { ref: \"ada\" } } });\n const one = (await answerAndSubmit(person, { name: \"round 1\" })).json<{\n id: string;\n epoch: number;\n }>();\n const written = await person.write({ name: \"round 2\" }, { baseRevision: \"1\" });\n const revision = written.json<{ revision: string }>().revision;\n const twoAnswer = await (person.ticket.submitChannels.includes(\"artifact\")\n ? person.submit(revision)\n : person.shellSubmit(revision));\n same(twoAnswer.status, 200, \"the second round's submit\");\n const two = twoAnswer.json<{ id: string; epoch: number }>();\n same([one.epoch, two.epoch], [1, 2], \"the rounds' epochs\");\n const results = await context.results(rounds.artifactId, two.id);\n same(results.submission.previous, one.id, \"the second round's previous submission\");\n // none: no submission at all.\n const board = await context.published(FORM, { policy: { policy: \"none\" } });\n const viewer = await context.viewer(board.artifactId);\n same(viewer.ticket.policy.policy, \"none\", \"the view's policy\");\n same(\n await code(await answerAndSubmit(viewer, { name: \"x\" })),\n \"MOSTRA_SUBMIT_POLICY_NONE\",\n \"a submit under none\",\n );\n const wait = await context.host\n .call(\"wait\", {\n artifact: { artifactId: board.artifactId },\n until: \"submitted\",\n timeoutMs: 0,\n })\n .then(\n () => undefined,\n (error: unknown) => codeOf(error),\n );\n same(wait, \"MOSTRA_SUBMIT_POLICY_NONE\", \"wait --until submitted under none\");\n },\n};\n\n/** IN-08, H-09: a named, filtered subscription resumes after what it acknowledged, restarts included. */\nexport const subscriptions: Scenario = {\n id: \"events.subscription\",\n title:\n \"A host's named, filtered event stream sees only the types it asked for, in cursor order, and resumes after its acknowledged cursor across an instance restart\",\n covers: [\"HO-01\", \"HO-05\", \"IN-08\", \"H-09\"],\n needs: [\"events\"],\n async run(context) {\n await context.start();\n const name = \"conformance-host\";\n const filter = { types: [\"submission.created\"] };\n // A new name starts now: nothing earlier is read.\n same(\n (await context.host.events({ name, filter, pages: 1, timeoutMs: 500 })).pages.length,\n 0,\n \"pages for a new name\",\n );\n const submit = async (who: string): Promise<string> => {\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n return (await answerAndSubmit(viewer, { name: who })).json<{ id: string }>().id;\n };\n const first = await submit(\"Ada\");\n const read = await context.host.events({ name, filter, pages: 1, timeoutMs: 10_000 });\n const events = read.pages.flatMap((page) => page.events);\n same(\n events.map((event) => event.type),\n [\"submission.created\"],\n \"the filtered stream's events\",\n );\n same(\n (events[0]?.[\"payload\"] as { submissionId?: string } | undefined)?.submissionId,\n first,\n \"the submission it names\",\n );\n await context.restart();\n const second = await submit(\"Grace\");\n const resumed = await context.host.events({ name, filter, pages: 1, timeoutMs: 10_000 });\n const after = resumed.pages.flatMap((page) => page.events);\n same(\n after.map((event) => (event[\"payload\"] as { submissionId?: string }).submissionId),\n [second],\n \"the resumed stream: the next submission, no repeat, no gap\",\n );\n const cursors = [...events, ...after].map((event) => BigInt(event.cursor));\n check(\n cursors.every((cursor, i) => i === 0 || cursor > (cursors[i - 1] as bigint)),\n \"cursors in order\",\n );\n },\n};\n\n/** IN-09: signals are events; Mostra wakes nobody. */\nexport const signals: Scenario = {\n id: \"events.signals\",\n title:\n \"A page's signal and every submit appear as signal.raised events the host filters; Mostra calls no port and wakes nobody for them\",\n covers: [\"HO-05\", \"IN-09\", \"H-09\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const before = await context.store();\n same((await viewer.signal(\"ping\", { n: 1 })).status, 200, \"a page's signal\");\n const raised = await context.events({\n artifacts: [receipt.artifactId],\n types: [\"signal.raised\"],\n });\n const ping = raised.events.find((event) => event.payload?.[\"name\"] === \"ping\");\n check(ping, \"no signal.raised for the page's signal\");\n same(ping.payload[\"source\"], \"artifact\", \"the signal's source\");\n same(ping.payload[\"payload\"], { n: 1 }, \"the signal's payload\");\n const after = await context.store();\n same(after.deliveries.length, before.deliveries.length, \"deliveries a signal caused\");\n same(after.drafts.length, before.drafts.length, \"draft mirrors a signal caused\");\n same((await answerAndSubmit(viewer, { name: \"Ada\" })).status, 200, \"the submit\");\n const all = await context.events({ artifacts: [receipt.artifactId], types: [\"signal.*\"] });\n check(\n all.events.some((event) => event.payload?.[\"name\"] === \"submit\"),\n \"a submit raises no signal.raised named submit (D106)\",\n );\n },\n};\n\n/** IN-10: waits are level- or edge-triggered as specified, and a timeout loses nothing. */\nexport const waits: Scenario = {\n id: \"interaction.wait\",\n title:\n \"wait returns still_waiting with a cursor on timeout and loses nothing; signal and state waits are edge-triggered after the cursor; submitted is level-triggered under once\",\n covers: [\"HO-05\", \"IN-10\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const artifact = { artifactId: receipt.artifactId };\n const timedOut = await context.host.call<{ status: string; cursor: string }>(\"wait\", {\n artifact,\n until: \"signal:ping\",\n timeoutMs: 0,\n });\n same(timedOut.status, \"still_waiting\", \"a wait that times out\");\n const viewer = await context.viewer(receipt.artifactId);\n await viewer.signal(\"ping\");\n const caught = await context.host.call<{ status: string; cursor: string }>(\"wait\", {\n artifact,\n until: \"signal:ping\",\n after: timedOut.cursor,\n timeoutMs: 10_000,\n });\n same(caught.status, \"satisfied\", \"a wait after the cursor of a timed-out wait\");\n const edge = await context.host.call<{ status: string }>(\"wait\", {\n artifact,\n until: \"signal:ping\",\n after: caught.cursor,\n timeoutMs: 0,\n });\n same(edge.status, \"still_waiting\", \"the same signal waited for after its own cursor\");\n const state = context.host.call<{ status: string }>(\"wait\", {\n artifact,\n until: \"state:done\",\n after: caught.cursor,\n timeoutMs: 15_000,\n });\n await context.host.call(\"state/patch\", {\n artifact,\n ops: [{ id: \"done\", value: true }],\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XC\",\n as: \"host\",\n });\n same((await state).status, \"satisfied\", \"a state wait when the host sets the field\");\n await answerAndSubmit(viewer, { name: \"Ada\" });\n const level = await context.host.call<{ status: string; cursor: string }>(\"wait\", {\n artifact,\n until: \"submitted\",\n timeoutMs: 0,\n });\n same(level.status, \"satisfied\", \"submitted, after the fact, under once (level-triggered)\");\n const levelAfter = await context.host.call<{ status: string }>(\"wait\", {\n artifact,\n until: \"submitted\",\n after: level.cursor,\n timeoutMs: 0,\n });\n same(levelAfter.status, \"satisfied\", \"submitted after a later cursor, under once per artifact\");\n },\n};\n\n/** LL-02 and D63: artifact state shared by viewers and the host, with conflicts on both sides. */\nexport const longLived: Scenario = {\n id: \"interaction.long-lived-state\",\n title:\n \"Under policy none, viewers and the host share artifact state through compare-and-set: an overlapping write is a conflict on either side, and every change is a state.changed event\",\n covers: [\"HO-05\", \"LL-02\", \"IN-07\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM, { policy: { policy: \"none\" } });\n const artifact = { artifactId: receipt.artifactId };\n const hostWrite = await context.host.call<{ revision: string }>(\"state/patch\", {\n artifact,\n ops: [{ id: \"count\", value: 1 }],\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XD\",\n as: \"host\",\n });\n const viewer = await context.viewer(receipt.artifactId);\n const stale = await viewer.write({ count: 5 }, { scope: \"artifact\", baseRevision: \"0\" });\n same(stale.status, 200, \"a stale viewer write's status\");\n const conflicts = stale.json<{ conflicts: { id: string }[] }>().conflicts;\n same(\n conflicts.map((conflict) => conflict.id),\n [\"count\"],\n \"the viewer's conflicts\",\n );\n const fresh = await viewer.write(\n { count: 2 },\n { scope: \"artifact\", baseRevision: hostWrite.revision },\n );\n const freshRevision = fresh.json<{ revision: string; conflicts: unknown[] }>();\n same(freshRevision.conflicts, [], \"a viewer write on the current revision\");\n const hostStale = await context.host.call<{ conflicts: { id: string }[] }>(\"state/patch\", {\n artifact,\n ops: [{ id: \"count\", value: 9 }],\n baseRevision: hostWrite.revision,\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XE\",\n as: \"host\",\n });\n same(\n hostStale.conflicts.map((conflict) => conflict.id),\n [\"count\"],\n \"the host's conflicts on a field a viewer changed\",\n );\n const state = await context.host.call<{ fields: Record<string, { value: unknown }> }>(\n \"state/get\",\n {\n artifact,\n },\n );\n same(state.fields[\"count\"]?.value, 2, \"the shared state\");\n const changed = await context.events({\n artifacts: [receipt.artifactId],\n types: [\"state.changed\"],\n });\n same(changed.events.length, 2, \"state.changed events (one per applied write)\");\n },\n};\n\n/** H-06, H-08, H-10: results name exactly what the viewer saw, stale views flagged. */\nexport const results: Scenario = {\n id: \"interaction.results\",\n title:\n \"results/get returns the complete submission: metadata, answers with labels, the exact version and view, a stale view flagged with the newer version, and Markdown\",\n covers: [\"HO-05\", \"IN-11\", \"H-06\", \"H-08\", \"H-10\"],\n async run(context) {\n await context.start();\n const v1 = await context.published(FORM);\n const viewer = await context.viewer(v1.artifactId);\n context.rewrite(v1.dir, FORM_V2);\n const v2 = await context.publish(v1.dir);\n same(v2.version, 2, \"the second version's number\");\n const submitted = await viewer.answer(\n { name: \"Ada\", comment: \"on the first version\" },\n viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\",\n { name: \"Your name\", comment: \"Comment\" },\n );\n same(submitted.status, 200, \"a submit from the older view\");\n const read = await context.results(v1.artifactId);\n same(read.artifact.family, \"questionnaire\", \"the artifact's family\");\n same(read.artifact.links, [{ rel: \"round-of\", artifact: \"conformance-round-1\" }], \"its links\");\n const submission = read.submission;\n same(\n [submission.versionId, submission.version],\n [v1.versionId, 1],\n \"the version the viewer saw\",\n );\n same(submission.viewId, viewer.viewId, \"the view\");\n same(\n [submission.staleView, submission.latestVersion],\n [true, 2],\n \"the stale view and the newer version\",\n );\n same(read.answers, { name: \"Ada\", comment: \"on the first version\" }, \"the answers\");\n check(\n read.fields.some((field) => field.id === \"name\" && field.label === \"Your name\"),\n \"the answers' labels\",\n );\n const markdown = await context.host.call<{ markdown: string }>(\"results/get\", {\n artifact: { artifactId: v1.artifactId },\n format: \"md\",\n });\n check(markdown.markdown.includes(\"Your name\"), \"the Markdown results name answers by label\");\n },\n};\n\n/** H-03: request IDs make retries converge; the same ID for another request is refused. */\nexport const idempotency: Scenario = {\n id: \"interaction.request-ids\",\n title:\n \"A retried request with the same requestId or mutationId returns the recorded result; the same ID with other parameters is refused\",\n covers: [\"HO-05\", \"H-03\"],\n async run(context) {\n await context.start();\n const dir = context.author(FORM);\n const first = await context.publish(dir, { requestId: \"req-publish-1\" });\n const retried = await context.publish(dir, { requestId: \"req-publish-1\" });\n same(retried, first, \"a retried publish's receipt\");\n const reused = await context\n .publish(dir, { requestId: \"req-publish-1\", policy: { policy: \"epochs\" } })\n .then(\n () => undefined,\n (error: unknown) => codeOf(error),\n );\n same(reused, \"MOSTRA_HOST_REQUEST_ID_REUSED\", \"a request ID reused with other parameters\");\n const patch = {\n artifact: { artifactId: first.artifactId },\n ops: [{ id: \"count\", value: 3 }],\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XF\",\n as: \"host\",\n };\n const once = await context.host.call(\"state/patch\", patch);\n const twice = await context.host.call(\"state/patch\", patch);\n same(twice, once, \"a retried state/patch\");\n const link = { artifact: { artifactId: first.artifactId }, requestId: \"req-link-1\" };\n same(\n (await context.host.call<{ url: string }>(\"view/url\", link)).url,\n (await context.host.call<{ url: string }>(\"view/url\", link)).url,\n \"a retried view/url\",\n );\n },\n};\n\n/** Durability: what Mostra acknowledged survives the instance stopping and starting again. */\nexport const durability: Scenario = {\n id: \"interaction.durability\",\n title:\n \"Everything acknowledged (versions, drafts, state, submissions, events) survives the instance stopping and starting again\",\n covers: [\"HO-05\", \"IN-12\", \"H-04\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n await viewer.write({ comment: \"a draft only\" });\n await context.host.call(\"state/patch\", {\n artifact: { artifactId: receipt.artifactId },\n ops: [{ id: \"count\", value: 7 }],\n mutationId: \"mut_01JB8Z3QF6S7W3N8D5K2C4V9XG\",\n as: \"host\",\n });\n const submitter = await context.viewer(receipt.artifactId, {\n link: { viewer: { ref: \"ada\" } },\n });\n same((await answerAndSubmit(submitter, { name: \"Ada\" })).status, 200, \"the submit\");\n const before = await context.results(receipt.artifactId);\n const eventsBefore = await context.events({ artifacts: [receipt.artifactId] });\n await context.restart();\n const after = await context.results(receipt.artifactId);\n same(\n after.submission.digest,\n before.submission.digest,\n \"the submission's digest after a restart\",\n );\n const state = await context.host.call<{ fields: Record<string, { value: unknown }> }>(\n \"state/get\",\n {\n artifact: { artifactId: receipt.artifactId },\n },\n );\n same(state.fields[\"count\"]?.value, 7, \"artifact state after a restart\");\n const eventsAfter = await context.events({ artifacts: [receipt.artifactId] });\n same(\n eventsAfter.events.slice(0, eventsBefore.events.length).map((event) => event.cursor),\n eventsBefore.events.map((event) => event.cursor),\n \"the event log after a restart\",\n );\n // The viewer's draft is still the canonical one: the same link continues it.\n const poll = await viewer.poll();\n same(\n poll.json<{ snapshot?: { draft?: { fields?: Record<string, { value: unknown }> } } }>()\n .snapshot?.draft?.fields?.[\"comment\"]?.value,\n \"a draft only\",\n \"the viewer's draft after a restart\",\n );\n },\n};\n\n/** The interaction scenarios. */\nexport const INTERACTION_SCENARIOS: readonly Scenario[] = [\n policies,\n subscriptions,\n signals,\n waits,\n longLived,\n results,\n idempotency,\n durability,\n];\n","/**\n * The host's ports, each with and without registration (HO-01): identity, trusted controls,\n * secrets, and what server code raises for the host (D108, D131, D143, AC-05, H-05, H-14).\n */\nimport { ACTIONS, FORM } from \"../fixtures.ts\";\nimport { check, type Scenario, same } from \"../scenario.ts\";\nimport { OpenError, resultOf } from \"../viewer.ts\";\n\n/** D143: the identity port names the person behind a link minted without a viewer. */\nexport const identity: Scenario = {\n id: \"ports.identity\",\n title:\n \"With an identity port, a link minted without a viewer acts as the person the host names from the request's headers (never its cookies); without one, as the home's local user\",\n covers: [\"HO-01\", \"HO-05\", \"H-05\", \"H-14\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM, { policy: { policy: \"epochs\" } });\n // The exchange carries a cookie and a Mostra header, so the filter that keeps them from the\n // host is really tested (Opus review of WP-12, finding 9).\n const headers = {\n \"x-forwarded-user\": \"ada@example.com\",\n cookie: \"elsewhere=1\",\n \"x-mostra-csrf\": \"not-for-the-host\",\n };\n const viewer = await context.viewer(receipt.artifactId, { headers });\n const channel = viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\";\n same((await viewer.answer({ name: \"Ada\" }, channel)).status, 200, \"the submit\");\n const read = await context.results(receipt.artifactId);\n if (!context.host.serves(\"identity\")) {\n same(read.submission.viewer.kind, \"local\", \"the viewer without an identity port\");\n return;\n }\n const calls = (await context.store()).identity;\n const call = calls.at(-1);\n check(call, \"the host's identity port was never asked\");\n // The session acts as whoever the host named, in its own terms (D143 item 2): the kit judges\n // the session by the host's answer, not by any one way of naming people.\n check(\n call.answer !== undefined,\n \"the host's store doesn't report what its identity port answered (harness/store)\",\n );\n same(\n call.answer === null\n ? [read.submission.viewer.kind]\n : [read.submission.viewer.kind, read.submission.viewer.ref],\n call.answer === null ? [\"local\"] : [\"host\", call.answer.ref],\n \"the submission's viewer, by the host's answer\",\n );\n same(call.via, \"local\", \"how the request reached the gateway\");\n check(\n call.headers.includes(\"x-forwarded-user\"),\n \"the port didn't receive the request's headers\",\n );\n check(\n !call.headers.some((name) => name === \"cookie\" || name.startsWith(\"x-mostra-\")),\n `the port received Mostra's credentials (${call.headers.join(\", \")})`,\n );\n // A link minted for a person keeps that person; the port isn't asked (D104).\n const minted = await context.viewer(receipt.artifactId, {\n link: { viewer: { ref: \"grace@example.com\", name: \"Grace\" } },\n headers,\n });\n same(\n (await context.store()).identity.length,\n calls.length,\n \"identity calls for a link with a viewer\",\n );\n same((await minted.answer({ name: \"Grace\" }, channel)).status, 200, \"the minted link's submit\");\n const graces = await context.results(receipt.artifactId);\n same(\n [graces.submission.viewer.kind, graces.submission.viewer.ref],\n [\"token\", \"grace@example.com\"],\n \"the viewer a link was minted for\",\n );\n if (context.host.supports(\"faults\")) {\n // A host that can't answer refuses the link rather than guess (D143).\n await context.host.script({ port: \"identity\", answer: \"fail\" });\n const refused = await context.viewer(receipt.artifactId, { headers }).then(\n () => undefined,\n (error: unknown) => error,\n );\n check(refused instanceof OpenError, \"a failing identity port still opened the link\");\n same(\n [refused.status, refused.code],\n [503, \"MOSTRA_HOST_IDENTITY_UNAVAILABLE\"],\n \"the refusal\",\n );\n await context.host.script({ port: \"identity\", answer: null });\n const local = await context.viewer(receipt.artifactId, { headers });\n same(\n (await local.answer({ name: \"local\" }, channel)).status,\n 200,\n \"a submit as the local user\",\n );\n same(\n (await context.results(receipt.artifactId)).submission.viewer.kind,\n \"local\",\n \"a null answer's viewer\",\n );\n }\n },\n};\n\n/** D108, H-05, SH-02: the host decides the channels; the artifact can't submit where it may not. */\nexport const trustedControls: Scenario = {\n id: \"ports.trusted-controls\",\n title:\n \"The host's trustedControls policy decides each view's channels: the artifact channel is refused with MOSTRA_SUBMIT_CHANNEL_DENIED, the shell's trusted Submit records the shell channel, and the host hears it was used\",\n covers: [\"HO-01\", \"HO-05\", \"SH-02\", \"H-05\"],\n async run(context) {\n await context.start();\n if (!context.host.serves(\"trustedControls\")) {\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n same(\n [...viewer.ticket.submitChannels].sort(),\n [\"artifact\", \"shell\"],\n \"the standalone channels (D40)\",\n );\n same(\n (await viewer.answer({ name: \"Ada\" }, \"artifact\")).status,\n 200,\n \"an artifact-channel submit\",\n );\n same(\n (await context.results(receipt.artifactId)).submission.channel,\n \"artifact\",\n \"the recorded channel\",\n );\n return;\n }\n // A host that can script its policy is asked for shell-only, the case hosts that need\n // provenance use (H-05); any other host is judged by the policy it answered itself.\n const scripted = context.host.supports(\"faults\")\n ? { submitChannels: [\"shell\"], controls: [\"submit\"] }\n : undefined;\n if (scripted) await context.host.script({ port: \"trustedControls\", answer: scripted });\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const asked = (await context.store()).policies.find(\n (entry) => entry.artifactId === receipt.artifactId,\n );\n check(asked, \"the host's policy wasn't asked when the view opened\");\n const policy = scripted ?? asked.answer;\n check(\n policy,\n \"the host's store doesn't report what its trustedControls policy answered (harness/store)\",\n );\n same(\n [...viewer.ticket.submitChannels].sort(),\n [...policy.submitChannels].sort(),\n \"the view's channels under the host's policy\",\n );\n const written = await viewer.write({ name: \"Ada\" });\n const revision = written.json<{ revision: string }>().revision;\n const artifactAllowed = policy.submitChannels.includes(\"artifact\");\n if (!artifactAllowed) {\n const denied = await viewer.submit(revision);\n same(\n [denied.status, denied.json<{ code?: string }>().code],\n [403, \"MOSTRA_SUBMIT_CHANNEL_DENIED\"],\n \"the artifact channel's submit\",\n );\n }\n if (!policy.submitChannels.includes(\"shell\")) {\n // A host that allows the artifact channel alone: the page's submit is recorded as such.\n same((await viewer.submit(revision)).status, 200, \"the artifact channel's submit\");\n same(\n (await context.results(receipt.artifactId)).submission.channel,\n \"artifact\",\n \"the recorded channel\",\n );\n return;\n }\n const trusted = await viewer.shellSubmit(revision);\n same(trusted.status, 200, \"the shell's trusted Submit\");\n same(\n (await context.results(receipt.artifactId)).submission.channel,\n \"shell\",\n \"the recorded channel\",\n );\n const activation = await context.eventually(\n \"the host hears the trusted Submit was used\",\n async () =>\n (await context.store()).activations.find(\n (entry) => entry.artifactId === receipt.artifactId,\n ),\n );\n same([activation.control, activation.viewId], [\"submit\", viewer.viewId], \"the activation\");\n if (context.host.supports(\"faults\")) {\n // A policy that fails narrows the view to the shell channel (D108).\n await context.host.script({ port: \"trustedControls\", answer: \"fail\" });\n const other = await context.published(FORM);\n const narrowed = await context.viewer(other.artifactId);\n same(narrowed.ticket.submitChannels, [\"shell\"], \"the channels when the host's policy fails\");\n }\n },\n};\n\n/** D131: secret() asks the host first; the value never reaches events or results. */\nexport const secrets: Scenario = {\n id: \"ports.secrets\",\n title:\n \"secret() in server code asks the host's secrets port first and falls back to the home's store on null; the value appears in no event\",\n covers: [\"HO-01\", \"HO-05\"],\n async run(context) {\n await context.start();\n await context.host.call(\"secret/set\", { name: \"HOME_ONLY\", value: \"from-the-home-store\" });\n const receipt = await context.published(ACTIONS);\n const viewer = await context.viewer(receipt.artifactId);\n const fromHome = await viewer.run(\"actions.ts#secretLength\", [\"HOME_ONLY\"]);\n same(\n fromHome.status,\n \"succeeded\",\n `a run reading the home's secret (${JSON.stringify(fromHome[\"error\"] ?? \"\")})`,\n );\n same(await resultOf(fromHome), \"from-the-home-store\".length, \"the home secret's length\");\n if (context.host.serves(\"secrets\") && context.host.supports(\"faults\")) {\n await context.host.script({ port: \"secrets\", answer: { API_KEY: \"s3cret-from-the-host\" } });\n const fromHost = await viewer.run(\"actions.ts#secretLength\", [\"API_KEY\"]);\n same(await resultOf(fromHost), \"s3cret-from-the-host\".length, \"the host secret's length\");\n check(\n (await context.store()).secrets.some((entry) => entry.name === \"API_KEY\"),\n \"the host's secrets port wasn't asked\",\n );\n const events = await context.events({ artifacts: [receipt.artifactId] });\n check(\n !JSON.stringify(events).includes(\"s3cret-from-the-host\"),\n \"a secret reached the event log\",\n );\n }\n },\n};\n\n/** AC-05, IN-09: server code's signals and host events reach the host as events, with the run. */\nexport const serverEvents: Scenario = {\n id: \"ports.server-events\",\n title:\n \"An action's signal() and emit() reach the host as signal.raised (source action) and host.* events caused by the run; Mostra wakes nobody for them\",\n covers: [\"HO-05\", \"IN-09\", \"AC-05\", \"H-09\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(ACTIONS);\n const viewer = await context.viewer(receipt.artifactId);\n const before = await context.store();\n const run = await viewer.run(\"actions.ts#notify\", [\"ada@example.com\"]);\n same(run.status, \"succeeded\", `the action run (${JSON.stringify(run[\"error\"] ?? \"\")})`);\n const read = await context.events({\n artifacts: [receipt.artifactId],\n types: [\"signal.raised\", \"host.*\", \"action.*\"],\n });\n const types = read.events.map((event) => event.type as string);\n const signal = read.events.find((event) => event.type === \"signal.raised\");\n const emitted = read.events.find((event) => event.type === \"host.mail.sent\");\n check(signal && emitted, `the run's signal or host event is missing (${types.join(\", \")})`);\n same([signal.payload[\"name\"], signal.payload[\"source\"]], [\"mail.sent\", \"action\"], \"the signal\");\n same(signal.causation?.[\"runId\"], run.runId, \"the signal's causing run\");\n same(emitted.payload[\"data\"], { to: \"ada@example.com\" }, \"the host event's data\");\n const started = types.indexOf(\"action.started\");\n const ended = types.indexOf(\"action.succeeded\");\n check(\n started >= 0 &&\n ended > types.indexOf(\"host.mail.sent\") &&\n started < types.indexOf(\"signal.raised\"),\n `the order of the run's events (${types.join(\", \")})`,\n );\n const after = await context.store();\n same(after.deliveries.length, before.deliveries.length, \"deliveries the run caused\");\n },\n};\n\n/** The port scenarios. */\nexport const PORT_SCENARIOS: readonly Scenario[] = [\n identity,\n trustedControls,\n secrets,\n serverEvents,\n];\n","/**\n * The session, process models, the home and privacy: what every host gets right before anything\n * else (HO-02, HO-08, RT-06, H-11, H-12, H-13, H-16).\n */\nimport { readFileSync, realpathSync, rmSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { HOST_PROTOCOL_REVISIONS } from \"@mostra/protocol\";\nimport { FORM } from \"../fixtures.ts\";\nimport { codeOf } from \"../harness/client.ts\";\nimport { check, connectSocket, rpcCode, type Scenario, same } from \"../scenario.ts\";\nimport { send } from \"../viewer.ts\";\n\n/** The session: a revision both sides speak, every registered port supported, order enforced. */\nexport const negotiation: Scenario = {\n id: \"session.negotiation\",\n title:\n \"The host negotiates a revision the instance speaks, registers only ports it supports, and an instance refuses a client with no common revision\",\n covers: [\"HO-02\", \"HO-05\", \"H-13\", \"H-15\"],\n async run(context) {\n const started = await context.start();\n check(\n (HOST_PROTOCOL_REVISIONS as readonly string[]).includes(started.revision),\n `the negotiated revision ${started.revision} isn't one this kit knows (${HOST_PROTOCOL_REVISIONS.join(\", \")})`,\n );\n const unsupported = started.warnings.filter(\n (warning) => warning.code === \"MOSTRA_HOST_PORT_UNSUPPORTED\",\n );\n check(\n unsupported.length === 0,\n \"the host registers a port the instance doesn't support (MOSTRA_HOST_PORT_UNSUPPORTED)\",\n );\n // mostra/initialize is sent once per connection; the host's client surfaces the refusal.\n const again = await context.host.callRaw(\"mostra/initialize\", {\n client: { name: \"again\", version: \"0\" },\n revisions: [...HOST_PROTOCOL_REVISIONS],\n capabilities: {},\n ports: [],\n });\n check(\"error\" in again, \"a second mostra/initialize on the host's connection was accepted\");\n same(again.error.data.code, \"MOSTRA_HOST_INITIALIZE_ORDER\", \"a second initialize's code\");\n // A client with no revision in common is refused with a typed error; one with any is served.\n const socket = context.socket();\n check(socket, \"the instance's home has no instance.json naming its socket (D81)\");\n const old = await connectSocket(socket, [\"2020-01-01\"]);\n const refused = await old.initialize.then(\n () => undefined,\n (error: unknown) => rpcCode(error),\n );\n old.close();\n same(refused, \"MOSTRA_HOST_REVISION_UNSUPPORTED\", \"a client offering only 2020-01-01\");\n const mixed = await connectSocket(socket, [\"2020-01-01\", ...HOST_PROTOCOL_REVISIONS]);\n const answer = (await mixed.initialize) as { revision: string };\n mixed.close();\n same(\n answer.revision,\n started.revision,\n \"the revision negotiated with an older and a current one\",\n );\n },\n};\n\n/** One supervisor per home: a second host of the same home meets the lock, attached ones share it. */\nexport const processModels: Scenario = {\n id: \"session.process-models\",\n title:\n \"A host spawns its instance over stdio or attaches to the home's daemon; a second spawn of the same home is refused with MOSTRA_HOME_LOCKED\",\n covers: [\"HO-05\", \"RT-06\", \"H-12\"],\n async run(context) {\n const second = await context.anotherHost();\n if (context.host.supports(\"attach\")) {\n const first = await context.start({ mode: \"attach\" });\n same(first.instance.mode, \"daemon\", \"an attached host's instance mode\");\n const other = await context.start({ mode: \"attach\", host: second });\n same(other.instance.pid, first.instance.pid, \"the daemon two attached hosts reach\");\n const third = await context.anotherHost();\n const locked = await context.start({ host: third }).then(\n () => undefined,\n (error: unknown) => codeOf(error),\n );\n same(locked, \"MOSTRA_HOME_LOCKED\", \"a spawn while the daemon owns the home\");\n await second.stopInstance();\n await context.host.stopInstance();\n return;\n }\n const first = await context.start();\n same(first.instance.mode, \"host\", \"a spawned instance's mode\");\n same(first.instance.pid > 0, true, \"the instance reports its PID\");\n const locked = await context.start({ host: second }).then(\n () => undefined,\n (error: unknown) => codeOf(error),\n );\n same(locked, \"MOSTRA_HOME_LOCKED\", \"a second spawn of the same home\");\n },\n};\n\n/**\n * HO-08 and H-11: the host chooses the home, and what was published stays readable after the\n * authoring directory is removed and the instance restarts.\n */\nexport const authoringRemoved: Scenario = {\n id: \"home.authoring-removed\",\n title:\n \"The host chooses the home; artifacts, versions and submissions stay readable after the authoring directory is removed\",\n covers: [\"HO-05\", \"HO-08\", \"H-11\"],\n async run(context) {\n const started = await context.start();\n same(started.instance.home, realpathSync(context.home), \"the home the instance owns\");\n const receipt = await context.published(FORM);\n const viewer = await context.viewer(receipt.artifactId);\n const channel = viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\";\n const submitted = await viewer.answer({ name: \"Ada\", comment: \"kept\" }, channel);\n same(submitted.status, 200, \"the submit's status\");\n const before = await context.results(receipt.artifactId);\n rmSync(receipt.dir, { recursive: true, force: true });\n await context.restart();\n const byId = await context.host.call<{ id: string; versions: { id: string }[] }>(\n \"artifact/get\",\n { artifact: { artifactId: receipt.artifactId } },\n );\n same(byId.versions[0]?.id, receipt.versionId, \"the version, by artifact ID\");\n const byPath = await context.host.call<{ id: string }>(\"artifact/get\", {\n artifact: { path: receipt.dir },\n });\n same(byPath.id, receipt.artifactId, \"the artifact its deleted path still names\");\n const after = await context.results(receipt.artifactId);\n same(after.submission.digest, before.submission.digest, \"the submission's digest\");\n same(after.answers, before.answers, \"the submission's answers\");\n // The version still serves: its files live in the home, not in the authoring directory.\n const again = await context.viewer(receipt.artifactId);\n const page = await again.browser.ask({\n url: `${again.ticket.artifactOrigin}/`,\n headers: { accept: \"text/html\", \"sec-fetch-site\": \"same-origin\", \"sec-fetch-dest\": \"iframe\" },\n });\n same(page.status, 200, \"the version's page after the source is gone\");\n check(\n statSync(join(context.home, \"sources\", receipt.artifactId)).isDirectory(),\n \"the home keeps the version's source snapshot (DATA_MODEL §1)\",\n );\n },\n};\n\n/** H-16: a host-embedded instance sends no telemetry, keeps its home private, binds loopback. */\nexport const privacy: Scenario = {\n id: \"home.privacy\",\n title:\n \"A host's home is marked host-configured (no telemetry), owner-only (0700, secrets 0600), and its gateway binds loopback\",\n covers: [\"HO-05\", \"H-16\", \"EN-08\"],\n async run(context) {\n const started = await context.start();\n const config = JSON.parse(readFileSync(join(context.home, \"config.json\"), \"utf8\")) as {\n hostConfigured?: { client: string };\n };\n check(config.hostConfigured, \"config.json has no hostConfigured mark (D140 item 4)\");\n same(statSync(context.home).mode & 0o777, 0o700, \"the home's mode\");\n await context.host.call(\"secret/set\", { name: \"CONFORMANCE_TOKEN\", value: \"kept-private-123\" });\n same(\n statSync(join(context.home, \"secrets\", \"home\", \"CONFORMANCE_TOKEN\")).mode & 0o777,\n 0o600,\n \"a secret's mode\",\n );\n const status = await context.host.call<{ gateway?: { bind: string; shell: string } }>(\n \"instance/status\",\n {},\n );\n same(status.gateway?.bind, \"127.0.0.1\", \"the gateway's bind address\");\n // Nothing answers on any address but loopback: the shell's port on the machine's name fails.\n const shell = new URL(status.gateway?.shell ?? \"http://127.0.0.1:1\");\n const elsewhere = await send({ url: `http://localhost:${shell.port}/` }).catch(() => undefined);\n check(\n elsewhere === undefined || elsewhere.status === 421,\n `the shell answered a request for another host name (${elsewhere?.status})`,\n );\n same(started.instance.mode === \"host\" || started.instance.mode === \"daemon\", true, \"the mode\");\n },\n};\n\n/** The session scenarios. */\nexport const SESSION_SCENARIOS: readonly Scenario[] = [\n negotiation,\n processModels,\n authoringRemoved,\n privacy,\n];\n","/**\n * Viewing: capability links the host mints, and the gateway's hygiene against strangers (H-07,\n * H-14, HY-01, HY-03), then the shell and its bridge in a real browser (D108, SH-02).\n */\nimport { FORM, FORM_V2 } from \"../fixtures.ts\";\nimport { check, NotApplicable, type Scenario, same } from \"../scenario.ts\";\nimport { OpenError, parseLink, send, Viewer } from \"../viewer.ts\";\n\n/** H-07, H-14: publish answers a durable receipt with a link; links are scoped, revoked, rotated. */\nexport const links: Scenario = {\n id: \"viewing.links\",\n title:\n \"Publish returns a durable receipt with the artifact's link; view/url mints scoped links, a link without submit can't submit, and revoked or rotated links answer 410\",\n covers: [\"HO-05\", \"H-07\", \"H-14\", \"HY-03\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n check(receipt.url && receipt.tokenId, \"the publish receipt has no link (H-07)\");\n check(/^\\d+$/.test(receipt.cursor), `the receipt's cursor (${receipt.cursor})`);\n const viewOnly = await context.viewer(receipt.artifactId, { link: { scopes: [\"view\"] } });\n const written = await viewOnly.write({ name: \"x\" });\n same(\n [written.status, written.json<{ code?: string }>().code],\n [403, \"MOSTRA_HYGIENE_SCOPE_DENIED\"],\n \"a view-only link's write\",\n );\n const minted = await context.host.call<{ url: string; tokenId: string }>(\"view/url\", {\n artifact: { artifactId: receipt.artifactId },\n });\n await context.host.call(\"view/revoke\", { tokenId: minted.tokenId });\n const revoked = await Viewer.open(minted.url).then(\n () => undefined,\n (error: unknown) => error,\n );\n check(revoked instanceof OpenError, \"a revoked link still opened\");\n same([revoked.status, revoked.code], [410, \"MOSTRA_HYGIENE_TOKEN_REVOKED\"], \"a revoked link\");\n const rotated = await context.host.call<{ url: string }>(\"view/rotate\", {\n tokenId: receipt.tokenId,\n });\n const old = await Viewer.open(receipt.url).then(\n () => undefined,\n (error: unknown) => error,\n );\n check(\n old instanceof OpenError && old.status === 410,\n \"the default link still opens after its rotation\",\n );\n await Viewer.open(rotated.url);\n // A link that names a version opens that version, also after a newer one.\n context.rewrite(receipt.dir, FORM_V2);\n await context.publish(receipt.dir);\n const pinned = await context.viewer(receipt.artifactId, { link: { version: 1 } });\n same(pinned.ticket.version.number, 1, \"the version a pinned link opens\");\n same(pinned.ticket.latest.number, 2, \"the latest version it reports\");\n },\n};\n\n/** HY-01: the gateway refuses strangers: wrong Host, wrong Origin, no token, no CSRF token. */\nexport const hygiene: Scenario = {\n id: \"viewing.hygiene\",\n title:\n \"The host's instance refuses requests from strangers: an unknown Host (421), a foreign Origin (403), a wrong token (401), a mutation without its CSRF token (403)\",\n covers: [\"HO-05\", \"HY-01\"],\n async run(context) {\n await context.start();\n const receipt = await context.published(FORM);\n const link = parseLink(await context.link(receipt.artifactId));\n const exchange = `${link.origin}/a/${link.artifactId}/_mostra/session`;\n const post = (headers: Record<string, string>, body: unknown) =>\n send({\n method: \"POST\",\n url: exchange,\n headers: {\n \"content-type\": \"application/json\",\n \"sec-fetch-site\": \"same-origin\",\n origin: link.origin,\n ...headers,\n },\n body: JSON.stringify(body),\n });\n const host = await post({ host: \"evil.example\" }, { token: link.secret });\n same(host.status, 421, \"an unknown Host\");\n const origin = await post({ origin: \"http://evil.example\" }, { token: link.secret });\n same(origin.status, 403, \"a foreign Origin\");\n const token = await post({}, { token: \"A\".repeat(26) });\n same(token.status, 401, \"a wrong token\");\n const viewer = await Viewer.open(await context.link(receipt.artifactId));\n const noCsrf = await viewer.browser.ask({\n method: \"POST\",\n url: `${viewer.ticket.artifactOrigin}/_mostra/v/2026-10-15/signal`,\n headers: {\n \"content-type\": \"application/json\",\n origin: viewer.ticket.artifactOrigin,\n \"sec-fetch-site\": \"same-origin\",\n },\n body: JSON.stringify({ viewId: viewer.viewId, name: \"ping\" }),\n });\n same(noCsrf.status, 403, \"a mutation without its CSRF token\");\n for (const answer of [host, origin, token, noCsrf]) {\n check(\n !Object.keys(answer.headers).some((name) => name.startsWith(\"access-control-\")),\n \"a refusal carries a CORS header\",\n );\n }\n },\n};\n\n/**\n * D108, SH-02, SH-04: the shell and the page in a real browser. The trusted Submit carries the\n * label the page asked for (`mostra/controls.request`), lists the required answer by label\n * (`mostra/fields`) and focuses it in the page (`mostra/field.focus`), submits only after the page\n * flushed its saves, the defaults it showed included (`mostra/flush`, D110), and a new version\n * shows the trusted banner (`mostra/version.available`).\n */\nexport const shellBridge: Scenario = {\n id: \"viewing.shell-bridge\",\n title:\n \"In a browser, the shell and the page speak the bridge: a labelled trusted Submit, blockers by label that focus the field, a flush before submit, and the new-version banner\",\n covers: [\"HO-05\", \"SH-02\", \"SH-04\", \"H-05\"],\n async run(context) {\n let chromium: typeof import(\"playwright-core\").chromium;\n try {\n ({ chromium } = await import(\"playwright-core\"));\n } catch {\n throw new NotApplicable(\"playwright-core isn't installed\");\n }\n const browser = await chromium.launch().catch((error: unknown) => {\n throw new NotApplicable(\n `no browser to run the shell in (${(error as Error).message.split(\"\\n\")[0]})`,\n );\n });\n try {\n await context.start();\n const receipt = await context.published(FORM);\n const page = await browser.newPage();\n await page.goto(await context.link(receipt.artifactId));\n await page.waitForSelector('html[data-shell=\"ready\"]', { timeout: 60_000 });\n const frame = page.frameLocator(\"iframe\");\n const submit = page.locator(\"#mostra-submit\");\n await submit.waitFor();\n check(\n (await submit.textContent())?.includes(\"Send answers\"),\n \"the trusted Submit's label isn't the one the page asked for\",\n );\n // The required answer is listed by label, and picking it focuses the field in the page.\n await page.waitForTimeout(600);\n await submit.click();\n const blocker = page.locator(\"[data-mostra-blocker=name]\");\n await blocker.waitFor({ timeout: 10_000 });\n same((await blocker.textContent())?.trim(), \"Your name\", \"the blocker's label\");\n await blocker.click();\n await frame.getByLabel(\"Your name\").waitFor();\n await context.eventually(\n \"picking the blocker focuses the field in the page (mostra/field.focus)\",\n () =>\n frame\n .locator('[name=\"name\"]')\n .evaluate(\n (element: { ownerDocument: { activeElement: unknown } }) =>\n element === element.ownerDocument.activeElement,\n ),\n 10_000,\n );\n await frame.getByLabel(\"Your name\").fill(\"Ada\");\n await context.eventually(\"the trusted Submit submits\", async () => {\n if ((await submit.textContent())?.includes(\"Submitted\")) return true;\n await submit.click().catch(() => undefined);\n return (await submit.textContent())?.includes(\"Submitted\");\n });\n const read = await context.results(receipt.artifactId);\n same(read[\"submission\"].channel, \"shell\", \"the trusted Submit's channel\");\n // The page flushed first: the answer typed, and the default it showed for \"comment\".\n same(read[\"answers\"], { name: \"Ada\", comment: \"\" }, \"the answers, defaults included (D110)\");\n context.rewrite(receipt.dir, FORM_V2);\n await context.publish(receipt.dir);\n await page.locator('[data-mostra-banner=\"2\"]').waitFor({ timeout: 15_000 });\n } finally {\n await browser.close();\n }\n },\n};\n\n/** The viewing scenarios. */\nexport const VIEWING_SCENARIOS: readonly Scenario[] = [links, hygiene, shellBridge];\n","/**\n * Every scenario of the kit, in the order a run takes them. A scenario's ID is stable surface:\n * baselines name it. New scenarios join additively (WP-13 adds addressing, WP-20 reviews and\n * capture, WP-29 remote and WP-31 team scenarios).\n */\nimport type { Scenario } from \"../scenario.ts\";\nimport { DELIVERY_SCENARIOS } from \"./delivery.ts\";\nimport { INTERACTION_SCENARIOS } from \"./interaction.ts\";\nimport { PORT_SCENARIOS } from \"./ports.ts\";\nimport { SESSION_SCENARIOS } from \"./session.ts\";\nimport { VIEWING_SCENARIOS } from \"./viewing.ts\";\n\n/** Every scenario. */\nexport const SCENARIOS: readonly Scenario[] = [\n ...SESSION_SCENARIOS,\n ...DELIVERY_SCENARIOS,\n ...INTERACTION_SCENARIOS,\n ...PORT_SCENARIOS,\n ...VIEWING_SCENARIOS,\n];\n","/**\n * Runs scenarios against a host (HO-05): each in a fresh directory with a fresh shim and home,\n * one at a time, each bounded in time; then judges the run against the host's baseline.\n */\nimport { mkdtempSync, rmdirSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { type Baseline, NO_BASELINE } from \"./baseline.ts\";\nimport type { InitializeResult } from \"./harness/protocol.ts\";\nimport { NotApplicable, type RunSettings, type Scenario, ScenarioContext } from \"./scenario.ts\";\nimport { SCENARIOS } from \"./scenarios/index.ts\";\n\n/** How one scenario went. */\nexport type ScenarioStatus =\n /** The property held. */\n | \"passed\"\n /** It didn't, and the baseline doesn't expect that: the run fails. */\n | \"failed\"\n /** The host lacks a port or feature the scenario needs. */\n | \"skipped\"\n /** It didn't, as the baseline expects. */\n | \"expected-failure\"\n /** It held, though the baseline expects it to fail: the baseline is stale, the run fails. */\n | \"unexpected-pass\";\n\n/** One scenario's outcome. */\nexport interface ScenarioOutcome {\n /** The scenario's ID. */\n readonly id: string;\n /** What the scenario proves. */\n readonly title: string;\n /** The requirements and host needs it exercises. */\n readonly covers: readonly string[];\n /** How it went. */\n readonly status: ScenarioStatus;\n /** Why it failed or was skipped, or what the baseline says. */\n readonly reason?: string;\n /** How long it took. */\n readonly durationMs: number;\n}\n\n/** A run's report. */\nexport interface ConformanceReport {\n /** What the host said about itself. */\n readonly host: InitializeResult | undefined;\n /** Each scenario's outcome, in the order they ran. */\n readonly outcomes: readonly ScenarioOutcome[];\n /** Whether the run passes: nothing `failed` and nothing `unexpected-pass`. */\n readonly ok: boolean;\n}\n\n/** Options of {@link runConformance}. */\nexport interface RunOptions {\n /** The host's harness shim, as a command line (run through the shell). */\n readonly host: string;\n /** Variables for the shim's process, on top of this process's. */\n readonly hostEnv?: Readonly<Record<string, string>>;\n /** Only the scenarios whose ID equals or starts with one of these (`delivery.`). */\n readonly only?: readonly string[];\n /** The host's expected failures. */\n readonly baseline?: Baseline;\n /** Publish through verify's gate (needs the verify browser). Default false. */\n readonly verify?: boolean;\n /** Each scenario's time limit. Default 240 s. */\n readonly timeoutMs?: number;\n /** Where scenario directories go. Default a fresh directory under `/tmp` (short socket paths). */\n readonly workDir?: string;\n /** Each outcome as it is known. */\n readonly onOutcome?: (outcome: ScenarioOutcome) => void;\n /** The scenarios to choose from. Default every scenario of the kit. */\n readonly scenarios?: readonly Scenario[];\n}\n\nfunction selected(scenarios: readonly Scenario[], only: readonly string[] | undefined): Scenario[] {\n if (!only || only.length === 0) return [...scenarios];\n return scenarios.filter((scenario) =>\n only.some((prefix) => scenario.id === prefix || scenario.id.startsWith(prefix)),\n );\n}\n\n/** Runs one scenario: `passed`, `failed` or `skipped`, before the baseline. */\nasync function runOne(\n scenario: Scenario,\n settings: RunSettings,\n dir: string,\n timeoutMs: number,\n): Promise<{ status: \"passed\" | \"failed\" | \"skipped\"; reason?: string; host?: InitializeResult }> {\n const context = new ScenarioContext(settings, dir);\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await context.open();\n for (const feature of scenario.needs ?? []) context.requireFeature(feature);\n await Promise.race([\n scenario.run(context),\n new Promise<never>((_, fail) => {\n timer = setTimeout(\n () => fail(new Error(`the scenario didn't finish within ${timeoutMs / 1000} s`)),\n timeoutMs,\n );\n }),\n ]);\n return { status: \"passed\", ...(context.host.info ? { host: context.host.info } : {}) };\n } catch (error) {\n const host = context.host?.info;\n if (error instanceof NotApplicable)\n return { status: \"skipped\", reason: error.message, ...(host ? { host } : {}) };\n const stderr = context.host?.stderr.slice(-3).join(\" | \");\n const message = (error as Error).message ?? String(error);\n return {\n status: \"failed\",\n reason:\n stderr && !(error as Error).name?.startsWith(\"Scenario\")\n ? `${message} (host: ${stderr})`\n : message,\n ...(host ? { host } : {}),\n };\n } finally {\n clearTimeout(timer);\n await context.close().catch(() => undefined);\n }\n}\n\n/** Runs the kit's scenarios against a host and judges them against its baseline. */\nexport async function runConformance(options: RunOptions): Promise<ConformanceReport> {\n const baseline = options.baseline ?? NO_BASELINE;\n // A baseline naming a scenario the run doesn't know would expect nothing, silently: refused here\n // as `readBaseline` refuses it, whoever built the baseline (GPT review of WP-12, finding 9).\n const catalog = (options.scenarios ?? SCENARIOS).map((scenario) => scenario.id);\n const unknown = Object.keys(baseline.expectedFailures).filter((id) => !catalog.includes(id));\n if (unknown.length > 0) {\n throw new Error(`The baseline names scenarios the kit doesn't have: ${unknown.join(\", \")}.`);\n }\n const settings: RunSettings = {\n host: options.host,\n hostEnv: options.hostEnv ?? {},\n verify: options.verify ?? false,\n };\n const root =\n options.workDir ?? mkdtempSync(join(process.platform === \"darwin\" ? \"/tmp\" : tmpdir(), \"mc-\"));\n const outcomes: ScenarioOutcome[] = [];\n let host: InitializeResult | undefined;\n let index = 0;\n for (const scenario of selected(options.scenarios ?? SCENARIOS, options.only)) {\n index += 1;\n const started = Date.now();\n const result = await runOne(\n scenario,\n settings,\n join(root, `s${index}`),\n options.timeoutMs ?? 240_000,\n );\n host ??= result.host;\n const expected = baseline.expectedFailures[scenario.id];\n let status: ScenarioStatus = result.status;\n let reason = result.reason;\n if (expected !== undefined && result.status === \"failed\") {\n status = \"expected-failure\";\n reason = `${expected} (${result.reason ?? \"failed\"})`;\n } else if (expected !== undefined && result.status === \"passed\") {\n status = \"unexpected-pass\";\n reason = `the baseline expects a failure (${expected}), and it passed: remove it from the baseline`;\n }\n const outcome: ScenarioOutcome = {\n id: scenario.id,\n title: scenario.title,\n covers: scenario.covers,\n status,\n ...(reason !== undefined ? { reason } : {}),\n durationMs: Date.now() - started,\n };\n outcomes.push(outcome);\n options.onOutcome?.(outcome);\n }\n // Each scenario removed its own directory; the run's own is removed when the kit made it.\n if (options.workDir === undefined) {\n try {\n rmdirSync(root);\n } catch {\n // Not empty: something a scenario couldn't remove stays for a look.\n }\n }\n return {\n host,\n outcomes,\n ok: outcomes.every(\n (outcome) => outcome.status !== \"failed\" && outcome.status !== \"unexpected-pass\",\n ),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,iBAAsC,EAAE,aAAa;CACzD,eAAe,EAAE,QAAQ,CAAC;CAC1B,kBAAkB,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC;AACjE,CAAC;;AAGD,MAAa,cAAwB;CAAE,eAAe;CAAG,kBAAkB,CAAC;AAAE;;;;;AAM9E,SAAgB,aAAa,MAAc,OAAoC;CAC7E,IAAI;CACJ,IAAI;EACF,OAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CAC9C,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,KAAK,mCAAoC,MAAgB,SAAS;CACvF;CACA,MAAM,SAAS,eAAe,UAAU,IAAI;CAC5C,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,MACR,GAAG,KAAK,sGACV;CAEF,MAAM,UAAU,OAAO,KAAK,OAAO,KAAK,gBAAgB,CAAC,CAAC,QAAQ,OAAO,CAAC,MAAM,SAAS,EAAE,CAAC;CAC5F,IAAI,QAAQ,SAAS,GACnB,MAAM,IAAI,MAAM,GAAG,KAAK,yCAAyC,QAAQ,KAAK,IAAI,EAAE,EAAE;CACxF,OAAO,OAAO;AAChB;;;;ACxCA,MAAa,OAAgB,EAC3B,aAAa;;;;;;;;;;;;;;;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