@mostra/conformance 0.6.2 → 0.8.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner-DYbtXiL9.js","names":["InitializeResultSchema","StartResultSchema","CallResultSchema","StoreResultSchema","EventsResultSchema","httpRequest"],"sources":["../src/baseline.ts","../src/fixtures.ts","../src/harness/tree.ts","../src/harness/client.ts","../src/viewer.ts","../src/scenario.ts","../src/scenarios/delivery.ts","../src/scenarios/interaction.ts","../src/scenarios/ports.ts","../src/privacy.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 * A shim's process tree on Windows, for ending it when the shim won't close (Opus review of WP-W3,\n * finding 3). Windows has no process groups: `taskkill /T` walks parent PIDs from a process that\n * must still run, so once the shell a host command runs in has exited, its descendants can't be\n * reached from its PID. The kit therefore notes the tree while the shell runs (the helper's\n * `processes`: PID, parent and creation time of every process) and ends exactly those processes\n * later with the helper's `reap`, which ends a process only while its creation time still matches,\n * so a PID Windows handed to another process meanwhile is never touched.\n */\nimport { spawnSync } from \"node:child_process\";\n\n/** One process as `mostra-win processes` lists it. */\nexport interface ProcessEntry {\n readonly pid: number;\n readonly ppid?: number | undefined;\n /** `win/<100 ns since 1601>`; absent for a process this user can't open. */\n readonly startTime?: string | undefined;\n}\n\n/** A process to end later: its PID and creation time. */\nexport interface TreeMember {\n readonly pid: number;\n readonly startTime: string;\n}\n\nfunction created(entry: ProcessEntry): bigint | undefined {\n const match = /^win\\/(\\d+)$/.exec(entry.startTime ?? \"\");\n return match ? BigInt(match[1] as string) : undefined;\n}\n\n/**\n * `root` and every process below it in `processes`. A process counts as a child of another only\n * when it was created after it, since a parent PID outlives its process and can name a later one;\n * processes without a creation time (another user's) are left out, as they can't be ended safely.\n */\nexport function treeOf(processes: readonly ProcessEntry[], root: number): TreeMember[] {\n const byParent = new Map<number, ProcessEntry[]>();\n for (const entry of processes) {\n if (entry.ppid === undefined || entry.ppid === entry.pid) continue;\n const siblings = byParent.get(entry.ppid) ?? [];\n siblings.push(entry);\n byParent.set(entry.ppid, siblings);\n }\n const top = processes.find((entry) => entry.pid === root);\n const topCreated = top ? created(top) : undefined;\n if (top === undefined || topCreated === undefined) return [];\n const out: TreeMember[] = [{ pid: root, startTime: top.startTime as string }];\n const queue: [number, bigint][] = [[root, topCreated]];\n const seen = new Set([root]);\n while (queue.length > 0) {\n const [parent, parentCreated] = queue.shift() as [number, bigint];\n for (const child of byParent.get(parent) ?? []) {\n const born = created(child);\n if (born === undefined || born < parentCreated || seen.has(child.pid)) continue;\n seen.add(child.pid);\n out.push({ pid: child.pid, startTime: child.startTime as string });\n queue.push([child.pid, born]);\n }\n }\n return out;\n}\n\n/** Runs the helper with `args`; its `result`, or `undefined` when it fails. */\nfunction helperResult(helper: string, args: readonly string[]): unknown {\n const run = spawnSync(helper, args, { encoding: \"utf8\", windowsHide: true, timeout: 30_000 });\n if (run.status !== 0) return undefined;\n try {\n const answer = JSON.parse(run.stdout) as { ok?: boolean; result?: unknown };\n return answer.ok === true ? answer.result : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The tree under `root` now, through the helper; empty when the helper can't list processes. */\nexport function snapshotTree(helper: string, root: number): TreeMember[] {\n const listed = helperResult(helper, [\"processes\"]);\n return Array.isArray(listed) ? treeOf(listed as ProcessEntry[], root) : [];\n}\n\n/** Ends every member still running with its noted creation time (`mostra-win reap`). */\nexport function endTree(helper: string, members: readonly TreeMember[]): void {\n if (members.length === 0) return;\n helperResult(helper, [\"reap\", ...members.map((member) => `${member.pid}:${member.startTime}`)]);\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, spawnSync } from \"node:child_process\";\nimport {\n createDiagnostic,\n type Diagnostic,\n encodeLine,\n LineSplitter,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport { resolveRuntime, windowsHelper } from \"@mostra/sdk\";\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\";\nimport { endTree, snapshotTree } from \"./tree.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/** Whether the kit runs on Windows, where a shim's tree ends by `taskkill`. */\nconst WINDOWS = process.platform === \"win32\";\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 // A process group of its own on POSIX, so `close` can end the shim and everything it\n // started. On Windows `detached` starts the shell with no console, and the shim it runs then\n // never answers (VERIFIED_FACTS, WP-W3): there `close` ends the tree with `taskkill`.\n detached: !WINDOWS,\n windowsHide: 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 /**\n * Ends the shim: stdin closes, then SIGTERM to its process group, then SIGKILL. Windows has no\n * process groups or signals (D150 item 6): there the kit notes the shell's process tree while it\n * runs, and after 5 s ends the shell's tree (`taskkill /T`, while the shell lives) and every\n * process it noted (`mostra-win reap`, which ends one only while its creation time matches), so\n * a descendant of a shell that already exited is ended too (Opus review of WP-W3, finding 3).\n */\n async close(): Promise<void> {\n const pid = this.#child.pid;\n const helper = WINDOWS && pid !== undefined ? await windowsHelperOrNone() : undefined;\n const tree = helper !== undefined && pid !== undefined ? snapshotTree(helper, pid) : [];\n this.#child.stdin?.end();\n const wait = (ms: number): Promise<\"exited\" | \"waiting\"> =>\n Promise.race([\n this.#exited.then(() => \"exited\" as const),\n new Promise<\"waiting\">((done) => setTimeout(() => done(\"waiting\"), ms)),\n ]);\n if (WINDOWS) {\n if ((await wait(5000)) === \"waiting\" && pid !== undefined) {\n const system = process.env[\"SystemRoot\"] ?? \"C:\\\\Windows\";\n spawnSync(`${system}\\\\System32\\\\taskkill.exe`, [\"/pid\", String(pid), \"/T\", \"/F\"], {\n stdio: \"ignore\",\n windowsHide: true,\n });\n if (helper !== undefined) endTree(helper, tree);\n await wait(5000);\n }\n this.#peer.close();\n return;\n }\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 if ((await wait(5000)) === \"waiting\") {\n signal(\"SIGTERM\");\n if ((await wait(5000)) === \"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/** The Windows helper beside the runtime the kit resolves, or none (the tree then isn't noted). */\nasync function windowsHelperOrNone(): Promise<string | undefined> {\n try {\n return windowsHelper(await resolveRuntime().catch(() => undefined), process.env);\n } catch {\n return undefined;\n }\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. Where the shell and the artifact are two\n * sites (a host's external bases, a Cloudflare share), it enters the frame as the bootstrap page\n * does and signs the frame's requests as Mostra's service worker does (D70, D158 item 5).\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 // `localhost` and its subdomains are this machine, as browsers resolve them (WHATWG URL,\n // RFC 6761); Mostra's listeners bind 127.0.0.1.\n host: /(^|\\.)localhost$/i.test(url.hostname)\n ? \"127.0.0.1\"\n : url.hostname.replace(/^\\[|\\]$/g, \"\"),\n port: url.port,\n method: ask.method ?? \"GET\",\n path: `${url.pathname}${url.search}`,\n headers: { host: url.host, ...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 /** Worker-mode frame sessions by origin: the header Mostra's service worker adds (D70). */\n readonly #frames = new Map<string, string>();\n\n /** Signs every later request to `origin` with a worker-mode frame session, as its worker does. */\n enterFrame(origin: string, secret: string): void {\n this.#frames.set(origin, secret);\n }\n\n /** Whether `origin` has a worker-mode frame session in this browser. */\n workerFrame(origin: string): boolean {\n return this.#frames.has(origin);\n }\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 url = new URL(ask.url);\n // The service worker signs every same-origin request but a ticketed one, which bypasses it.\n const frame = url.searchParams.has(\"ticket\") ? undefined : this.#frames.get(url.origin);\n const answer = await send({\n ...ask,\n headers: {\n ...(cookie ? { cookie } : {}),\n ...(frame !== undefined ? { \"x-mostra-frame\": frame } : {}),\n ...ask.headers,\n },\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 if (ticket.mode === \"worker\") {\n // The bootstrap page (D70): it loads, then exchanges the ticket in its fragment.\n const page = await browser.ask({\n url: ticket.src.replace(/#.*$/, \"\"),\n headers: {\n accept: \"text/html\",\n \"sec-fetch-mode\": \"navigate\",\n \"sec-fetch-dest\": \"iframe\",\n \"sec-fetch-site\": \"cross-site\",\n },\n });\n if (page.status !== 200) throw new OpenError(\"bootstrap\", page);\n const fragment = new URLSearchParams(new URL(ticket.src).hash.slice(1)).get(\"t\") ?? \"\";\n const entered = await browser.fetchJson(ticket.artifactOrigin, \"/_mostra/enter\", {\n body: { ticket: fragment },\n });\n if (entered.status !== 200) throw new OpenError(\"enter\", entered);\n browser.enterFrame(ticket.artifactOrigin, entered.json<{ session: string }>().session);\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 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); in worker mode with its ticket (D70). */\n async poll(cursor?: string): Promise<Answer> {\n let query = `view=${this.viewId}&wait=0${cursor !== undefined ? `&cursor=${cursor}` : \"\"}`;\n if (this.browser.workerFrame(this.ticket.artifactOrigin)) {\n const ticket = await this.page(\"ticket\", { purpose: \"stream\" });\n if (ticket.status !== 200) return ticket;\n query += `&ticket=${ticket.json<{ ticket: string }>().ticket}`;\n }\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 { spawn } from \"node:child_process\";\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 { fileURLToPath } from \"node:url\";\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, windowsHelper } 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/**\n * The local stand-ins for `tailscale` and `cloudflared` the share scenarios start instances with\n * (`MOSTRA_TEST_TUNNELS`, D158): shipped in the kit's package beside `src` and `dist`.\n */\nexport const TUNNELS: string = fileURLToPath(new URL(\"../tunnels/\", import.meta.url));\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 await removeTree(this.dir);\n }\n}\n\n/**\n * Removes a scenario's directory. A home's versions are sealed read-only (DATA_MODEL §1): on POSIX\n * by mode (files 0444, directories 0555), so directories are made writable first; on Windows by\n * a protected access list (D150 item 3), which only the runtime's helper resets (`mostra-win\n * unseal`, found beside the runtime as every client finds it). Windows also holds a file a process\n * just closed (Defender, the indexer), so removal is retried for a while.\n */\nexport async function removeTree(dir: string): Promise<void> {\n if (process.platform === \"win32\") {\n const helper = windowsHelper(await resolveRuntime().catch(() => undefined), process.env);\n await new Promise<void>((done) => {\n const child = spawn(helper, [\"unseal\", dir], { stdio: \"ignore\", windowsHide: true });\n child.on(\"exit\", () => done());\n child.on(\"error\", () => done());\n });\n } else {\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 }\n rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 300 });\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 // A delivery reads pending from the moment it is enqueued, before its first attempt; the\n // event follows the host's first retry answer, so it is waited for, while the host still\n // answers retry and the delivery still waits (it once ran before the first answer, under load).\n await context.eventually(\n \"a submission.retrying event while the delivery waits (IN-13)\",\n async () => {\n const retrying = await context.events({\n artifacts: [artifactId],\n types: [\"submission.retrying\"],\n });\n return retrying.events.length > 0 ? retrying : undefined;\n },\n );\n check(\n (await context.results(artifactId)).submission.delivery === \"pending\",\n \"the delivery stopped waiting while the host still answered retry\",\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, addressing, trusted\n * controls, secrets, and what server code raises for the host (D108, D131, D143, D158, AC-05,\n * H-05, H-14).\n */\nimport { ACTIONS, FORM } from \"../fixtures.ts\";\nimport { check, type Scenario, type ScenarioContext, same, TUNNELS } from \"../scenario.ts\";\nimport { Browser, OpenError, resultOf, send, Viewer } from \"../viewer.ts\";\n\n/** What `share/start` answers, as the scenarios read it. */\ninterface Shared {\n readonly shareId: string;\n readonly url: string;\n readonly tokenId: string;\n readonly mode: string;\n}\n\n/** The person the stand-in for Tailscale Serve names on every tailnet request (D158 item 2). */\nconst TAILNET_PERSON = { ref: \"ada@example.com\", name: \"Ada Lövelace\" };\n\n/** Starts the host's instance with the stand-ins for `tailscale` and `cloudflared` (D158). */\nfunction startWithTunnels(context: ScenarioContext): Promise<unknown> {\n return context.start({\n env: {\n MOSTRA_TEST_TUNNELS: TUNNELS,\n MOSTRA_FAKE_TAILNET_USER: `${TAILNET_PERSON.ref}|${TAILNET_PERSON.name}`,\n },\n });\n}\n\n/**\n * Opens a share of `artifactId` through `via`, answers on it, and returns the submission's viewer\n * with the identity calls the host saw meanwhile.\n */\nasync function answeredThrough(\n context: ScenarioContext,\n artifactId: string,\n via: \"tailnet\" | \"cloudflare\",\n): Promise<{\n readonly shared: Shared;\n readonly viewer: { readonly kind: string; readonly ref?: string };\n readonly calls: Awaited<ReturnType<ScenarioContext[\"store\"]>>[\"identity\"];\n}> {\n const before = context.host.serves(\"identity\") ? (await context.store()).identity.length : 0;\n const shared = await context.host.call<Shared>(\n \"share/start\",\n { artifact: { artifactId }, via },\n 120_000,\n );\n try {\n const viewer = await Viewer.open(shared.url);\n const channel = viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\";\n same((await viewer.answer({ name: via }, channel)).status, 200, `the submit through ${via}`);\n const read = await context.results(artifactId);\n const calls = context.host.serves(\"identity\")\n ? (await context.store()).identity.slice(before)\n : [];\n return { shared, viewer: read.submission.viewer, calls };\n } finally {\n await context.host.call(\"share/stop\", { shareId: shared.shareId });\n }\n}\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 await sharedIdentity(context);\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/**\n * D143 item 2, D158 item 2: through Tailscale Serve the identity port hears `via: \"tailnet\"` with\n * Serve's identity headers, and through a public share `via: \"token\"`; a host's answer names the\n * person, and without one the tailnet person, or the link itself, is the viewer, never the home's\n * local user.\n */\nasync function sharedIdentity(context: ScenarioContext): Promise<void> {\n await context.host.stopInstance();\n await startWithTunnels(context);\n const receipt = await context.published(FORM, { policy: { policy: \"epochs\" } });\n for (const via of [\"tailnet\", \"cloudflare\"] as const) {\n const { shared, viewer, calls } = await answeredThrough(context, receipt.artifactId, via);\n const call = calls.at(-1);\n const expected = via === \"tailnet\" ? \"tailnet\" : \"token\";\n if (call !== undefined) {\n same(call.via, expected, `how a request through ${via} reached the gateway`);\n if (via === \"tailnet\") {\n check(\n call.headers.includes(\"tailscale-user-login\"),\n \"the port didn't receive Tailscale Serve's identity headers\",\n );\n }\n } else {\n check(!context.host.serves(\"identity\"), `the identity port wasn't asked through ${via}`);\n }\n if (call?.answer) {\n same(\n [viewer.kind, viewer.ref],\n [\"host\", call.answer.ref],\n `the viewer the host named (${via})`,\n );\n } else if (via === \"tailnet\") {\n same([viewer.kind, viewer.ref], [\"tailnet\", TAILNET_PERSON.ref], \"the tailnet person\");\n } else {\n same(\n [viewer.kind, viewer.ref],\n [\"token\", `link:${shared.tokenId}`],\n \"the public link's viewer\",\n );\n }\n }\n}\n\n/**\n * HO-10, D158 item 6: a host's `addressing` port gives the external base of an artifact's links.\n * The base appears in the links Mostra mints and passes the Host and Origin checks, a frame on\n * another site enters in worker mode, a base the host withdraws stops working, and without the\n * port every link stays on loopback.\n */\nexport const addressing: Scenario = {\n id: \"ports.addressing\",\n title:\n \"With an addressing port, the links Mostra mints use the host's external base, which passes the Host and Origin checks and opens a frame on another site in worker mode; a withdrawn base stops working; without the port, links stay on loopback\",\n covers: [\"HO-01\", \"HO-05\", \"HO-10\", \"HY-07\", \"H-14\"],\n async run(context) {\n await context.start();\n // Epochs: the loopback link after the withdrawal answers again (a once artifact takes one).\n const receipt = await context.published(FORM, { policy: { policy: \"epochs\" } });\n const loopback = (link: string): boolean =>\n [\"127.0.0.1\", \"[::1]\"].includes(new URL(link).hostname);\n if (!context.host.serves(\"addressing\")) {\n check(receipt.url !== undefined && loopback(receipt.url), \"the publish receipt's link\");\n check(loopback(await context.link(receipt.artifactId)), \"a minted link without the port\");\n return;\n }\n // A host that can be scripted puts the shell and the artifact on two sites (`localhost` and\n // `127.0.0.1` are as cross-site as two tunnel hostnames); any other host is judged by its own\n // answers.\n if (context.host.supports(\"faults\")) {\n await context.host.script({\n port: \"addressing\",\n answer: { shellHost: \"localhost\", artifactHost: \"127.0.0.1\" },\n });\n }\n const link = await context.link(receipt.artifactId);\n const calls = (await context.store()).addressing ?? [];\n const asked = calls.filter(\n (call) => call.artifactId === receipt.artifactId && call.listener === \"shell\",\n );\n const answer = asked.at(-1)?.answer;\n check(asked.length > 0, \"the host's addressing port wasn't asked for the link's base\");\n if (!answer) {\n check(loopback(link), \"a link whose host gave no base\");\n return;\n }\n same(new URL(link).origin, answer.origin, \"the minted link's base\");\n const local = asked.at(-1)?.local as string;\n check(loopback(local), `the loopback origin the host forwards to (${local})`);\n const viewer = await Viewer.open(link);\n const frameBase = (await context.store()).addressing?.findLast(\n (call) => call.artifactId === receipt.artifactId && call.listener === \"artifact\",\n )?.answer;\n if (frameBase) {\n same(viewer.ticket.artifactOrigin, frameBase.origin, \"the frame's base\");\n const crossSite = new URL(frameBase.origin).hostname !== new URL(answer.origin).hostname;\n same(\n viewer.ticket.mode ?? \"cookie\",\n frameBase.mode ?? (crossSite ? \"worker\" : \"cookie\"),\n \"the frame's session mode\",\n );\n }\n const channel = viewer.ticket.submitChannels.includes(\"artifact\") ? \"artifact\" : \"shell\";\n same((await viewer.answer({ name: \"Ada\" }, channel)).status, 200, \"a submit at the base\");\n const polled = await viewer.poll();\n same(polled.status, 200, \"the page's long poll at the base\");\n // The base passes the Host and Origin checks; another Host or Origin is refused.\n const parsed = new URL(link);\n const strangerHost = await send({\n url: `${parsed.origin}/a/${receipt.artifactId}`,\n headers: { host: `evil.example:${parsed.port}`, accept: \"text/html\" },\n });\n same(strangerHost.status, 421, \"another Host at the base\");\n const otherOrigin = await new Browser().ask({\n method: \"POST\",\n url: `${parsed.origin}/a/${receipt.artifactId}/_mostra/session`,\n headers: {\n origin: local,\n \"content-type\": \"application/json\",\n \"sec-fetch-site\": \"cross-site\",\n },\n body: JSON.stringify({ token: new URLSearchParams(parsed.hash.slice(1)).get(\"t\") }),\n });\n same(otherOrigin.status, 403, \"an exchange from another origin\");\n if (!context.host.supports(\"faults\")) return;\n // The host withdraws its base: new links are on loopback, and the old one stops working.\n await context.host.script({ port: \"addressing\", answer: null });\n const after = await context.link(receipt.artifactId);\n check(loopback(after), `a link minted after the base was withdrawn (${after})`);\n const stale = await Viewer.open(link).then(\n () => \"opened\",\n (error: unknown) => (error instanceof OpenError ? error.status : \"unreachable\"),\n );\n check(stale !== \"opened\", \"a link at a withdrawn base still opened\");\n const reopened = await Viewer.open(after);\n same((await reopened.answer({ name: \"Grace\" }, channel)).status, 200, \"a submit on loopback\");\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 addressing,\n trustedControls,\n secrets,\n serverEvents,\n];\n","/**\n * Whether a path of a host's home is owner-only, as the kit judges it (H-16, D44, D85, D150\n * item 3): on POSIX by its mode (`0700` for a directory, `0600` for a file); on Windows by its\n * access list, which allows no one but the user and `SYSTEM`, and for a directory is protected\n * (inherits nothing from above; a file inside inherits the directory's). Windows has no modes, and Node.js reads no access list, so the kit reads the\n * list's SDDL (the same in every language) through Windows PowerShell's `Get-Acl`, and the user's\n * SID through `whoami`.\n */\nimport { spawnSync } from \"node:child_process\";\nimport { statSync } from \"node:fs\";\n\n/** `SYSTEM`, as SDDL names it by alias and by SID. */\nconst SYSTEM = new Set([\"SY\", \"S-1-5-18\"]);\n\n/** `CREATOR OWNER`: an inheritable entry for whoever creates a child, which in an owner-only\n * directory only the user or `SYSTEM` can do (Opus review of WP-W3, finding 7). */\nconst CREATOR_OWNER = new Set([\"CO\", \"S-1-3-0\"]);\n\n/** The entry types that deny: they grant no one anything (finding 7). */\nconst DENY = new Set([\"D\", \"OD\", \"XD\"]);\n\n/**\n * The SIDs this machine's own account aliases stand for: SDDL writes the built-in Administrator\n * (`LA`) and Guest (`LG`) of the local machine by alias (GitHub's runners run as the former). An\n * alias is the user only when it resolves to exactly the user's SID, never by its relative ID\n * alone: a domain's Administrator ends in -500 too (finding 6). An alias that couldn't be resolved\n * is no one's, so its entry fails the check.\n */\nexport type AccountAliases = Readonly<Record<string, string>>;\n\n/** Whether an SDDL trustee (a SID or an alias) is the user `user` (a SID). */\nfunction isUser(trustee: string, user: string, aliases: AccountAliases): boolean {\n return trustee === user || (Object.hasOwn(aliases, trustee) && aliases[trustee] === user);\n}\n\n/** What is wrong with `path`'s privacy, or `undefined` when it is owner-only. */\nexport function notOwnerOnly(\n path: string,\n platform: string = process.platform,\n): string | undefined {\n if (platform !== \"win32\") {\n const stats = statSync(path);\n const want = stats.isDirectory() ? 0o700 : 0o600;\n const mode = stats.mode & 0o777;\n return mode === want ? undefined : `mode ${mode.toString(8)}, not ${want.toString(8)}`;\n }\n const { sddl, aliases } = windowsSddl(path);\n return judgeSddl(sddl, windowsUser(), statSync(path).isDirectory(), aliases);\n}\n\n/** What is wrong with a Windows access list (`sddl`) for the user `user` (a SID). */\nexport function judgeSddl(\n sddl: string,\n user: string,\n directory: boolean,\n aliases: AccountAliases = {},\n): string | undefined {\n const start = sddl.indexOf(\"D:\");\n if (start < 0) return `no access list (${sddl})`;\n const rest = sddl.slice(start + 2);\n const end = rest.search(/S:/);\n const dacl = end < 0 ? rest : rest.slice(0, end);\n const flags = dacl.slice(0, dacl.indexOf(\"(\") < 0 ? dacl.length : dacl.indexOf(\"(\"));\n // A NULL access list (the flag `NO_ACCESS_CONTROL`, beside any others) holds no entry and\n // grants everyone everything (GPT review of WP-W3).\n if (flags.includes(\"NO_ACCESS_CONTROL\"))\n return `its access list is NULL, which grants everyone access (${dacl})`;\n if (directory && !flags.includes(\"P\")) return `its access list inherits from above (${dacl})`;\n for (const ace of dacl.matchAll(/\\(([^)]*)\\)/g)) {\n const fields = (ace[1] ?? \"\").split(\";\");\n const [type, , , , , sid] = fields;\n if (type !== undefined && DENY.has(type)) continue;\n if (\n sid === undefined ||\n !(isUser(sid, user, aliases) || SYSTEM.has(sid) || CREATOR_OWNER.has(sid))\n ) {\n return `it grants ${sid ?? \"someone\"} access (${dacl})`;\n }\n }\n return undefined;\n}\n\nfunction windowsUser(): string {\n // Windows' own, by path: a `whoami` earlier on `PATH` (Git's coreutils) takes no `/user`.\n const system = process.env[\"SystemRoot\"] ?? \"C:\\\\Windows\";\n const answer = spawnSync(`${system}\\\\System32\\\\whoami.exe`, [\"/user\", \"/fo\", \"csv\", \"/nh\"], {\n encoding: \"utf8\",\n windowsHide: true,\n });\n const sid = /\"(S-1-[0-9-]+)\"/.exec(answer.stdout ?? \"\")?.[1];\n if (sid === undefined) throw new Error(`whoami named no SID: ${answer.stdout}${answer.stderr}`);\n return sid;\n}\n\n/** The path's SDDL, and the SIDs of this machine's `LA` and `LG` (absent when unresolvable). */\nfunction windowsSddl(path: string): { sddl: string; aliases: AccountAliases } {\n const system = process.env[\"SystemRoot\"] ?? \"C:\\\\Windows\";\n const answer = spawnSync(\n `${system}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`,\n [\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-Command\",\n [\n \"(Get-Acl -LiteralPath $env:MOSTRA_KIT_PATH).Sddl\",\n // Single quotes only: Windows PowerShell 5 takes double quotes in `-Command` apart.\n \"foreach ($a in 'LA','LG') { try { $a + '=' + ([Security.Principal.SecurityIdentifier]$a).Value } catch { $a + '=' } }\",\n ].join(\"; \"),\n ],\n { encoding: \"utf8\", windowsHide: true, env: { ...process.env, MOSTRA_KIT_PATH: path } },\n );\n const [sddl = \"\", ...rest] = (answer.stdout ?? \"\").trim().split(/\\r?\\n/);\n if (answer.status !== 0 || sddl.trim() === \"\") {\n throw new Error(`Get-Acl couldn't read ${path}: ${answer.stderr}`);\n }\n const aliases: Record<string, string> = {};\n for (const line of rest) {\n const match = /^(LA|LG)=(S-1-[0-9-]+)\\s*$/.exec(line.trim());\n if (match) aliases[match[1] as string] = match[2] as string;\n }\n return { sddl: sddl.trim(), aliases };\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 { notOwnerOnly } from \"../privacy.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 // The instance spells its home as the system does (D151 item 5): links followed, Windows'\n // 8.3 short names written out.\n same(started.instance.home, realpathSync.native(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 // Owner-only: modes 0700 and 0600 on POSIX, an access list for the user and SYSTEM alone on\n // Windows (D150 item 3).\n const home = notOwnerOnly(context.home);\n check(home === undefined, `the home isn't owner-only: ${home}`);\n await context.host.call(\"secret/set\", { name: \"CONFORMANCE_TOKEN\", value: \"kept-private-123\" });\n const secret = notOwnerOnly(join(context.home, \"secrets\", \"home\", \"CONFORMANCE_TOKEN\"));\n check(secret === undefined, `a secret isn't owner-only: ${secret}`);\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;;;;;;;;;;;;;;;;;;;;;;;;;EA0Bf;;AAGA,MA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,GAAI,WAAW,KAAA,IAAY,EAAE,OAAO,IAAI,CAAC;GACzC,YAAY,KAAK,IAAI,IAAI;EAC3B;EACA,SAAS,KAAK,OAAO;EACrB,QAAQ,YAAY,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.6.2",
3
+ "version": "0.8.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",
@@ -25,6 +25,7 @@
25
25
  "dist",
26
26
  "src",
27
27
  "baselines",
28
+ "tunnels",
28
29
  "!src/**/*.test.ts"
29
30
  ],
30
31
  "engines": {
@@ -35,8 +36,8 @@
35
36
  "provenance": true
36
37
  },
37
38
  "dependencies": {
38
- "@mostra/protocol": "0.6.2",
39
- "@mostra/sdk": "0.6.2",
39
+ "@mostra/protocol": "0.8.0",
40
+ "@mostra/sdk": "0.8.0",
40
41
  "playwright-core": "1.64.1",
41
42
  "zod": "4.6.7"
42
43
  },
@@ -46,7 +47,7 @@
46
47
  "tsdown": "0.23.1",
47
48
  "typescript": "7.0.2",
48
49
  "vitest": "5.0.5",
49
- "@mostra/runtime": "0.6.2"
50
+ "@mostra/runtime": "0.8.0"
50
51
  },
