@mostra/conformance 0.0.0-placeholder → 0.2.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,1940 @@
1
+ import { a as HARNESS_METHODS, d as StoreResult, f as kitVersion, i as EventsResult, n as CallResult, o as HARNESS_REVISIONS, s as InitializeResult, u as StartResult } from "./protocol-RQ9lbehE.js";
2
+ import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
3
+ import * as z from "zod";
4
+ import { spawn } from "node:child_process";
5
+ import { BROWSER_PROTOCOL_REVISIONS, HOST_PROTOCOL_REVISIONS, LineSplitter, MutationId, RpcError, RpcPeer, createDiagnostic, deserializeAll, encodeLine, serializeAll } from "@mostra/protocol";
6
+ import { dirname, join } from "node:path";
7
+ import { tmpdir } from "node:os";
8
+ import { createConnection } from "node:net";
9
+ import { request } from "node:http";
10
+ //#region src/baseline.ts
11
+ /**
12
+ * Expected-failure baselines (HO-05): a host that knows it fails some scenarios today records them,
13
+ * with why, so a run stays green while the gap is known and goes red the moment anything changes:
14
+ * a scenario that newly fails, or one the baseline expects to fail that passes (the baseline is
15
+ * then stale and must shrink). The pattern of the MCP conformance suite and WPT's expectations.
16
+ *
17
+ * ```json
18
+ * { "schemaVersion": 1, "expectedFailures": { "delivery.exactly-once": "our store isn't idempotent yet (#123)" } }
19
+ * ```
20
+ */
21
+ const BaselineSchema = z.strictObject({
22
+ schemaVersion: z.literal(1),
23
+ expectedFailures: z.record(z.string().min(1), z.string().min(1))
24
+ });
25
+ /** An empty baseline: every scenario must pass. */
26
+ const NO_BASELINE = {
27
+ schemaVersion: 1,
28
+ expectedFailures: {}
29
+ };
30
+ /**
31
+ * Reads a baseline file. Throws on a file that isn't one, and on a scenario ID no scenario of
32
+ * `known` has (a typo would otherwise expect nothing, silently).
33
+ */
34
+ function readBaseline(path, known) {
35
+ let data;
36
+ try {
37
+ data = JSON.parse(readFileSync(path, "utf8"));
38
+ } catch (error) {
39
+ throw new Error(`${path} isn't a readable JSON baseline: ${error.message}`);
40
+ }
41
+ const parsed = BaselineSchema.safeParse(data);
42
+ if (!parsed.success) throw new Error(`${path} isn't a conformance baseline: { "schemaVersion": 1, "expectedFailures": { "<scenario>": "<why>" } }.`);
43
+ const unknown = Object.keys(parsed.data.expectedFailures).filter((id) => !known.includes(id));
44
+ if (unknown.length > 0) throw new Error(`${path} names scenarios the kit doesn't have: ${unknown.join(", ")}.`);
45
+ return parsed.data;
46
+ }
47
+ //#endregion
48
+ //#region src/fixtures.ts
49
+ /** A questionnaire with viewer fields, an artifact-scoped counter, a family and a link (H-06). */
50
+ const FORM = { "index.tsx": `import { defineArtifact, useField, useSubmitControl } from "@mostra/react";
51
+
52
+ export const artifact = defineArtifact({
53
+ title: "Conformance questionnaire",
54
+ description: "The form the host conformance kit answers.",
55
+ family: "questionnaire",
56
+ links: [{ rel: "round-of", artifact: "conformance-round-1" }],
57
+ });
58
+
59
+ export default function Page() {
60
+ useSubmitControl({ label: "Send answers" });
61
+ const [name, setName] = useField("name", "", { label: "Your name", required: true });
62
+ const [comment, setComment] = useField("comment", "", { label: "Comment" });
63
+ const [count, setCount] = useField("count", 0, { label: "Count", scope: "artifact" });
64
+ const [done, setDone] = useField("done", false, { label: "Done", scope: "artifact" });
65
+ return (
66
+ <main>
67
+ <h1>Conformance questionnaire</h1>
68
+ <input name="name" aria-label="Your name" value={name} onChange={(e) => setName(e.target.value)} />
69
+ <textarea name="comment" aria-label="Comment" value={comment} onChange={(e) => setComment(e.target.value)} />
70
+ <button type="button" onClick={() => setCount(count + 1)}>Count {count}</button>
71
+ <label><input type="checkbox" checked={done} onChange={(e) => setDone(e.target.checked)} /> Done</label>
72
+ </main>
73
+ );
74
+ }
75
+ ` };
76
+ /** The same questionnaire with one more question: a second version of {@link FORM}. */
77
+ const FORM_V2 = { "index.tsx": FORM["index.tsx"].replace("<h1>Conformance questionnaire</h1>", "<h1>Conformance questionnaire, round 2</h1>").replace(" const [done, setDone]", " const [extra, setExtra] = useField(\"extra\", \"\", { label: \"Extra\" });\n const [done, setDone]").replace(" <label>", " <input name=\"extra\" aria-label=\"Extra\" value={extra} onChange={(e) => setExtra(e.target.value)} />\n <label>") };
78
+ /**
79
+ * Server code: an action that raises a signal and emits a host event (AC-05), and one that reads
80
+ * a secret through `secret()` (D131) and returns only its length, never the value.
81
+ */
82
+ const ACTIONS = {
83
+ "index.tsx": `import { defineArtifact } from "@mostra/react";
84
+
85
+ export const artifact = defineArtifact({ title: "Conformance actions" });
86
+
87
+ export default function Page() {
88
+ return <main><h1>Conformance actions</h1></main>;
89
+ }
90
+ `,
91
+ "actions.ts": `"use server";
92
+ import { emit, secret, signal } from "@mostra/server";
93
+
94
+ export async function notify(to: string): Promise<string> {
95
+ signal("mail.sent", { to });
96
+ emit("host.mail.sent", { to });
97
+ return "sent";
98
+ }
99
+
100
+ export async function secretLength(name: string): Promise<number> {
101
+ return secret(name).length;
102
+ }
103
+ `
104
+ };
105
+ /** The bundled fixtures by name. */
106
+ const FIXTURES = {
107
+ form: FORM,
108
+ "form-v2": FORM_V2,
109
+ actions: ACTIONS
110
+ };
111
+ //#endregion
112
+ //#region src/harness/client.ts
113
+ /**
114
+ * The kit's side of the harness protocol: starts a host's shim (a command line), speaks to it
115
+ * over its stdio, and gives scenarios typed methods. The shim's stderr is kept (its last lines
116
+ * explain a failure). A shim that exits ends every pending call with
117
+ * `MOSTRA_HOST_CONNECTION_CLOSED`.
118
+ */
119
+ /** How long one harness request may take before the kit gives up on the host. */
120
+ const HARNESS_TIMEOUT_MS = 12e4;
121
+ /** An instance's error, carried through the host: its diagnostic code and JSON-RPC code. */
122
+ var InstanceError = class extends Error {
123
+ /** The diagnostic code (`MOSTRA_…`). */
124
+ code;
125
+ /** The JSON-RPC error code. */
126
+ rpcCode;
127
+ /** The diagnostic as it arrived. */
128
+ data;
129
+ constructor(method, error) {
130
+ super(`${method} failed with ${error.data.code}: ${error.data.message ?? ""}`);
131
+ this.name = "InstanceError";
132
+ this.code = error.data.code;
133
+ this.rpcCode = error.code;
134
+ this.data = error.data;
135
+ }
136
+ };
137
+ /** A host under test, reached through its harness shim. */
138
+ var HostUnderTest = class HostUnderTest {
139
+ #child;
140
+ #peer;
141
+ #stderr = [];
142
+ #exited;
143
+ /** What the host said about itself. */
144
+ info;
145
+ constructor(command, env) {
146
+ this.#child = spawn(command, {
147
+ shell: true,
148
+ stdio: [
149
+ "pipe",
150
+ "pipe",
151
+ "pipe"
152
+ ],
153
+ env: {
154
+ ...process.env,
155
+ ...env
156
+ },
157
+ detached: true
158
+ });
159
+ this.#exited = new Promise((done) => {
160
+ this.#child.on("close", (code) => done(code));
161
+ this.#child.on("error", () => done(null));
162
+ });
163
+ this.#peer = new RpcPeer({ send: (message) => {
164
+ if (this.#child.stdin?.writable) this.#child.stdin.write(encodeLine(message));
165
+ } });
166
+ const lines = new LineSplitter();
167
+ this.#child.stdout?.setEncoding("utf8");
168
+ this.#child.stdout?.on("data", (chunk) => {
169
+ for (const line of lines.push(chunk)) this.#peer.receiveLine(line);
170
+ });
171
+ const errors = new LineSplitter();
172
+ this.#child.stderr?.setEncoding("utf8");
173
+ this.#child.stderr?.on("data", (chunk) => {
174
+ for (const line of errors.push(chunk)) {
175
+ this.#stderr.push(line);
176
+ if (this.#stderr.length > 40) this.#stderr.shift();
177
+ }
178
+ });
179
+ this.#child.stdin?.on("error", () => {});
180
+ this.#exited.then((code) => this.#peer.close(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", { message: `The host under test exited (${code ?? "signal"}): ${this.#stderr.slice(-3).join(" | ")}` })));
181
+ }
182
+ /** Starts the shim and asks it who it is. */
183
+ static async start(command, env = {}) {
184
+ const host = new HostUnderTest(command, env);
185
+ try {
186
+ const answer = await host.#request(HARNESS_METHODS.initialize, {
187
+ revision: HARNESS_REVISIONS.at(-1),
188
+ kit: {
189
+ name: "@mostra/conformance",
190
+ version: kitVersion()
191
+ }
192
+ });
193
+ host.info = InitializeResult.parse(answer);
194
+ } catch (error) {
195
+ await host.close();
196
+ throw error;
197
+ }
198
+ return host;
199
+ }
200
+ /** The host's last stderr lines. */
201
+ get stderr() {
202
+ return this.#stderr;
203
+ }
204
+ /** Whether the host serves `port` / supports `feature`. */
205
+ serves(port) {
206
+ return this.info?.ports.includes(port) ?? false;
207
+ }
208
+ /** Whether the host supports the harness feature `feature`. */
209
+ supports(feature) {
210
+ return this.info?.features.includes(feature) ?? false;
211
+ }
212
+ #request(method, params, timeoutMs = HARNESS_TIMEOUT_MS) {
213
+ return this.#peer.request(method, params, { timeoutMs });
214
+ }
215
+ /** `harness/start`: the host starts or attaches to its instance. */
216
+ async startInstance(params) {
217
+ return StartResult.parse(await this.#request(HARNESS_METHODS.start, params));
218
+ }
219
+ /** `harness/call`, raw: the instance's answer or error as the host received it. */
220
+ async callRaw(method, params, timeoutMs) {
221
+ return CallResult.parse(await this.#request(HARNESS_METHODS.call, {
222
+ method,
223
+ params,
224
+ ...timeoutMs !== void 0 ? { timeoutMs } : {}
225
+ }, (timeoutMs ?? 6e4) + 3e4));
226
+ }
227
+ /** `harness/call`: the answer, or an {@link InstanceError}. */
228
+ async call(method, params, timeoutMs) {
229
+ const answer = await this.callRaw(method, params, timeoutMs);
230
+ if ("error" in answer) throw new InstanceError(method, answer.error);
231
+ return answer.result;
232
+ }
233
+ /** `harness/stop`: the host ends its session. */
234
+ async stopInstance() {
235
+ await this.#request(HARNESS_METHODS.stop, {});
236
+ }
237
+ /** `harness/store`. */
238
+ async store() {
239
+ return StoreResult.parse(await this.#request(HARNESS_METHODS.store, {}));
240
+ }
241
+ /** `harness/script` (feature `faults`). */
242
+ async script(params) {
243
+ await this.#request(HARNESS_METHODS.script, params);
244
+ }
245
+ /** `harness/events` (feature `events`). */
246
+ async events(params) {
247
+ return EventsResult.parse(await this.#request(HARNESS_METHODS.events, params, params.timeoutMs + 3e4));
248
+ }
249
+ /** Ends the shim: stdin closes, then SIGTERM to its process group, then SIGKILL. */
250
+ async close() {
251
+ this.#child.stdin?.end();
252
+ const pid = this.#child.pid;
253
+ const signal = (name) => {
254
+ if (pid === void 0) return;
255
+ try {
256
+ process.kill(-pid, name);
257
+ } catch {}
258
+ };
259
+ if (await Promise.race([this.#exited.then(() => "exited"), new Promise((done) => setTimeout(() => done("waiting"), 5e3))]) === "waiting") {
260
+ signal("SIGTERM");
261
+ if (await Promise.race([this.#exited.then(() => "exited"), new Promise((done) => setTimeout(() => done("waiting"), 5e3))]) === "waiting") signal("SIGKILL");
262
+ }
263
+ this.#peer.close();
264
+ }
265
+ };
266
+ /** A diagnostic code from an error the kit saw: the instance's, an RPC error's, or none. */
267
+ function codeOf(error) {
268
+ if (error instanceof InstanceError) return error.code;
269
+ if (error instanceof RpcError) return error.diagnostic.code;
270
+ }
271
+ //#endregion
272
+ //#region src/viewer.ts
273
+ /**
274
+ * A viewer as the kit plays one: it opens a capability link the way the shell does (the token for
275
+ * a shell session, a frame ticket, the frame's entry) and speaks the browser protocol the way a
276
+ * page does, with a per-host cookie jar (browsers keep cookies per host, not per port, D98) and the
277
+ * `Origin`, `Sec-Fetch-*` and CSRF headers a browser sends. It also sends what no browser would,
278
+ * for the hygiene scenarios. It never follows redirects.
279
+ */
280
+ /** The browser-protocol revision the kit speaks: the first, which every gateway serves. */
281
+ const REVISION = BROWSER_PROTOCOL_REVISIONS[0];
282
+ /** Sends one request, never following a redirect. */
283
+ function send(ask) {
284
+ const url = new URL(ask.url);
285
+ return new Promise((resolve, reject) => {
286
+ const req = request({
287
+ host: url.hostname.replace(/^\[|\]$/g, ""),
288
+ port: url.port,
289
+ method: ask.method ?? "GET",
290
+ path: `${url.pathname}${url.search}`,
291
+ headers: ask.headers,
292
+ agent: false
293
+ }, (res) => {
294
+ const chunks = [];
295
+ res.on("data", (chunk) => chunks.push(chunk));
296
+ res.on("end", () => {
297
+ const headers = {};
298
+ for (let index = 0; index + 1 < res.rawHeaders.length; index += 2) {
299
+ const name = res.rawHeaders[index].toLowerCase();
300
+ const values = headers[name] ?? [];
301
+ values.push(res.rawHeaders[index + 1]);
302
+ headers[name] = values;
303
+ }
304
+ const body = Buffer.concat(chunks).toString("utf8");
305
+ resolve({
306
+ status: res.statusCode ?? 0,
307
+ headers,
308
+ body,
309
+ json: () => {
310
+ try {
311
+ return JSON.parse(body);
312
+ } catch {
313
+ return {};
314
+ }
315
+ }
316
+ });
317
+ });
318
+ });
319
+ req.setTimeout(6e4, () => req.destroy(/* @__PURE__ */ new Error(`${ask.url} didn't answer in 60 s`)));
320
+ req.on("error", reject);
321
+ if (ask.body !== void 0) req.write(ask.body);
322
+ req.end();
323
+ });
324
+ }
325
+ /** Reads a capability link (`http://host:port/a/<artifactId>[/v/<n>]#t=<secret>`). */
326
+ function parseLink(link) {
327
+ const url = new URL(link);
328
+ const match = /^\/a\/(art_[0-9A-Z]{26})(?:\/v\/(\d+))?$/.exec(url.pathname);
329
+ const secret = new URLSearchParams(url.hash.slice(1)).get("t");
330
+ if (!match?.[1] || !secret) throw new Error(`${url.origin}${url.pathname} isn't a capability link.`);
331
+ return {
332
+ origin: url.origin,
333
+ artifactId: match[1],
334
+ secret,
335
+ ...match[2] !== void 0 ? { version: match[2] } : {}
336
+ };
337
+ }
338
+ /** A browser-like client with a per-host cookie jar. */
339
+ var Browser = class {
340
+ #jar = /* @__PURE__ */ new Map();
341
+ /** The cookies the jar sends to `url`: every cookie of the host whose path matches. */
342
+ cookiesFor(url) {
343
+ const { pathname } = new URL(url);
344
+ return [...this.#jar].filter(([, cookie]) => {
345
+ const prefix = cookie.path.endsWith("/") ? cookie.path : `${cookie.path}/`;
346
+ return pathname === cookie.path || pathname.startsWith(prefix);
347
+ }).map(([key, cookie]) => `${key.split(" ")[0]}=${cookie.value}`).join("; ");
348
+ }
349
+ /** Sends a request with the jar's cookies and keeps the ones that come back. */
350
+ async ask(ask) {
351
+ const cookie = ask.noCookies ? "" : this.cookiesFor(ask.url);
352
+ const answer = await send({
353
+ ...ask,
354
+ headers: {
355
+ ...cookie ? { cookie } : {},
356
+ ...ask.headers
357
+ }
358
+ });
359
+ for (const line of answer.headers["set-cookie"] ?? []) {
360
+ const [pair = "", ...attributes] = line.split(";").map((part) => part.trim());
361
+ const at = pair.indexOf("=");
362
+ const path = attributes.find((attribute) => attribute.toLowerCase().startsWith("path="))?.slice(5) ?? "/";
363
+ this.#jar.set(`${pair.slice(0, at)} ${path}`, {
364
+ value: pair.slice(at + 1),
365
+ path
366
+ });
367
+ }
368
+ return answer;
369
+ }
370
+ /** A page on `origin` posting or fetching JSON from its own origin. */
371
+ fetchJson(origin, path, init = {}) {
372
+ const method = init.method ?? (init.body === void 0 ? "GET" : "POST");
373
+ return this.ask({
374
+ method,
375
+ url: `${origin}${path}`,
376
+ headers: {
377
+ "sec-fetch-site": "same-origin",
378
+ "sec-fetch-mode": "cors",
379
+ "sec-fetch-dest": "empty",
380
+ ...method === "GET" ? {} : {
381
+ origin,
382
+ "content-type": "application/json"
383
+ },
384
+ ...init.csrf ? { "x-mostra-csrf": init.csrf } : {},
385
+ ...init.headers
386
+ },
387
+ ...init.body === void 0 ? {} : { body: JSON.stringify(init.body) }
388
+ });
389
+ }
390
+ };
391
+ /** Why a viewer couldn't open its link: the step and the gateway's answer. */
392
+ var OpenError = class extends Error {
393
+ /** The HTTP status of the refused step. */
394
+ status;
395
+ /** The diagnostic code (`MOSTRA_…`). */
396
+ code;
397
+ constructor(step, answer) {
398
+ const code = answer.json().code;
399
+ super(`${step}: HTTP ${answer.status}${code ? ` ${code}` : ""}`);
400
+ this.name = "OpenError";
401
+ this.status = answer.status;
402
+ this.code = code;
403
+ }
404
+ };
405
+ /** One opened view: a shell session, a frame session and the view they show. */
406
+ var Viewer = class Viewer {
407
+ /** The cookie jar this viewer's requests use. */
408
+ browser;
409
+ /** The link it opened. */
410
+ link;
411
+ /** The frame ticket the shell got: the view, its version, channels and controls. */
412
+ ticket;
413
+ #shellCsrf;
414
+ #frameCsrf;
415
+ constructor(browser, link, ticket, shellCsrf, frameCsrf) {
416
+ this.browser = browser;
417
+ this.link = link;
418
+ this.ticket = ticket;
419
+ this.#shellCsrf = shellCsrf;
420
+ this.#frameCsrf = frameCsrf;
421
+ }
422
+ /**
423
+ * Opens `link` as the shell does. `headers` go with the session exchange (the request the
424
+ * `identity` port judges, D143). Throws an {@link OpenError} for a refused step.
425
+ */
426
+ static async open(link, options = {}) {
427
+ const browser = options.browser ?? new Browser();
428
+ const parsed = parseLink(link);
429
+ const api = `/a/${parsed.artifactId}/_mostra`;
430
+ const exchange = await browser.fetchJson(parsed.origin, `${api}/session`, {
431
+ body: { token: parsed.secret },
432
+ ...options.headers ? { headers: options.headers } : {}
433
+ });
434
+ if (exchange.status !== 200) throw new OpenError("exchange", exchange);
435
+ const shellCsrf = exchange.json().csrf;
436
+ const ticketAnswer = await browser.fetchJson(parsed.origin, `${api}/ticket`, {
437
+ body: parsed.version !== void 0 ? { version: Number(parsed.version) } : {},
438
+ csrf: shellCsrf
439
+ });
440
+ if (ticketAnswer.status !== 200) throw new OpenError("ticket", ticketAnswer);
441
+ const ticket = ticketAnswer.json();
442
+ const enter = await browser.ask({
443
+ url: ticket.src,
444
+ headers: {
445
+ accept: "text/html",
446
+ "sec-fetch-mode": "navigate",
447
+ "sec-fetch-dest": "iframe",
448
+ "sec-fetch-site": "same-site"
449
+ }
450
+ });
451
+ if (enter.status !== 303) throw new OpenError("enter", enter);
452
+ const session = await browser.fetchJson(ticket.artifactOrigin, "/_mostra/session");
453
+ if (session.status !== 200) throw new OpenError("frame session", session);
454
+ return new Viewer(browser, parsed, ticket, shellCsrf, session.json().csrf);
455
+ }
456
+ /** The view this frame load is (D104). */
457
+ get viewId() {
458
+ return this.ticket.viewId;
459
+ }
460
+ /** A browser-protocol request from the page. */
461
+ page(path, body) {
462
+ return this.browser.fetchJson(this.ticket.artifactOrigin, `/_mostra/v/${REVISION}/${path}`, {
463
+ body,
464
+ csrf: this.#frameCsrf
465
+ });
466
+ }
467
+ /** A request of the shell (its own origin, under `/a/<artifactId>`). */
468
+ shell(path, body, method) {
469
+ return this.browser.fetchJson(this.link.origin, `/a/${this.link.artifactId}/_mostra/${path}`, {
470
+ ...body === void 0 ? {} : { body },
471
+ ...method ? { method } : {},
472
+ csrf: this.#shellCsrf
473
+ });
474
+ }
475
+ /**
476
+ * Writes fields of the viewer's draft (or, with `scope: "artifact"`, the artifact state), with
477
+ * the labels a page sends for them (D106).
478
+ */
479
+ write(fields, options = {}) {
480
+ return this.page("fields", {
481
+ mutationId: MutationId.create(),
482
+ scope: options.scope ?? "viewer",
483
+ baseRevision: options.baseRevision ?? "0",
484
+ viewId: this.viewId,
485
+ ops: Object.entries(fields).map(([id, value]) => ({
486
+ id,
487
+ value,
488
+ ...options.labels?.[id] !== void 0 ? { label: options.labels[id] } : {}
489
+ }))
490
+ });
491
+ }
492
+ /** Submits on the artifact channel (D40). */
493
+ submit(expectedRevision) {
494
+ return this.page("submit", {
495
+ viewId: this.viewId,
496
+ expectedRevision,
497
+ channel: "artifact"
498
+ });
499
+ }
500
+ /** The trusted Submit, on the shell channel (D40, D108). */
501
+ shellSubmit(expectedRevision) {
502
+ return this.shell(`v/${REVISION}/submit`, {
503
+ viewId: this.viewId,
504
+ expectedRevision
505
+ });
506
+ }
507
+ /** Writes `fields`, then submits on `channel`; answers the submit. */
508
+ async answer(fields, channel = "artifact", labels) {
509
+ const written = await this.write(fields, labels ? { labels } : {});
510
+ if (written.status !== 200) return written;
511
+ const { revision } = written.json();
512
+ return channel === "artifact" ? this.submit(revision) : this.shellSubmit(revision);
513
+ }
514
+ /** Raises a signal from the page (IN-09). */
515
+ signal(name, payload) {
516
+ return this.page("signal", {
517
+ viewId: this.viewId,
518
+ name,
519
+ ...payload === void 0 ? {} : { payload }
520
+ });
521
+ }
522
+ /** Starts an action run (D130) and follows it until it ends. */
523
+ async run(fnId, args, timeoutMs = 6e4) {
524
+ const started = await this.page("runs", {
525
+ viewId: this.viewId,
526
+ fnId,
527
+ args: await serializeAll(args, { mode: "argument" }),
528
+ clientKey: `ck-${MutationId.create()}`
529
+ });
530
+ if (started.status !== 200) throw new OpenError("run", started);
531
+ const runId = started.json().runId;
532
+ const deadline = Date.now() + timeoutMs;
533
+ for (;;) {
534
+ const state = (await this.page("runs/attach", {
535
+ viewId: this.viewId,
536
+ runIds: [runId]
537
+ })).json().runs?.[0];
538
+ if (state && [
539
+ "succeeded",
540
+ "failed",
541
+ "cancelled"
542
+ ].includes(state.status)) return state;
543
+ if (Date.now() > deadline) throw new Error(`run ${runId} didn't end in ${timeoutMs} ms`);
544
+ await new Promise((done) => setTimeout(done, 100));
545
+ }
546
+ }
547
+ /** The page's long poll: events after `cursor` (D47). */
548
+ poll(cursor) {
549
+ const query = `view=${this.viewId}&wait=0${cursor !== void 0 ? `&cursor=${cursor}` : ""}`;
550
+ return this.browser.fetchJson(this.ticket.artifactOrigin, `/_mostra/v/${REVISION}/events/poll?${query}`);
551
+ }
552
+ };
553
+ /** A run's result, from its stored batches. */
554
+ async function resultOf(state) {
555
+ return state.batches.length === 0 ? void 0 : deserializeAll([...state.batches]);
556
+ }
557
+ //#endregion
558
+ //#region src/scenario.ts
559
+ /**
560
+ * Scenarios and what they get to work with. A scenario is one property a host integration must
561
+ * have, checked through the host's own client and ports (the harness) and a viewer playing the
562
+ * browser. Each runs against a fresh home in its own directory, with a fresh host shim.
563
+ */
564
+ /** A property that didn't hold. */
565
+ var ScenarioFailure = class extends Error {
566
+ constructor(message) {
567
+ super(message);
568
+ this.name = "ScenarioFailure";
569
+ }
570
+ };
571
+ /** Thrown to say a scenario doesn't apply to this host (a port or feature it lacks). */
572
+ var NotApplicable = class extends Error {
573
+ constructor(reason) {
574
+ super(reason);
575
+ this.name = "NotApplicable";
576
+ }
577
+ };
578
+ /** Fails the scenario with `message` unless `condition` holds. */
579
+ function check(condition, message) {
580
+ if (!condition) throw new ScenarioFailure(message);
581
+ }
582
+ /** `value` as JSON with every object's keys sorted, so key order never decides equality. */
583
+ function canonical(value) {
584
+ return JSON.stringify(value, (_key, inner) => inner !== null && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : inner);
585
+ }
586
+ /** Fails unless `actual` deep-equals `expected` (JSON comparison, key order aside). */
587
+ function same(actual, expected, what) {
588
+ const a = canonical(actual);
589
+ const b = canonical(expected);
590
+ if (a !== b) throw new ScenarioFailure(`${what}: expected ${b}, got ${a}`);
591
+ }
592
+ /** What a scenario works with: its host, its home, its viewers. */
593
+ var ScenarioContext = class {
594
+ /** The run's settings. */
595
+ settings;
596
+ /** The scenario's directory: the home, the authoring directories, the runtime directory. */
597
+ dir;
598
+ /** The home the host is told to use (HO-08). */
599
+ home;
600
+ /** The host: its name and version. */
601
+ host;
602
+ #hosts = [];
603
+ #published = 0;
604
+ constructor(settings, dir) {
605
+ this.settings = settings;
606
+ this.dir = dir;
607
+ this.home = join(dir, "home");
608
+ }
609
+ /** Starts the scenario's host shim (the runner does this before `run`). */
610
+ async open() {
611
+ this.host = await this.anotherHost();
612
+ }
613
+ /** A second shim of the same host, for scenarios about two hosts of one home. */
614
+ async anotherHost() {
615
+ const host = await HostUnderTest.start(this.settings.host, this.settings.hostEnv);
616
+ this.#hosts.push(host);
617
+ return host;
618
+ }
619
+ /** The variables every instance of the run gets: its own runtime and config directories. */
620
+ instanceEnv(extra = {}) {
621
+ return {
622
+ MOSTRA_RUNTIME_DIR: join(this.dir, "run"),
623
+ MOSTRA_CONFIG_DIR: join(this.dir, "config"),
624
+ ...this.settings.verify ? {} : { MOSTRA_TEST_UNVERIFIED_PUBLISH: "1" },
625
+ ...extra
626
+ };
627
+ }
628
+ /** `harness/start` on this scenario's home. */
629
+ start(options = {}) {
630
+ mkdirSync(join(this.dir, "run"), {
631
+ recursive: true,
632
+ mode: 448
633
+ });
634
+ return (options.host ?? this.host).startInstance({
635
+ home: this.home,
636
+ env: this.instanceEnv(options.env),
637
+ ...options.mode ? { mode: options.mode } : {}
638
+ });
639
+ }
640
+ /** Stops the host's instance and starts it again (the same home). */
641
+ async restart(options = {}) {
642
+ await this.host.stopInstance();
643
+ return this.start(options);
644
+ }
645
+ /** Writes a fixture into a fresh authoring directory and returns the directory. */
646
+ author(fixture, name = "artifact") {
647
+ this.#published += 1;
648
+ const dir = join(this.dir, "authoring", `${name}-${this.#published}`);
649
+ for (const [path, text] of Object.entries(fixture)) {
650
+ mkdirSync(dirname(join(dir, path)), { recursive: true });
651
+ writeFileSync(join(dir, path), text);
652
+ }
653
+ return dir;
654
+ }
655
+ /** Writes `files` over the authoring directory `dir` (a new version of the same artifact). */
656
+ rewrite(dir, fixture) {
657
+ for (const [path, text] of Object.entries(fixture)) writeFileSync(join(dir, path), text);
658
+ }
659
+ /** Publishes `dir` through the host (`artifact/publish`). */
660
+ publish(dir, options = {}) {
661
+ return this.host.call("artifact/publish", {
662
+ source: { path: dir },
663
+ ...options.policy !== void 0 ? { policy: options.policy } : {},
664
+ ...options.requestId ? { requestId: options.requestId } : {}
665
+ });
666
+ }
667
+ /** Authors and publishes a fixture; the receipt with its authoring directory. */
668
+ async published(fixture, options = {}) {
669
+ const dir = this.author(fixture);
670
+ return {
671
+ ...await this.publish(dir, options),
672
+ dir
673
+ };
674
+ }
675
+ /** A new capability link through the host (`view/url`). */
676
+ async link(artifactId, params = {}) {
677
+ return (await this.host.call("view/url", {
678
+ artifact: { artifactId },
679
+ ...params
680
+ })).url;
681
+ }
682
+ /** Opens a new link as a viewer. */
683
+ async viewer(artifactId, options = {}) {
684
+ return Viewer.open(await this.link(artifactId, options.link ?? {}), { ...options.headers ? { headers: options.headers } : {} });
685
+ }
686
+ /** `results/get` through the host. */
687
+ results(artifactId, submission) {
688
+ return this.host.call("results/get", {
689
+ artifact: { artifactId },
690
+ ...submission ? { submission } : {}
691
+ });
692
+ }
693
+ /** `events/read` through the host. */
694
+ async events(filter, after) {
695
+ return this.host.call("events/read", {
696
+ filter,
697
+ ...after ? { after } : {},
698
+ limit: 100
699
+ });
700
+ }
701
+ /** The host's store. */
702
+ store() {
703
+ return this.host.store();
704
+ }
705
+ /** Waits for `condition` to hold, checking every 100 ms; fails with `what` after `timeoutMs`. */
706
+ async eventually(what, condition, timeoutMs = 3e4) {
707
+ const deadline = Date.now() + timeoutMs;
708
+ for (;;) {
709
+ const value = await condition();
710
+ if (value !== void 0 && value !== false) return value;
711
+ if (Date.now() > deadline) throw new ScenarioFailure(`${what} (waited ${timeoutMs} ms)`);
712
+ await new Promise((done) => setTimeout(done, 100));
713
+ }
714
+ }
715
+ /** Skips the scenario unless the host serves `port`. */
716
+ requirePort(port) {
717
+ if (!this.host.serves(port)) throw new NotApplicable(`the host serves no ${port} port`);
718
+ }
719
+ /** Skips the scenario unless the host supports `feature`. */
720
+ requireFeature(feature) {
721
+ if (!this.host.supports(feature)) throw new NotApplicable(`the host lacks the ${feature} feature`);
722
+ }
723
+ /** The socket of the home's running instance, from `instance.json` (D81). */
724
+ socket() {
725
+ try {
726
+ return JSON.parse(readFileSync(join(this.home, "instance.json"), "utf8")).socket;
727
+ } catch {
728
+ return;
729
+ }
730
+ }
731
+ /** Ends every shim, stops a daemon the scenario left, and removes the directory. */
732
+ async close() {
733
+ for (const host of this.#hosts) {
734
+ await host.stopInstance().catch(() => void 0);
735
+ await host.close().catch(() => void 0);
736
+ }
737
+ const socket = this.socket();
738
+ if (socket) {
739
+ const session = await connectSocket(socket).catch(() => void 0);
740
+ await session?.peer.request("mostra/shutdown", {}, { timeoutMs: 1e4 }).catch(() => void 0);
741
+ session?.close();
742
+ }
743
+ removeTree(this.dir);
744
+ }
745
+ };
746
+ /**
747
+ * Removes a scenario's directory. A home's versions are sealed read-only (files 0444,
748
+ * directories 0555, DATA_MODEL §1), so directories are made writable first.
749
+ */
750
+ function removeTree(dir) {
751
+ const open = (path) => {
752
+ let stats;
753
+ try {
754
+ stats = lstatSync(path);
755
+ } catch {
756
+ return;
757
+ }
758
+ if (!stats.isDirectory()) return;
759
+ chmodSync(path, 448);
760
+ for (const name of readdirSync(path)) open(join(path, name));
761
+ };
762
+ open(dir);
763
+ rmSync(dir, {
764
+ recursive: true,
765
+ force: true,
766
+ maxRetries: 5,
767
+ retryDelay: 200
768
+ });
769
+ }
770
+ /** Connects to an instance's socket and initializes a session as `@mostra/conformance`. */
771
+ async function connectSocket(path, revisions = HOST_PROTOCOL_REVISIONS) {
772
+ const socket = await new Promise((resolve, reject) => {
773
+ const connection = createConnection(path);
774
+ connection.once("connect", () => resolve(connection));
775
+ connection.once("error", reject);
776
+ });
777
+ const peer = new RpcPeer({ send: (message) => {
778
+ if (!socket.destroyed) socket.write(encodeLine(message));
779
+ } });
780
+ const lines = new LineSplitter();
781
+ socket.setEncoding("utf8");
782
+ socket.on("data", (chunk) => {
783
+ for (const line of lines.push(chunk)) peer.receiveLine(line);
784
+ });
785
+ socket.on("error", () => socket.destroy());
786
+ socket.on("close", () => peer.close(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", { message: "socket closed" })));
787
+ const initialize = peer.request("mostra/initialize", {
788
+ client: {
789
+ name: "mostra-conformance",
790
+ version: kitVersion()
791
+ },
792
+ revisions: [...revisions],
793
+ capabilities: {},
794
+ ports: []
795
+ }, { timeoutMs: 1e4 });
796
+ initialize.catch(() => void 0);
797
+ return {
798
+ peer,
799
+ initialize,
800
+ close: () => socket.destroy()
801
+ };
802
+ }
803
+ /** The diagnostic code of a rejected request. */
804
+ function rpcCode(error) {
805
+ return error instanceof RpcError ? error.diagnostic.code : void 0;
806
+ }
807
+ //#endregion
808
+ //#region src/scenarios/delivery.ts
809
+ /**
810
+ * Submissions reaching the host: durable first, delivered whole, once in effect across crashes,
811
+ * retried while the host can't take them, replayed in order when it returns, and never confused
812
+ * with draft mirrors (IN-06, IN-12, H-01, H-03, H-04, H-08).
813
+ */
814
+ /** Publishes the form, answers it and submits on the artifact channel; the submission's ID. */
815
+ async function submitForm(context, fields = {
816
+ name: "Ada",
817
+ comment: "Looks good"
818
+ }) {
819
+ const receipt = await context.published(FORM);
820
+ const viewer = await context.viewer(receipt.artifactId);
821
+ const answer = await viewer.answer(fields, viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell");
822
+ same(answer.status, 200, `the submit's status (${answer.body})`);
823
+ return {
824
+ artifactId: receipt.artifactId,
825
+ submissionId: answer.json().id
826
+ };
827
+ }
828
+ /** The delivery scenarios. */
829
+ const DELIVERY_SCENARIOS = [
830
+ {
831
+ id: "delivery.submission",
832
+ title: "A submission is durable before delivery, reaches the host's submissions port once with the full results, and is readable through results/get",
833
+ covers: [
834
+ "HO-01",
835
+ "HO-05",
836
+ "IN-12",
837
+ "H-01",
838
+ "H-08"
839
+ ],
840
+ async run(context) {
841
+ await context.start();
842
+ const { artifactId, submissionId } = await submitForm(context);
843
+ same((await context.host.call("wait", {
844
+ artifact: { artifactId },
845
+ until: "submitted",
846
+ timeoutMs: 0
847
+ })).status, "satisfied", "wait --until submitted right after the submit");
848
+ if (context.host.serves("submissions")) {
849
+ const stored = await context.eventually("the host's store holds the submission", async () => (await context.store()).deliveries.find((entry) => entry.submissionId === submissionId));
850
+ same(stored.kind, "submission", "the envelope's kind");
851
+ same(stored.stored, 1, "copies the host's store holds");
852
+ check(stored.deliveryId.startsWith("dlv_"), `a delivery ID (${stored.deliveryId})`);
853
+ const results = await context.eventually("the delivery is recorded as delivered", async () => {
854
+ const read = await context.results(artifactId);
855
+ return read.submission.delivery === "delivered" ? read : void 0;
856
+ });
857
+ same(results.submission.id, submissionId, "the submission results/get reads");
858
+ same(results.answers, {
859
+ name: "Ada",
860
+ comment: "Looks good"
861
+ }, "the answers");
862
+ } else same((await context.eventually("the built-in adapter accepts it", async () => {
863
+ const read = await context.results(artifactId);
864
+ return read.submission.delivery === "delivered" ? read : void 0;
865
+ })).answers, {
866
+ name: "Ada",
867
+ comment: "Looks good"
868
+ }, "the answers");
869
+ }
870
+ },
871
+ {
872
+ id: "delivery.exactly-once",
873
+ title: "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",
874
+ covers: [
875
+ "HO-05",
876
+ "IN-12",
877
+ "H-03"
878
+ ],
879
+ async run(context) {
880
+ context.requirePort("submissions");
881
+ await context.start({ env: { MOSTRA_TEST_FAULTS: "deliver:after-answer:crash" } });
882
+ const { artifactId, submissionId } = await submitForm(context);
883
+ const first = await context.eventually("the host received the first attempt", async () => (await context.store()).deliveries.find((entry) => entry.submissionId === submissionId));
884
+ await context.host.stopInstance().catch(() => void 0);
885
+ await context.start();
886
+ const after = await context.eventually("the restarted instance redelivers it", async () => {
887
+ const entry = (await context.store()).deliveries.find((candidate) => candidate.submissionId === submissionId);
888
+ return entry && entry.calls >= 2 ? entry : void 0;
889
+ });
890
+ same(after.deliveryId, first.deliveryId, "the redelivery's deliveryId");
891
+ same(after.stored, 1, "copies the host's store holds after the redelivery");
892
+ check((after.attempts.at(-1) ?? 0) > (after.attempts[0] ?? 0), `the redelivery's attempt counts up (${after.attempts.join(", ")})`);
893
+ same((await context.eventually("the delivery ends delivered", async () => {
894
+ const read = await context.results(artifactId);
895
+ return read.submission.delivery === "delivered" ? read : void 0;
896
+ })).submission.id, submissionId, "the submission");
897
+ }
898
+ },
899
+ {
900
+ id: "delivery.retry",
901
+ title: "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",
902
+ covers: [
903
+ "HO-05",
904
+ "IN-12",
905
+ "H-04"
906
+ ],
907
+ needs: ["faults"],
908
+ async run(context) {
909
+ context.requirePort("submissions");
910
+ await context.start();
911
+ await context.host.script({
912
+ port: "submissions",
913
+ answer: "retry"
914
+ });
915
+ const { artifactId, submissionId } = await submitForm(context);
916
+ await context.eventually("the delivery is pending while the host can't take it", async () => {
917
+ const read = await context.results(artifactId);
918
+ return read.submission.delivery === "pending" ? read : void 0;
919
+ });
920
+ check((await context.events({
921
+ artifacts: [artifactId],
922
+ types: ["submission.retrying"]
923
+ })).events.length > 0, "no submission.retrying event while the delivery waits (IN-13)");
924
+ await context.host.script({
925
+ port: "submissions",
926
+ answer: "accept"
927
+ });
928
+ await context.eventually("the delivery arrives once the host can take it", async () => (await context.store()).deliveries.find((entry) => entry.submissionId === submissionId), 45e3);
929
+ await context.eventually("the delivery ends delivered", async () => {
930
+ const read = await context.results(artifactId);
931
+ return read.submission.delivery === "delivered" ? read : void 0;
932
+ });
933
+ await context.host.script({
934
+ port: "submissions",
935
+ answer: "undeliverable"
936
+ });
937
+ const second = await submitForm(context, { name: "Grace" });
938
+ await context.eventually("the delivery ends undeliverable", async () => {
939
+ const read = await context.results(second.artifactId);
940
+ return read.submission.delivery === "undeliverable" ? read : void 0;
941
+ });
942
+ await context.host.script({
943
+ port: "submissions",
944
+ answer: "accept"
945
+ });
946
+ await new Promise((done) => setTimeout(done, 3e3));
947
+ check(!(await context.store()).deliveries.some((entry) => entry.submissionId === second.submissionId), "an undeliverable delivery was retried");
948
+ }
949
+ },
950
+ {
951
+ id: "delivery.outbox-replay",
952
+ title: "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",
953
+ covers: [
954
+ "HO-05",
955
+ "IN-12",
956
+ "H-04"
957
+ ],
958
+ needs: ["attach"],
959
+ async run(context) {
960
+ context.requirePort("submissions");
961
+ await context.start({ mode: "attach" });
962
+ const first = await context.published(FORM);
963
+ const second = await context.published(FORM);
964
+ const viewers = [await context.viewer(first.artifactId), await context.viewer(second.artifactId)];
965
+ await context.host.stopInstance();
966
+ const submissions = [];
967
+ for (const viewer of viewers) {
968
+ const channel = viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell";
969
+ const answer = await viewer.answer({ name: `Ada ${submissions.length + 1}` }, channel);
970
+ same(answer.status, 200, `a submit while the host is away (${answer.body})`);
971
+ submissions.push(answer.json().id);
972
+ }
973
+ const socket = context.socket();
974
+ check(socket, "the daemon kept the home but left no instance.json to find it by");
975
+ const kit = await connectSocket(socket);
976
+ await kit.initialize;
977
+ const pending = await kit.peer.request("results/get", { artifact: { artifactId: first.artifactId } });
978
+ kit.close();
979
+ same(pending.submission.delivery, "pending", "a delivery while its host is away");
980
+ check((await context.store()).deliveries.length === 0, "the host received a delivery while it was away");
981
+ await context.start({ mode: "attach" });
982
+ const store = await context.eventually("both deliveries replay", async () => {
983
+ const read = await context.store();
984
+ return read.deliveries.length >= 2 ? read : void 0;
985
+ });
986
+ same(store.deliveries.map((entry) => entry.submissionId), submissions, "the replay's order (submission order)");
987
+ check(store.deliveries.every((entry) => entry.stored === 1), "a replayed delivery stored twice");
988
+ await context.host.stopInstance();
989
+ }
990
+ },
991
+ {
992
+ id: "drafts.mirror",
993
+ title: "Draft revisions reach the host only through drafts.mirror, labelled kind: draft, and never through the submissions port",
994
+ covers: [
995
+ "HO-01",
996
+ "HO-05",
997
+ "IN-06",
998
+ "H-01"
999
+ ],
1000
+ async run(context) {
1001
+ await context.start();
1002
+ const receipt = await context.published(FORM);
1003
+ const viewer = await context.viewer(receipt.artifactId);
1004
+ const written = await viewer.write({ name: "Ada" });
1005
+ same(written.status, 200, "a draft write");
1006
+ if (context.host.serves("drafts")) same((await context.eventually("the host receives the draft's mirror", async () => (await context.store()).drafts.find((entry) => entry.artifactId === receipt.artifactId))).kind, "draft", "the mirror's kind");
1007
+ const before = await context.store();
1008
+ check(before.deliveries.every((entry) => entry.kind === "submission") && !before.deliveries.some((entry) => entry.artifactId === receipt.artifactId), "a draft reached the host as a delivery before any submit (IN-06)");
1009
+ const { revision } = written.json();
1010
+ same((await (viewer.ticket.submitChannels.includes("artifact") ? viewer.submit(revision) : viewer.shellSubmit(revision))).status, 200, "the submit");
1011
+ if (context.host.serves("submissions")) {
1012
+ await context.eventually("the submission arrives", async () => (await context.store()).deliveries.find((entry) => entry.artifactId === receipt.artifactId));
1013
+ const after = await context.store();
1014
+ same(after.deliveries.filter((entry) => entry.artifactId === receipt.artifactId).length, 1, "deliveries for the artifact");
1015
+ check(after.deliveries.every((entry) => entry.kind === "submission"), "the host stores something that isn't a submission as one (IN-06)");
1016
+ }
1017
+ }
1018
+ }
1019
+ ];
1020
+ //#endregion
1021
+ //#region src/scenarios/interaction.ts
1022
+ /**
1023
+ * The interaction model a host builds on: submission policies, events with durable cursors,
1024
+ * signals, waits, artifact state, complete results, idempotent requests and durability across
1025
+ * restarts (IN-07 to IN-10, LL-02, H-02, H-03, H-06 to H-10).
1026
+ */
1027
+ /** Answers and submits on whichever channel the view allows. */
1028
+ async function answerAndSubmit(viewer, fields) {
1029
+ return viewer.answer(fields, viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell");
1030
+ }
1031
+ async function code(answer) {
1032
+ return answer.json().code;
1033
+ }
1034
+ /** The interaction scenarios. */
1035
+ const INTERACTION_SCENARIOS = [
1036
+ {
1037
+ id: "interaction.policies",
1038
+ title: "once per artifact answers a second submit with MOSTRA_SUBMIT_ALREADY and the existing submission; once per viewer, epochs and none behave as specified",
1039
+ covers: [
1040
+ "HO-05",
1041
+ "IN-07",
1042
+ "LL-02",
1043
+ "H-02"
1044
+ ],
1045
+ async run(context) {
1046
+ await context.start();
1047
+ const once = await context.published(FORM, { policy: { policy: "once" } });
1048
+ const accepted = await answerAndSubmit(await context.viewer(once.artifactId), { name: "Ada" });
1049
+ same(accepted.status, 200, "the first submit under once");
1050
+ const conflict = await answerAndSubmit(await context.viewer(once.artifactId), { name: "Grace" });
1051
+ check(conflict.status === 409, `a second submit under once answered ${conflict.status}`);
1052
+ same(await code(conflict), "MOSTRA_SUBMIT_ALREADY", "a second submit's code");
1053
+ same(conflict.json().submission?.id, accepted.json().id, "the existing submission carried beside the conflict");
1054
+ const survey = await context.published(FORM, { policy: {
1055
+ policy: "once",
1056
+ scope: "per-viewer"
1057
+ } });
1058
+ for (const ref of ["ada@example.com", "grace@example.com"]) same((await answerAndSubmit(await context.viewer(survey.artifactId, { link: { viewer: { ref } } }), { name: ref })).status, 200, `${ref}'s submit`);
1059
+ same(await code(await answerAndSubmit(await context.viewer(survey.artifactId, { link: { viewer: { ref: "ada@example.com" } } }), { name: "again" })), "MOSTRA_SUBMIT_ALREADY", "a person's second submit");
1060
+ const rounds = await context.published(FORM, { policy: { policy: "epochs" } });
1061
+ const person = await context.viewer(rounds.artifactId, { link: { viewer: { ref: "ada" } } });
1062
+ const one = (await answerAndSubmit(person, { name: "round 1" })).json();
1063
+ const revision = (await person.write({ name: "round 2" }, { baseRevision: "1" })).json().revision;
1064
+ const twoAnswer = await (person.ticket.submitChannels.includes("artifact") ? person.submit(revision) : person.shellSubmit(revision));
1065
+ same(twoAnswer.status, 200, "the second round's submit");
1066
+ const two = twoAnswer.json();
1067
+ same([one.epoch, two.epoch], [1, 2], "the rounds' epochs");
1068
+ same((await context.results(rounds.artifactId, two.id)).submission.previous, one.id, "the second round's previous submission");
1069
+ const board = await context.published(FORM, { policy: { policy: "none" } });
1070
+ const viewer = await context.viewer(board.artifactId);
1071
+ same(viewer.ticket.policy.policy, "none", "the view's policy");
1072
+ same(await code(await answerAndSubmit(viewer, { name: "x" })), "MOSTRA_SUBMIT_POLICY_NONE", "a submit under none");
1073
+ same(await context.host.call("wait", {
1074
+ artifact: { artifactId: board.artifactId },
1075
+ until: "submitted",
1076
+ timeoutMs: 0
1077
+ }).then(() => void 0, (error) => codeOf(error)), "MOSTRA_SUBMIT_POLICY_NONE", "wait --until submitted under none");
1078
+ }
1079
+ },
1080
+ {
1081
+ id: "events.subscription",
1082
+ title: "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",
1083
+ covers: [
1084
+ "HO-01",
1085
+ "HO-05",
1086
+ "IN-08",
1087
+ "H-09"
1088
+ ],
1089
+ needs: ["events"],
1090
+ async run(context) {
1091
+ await context.start();
1092
+ const name = "conformance-host";
1093
+ const filter = { types: ["submission.created"] };
1094
+ same((await context.host.events({
1095
+ name,
1096
+ filter,
1097
+ pages: 1,
1098
+ timeoutMs: 500
1099
+ })).pages.length, 0, "pages for a new name");
1100
+ const submit = async (who) => {
1101
+ const receipt = await context.published(FORM);
1102
+ return (await answerAndSubmit(await context.viewer(receipt.artifactId), { name: who })).json().id;
1103
+ };
1104
+ const first = await submit("Ada");
1105
+ const events = (await context.host.events({
1106
+ name,
1107
+ filter,
1108
+ pages: 1,
1109
+ timeoutMs: 1e4
1110
+ })).pages.flatMap((page) => page.events);
1111
+ same(events.map((event) => event.type), ["submission.created"], "the filtered stream's events");
1112
+ same((events[0]?.["payload"])?.submissionId, first, "the submission it names");
1113
+ await context.restart();
1114
+ const second = await submit("Grace");
1115
+ const after = (await context.host.events({
1116
+ name,
1117
+ filter,
1118
+ pages: 1,
1119
+ timeoutMs: 1e4
1120
+ })).pages.flatMap((page) => page.events);
1121
+ same(after.map((event) => event["payload"].submissionId), [second], "the resumed stream: the next submission, no repeat, no gap");
1122
+ const cursors = [...events, ...after].map((event) => BigInt(event.cursor));
1123
+ check(cursors.every((cursor, i) => i === 0 || cursor > cursors[i - 1]), "cursors in order");
1124
+ }
1125
+ },
1126
+ {
1127
+ id: "events.signals",
1128
+ title: "A page's signal and every submit appear as signal.raised events the host filters; Mostra calls no port and wakes nobody for them",
1129
+ covers: [
1130
+ "HO-05",
1131
+ "IN-09",
1132
+ "H-09"
1133
+ ],
1134
+ async run(context) {
1135
+ await context.start();
1136
+ const receipt = await context.published(FORM);
1137
+ const viewer = await context.viewer(receipt.artifactId);
1138
+ const before = await context.store();
1139
+ same((await viewer.signal("ping", { n: 1 })).status, 200, "a page's signal");
1140
+ const ping = (await context.events({
1141
+ artifacts: [receipt.artifactId],
1142
+ types: ["signal.raised"]
1143
+ })).events.find((event) => event.payload?.["name"] === "ping");
1144
+ check(ping, "no signal.raised for the page's signal");
1145
+ same(ping.payload["source"], "artifact", "the signal's source");
1146
+ same(ping.payload["payload"], { n: 1 }, "the signal's payload");
1147
+ const after = await context.store();
1148
+ same(after.deliveries.length, before.deliveries.length, "deliveries a signal caused");
1149
+ same(after.drafts.length, before.drafts.length, "draft mirrors a signal caused");
1150
+ same((await answerAndSubmit(viewer, { name: "Ada" })).status, 200, "the submit");
1151
+ check((await context.events({
1152
+ artifacts: [receipt.artifactId],
1153
+ types: ["signal.*"]
1154
+ })).events.some((event) => event.payload?.["name"] === "submit"), "a submit raises no signal.raised named submit (D106)");
1155
+ }
1156
+ },
1157
+ {
1158
+ id: "interaction.wait",
1159
+ title: "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",
1160
+ covers: ["HO-05", "IN-10"],
1161
+ async run(context) {
1162
+ await context.start();
1163
+ const receipt = await context.published(FORM);
1164
+ const artifact = { artifactId: receipt.artifactId };
1165
+ const timedOut = await context.host.call("wait", {
1166
+ artifact,
1167
+ until: "signal:ping",
1168
+ timeoutMs: 0
1169
+ });
1170
+ same(timedOut.status, "still_waiting", "a wait that times out");
1171
+ const viewer = await context.viewer(receipt.artifactId);
1172
+ await viewer.signal("ping");
1173
+ const caught = await context.host.call("wait", {
1174
+ artifact,
1175
+ until: "signal:ping",
1176
+ after: timedOut.cursor,
1177
+ timeoutMs: 1e4
1178
+ });
1179
+ same(caught.status, "satisfied", "a wait after the cursor of a timed-out wait");
1180
+ same((await context.host.call("wait", {
1181
+ artifact,
1182
+ until: "signal:ping",
1183
+ after: caught.cursor,
1184
+ timeoutMs: 0
1185
+ })).status, "still_waiting", "the same signal waited for after its own cursor");
1186
+ const state = context.host.call("wait", {
1187
+ artifact,
1188
+ until: "state:done",
1189
+ after: caught.cursor,
1190
+ timeoutMs: 15e3
1191
+ });
1192
+ await context.host.call("state/patch", {
1193
+ artifact,
1194
+ ops: [{
1195
+ id: "done",
1196
+ value: true
1197
+ }],
1198
+ mutationId: "mut_01JB8Z3QF6S7W3N8D5K2C4V9XC",
1199
+ as: "host"
1200
+ });
1201
+ same((await state).status, "satisfied", "a state wait when the host sets the field");
1202
+ await answerAndSubmit(viewer, { name: "Ada" });
1203
+ const level = await context.host.call("wait", {
1204
+ artifact,
1205
+ until: "submitted",
1206
+ timeoutMs: 0
1207
+ });
1208
+ same(level.status, "satisfied", "submitted, after the fact, under once (level-triggered)");
1209
+ same((await context.host.call("wait", {
1210
+ artifact,
1211
+ until: "submitted",
1212
+ after: level.cursor,
1213
+ timeoutMs: 0
1214
+ })).status, "satisfied", "submitted after a later cursor, under once per artifact");
1215
+ }
1216
+ },
1217
+ {
1218
+ id: "interaction.long-lived-state",
1219
+ title: "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",
1220
+ covers: [
1221
+ "HO-05",
1222
+ "LL-02",
1223
+ "IN-07"
1224
+ ],
1225
+ async run(context) {
1226
+ await context.start();
1227
+ const receipt = await context.published(FORM, { policy: { policy: "none" } });
1228
+ const artifact = { artifactId: receipt.artifactId };
1229
+ const hostWrite = await context.host.call("state/patch", {
1230
+ artifact,
1231
+ ops: [{
1232
+ id: "count",
1233
+ value: 1
1234
+ }],
1235
+ mutationId: "mut_01JB8Z3QF6S7W3N8D5K2C4V9XD",
1236
+ as: "host"
1237
+ });
1238
+ const viewer = await context.viewer(receipt.artifactId);
1239
+ const stale = await viewer.write({ count: 5 }, {
1240
+ scope: "artifact",
1241
+ baseRevision: "0"
1242
+ });
1243
+ same(stale.status, 200, "a stale viewer write's status");
1244
+ const conflicts = stale.json().conflicts;
1245
+ same(conflicts.map((conflict) => conflict.id), ["count"], "the viewer's conflicts");
1246
+ same((await viewer.write({ count: 2 }, {
1247
+ scope: "artifact",
1248
+ baseRevision: hostWrite.revision
1249
+ })).json().conflicts, [], "a viewer write on the current revision");
1250
+ same((await context.host.call("state/patch", {
1251
+ artifact,
1252
+ ops: [{
1253
+ id: "count",
1254
+ value: 9
1255
+ }],
1256
+ baseRevision: hostWrite.revision,
1257
+ mutationId: "mut_01JB8Z3QF6S7W3N8D5K2C4V9XE",
1258
+ as: "host"
1259
+ })).conflicts.map((conflict) => conflict.id), ["count"], "the host's conflicts on a field a viewer changed");
1260
+ same((await context.host.call("state/get", { artifact })).fields["count"]?.value, 2, "the shared state");
1261
+ same((await context.events({
1262
+ artifacts: [receipt.artifactId],
1263
+ types: ["state.changed"]
1264
+ })).events.length, 2, "state.changed events (one per applied write)");
1265
+ }
1266
+ },
1267
+ {
1268
+ id: "interaction.results",
1269
+ title: "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",
1270
+ covers: [
1271
+ "HO-05",
1272
+ "IN-11",
1273
+ "H-06",
1274
+ "H-08",
1275
+ "H-10"
1276
+ ],
1277
+ async run(context) {
1278
+ await context.start();
1279
+ const v1 = await context.published(FORM);
1280
+ const viewer = await context.viewer(v1.artifactId);
1281
+ context.rewrite(v1.dir, FORM_V2);
1282
+ same((await context.publish(v1.dir)).version, 2, "the second version's number");
1283
+ same((await viewer.answer({
1284
+ name: "Ada",
1285
+ comment: "on the first version"
1286
+ }, viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell", {
1287
+ name: "Your name",
1288
+ comment: "Comment"
1289
+ })).status, 200, "a submit from the older view");
1290
+ const read = await context.results(v1.artifactId);
1291
+ same(read.artifact.family, "questionnaire", "the artifact's family");
1292
+ same(read.artifact.links, [{
1293
+ rel: "round-of",
1294
+ artifact: "conformance-round-1"
1295
+ }], "its links");
1296
+ const submission = read.submission;
1297
+ same([submission.versionId, submission.version], [v1.versionId, 1], "the version the viewer saw");
1298
+ same(submission.viewId, viewer.viewId, "the view");
1299
+ same([submission.staleView, submission.latestVersion], [true, 2], "the stale view and the newer version");
1300
+ same(read.answers, {
1301
+ name: "Ada",
1302
+ comment: "on the first version"
1303
+ }, "the answers");
1304
+ check(read.fields.some((field) => field.id === "name" && field.label === "Your name"), "the answers' labels");
1305
+ check((await context.host.call("results/get", {
1306
+ artifact: { artifactId: v1.artifactId },
1307
+ format: "md"
1308
+ })).markdown.includes("Your name"), "the Markdown results name answers by label");
1309
+ }
1310
+ },
1311
+ {
1312
+ id: "interaction.request-ids",
1313
+ title: "A retried request with the same requestId or mutationId returns the recorded result; the same ID with other parameters is refused",
1314
+ covers: ["HO-05", "H-03"],
1315
+ async run(context) {
1316
+ await context.start();
1317
+ const dir = context.author(FORM);
1318
+ const first = await context.publish(dir, { requestId: "req-publish-1" });
1319
+ same(await context.publish(dir, { requestId: "req-publish-1" }), first, "a retried publish's receipt");
1320
+ same(await context.publish(dir, {
1321
+ requestId: "req-publish-1",
1322
+ policy: { policy: "epochs" }
1323
+ }).then(() => void 0, (error) => codeOf(error)), "MOSTRA_HOST_REQUEST_ID_REUSED", "a request ID reused with other parameters");
1324
+ const patch = {
1325
+ artifact: { artifactId: first.artifactId },
1326
+ ops: [{
1327
+ id: "count",
1328
+ value: 3
1329
+ }],
1330
+ mutationId: "mut_01JB8Z3QF6S7W3N8D5K2C4V9XF",
1331
+ as: "host"
1332
+ };
1333
+ const once = await context.host.call("state/patch", patch);
1334
+ same(await context.host.call("state/patch", patch), once, "a retried state/patch");
1335
+ const link = {
1336
+ artifact: { artifactId: first.artifactId },
1337
+ requestId: "req-link-1"
1338
+ };
1339
+ same((await context.host.call("view/url", link)).url, (await context.host.call("view/url", link)).url, "a retried view/url");
1340
+ }
1341
+ },
1342
+ {
1343
+ id: "interaction.durability",
1344
+ title: "Everything acknowledged (versions, drafts, state, submissions, events) survives the instance stopping and starting again",
1345
+ covers: [
1346
+ "HO-05",
1347
+ "IN-12",
1348
+ "H-04"
1349
+ ],
1350
+ async run(context) {
1351
+ await context.start();
1352
+ const receipt = await context.published(FORM);
1353
+ const viewer = await context.viewer(receipt.artifactId);
1354
+ await viewer.write({ comment: "a draft only" });
1355
+ await context.host.call("state/patch", {
1356
+ artifact: { artifactId: receipt.artifactId },
1357
+ ops: [{
1358
+ id: "count",
1359
+ value: 7
1360
+ }],
1361
+ mutationId: "mut_01JB8Z3QF6S7W3N8D5K2C4V9XG",
1362
+ as: "host"
1363
+ });
1364
+ same((await answerAndSubmit(await context.viewer(receipt.artifactId, { link: { viewer: { ref: "ada" } } }), { name: "Ada" })).status, 200, "the submit");
1365
+ const before = await context.results(receipt.artifactId);
1366
+ const eventsBefore = await context.events({ artifacts: [receipt.artifactId] });
1367
+ await context.restart();
1368
+ same((await context.results(receipt.artifactId)).submission.digest, before.submission.digest, "the submission's digest after a restart");
1369
+ same((await context.host.call("state/get", { artifact: { artifactId: receipt.artifactId } })).fields["count"]?.value, 7, "artifact state after a restart");
1370
+ same((await context.events({ artifacts: [receipt.artifactId] })).events.slice(0, eventsBefore.events.length).map((event) => event.cursor), eventsBefore.events.map((event) => event.cursor), "the event log after a restart");
1371
+ same((await viewer.poll()).json().snapshot?.draft?.fields?.["comment"]?.value, "a draft only", "the viewer's draft after a restart");
1372
+ }
1373
+ }
1374
+ ];
1375
+ /** The port scenarios. */
1376
+ const PORT_SCENARIOS = [
1377
+ {
1378
+ id: "ports.identity",
1379
+ title: "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",
1380
+ covers: [
1381
+ "HO-01",
1382
+ "HO-05",
1383
+ "H-05",
1384
+ "H-14"
1385
+ ],
1386
+ async run(context) {
1387
+ await context.start();
1388
+ const receipt = await context.published(FORM, { policy: { policy: "epochs" } });
1389
+ const headers = {
1390
+ "x-forwarded-user": "ada@example.com",
1391
+ cookie: "elsewhere=1",
1392
+ "x-mostra-csrf": "not-for-the-host"
1393
+ };
1394
+ const viewer = await context.viewer(receipt.artifactId, { headers });
1395
+ const channel = viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell";
1396
+ same((await viewer.answer({ name: "Ada" }, channel)).status, 200, "the submit");
1397
+ const read = await context.results(receipt.artifactId);
1398
+ if (!context.host.serves("identity")) {
1399
+ same(read.submission.viewer.kind, "local", "the viewer without an identity port");
1400
+ return;
1401
+ }
1402
+ const calls = (await context.store()).identity;
1403
+ const call = calls.at(-1);
1404
+ check(call, "the host's identity port was never asked");
1405
+ check(call.answer !== void 0, "the host's store doesn't report what its identity port answered (harness/store)");
1406
+ same(call.answer === null ? [read.submission.viewer.kind] : [read.submission.viewer.kind, read.submission.viewer.ref], call.answer === null ? ["local"] : ["host", call.answer.ref], "the submission's viewer, by the host's answer");
1407
+ same(call.via, "local", "how the request reached the gateway");
1408
+ check(call.headers.includes("x-forwarded-user"), "the port didn't receive the request's headers");
1409
+ check(!call.headers.some((name) => name === "cookie" || name.startsWith("x-mostra-")), `the port received Mostra's credentials (${call.headers.join(", ")})`);
1410
+ const minted = await context.viewer(receipt.artifactId, {
1411
+ link: { viewer: {
1412
+ ref: "grace@example.com",
1413
+ name: "Grace"
1414
+ } },
1415
+ headers
1416
+ });
1417
+ same((await context.store()).identity.length, calls.length, "identity calls for a link with a viewer");
1418
+ same((await minted.answer({ name: "Grace" }, channel)).status, 200, "the minted link's submit");
1419
+ const graces = await context.results(receipt.artifactId);
1420
+ same([graces.submission.viewer.kind, graces.submission.viewer.ref], ["token", "grace@example.com"], "the viewer a link was minted for");
1421
+ if (context.host.supports("faults")) {
1422
+ await context.host.script({
1423
+ port: "identity",
1424
+ answer: "fail"
1425
+ });
1426
+ const refused = await context.viewer(receipt.artifactId, { headers }).then(() => void 0, (error) => error);
1427
+ check(refused instanceof OpenError, "a failing identity port still opened the link");
1428
+ same([refused.status, refused.code], [503, "MOSTRA_HOST_IDENTITY_UNAVAILABLE"], "the refusal");
1429
+ await context.host.script({
1430
+ port: "identity",
1431
+ answer: null
1432
+ });
1433
+ same((await (await context.viewer(receipt.artifactId, { headers })).answer({ name: "local" }, channel)).status, 200, "a submit as the local user");
1434
+ same((await context.results(receipt.artifactId)).submission.viewer.kind, "local", "a null answer's viewer");
1435
+ }
1436
+ }
1437
+ },
1438
+ {
1439
+ id: "ports.trusted-controls",
1440
+ title: "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",
1441
+ covers: [
1442
+ "HO-01",
1443
+ "HO-05",
1444
+ "SH-02",
1445
+ "H-05"
1446
+ ],
1447
+ async run(context) {
1448
+ await context.start();
1449
+ if (!context.host.serves("trustedControls")) {
1450
+ const receipt = await context.published(FORM);
1451
+ const viewer = await context.viewer(receipt.artifactId);
1452
+ same([...viewer.ticket.submitChannels].sort(), ["artifact", "shell"], "the standalone channels (D40)");
1453
+ same((await viewer.answer({ name: "Ada" }, "artifact")).status, 200, "an artifact-channel submit");
1454
+ same((await context.results(receipt.artifactId)).submission.channel, "artifact", "the recorded channel");
1455
+ return;
1456
+ }
1457
+ const scripted = context.host.supports("faults") ? {
1458
+ submitChannels: ["shell"],
1459
+ controls: ["submit"]
1460
+ } : void 0;
1461
+ if (scripted) await context.host.script({
1462
+ port: "trustedControls",
1463
+ answer: scripted
1464
+ });
1465
+ const receipt = await context.published(FORM);
1466
+ const viewer = await context.viewer(receipt.artifactId);
1467
+ const asked = (await context.store()).policies.find((entry) => entry.artifactId === receipt.artifactId);
1468
+ check(asked, "the host's policy wasn't asked when the view opened");
1469
+ const policy = scripted ?? asked.answer;
1470
+ check(policy, "the host's store doesn't report what its trustedControls policy answered (harness/store)");
1471
+ same([...viewer.ticket.submitChannels].sort(), [...policy.submitChannels].sort(), "the view's channels under the host's policy");
1472
+ const revision = (await viewer.write({ name: "Ada" })).json().revision;
1473
+ if (!policy.submitChannels.includes("artifact")) {
1474
+ const denied = await viewer.submit(revision);
1475
+ same([denied.status, denied.json().code], [403, "MOSTRA_SUBMIT_CHANNEL_DENIED"], "the artifact channel's submit");
1476
+ }
1477
+ if (!policy.submitChannels.includes("shell")) {
1478
+ same((await viewer.submit(revision)).status, 200, "the artifact channel's submit");
1479
+ same((await context.results(receipt.artifactId)).submission.channel, "artifact", "the recorded channel");
1480
+ return;
1481
+ }
1482
+ same((await viewer.shellSubmit(revision)).status, 200, "the shell's trusted Submit");
1483
+ same((await context.results(receipt.artifactId)).submission.channel, "shell", "the recorded channel");
1484
+ const activation = await context.eventually("the host hears the trusted Submit was used", async () => (await context.store()).activations.find((entry) => entry.artifactId === receipt.artifactId));
1485
+ same([activation.control, activation.viewId], ["submit", viewer.viewId], "the activation");
1486
+ if (context.host.supports("faults")) {
1487
+ await context.host.script({
1488
+ port: "trustedControls",
1489
+ answer: "fail"
1490
+ });
1491
+ const other = await context.published(FORM);
1492
+ same((await context.viewer(other.artifactId)).ticket.submitChannels, ["shell"], "the channels when the host's policy fails");
1493
+ }
1494
+ }
1495
+ },
1496
+ {
1497
+ id: "ports.secrets",
1498
+ title: "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",
1499
+ covers: ["HO-01", "HO-05"],
1500
+ async run(context) {
1501
+ await context.start();
1502
+ await context.host.call("secret/set", {
1503
+ name: "HOME_ONLY",
1504
+ value: "from-the-home-store"
1505
+ });
1506
+ const receipt = await context.published(ACTIONS);
1507
+ const viewer = await context.viewer(receipt.artifactId);
1508
+ const fromHome = await viewer.run("actions.ts#secretLength", ["HOME_ONLY"]);
1509
+ same(fromHome.status, "succeeded", `a run reading the home's secret (${JSON.stringify(fromHome["error"] ?? "")})`);
1510
+ same(await resultOf(fromHome), 19, "the home secret's length");
1511
+ if (context.host.serves("secrets") && context.host.supports("faults")) {
1512
+ await context.host.script({
1513
+ port: "secrets",
1514
+ answer: { API_KEY: "s3cret-from-the-host" }
1515
+ });
1516
+ same(await resultOf(await viewer.run("actions.ts#secretLength", ["API_KEY"])), 20, "the host secret's length");
1517
+ check((await context.store()).secrets.some((entry) => entry.name === "API_KEY"), "the host's secrets port wasn't asked");
1518
+ const events = await context.events({ artifacts: [receipt.artifactId] });
1519
+ check(!JSON.stringify(events).includes("s3cret-from-the-host"), "a secret reached the event log");
1520
+ }
1521
+ }
1522
+ },
1523
+ {
1524
+ id: "ports.server-events",
1525
+ title: "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",
1526
+ covers: [
1527
+ "HO-05",
1528
+ "IN-09",
1529
+ "AC-05",
1530
+ "H-09"
1531
+ ],
1532
+ async run(context) {
1533
+ await context.start();
1534
+ const receipt = await context.published(ACTIONS);
1535
+ const viewer = await context.viewer(receipt.artifactId);
1536
+ const before = await context.store();
1537
+ const run = await viewer.run("actions.ts#notify", ["ada@example.com"]);
1538
+ same(run.status, "succeeded", `the action run (${JSON.stringify(run["error"] ?? "")})`);
1539
+ const read = await context.events({
1540
+ artifacts: [receipt.artifactId],
1541
+ types: [
1542
+ "signal.raised",
1543
+ "host.*",
1544
+ "action.*"
1545
+ ]
1546
+ });
1547
+ const types = read.events.map((event) => event.type);
1548
+ const signal = read.events.find((event) => event.type === "signal.raised");
1549
+ const emitted = read.events.find((event) => event.type === "host.mail.sent");
1550
+ check(signal && emitted, `the run's signal or host event is missing (${types.join(", ")})`);
1551
+ same([signal.payload["name"], signal.payload["source"]], ["mail.sent", "action"], "the signal");
1552
+ same(signal.causation?.["runId"], run.runId, "the signal's causing run");
1553
+ same(emitted.payload["data"], { to: "ada@example.com" }, "the host event's data");
1554
+ const started = types.indexOf("action.started");
1555
+ const ended = types.indexOf("action.succeeded");
1556
+ check(started >= 0 && ended > types.indexOf("host.mail.sent") && started < types.indexOf("signal.raised"), `the order of the run's events (${types.join(", ")})`);
1557
+ same((await context.store()).deliveries.length, before.deliveries.length, "deliveries the run caused");
1558
+ }
1559
+ }
1560
+ ];
1561
+ /** The session scenarios. */
1562
+ const SESSION_SCENARIOS = [
1563
+ {
1564
+ id: "session.negotiation",
1565
+ title: "The host negotiates a revision the instance speaks, registers only ports it supports, and an instance refuses a client with no common revision",
1566
+ covers: [
1567
+ "HO-02",
1568
+ "HO-05",
1569
+ "H-13",
1570
+ "H-15"
1571
+ ],
1572
+ async run(context) {
1573
+ const started = await context.start();
1574
+ check(HOST_PROTOCOL_REVISIONS.includes(started.revision), `the negotiated revision ${started.revision} isn't one this kit knows (${HOST_PROTOCOL_REVISIONS.join(", ")})`);
1575
+ check(started.warnings.filter((warning) => warning.code === "MOSTRA_HOST_PORT_UNSUPPORTED").length === 0, "the host registers a port the instance doesn't support (MOSTRA_HOST_PORT_UNSUPPORTED)");
1576
+ const again = await context.host.callRaw("mostra/initialize", {
1577
+ client: {
1578
+ name: "again",
1579
+ version: "0"
1580
+ },
1581
+ revisions: [...HOST_PROTOCOL_REVISIONS],
1582
+ capabilities: {},
1583
+ ports: []
1584
+ });
1585
+ check("error" in again, "a second mostra/initialize on the host's connection was accepted");
1586
+ same(again.error.data.code, "MOSTRA_HOST_INITIALIZE_ORDER", "a second initialize's code");
1587
+ const socket = context.socket();
1588
+ check(socket, "the instance's home has no instance.json naming its socket (D81)");
1589
+ const old = await connectSocket(socket, ["2020-01-01"]);
1590
+ const refused = await old.initialize.then(() => void 0, (error) => rpcCode(error));
1591
+ old.close();
1592
+ same(refused, "MOSTRA_HOST_REVISION_UNSUPPORTED", "a client offering only 2020-01-01");
1593
+ const mixed = await connectSocket(socket, ["2020-01-01", ...HOST_PROTOCOL_REVISIONS]);
1594
+ const answer = await mixed.initialize;
1595
+ mixed.close();
1596
+ same(answer.revision, started.revision, "the revision negotiated with an older and a current one");
1597
+ }
1598
+ },
1599
+ {
1600
+ id: "session.process-models",
1601
+ title: "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",
1602
+ covers: [
1603
+ "HO-05",
1604
+ "RT-06",
1605
+ "H-12"
1606
+ ],
1607
+ async run(context) {
1608
+ const second = await context.anotherHost();
1609
+ if (context.host.supports("attach")) {
1610
+ const first = await context.start({ mode: "attach" });
1611
+ same(first.instance.mode, "daemon", "an attached host's instance mode");
1612
+ same((await context.start({
1613
+ mode: "attach",
1614
+ host: second
1615
+ })).instance.pid, first.instance.pid, "the daemon two attached hosts reach");
1616
+ const third = await context.anotherHost();
1617
+ same(await context.start({ host: third }).then(() => void 0, (error) => codeOf(error)), "MOSTRA_HOME_LOCKED", "a spawn while the daemon owns the home");
1618
+ await second.stopInstance();
1619
+ await context.host.stopInstance();
1620
+ return;
1621
+ }
1622
+ const first = await context.start();
1623
+ same(first.instance.mode, "host", "a spawned instance's mode");
1624
+ same(first.instance.pid > 0, true, "the instance reports its PID");
1625
+ same(await context.start({ host: second }).then(() => void 0, (error) => codeOf(error)), "MOSTRA_HOME_LOCKED", "a second spawn of the same home");
1626
+ }
1627
+ },
1628
+ {
1629
+ id: "home.authoring-removed",
1630
+ title: "The host chooses the home; artifacts, versions and submissions stay readable after the authoring directory is removed",
1631
+ covers: [
1632
+ "HO-05",
1633
+ "HO-08",
1634
+ "H-11"
1635
+ ],
1636
+ async run(context) {
1637
+ same((await context.start()).instance.home, realpathSync(context.home), "the home the instance owns");
1638
+ const receipt = await context.published(FORM);
1639
+ const viewer = await context.viewer(receipt.artifactId);
1640
+ const channel = viewer.ticket.submitChannels.includes("artifact") ? "artifact" : "shell";
1641
+ same((await viewer.answer({
1642
+ name: "Ada",
1643
+ comment: "kept"
1644
+ }, channel)).status, 200, "the submit's status");
1645
+ const before = await context.results(receipt.artifactId);
1646
+ rmSync(receipt.dir, {
1647
+ recursive: true,
1648
+ force: true
1649
+ });
1650
+ await context.restart();
1651
+ same((await context.host.call("artifact/get", { artifact: { artifactId: receipt.artifactId } })).versions[0]?.id, receipt.versionId, "the version, by artifact ID");
1652
+ same((await context.host.call("artifact/get", { artifact: { path: receipt.dir } })).id, receipt.artifactId, "the artifact its deleted path still names");
1653
+ const after = await context.results(receipt.artifactId);
1654
+ same(after.submission.digest, before.submission.digest, "the submission's digest");
1655
+ same(after.answers, before.answers, "the submission's answers");
1656
+ const again = await context.viewer(receipt.artifactId);
1657
+ same((await again.browser.ask({
1658
+ url: `${again.ticket.artifactOrigin}/`,
1659
+ headers: {
1660
+ accept: "text/html",
1661
+ "sec-fetch-site": "same-origin",
1662
+ "sec-fetch-dest": "iframe"
1663
+ }
1664
+ })).status, 200, "the version's page after the source is gone");
1665
+ check(statSync(join(context.home, "sources", receipt.artifactId)).isDirectory(), "the home keeps the version's source snapshot (DATA_MODEL §1)");
1666
+ }
1667
+ },
1668
+ {
1669
+ id: "home.privacy",
1670
+ title: "A host's home is marked host-configured (no telemetry), owner-only (0700, secrets 0600), and its gateway binds loopback",
1671
+ covers: [
1672
+ "HO-05",
1673
+ "H-16",
1674
+ "EN-08"
1675
+ ],
1676
+ async run(context) {
1677
+ const started = await context.start();
1678
+ check(JSON.parse(readFileSync(join(context.home, "config.json"), "utf8")).hostConfigured, "config.json has no hostConfigured mark (D140 item 4)");
1679
+ same(statSync(context.home).mode & 511, 448, "the home's mode");
1680
+ await context.host.call("secret/set", {
1681
+ name: "CONFORMANCE_TOKEN",
1682
+ value: "kept-private-123"
1683
+ });
1684
+ same(statSync(join(context.home, "secrets", "home", "CONFORMANCE_TOKEN")).mode & 511, 384, "a secret's mode");
1685
+ const status = await context.host.call("instance/status", {});
1686
+ same(status.gateway?.bind, "127.0.0.1", "the gateway's bind address");
1687
+ const elsewhere = await send({ url: `http://localhost:${new URL(status.gateway?.shell ?? "http://127.0.0.1:1").port}/` }).catch(() => void 0);
1688
+ check(elsewhere === void 0 || elsewhere.status === 421, `the shell answered a request for another host name (${elsewhere?.status})`);
1689
+ same(started.instance.mode === "host" || started.instance.mode === "daemon", true, "the mode");
1690
+ }
1691
+ }
1692
+ ];
1693
+ /** The viewing scenarios. */
1694
+ const VIEWING_SCENARIOS = [
1695
+ {
1696
+ id: "viewing.links",
1697
+ title: "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",
1698
+ covers: [
1699
+ "HO-05",
1700
+ "H-07",
1701
+ "H-14",
1702
+ "HY-03"
1703
+ ],
1704
+ async run(context) {
1705
+ await context.start();
1706
+ const receipt = await context.published(FORM);
1707
+ check(receipt.url && receipt.tokenId, "the publish receipt has no link (H-07)");
1708
+ check(/^\d+$/.test(receipt.cursor), `the receipt's cursor (${receipt.cursor})`);
1709
+ const written = await (await context.viewer(receipt.artifactId, { link: { scopes: ["view"] } })).write({ name: "x" });
1710
+ same([written.status, written.json().code], [403, "MOSTRA_HYGIENE_SCOPE_DENIED"], "a view-only link's write");
1711
+ const minted = await context.host.call("view/url", { artifact: { artifactId: receipt.artifactId } });
1712
+ await context.host.call("view/revoke", { tokenId: minted.tokenId });
1713
+ const revoked = await Viewer.open(minted.url).then(() => void 0, (error) => error);
1714
+ check(revoked instanceof OpenError, "a revoked link still opened");
1715
+ same([revoked.status, revoked.code], [410, "MOSTRA_HYGIENE_TOKEN_REVOKED"], "a revoked link");
1716
+ const rotated = await context.host.call("view/rotate", { tokenId: receipt.tokenId });
1717
+ const old = await Viewer.open(receipt.url).then(() => void 0, (error) => error);
1718
+ check(old instanceof OpenError && old.status === 410, "the default link still opens after its rotation");
1719
+ await Viewer.open(rotated.url);
1720
+ context.rewrite(receipt.dir, FORM_V2);
1721
+ await context.publish(receipt.dir);
1722
+ const pinned = await context.viewer(receipt.artifactId, { link: { version: 1 } });
1723
+ same(pinned.ticket.version.number, 1, "the version a pinned link opens");
1724
+ same(pinned.ticket.latest.number, 2, "the latest version it reports");
1725
+ }
1726
+ },
1727
+ {
1728
+ id: "viewing.hygiene",
1729
+ title: "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)",
1730
+ covers: ["HO-05", "HY-01"],
1731
+ async run(context) {
1732
+ await context.start();
1733
+ const receipt = await context.published(FORM);
1734
+ const link = parseLink(await context.link(receipt.artifactId));
1735
+ const exchange = `${link.origin}/a/${link.artifactId}/_mostra/session`;
1736
+ const post = (headers, body) => send({
1737
+ method: "POST",
1738
+ url: exchange,
1739
+ headers: {
1740
+ "content-type": "application/json",
1741
+ "sec-fetch-site": "same-origin",
1742
+ origin: link.origin,
1743
+ ...headers
1744
+ },
1745
+ body: JSON.stringify(body)
1746
+ });
1747
+ const host = await post({ host: "evil.example" }, { token: link.secret });
1748
+ same(host.status, 421, "an unknown Host");
1749
+ const origin = await post({ origin: "http://evil.example" }, { token: link.secret });
1750
+ same(origin.status, 403, "a foreign Origin");
1751
+ const token = await post({}, { token: "A".repeat(26) });
1752
+ same(token.status, 401, "a wrong token");
1753
+ const viewer = await Viewer.open(await context.link(receipt.artifactId));
1754
+ const noCsrf = await viewer.browser.ask({
1755
+ method: "POST",
1756
+ url: `${viewer.ticket.artifactOrigin}/_mostra/v/2026-10-15/signal`,
1757
+ headers: {
1758
+ "content-type": "application/json",
1759
+ origin: viewer.ticket.artifactOrigin,
1760
+ "sec-fetch-site": "same-origin"
1761
+ },
1762
+ body: JSON.stringify({
1763
+ viewId: viewer.viewId,
1764
+ name: "ping"
1765
+ })
1766
+ });
1767
+ same(noCsrf.status, 403, "a mutation without its CSRF token");
1768
+ for (const answer of [
1769
+ host,
1770
+ origin,
1771
+ token,
1772
+ noCsrf
1773
+ ]) check(!Object.keys(answer.headers).some((name) => name.startsWith("access-control-")), "a refusal carries a CORS header");
1774
+ }
1775
+ },
1776
+ {
1777
+ id: "viewing.shell-bridge",
1778
+ title: "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",
1779
+ covers: [
1780
+ "HO-05",
1781
+ "SH-02",
1782
+ "SH-04",
1783
+ "H-05"
1784
+ ],
1785
+ async run(context) {
1786
+ let chromium;
1787
+ try {
1788
+ ({chromium} = await import("playwright-core"));
1789
+ } catch {
1790
+ throw new NotApplicable("playwright-core isn't installed");
1791
+ }
1792
+ const browser = await chromium.launch().catch((error) => {
1793
+ throw new NotApplicable(`no browser to run the shell in (${error.message.split("\n")[0]})`);
1794
+ });
1795
+ try {
1796
+ await context.start();
1797
+ const receipt = await context.published(FORM);
1798
+ const page = await browser.newPage();
1799
+ await page.goto(await context.link(receipt.artifactId));
1800
+ await page.waitForSelector("html[data-shell=\"ready\"]", { timeout: 6e4 });
1801
+ const frame = page.frameLocator("iframe");
1802
+ const submit = page.locator("#mostra-submit");
1803
+ await submit.waitFor();
1804
+ check((await submit.textContent())?.includes("Send answers"), "the trusted Submit's label isn't the one the page asked for");
1805
+ await page.waitForTimeout(600);
1806
+ await submit.click();
1807
+ const blocker = page.locator("[data-mostra-blocker=name]");
1808
+ await blocker.waitFor({ timeout: 1e4 });
1809
+ same((await blocker.textContent())?.trim(), "Your name", "the blocker's label");
1810
+ await blocker.click();
1811
+ await frame.getByLabel("Your name").waitFor();
1812
+ await context.eventually("picking the blocker focuses the field in the page (mostra/field.focus)", () => frame.locator("[name=\"name\"]").evaluate((element) => element === element.ownerDocument.activeElement), 1e4);
1813
+ await frame.getByLabel("Your name").fill("Ada");
1814
+ await context.eventually("the trusted Submit submits", async () => {
1815
+ if ((await submit.textContent())?.includes("Submitted")) return true;
1816
+ await submit.click().catch(() => void 0);
1817
+ return (await submit.textContent())?.includes("Submitted");
1818
+ });
1819
+ const read = await context.results(receipt.artifactId);
1820
+ same(read["submission"].channel, "shell", "the trusted Submit's channel");
1821
+ same(read["answers"], {
1822
+ name: "Ada",
1823
+ comment: ""
1824
+ }, "the answers, defaults included (D110)");
1825
+ context.rewrite(receipt.dir, FORM_V2);
1826
+ await context.publish(receipt.dir);
1827
+ await page.locator("[data-mostra-banner=\"2\"]").waitFor({ timeout: 15e3 });
1828
+ } finally {
1829
+ await browser.close();
1830
+ }
1831
+ }
1832
+ }
1833
+ ];
1834
+ //#endregion
1835
+ //#region src/scenarios/index.ts
1836
+ /** Every scenario. */
1837
+ const SCENARIOS = [
1838
+ ...SESSION_SCENARIOS,
1839
+ ...DELIVERY_SCENARIOS,
1840
+ ...INTERACTION_SCENARIOS,
1841
+ ...PORT_SCENARIOS,
1842
+ ...VIEWING_SCENARIOS
1843
+ ];
1844
+ //#endregion
1845
+ //#region src/runner.ts
1846
+ /**
1847
+ * Runs scenarios against a host (HO-05): each in a fresh directory with a fresh shim and home,
1848
+ * one at a time, each bounded in time; then judges the run against the host's baseline.
1849
+ */
1850
+ function selected(scenarios, only) {
1851
+ if (!only || only.length === 0) return [...scenarios];
1852
+ return scenarios.filter((scenario) => only.some((prefix) => scenario.id === prefix || scenario.id.startsWith(prefix)));
1853
+ }
1854
+ /** Runs one scenario: `passed`, `failed` or `skipped`, before the baseline. */
1855
+ async function runOne(scenario, settings, dir, timeoutMs) {
1856
+ const context = new ScenarioContext(settings, dir);
1857
+ let timer;
1858
+ try {
1859
+ await context.open();
1860
+ for (const feature of scenario.needs ?? []) context.requireFeature(feature);
1861
+ await Promise.race([scenario.run(context), new Promise((_, fail) => {
1862
+ timer = setTimeout(() => fail(/* @__PURE__ */ new Error(`the scenario didn't finish within ${timeoutMs / 1e3} s`)), timeoutMs);
1863
+ })]);
1864
+ return {
1865
+ status: "passed",
1866
+ ...context.host.info ? { host: context.host.info } : {}
1867
+ };
1868
+ } catch (error) {
1869
+ const host = context.host?.info;
1870
+ if (error instanceof NotApplicable) return {
1871
+ status: "skipped",
1872
+ reason: error.message,
1873
+ ...host ? { host } : {}
1874
+ };
1875
+ const stderr = context.host?.stderr.slice(-3).join(" | ");
1876
+ const message = error.message ?? String(error);
1877
+ return {
1878
+ status: "failed",
1879
+ reason: stderr && !error.name?.startsWith("Scenario") ? `${message} (host: ${stderr})` : message,
1880
+ ...host ? { host } : {}
1881
+ };
1882
+ } finally {
1883
+ clearTimeout(timer);
1884
+ await context.close().catch(() => void 0);
1885
+ }
1886
+ }
1887
+ /** Runs the kit's scenarios against a host and judges them against its baseline. */
1888
+ async function runConformance(options) {
1889
+ const baseline = options.baseline ?? NO_BASELINE;
1890
+ const catalog = (options.scenarios ?? SCENARIOS).map((scenario) => scenario.id);
1891
+ const unknown = Object.keys(baseline.expectedFailures).filter((id) => !catalog.includes(id));
1892
+ if (unknown.length > 0) throw new Error(`The baseline names scenarios the kit doesn't have: ${unknown.join(", ")}.`);
1893
+ const settings = {
1894
+ host: options.host,
1895
+ hostEnv: options.hostEnv ?? {},
1896
+ verify: options.verify ?? false
1897
+ };
1898
+ const root = options.workDir ?? mkdtempSync(join(process.platform === "darwin" ? "/tmp" : tmpdir(), "mc-"));
1899
+ const outcomes = [];
1900
+ let host;
1901
+ let index = 0;
1902
+ for (const scenario of selected(options.scenarios ?? SCENARIOS, options.only)) {
1903
+ index += 1;
1904
+ const started = Date.now();
1905
+ const result = await runOne(scenario, settings, join(root, `s${index}`), options.timeoutMs ?? 24e4);
1906
+ host ??= result.host;
1907
+ const expected = baseline.expectedFailures[scenario.id];
1908
+ let status = result.status;
1909
+ let reason = result.reason;
1910
+ if (expected !== void 0 && result.status === "failed") {
1911
+ status = "expected-failure";
1912
+ reason = `${expected} (${result.reason ?? "failed"})`;
1913
+ } else if (expected !== void 0 && result.status === "passed") {
1914
+ status = "unexpected-pass";
1915
+ reason = `the baseline expects a failure (${expected}), and it passed: remove it from the baseline`;
1916
+ }
1917
+ const outcome = {
1918
+ id: scenario.id,
1919
+ title: scenario.title,
1920
+ covers: scenario.covers,
1921
+ status,
1922
+ ...reason !== void 0 ? { reason } : {},
1923
+ durationMs: Date.now() - started
1924
+ };
1925
+ outcomes.push(outcome);
1926
+ options.onOutcome?.(outcome);
1927
+ }
1928
+ if (options.workDir === void 0) try {
1929
+ rmdirSync(root);
1930
+ } catch {}
1931
+ return {
1932
+ host,
1933
+ outcomes,
1934
+ ok: outcomes.every((outcome) => outcome.status !== "failed" && outcome.status !== "unexpected-pass")
1935
+ };
1936
+ }
1937
+ //#endregion
1938
+ export { FIXTURES as _, ScenarioFailure as a, Browser as c, parseLink as d, resultOf as f, codeOf as g, InstanceError as h, ScenarioContext as i, OpenError as l, HostUnderTest as m, SCENARIOS as n, check as o, send as p, NotApplicable as r, same as s, runConformance as t, Viewer as u, NO_BASELINE as v, readBaseline as y };
1939
+
1940
+ //# sourceMappingURL=runner-CvoSJlfk.js.map