51
52
  "keywords": [
52
53
  "mostra",
@@ -223,6 +223,17 @@ export interface StoreResult {
223
223
  }[];
224
224
  /** `secrets.get` calls. */
225
225
  readonly secrets: readonly { readonly artifactId: string; readonly name: string }[];
226
+ /**
227
+ * `addressing.externalBase` calls (WP-13): the artifact, the listener, the loopback origin the
228
+ * host forwards to, and what the host answered (absent when it failed). A host without the port
229
+ * leaves it out.
230
+ */
231
+ readonly addressing?: readonly {
232
+ readonly artifactId: string;
233
+ readonly listener: string;
234
+ readonly local: string;
235
+ readonly answer?: { readonly origin: string; readonly mode?: string } | null;
236
+ }[];
226
237
  }
227
238
 
228
239
  /** The schema of `StoreResult`. */
@@ -275,6 +286,18 @@ export const StoreResult: z.ZodType<StoreResult> = z.object({
275
286
  }),
276
287
  ),
277
288
  secrets: z.array(z.object({ artifactId: z.string(), name: z.string() })),
289
+ addressing: z
290
+ .array(
291
+ z.object({
292
+ artifactId: z.string(),
293
+ listener: z.string(),
294
+ local: z.string(),
295
+ answer: z
296
+ .union([z.object({ origin: z.string(), mode: z.string().optional() }), z.null()])
297
+ .optional(),
298
+ }),
299
+ )
300
+ .optional(),
278
301
  }) as z.ZodType<StoreResult>;
279
302
 
280
303
  /** How a scripted port answers from now on (feature `faults`). */
@@ -303,7 +326,23 @@ export type ScriptParams =
303
326
  | null
304
327
  | { readonly ref: string; readonly name?: string };
305
328
  }
306
- | { readonly port: "secrets"; readonly answer: Readonly<Record<string, string>> };
329
+ | { readonly port: "secrets"; readonly answer: Readonly<Record<string, string>> }
330
+ | {
331
+ readonly port: "addressing";
332
+ /**
333
+ * `null`: no external base (the loopback ports); `fail`: the call fails; a pair of host
334
+ * names: each listener at its loopback port under that name (`http://<host>:<port>`), the
335
+ * shell's and the artifact's, which the kit sets apart to make them two sites (WP-13).
336
+ */
337
+ readonly answer:
338
+ | null
339
+ | "fail"
340
+ | {
341
+ readonly shellHost: string;
342
+ readonly artifactHost: string;
343
+ readonly mode?: "cookie" | "worker";
344
+ };
345
+ };
307
346
 
308
347
  /** The schema of `ScriptParams`. */
309
348
  export const ScriptParams: z.ZodType<ScriptParams> = z.union([
@@ -333,6 +372,18 @@ export const ScriptParams: z.ZodType<ScriptParams> = z.union([
333
372
  ]),
334
373
  }),
335
374
  z.object({ port: z.literal("secrets"), answer: z.record(z.string(), z.string()) }),
375
+ z.object({
376
+ port: z.literal("addressing"),
377
+ answer: z.union([
378
+ z.null(),
379
+ z.literal("fail"),
380
+ z.object({
381
+ shellHost: z.string(),
382
+ artifactHost: z.string(),
383
+ mode: z.enum(["cookie", "worker"]).optional(),
384
+ }),
385
+ ]),
386
+ }),
336
387
  ]) as z.ZodType<ScriptParams>;
337
388
 
338
389
  /** `harness/events`'s params: read pages from the host's own named stream (feature `events`). */