@mostra/runtime 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +2879 -8
- package/dist/bin.js.map +1 -1
- package/dist/builder/child/main.js +2 -2
- package/dist/{child-Chiavhdx.js → child-BmNZ4a70.js} +2 -2
- package/dist/{child-Chiavhdx.js.map → child-BmNZ4a70.js.map} +1 -1
- package/dist/deps/child/install.js +1 -1
- package/dist/{directories-mJ1qlVht.js → directories-BLJjeSPD.js} +5 -5
- package/dist/directories-BLJjeSPD.js.map +1 -0
- package/dist/{files-FygSJIzK.js → files-DGeWuE4I.js} +2 -2
- package/dist/{files-FygSJIzK.js.map → files-DGeWuE4I.js.map} +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{instance-BRfg27Rg.js → instance-FExcyENK.js} +3346 -395
- package/dist/instance-FExcyENK.js.map +1 -0
- package/package.json +7 -5
- package/src/actions/index.ts +163 -10
- package/src/bin.ts +78 -1
- package/src/gateway/actions.ts +20 -4
- package/src/gateway/browser.ts +118 -95
- package/src/gateway/capabilities.ts +15 -6
- package/src/gateway/index.ts +112 -15
- package/src/gateway/routes.ts +15 -7
- package/src/gc/index.ts +14 -0
- package/src/instance/index.ts +41 -2
- package/src/interaction/ephemeral.ts +32 -23
- package/src/interaction/events.ts +21 -1
- package/src/interaction/imports.ts +317 -0
- package/src/interaction/index.ts +172 -19
- package/src/interaction/outbox.ts +9 -0
- package/src/interaction/results.ts +22 -1
- package/src/interaction/runs.ts +52 -2
- package/src/interaction/submissions.ts +17 -1
- package/src/interaction/tally.ts +129 -0
- package/src/ledger/index.ts +104 -9
- package/src/ledger/migrations.ts +183 -0
- package/src/ledger/types.ts +8 -0
- package/src/link/binding.ts +289 -0
- package/src/link/hosted.ts +65 -0
- package/src/link/http.ts +136 -0
- package/src/link/index.ts +8 -0
- package/src/link/manager.ts +1385 -0
- package/src/link/relay.ts +512 -0
- package/src/live/index.ts +112 -2
- package/src/platform/filesystems.ts +78 -0
- package/src/platform/index.ts +1 -0
- package/src/protocol-server/index.ts +18 -1
- package/src/protocol-server/server.ts +38 -7
- package/src/protocol-server/websocket.ts +161 -0
- package/src/publish/bundle.ts +398 -0
- package/src/publish/manifest.ts +9 -0
- package/src/publish/methods.ts +12 -1
- package/src/publish/publisher.ts +127 -0
- package/src/registry/index.ts +35 -14
- package/src/server/api.ts +439 -0
- package/src/server/auth.ts +613 -0
- package/src/server/config.ts +221 -0
- package/src/server/data.ts +369 -0
- package/src/server/directory.ts +141 -0
- package/src/server/hosted.ts +822 -0
- package/src/server/index.ts +368 -0
- package/src/server/relay.ts +1163 -0
- package/src/share/index.ts +110 -6
- package/dist/directories-mJ1qlVht.js.map +0 -1
- package/dist/instance-BRfg27Rg.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"instance-BRfg27Rg.js","names":["failed","run","delay","connectSocket","childEntry","failed","diagnose","unreadable","runtimeRoot","runtimeRoot","oxc","parser","position","literal","KeyedQueue","invalid","tooLarge","viewerById","notFound","literal","STATUS","answer","failure","body","CROCKFORD","request","httpRequest","createServer","runtimeRoot","WorkerStartResultSchema","WorkerCallOutcomeSchema","runtimeRoot","canonicalJson","ENTRY_NAMES","unreadable","hashFile","fsConstants","CROCKFORD","canonicalJson","missing","runtimeRoot"],"sources":["../src/log.ts","../src/actions/index.ts","../src/addressing/index.ts","../src/builder/coverage.ts","../src/platform/identity.ts","../src/platform/launch.ts","../src/platform/control.ts","../src/platform/environment.ts","../src/platform/tools.ts","../src/builder/index.ts","../src/faults.ts","../src/ledger/migrations.ts","../src/ledger/requests.ts","../src/ledger/index.ts","../src/processes/environment.ts","../src/processes/manager.ts","../src/deps/warm.ts","../src/deps/installer.ts","../src/deps/lock.ts","../src/deps/specifier.ts","../src/deps/scan.ts","../src/deps/index.ts","../src/protocol-server/streams.ts","../src/protocol-server/server.ts","../src/protocol-server/client.ts","../src/protocol-server/index.ts","../src/interaction/events.ts","../src/interaction/fields.ts","../src/interaction/policy.ts","../src/interaction/signals.ts","../src/interaction/viewers.ts","../src/interaction/submissions.ts","../src/interaction/results.ts","../src/interaction/outbox.ts","../src/interaction/runs.ts","../src/interaction/subscriptions.ts","../src/interaction/wait.ts","../src/interaction/ephemeral.ts","../src/interaction/index.ts","../src/registry/store.ts","../src/registry/index.ts","../src/verify/fields.ts","../src/verify/regression.ts","../src/gateway/http.ts","../src/gateway/actions.ts","../src/gateway/browser.ts","../src/gateway/capabilities.ts","../src/gateway/dev.ts","../src/gateway/identity.ts","../src/gateway/integrity.ts","../src/gateway/routes.ts","../src/gateway/listener.ts","../src/gateway/serve.ts","../src/gateway/worker.ts","../src/gateway/controls.ts","../src/gateway/index.ts","../src/live/index.ts","../src/workers/launcher.ts","../src/workers/pool.ts","../src/verify/sandbox.ts","../src/verify/typecheck.ts","../src/verify/runner.ts","../src/verify/index.ts","../src/publish/digest.ts","../src/publish/manifest.ts","../src/publish/scaffold.ts","../src/publish/source.ts","../src/publish/tar.ts","../src/publish/publisher.ts","../src/publish/checks.ts","../src/publish/methods.ts","../src/dev/index.ts","../src/gate.ts","../src/gc/index.ts","../src/home/paths.ts","../src/home/record.ts","../src/home/acquire.ts","../src/home/platform.ts","../src/home/settings.ts","../src/secrets/index.ts","../src/service/idle.ts","../src/service/unit.ts","../src/share/tunnel.ts","../src/share/cloudflare.ts","../src/share/tailscale.ts","../src/share/index.ts","../src/instance/index.ts"],"sourcesContent":["/**\n * The supervisor's log: JSON lines in `<home>/logs/supervisor.log`, rotated by size (DATA_MODEL\n * §1). Every module receives a {@link Log} and writes structured events; nothing here formats\n * for people. Every string written passes through the instance's {@link Redactor}, so secrets and\n * capability tokens never reach the file or its mirror (STANDARDS security).\n */\n\nimport { appendFileSync, mkdirSync, renameSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { fromBase64, toBase64 } from \"@mostra/protocol\";\n\n/** Structured fields of one log event. Values must be JSON-serializable. */\nexport type LogFields = Readonly<Record<string, unknown>>;\n\n/** Where modules write what happened. */\nexport interface Log {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n error(event: string, fields?: LogFields): void;\n}\n\n/** A log that drops everything, for code paths that run before a home exists. */\nexport const silentLog: Log = { info() {}, warn() {}, error() {} };\n\n/** What replaces a redacted value. */\nexport const REDACTED = \"[redacted]\";\n\n/** Query and fragment parameters that carry capability material in Mostra URLs. */\nconst CAPABILITY_PARAMS = /([?#&](?:t|token|ticket|capability)=)[^&#\\s\"']+/gi;\n\n/** Environment variable names whose values are treated as secrets. */\nconst SECRET_NAME =\n /TOKEN|SECRET|PASSWORD|PASSWD|PASSPHRASE|CREDENTIAL|API_?KEY|PRIVATE_?KEY|ACCESS_?KEY|AUTH/i;\n\n/** The shortest value worth redacting; shorter ones would mangle ordinary text. */\nconst MIN_SECRET_LENGTH = 8;\n\n/** The shortest named secret redacted (`mostra secret set`). */\nconst MIN_NAMED_SECRET_LENGTH = 4;\n\n/** The shortest line of a multi-line secret that is protected on its own. */\nconst MIN_SECRET_LINE_LENGTH = 8;\n\n/**\n * Removes secrets and capability material from text before it is logged or reported: values the\n * instance registered (secrets it hands to children, token secrets) and the token parameters of\n * capability URLs.\n */\nexport class Redactor {\n readonly #values = new Set<string>();\n\n /** Registers a value that must never appear in logs or reports. Short values are ignored. */\n protect(value: string): void {\n if (value.length >= MIN_SECRET_LENGTH) this.#values.add(value);\n }\n\n /**\n * Registers a named secret's value (D44): one a person set on purpose, so it is protected from\n * 4 characters on; a shorter one would match ordinary text everywhere.\n */\n protectSecret(value: string): void {\n if (value.length < MIN_NAMED_SECRET_LENGTH) return;\n this.#values.add(value);\n // As it appears inside JSON text (an event payload, a log line), escapes and all.\n const escaped = JSON.stringify(value).slice(1, -1);\n if (escaped !== value) this.#values.add(escaped);\n // A multi-line secret (a PEM key, a service account's JSON) also reaches output a line at a\n // time: a child's output is split into lines before it is kept, and `util.inspect` splits\n // long strings (Opus review 8). Each line long enough to be specific is protected too.\n if (/[\\r\\n]/.test(value)) {\n for (const line of value.split(/\\r?\\n|\\r/)) {\n const trimmed = line.trim();\n if (trimmed.length >= MIN_SECRET_LINE_LENGTH) this.#values.add(trimmed);\n }\n }\n }\n\n /** The UTF-8 bytes of every protected value, for redacting binary output. */\n protectedBytes(): Uint8Array[] {\n const encoder = new TextEncoder();\n return [...this.#values].map((value) => encoder.encode(value));\n }\n\n /** Registers the values of variables whose names look like secrets (`*_TOKEN`, `*_SECRET` …). */\n protectEnvironment(env: Environment): void {\n for (const [name, value] of Object.entries(env)) {\n if (value !== undefined && SECRET_NAME.test(name)) this.protect(value);\n }\n }\n\n /** Returns `text` with every registered value and capability parameter replaced. */\n redact(text: string): string {\n let result = text.replace(CAPABILITY_PARAMS, `$1${REDACTED}`);\n // Longest first, so a secret that contains another is replaced whole.\n for (const value of [...this.#values].sort((a, b) => b.length - a.length)) {\n if (result.includes(value)) result = result.split(value).join(REDACTED);\n }\n return result;\n }\n}\n\n/** Options for {@link openFileLog}. */\nexport interface FileLogOptions {\n /** The directory (`<home>/logs`), created with mode 0700. */\n readonly dir: string;\n /** Rotate when the file reaches this size. Default 10 MiB. */\n readonly maxBytes?: number;\n /** How many rotated files to keep (`supervisor.log.1` …). Default 3. */\n readonly keep?: number;\n /** Also mirrors warnings and errors here, such as stderr. */\n readonly mirror?: (line: string) => void;\n /** Applied to every string field. Default: a redactor for capability parameters only. */\n readonly redactor?: Redactor;\n}\n\n/**\n * Opens the supervisor's file log. Writes are synchronous appends, so the last lines before a\n * crash are on disk. A write that fails (the home was removed) is dropped; the log never throws.\n */\nexport function openFileLog(options: FileLogOptions): Log {\n const maxBytes = options.maxBytes ?? 10 * 1024 * 1024;\n const keep = options.keep ?? 3;\n const redactor = options.redactor ?? new Redactor();\n const replacer = (_key: string, value: unknown): unknown => {\n if (value instanceof Error) {\n return {\n name: value.name,\n message: redactor.redact(value.message),\n stack: value.stack && redactor.redact(value.stack),\n };\n }\n return typeof value === \"string\" ? redactor.redact(value) : value;\n };\n const file = join(options.dir, \"supervisor.log\");\n let size = 0;\n try {\n mkdirSync(options.dir, { recursive: true, mode: 0o700 });\n size = statSync(file).size;\n } catch {\n size = 0;\n }\n\n const rotate = (): void => {\n for (let index = keep - 1; index >= 1; index--) {\n try {\n renameSync(`${file}.${index}`, `${file}.${index + 1}`);\n } catch {\n // The older file doesn't exist yet.\n }\n }\n try {\n renameSync(file, `${file}.1`);\n } catch {\n // Nothing to rotate.\n }\n size = 0;\n };\n\n const write = (level: \"info\" | \"warn\" | \"error\", event: string, fields?: LogFields): void => {\n const line = `${JSON.stringify({ at: new Date().toISOString(), level, pid: process.pid, event, ...fields }, replacer)}\\n`;\n const bytes = Buffer.byteLength(line);\n try {\n if (size + bytes > maxBytes) rotate();\n appendFileSync(file, line, { mode: 0o600 });\n size += bytes;\n } catch {\n // The log must never take the supervisor down.\n }\n if (level !== \"info\") options.mirror?.(line);\n };\n\n return {\n info: (event, fields) => write(\"info\", event, fields),\n warn: (event, fields) => write(\"warn\", event, fields),\n error: (event, fields) => write(\"error\", event, fields),\n };\n}\n\n/** Environment variables, as `process.env` holds them. */\nexport type Environment = Readonly<Record<string, string | undefined>>;\n\n/**\n * `value` with every string in it, keys too, passed through `redactor`: what server code hands to\n * Mostra (results, state, live values) never carries a secret Mostra knows (D44, AC-06).\n */\nexport function redactValue<T>(value: T, redactor: { redact(text: string): string }): T {\n const walk = (item: unknown): unknown => {\n if (typeof item === \"string\") return redactor.redact(item);\n if (Array.isArray(item)) return item.map(walk);\n if (item !== null && typeof item === \"object\") {\n return Object.fromEntries(\n Object.entries(item).map(([key, entry]) => [redactor.redact(key), walk(entry)]),\n );\n }\n return item;\n };\n return walk(value) as T;\n}\n\n/** Overwrites, in place, every occurrence of each needle in `bytes` with `*`; true if any. */\nfunction maskBytes(bytes: Uint8Array, needles: readonly Uint8Array[]): boolean {\n let masked = false;\n for (const needle of needles) {\n if (needle.length === 0 || needle.length > bytes.length) continue;\n const first = needle[0] as number;\n for (let at = bytes.indexOf(first); at !== -1 && at <= bytes.length - needle.length; ) {\n let match = true;\n for (let k = 1; k < needle.length; k++) {\n if (bytes[at + k] !== needle[k]) {\n match = false;\n break;\n }\n }\n if (match) {\n bytes.fill(0x2a, at, at + needle.length);\n masked = true;\n at = bytes.indexOf(first, at + needle.length);\n } else at = bytes.indexOf(first, at + 1);\n }\n }\n return masked;\n}\n\n/**\n * Redacts one batch of the server-function serializer's frames (INTERFACES §2.4) as values, not as\n * text (Opus review 7): a string keeps its `$` escape, so a secret starting with `$` stays a\n * string; a registered symbol's name is redacted; the bytes of an `ArrayBuffer`, a typed array or\n * a file are searched for each protected value's UTF-8 bytes, which are overwritten with `*` in\n * place, so every typed array keeps its length. Frames this function doesn't recognize are\n * redacted as text.\n */\nexport function redactFrames<T>(\n batch: T,\n redactor: { redact(text: string): string; protectedBytes?(): Uint8Array[] },\n): T {\n if (!Array.isArray(batch)) return redactValue(batch, redactor);\n // Which chunks hold bytes: the references to them are in this batch (the writer puts a value's\n // chunks in the batch that refers to them).\n const kinds = new Map<number, \"A\" | \"T\" | \"B\">();\n const scan = (item: unknown): void => {\n if (typeof item === \"string\") {\n const match = /^\\$([ATB])([0-9]+)$/.exec(item);\n if (match) kinds.set(Number(match[2]), match[1] as \"A\" | \"T\" | \"B\");\n } else if (Array.isArray(item)) item.forEach(scan);\n else if (item !== null && typeof item === \"object\") Object.values(item).forEach(scan);\n };\n scan(batch);\n const needles = redactor.protectedBytes?.() ?? [];\n const maskBase64 = (text: unknown): unknown => {\n if (typeof text !== \"string\" || needles.length === 0) return text;\n let bytes: Uint8Array;\n try {\n bytes = fromBase64(text);\n } catch {\n return redactor.redact(text);\n }\n return maskBytes(bytes, needles) ? toBase64(bytes) : text;\n };\n const string = (text: string): string => {\n if (text.startsWith(\"$$\")) {\n const plain = redactor.redact(text.slice(1));\n return plain.startsWith(\"$\") ? `$${plain}` : plain;\n }\n if (text.startsWith(\"$S\")) return `$S${redactor.redact(text.slice(2))}`;\n if (text.startsWith(\"$\")) return text;\n const plain = redactor.redact(text);\n // A redaction can't make a plain string read as a reference.\n return plain.startsWith(\"$\") ? `$${plain}` : plain;\n };\n const value = (item: unknown): unknown => {\n if (typeof item === \"string\") return string(item);\n if (Array.isArray(item)) return item.map(value);\n if (item !== null && typeof item === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(item)) {\n Object.defineProperty(out, redactor.redact(key), {\n value: value(entry),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n return out;\n }\n return item;\n };\n return batch.map((frame: unknown) => {\n if (frame === null || typeof frame !== \"object\") return frame;\n const record = frame as Record<string, unknown>;\n if (typeof record[\"c\"] === \"number\") {\n const kind = kinds.get(record[\"c\"]);\n const v = record[\"v\"];\n if (kind === \"A\") return { ...record, v: maskBase64(v) };\n if (kind === \"T\" && Array.isArray(v)) return { ...record, v: [v[0], maskBase64(v[1])] };\n if (kind === \"B\" && v !== null && typeof v === \"object\" && !Array.isArray(v)) {\n const file = v as Record<string, unknown>;\n return {\n ...record,\n v: {\n ...file,\n data: maskBase64(file[\"data\"]),\n ...(typeof file[\"name\"] === \"string\" ? { name: redactor.redact(file[\"name\"]) } : {}),\n },\n };\n }\n return { ...record, v: value(v) };\n }\n // A promise or iterable frame: its value is encoded like a chunk's; an error is plain text.\n return Object.fromEntries(\n Object.entries(record).map(([key, entry]) => [\n key,\n key === \"v\" ? value(entry) : redactValue(entry, redactor),\n ]),\n );\n }) as T;\n}\n","/**\n * Server functions as pages call them (D54, ARCHITECTURE §7): plain calls, which stream their\n * result and leave no record, and durable action runs (AC-02 to AC-04), which the interaction core\n * records before a worker starts them and which outlive the tab that started them. Runs stream\n * progress, log lines and partial results to every view that follows them, as ephemeral messages,\n * and keep them with the run, so a reloaded page re-attaches and reads what it missed.\n *\n * This module also answers what server code asks of Mostra (the worker bridge): secrets by name,\n * signals and host events, and the artifact's shared state.\n */\nimport {\n ACTION_ARGS_MAX,\n ACTION_RESULT_MAX,\n type Batches,\n type CallLine,\n checkArgumentFrames,\n createDiagnostic,\n type Frame,\n RpcError,\n type RunDelta,\n type RunProgress,\n type RunState,\n ServerEmitParams,\n ServerSecretParams,\n ServerSignalParams,\n ServerStateGetParams,\n ServerStatePatchParams,\n type WireError,\n WORKER_METHODS,\n} from \"@mostra/protocol\";\nimport type { EphemeralBus, Interaction, PageIdentity, RunRow } from \"../interaction/index.ts\";\nimport { type Log, type Redactor, redactFrames, redactValue } from \"../log.ts\";\nimport type { Secrets } from \"../secrets/index.ts\";\nimport type {\n WorkerBridge,\n WorkerCrash,\n WorkerHandle,\n WorkerPool,\n WorkerVersion,\n} from \"../workers/index.ts\";\n\n/** How often a running run's output is written and sent to its views. */\nconst FLUSH_MS = 200;\n\n/** Options for {@link createActions}. */\nexport interface ActionsOptions {\n readonly interaction: Interaction;\n readonly pool: WorkerPool;\n readonly bus: EphemeralBus;\n readonly secrets: Secrets;\n readonly redactor: Redactor;\n readonly log: Log;\n /** What the pool needs to start a version's worker, or `undefined` for a version without server code. */\n readonly version: (versionId: string) => WorkerVersion | undefined;\n /**\n * A verify run's dry-run policy (D55, D138). With it, a function that opted into `dryRun()` runs\n * with `dryRun: true`, and any other is refused with `MOSTRA_VERIFY_ACTION_SKIPPED` before a run\n * is recorded or a worker starts, for plain calls and runs alike. Absent for viewers' pages.\n */\n readonly dryRun?: {\n readonly optedIn: (versionId: string, fnId: string) => boolean;\n /** Told about each refused function, for the verdict's `skippedActions`. */\n readonly skipped: (fnId: string) => void;\n };\n}\n\n/** Plain calls and action runs, and the bridge workers ask through. */\nexport interface Actions {\n /**\n * A plain call (D54): resolves once its worker has it (refusals throw here), with the result's\n * batches as they come and then how it ended.\n */\n call(\n page: PageIdentity,\n input: { readonly viewId: string; readonly fnId: string; readonly args: Batches },\n signal: AbortSignal,\n ): Promise<AsyncIterable<CallLine>>;\n /** Starts or joins a run (AC-02, AC-03); the page follows it from here. */\n startRun(\n page: PageIdentity,\n input: {\n readonly viewId: string;\n readonly fnId: string;\n readonly args: Batches;\n readonly key?: string;\n readonly clientKey: string;\n },\n ): RunState;\n /** Reads runs and follows them for a minute (re-attach, AC-02). */\n attach(\n page: PageIdentity,\n input: {\n readonly viewId: string;\n readonly runIds?: readonly string[];\n readonly keyed?: readonly { readonly fnId: string; readonly key: string }[];\n },\n ): RunState[];\n /** Cancels a run (AC-04): its `abortSignal` fires; a queued run ends at once. */\n cancel(page: PageIdentity, viewId: string, runId: string): RunState;\n /** What workers ask of the supervisor. */\n readonly bridge: Omit<WorkerBridge, \"liveValue\">;\n /** A worker crashed: its runs end `interrupted` (D24), the crash is an event. */\n crashed(crash: WorkerCrash): void;\n /** Ends the runs a stopped instance left open as `interrupted` (FAILURE_MODEL §2). */\n recover(): void;\n /** How many runs and calls are in flight: the daemon stays while any are (D62). */\n activity(): number;\n}\n\n/** A run this instance is executing. */\ninterface Executing {\n handle?: WorkerHandle;\n callId?: string;\n cancelled: boolean;\n /** Ends the run now: set while it waits for its worker, so a cancel needn't wait for one. */\n endNow?: () => void;\n}\n\nfunction failed(code: string, message: string): RpcError {\n return new RpcError(createDiagnostic(code as never, { message }));\n}\n\n/** Creates the actions module. */\nexport function createActions(options: ActionsOptions): Actions {\n const { interaction, pool, bus, log } = options;\n /** Runs executing in this instance: their worker call, for cancel and crashes. */\n const executing = new Map<string, Executing>();\n /** Which run each worker call is, for crashes. */\n const callRuns = new Map<string, string>();\n /** Why a run's worker stopped under it, until its `execute` ends it. */\n const crashCauses = new Map<string, string>();\n let calls = 0;\n\n const redact = (text: string): string => options.redactor.redact(text);\n const redactError = (error: WireError): WireError => ({\n message: redact(error.message),\n ...(error.code ? { code: error.code } : {}),\n });\n\n const versionOf = (versionId: string): WorkerVersion => {\n const version = options.version(versionId);\n if (!version) {\n throw failed(\n \"MOSTRA_ACTION_UNKNOWN_FUNCTION\",\n \"This version has no server code, so it has no server functions to call.\",\n );\n }\n return version;\n };\n\n /**\n * The view's version, which must have the function: a page can't record runs, start workers or\n * spend a key for a function its version doesn't have (INTERFACES §4; Opus review 6).\n */\n const functionOf = (versionId: string, fnId: string): WorkerVersion => {\n const version = versionOf(versionId);\n if (!version.functions.has(fnId)) {\n throw failed(\n \"MOSTRA_ACTION_UNKNOWN_FUNCTION\",\n `This version has no server function ${fnId.slice(0, 200)}.`,\n );\n }\n const policy = options.dryRun;\n if (policy && !policy.optedIn(versionId, fnId)) {\n policy.skipped(fnId);\n throw failed(\n \"MOSTRA_VERIFY_ACTION_SKIPPED\",\n `Skipped in verify: the server function ${fnId.slice(0, 200)} doesn't check dryRun(), so verify never runs it.`,\n );\n }\n return version;\n };\n\n const checkArgs = (args: Batches): void => {\n if (JSON.stringify(args).length > ACTION_ARGS_MAX) {\n throw failed(\n \"MOSTRA_ACTION_TOO_LARGE\",\n \"The serialized arguments are larger than 16 MiB; pass less data, such as identifiers.\",\n );\n }\n // What a worker would refuse is refused before one starts or a run is recorded: a page can't\n // make server code hold memory for the life of its process (Opus review 1).\n try {\n checkArgumentFrames(args);\n } catch (error) {\n throw failed(\"MOSTRA_ACTION_UNSERIALIZABLE\", (error as Error).message);\n }\n };\n\n const publish = (artifactId: string, run: RunDelta): void =>\n bus.publishRun(artifactId, { kind: \"run\", run });\n\n /** Runs a recorded run in its version's worker, writing its output as it comes. */\n const execute = async (row: RunRow): Promise<void> => {\n const entry: Executing = { cancelled: false };\n executing.set(row.id, entry);\n let pendingLines: string[] = [];\n let pendingBatches: Frame[][] = [];\n let pendingProgress: RunProgress | undefined;\n let tooLarge = false;\n let size = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const flush = (): void => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n if (pendingLines.length === 0 && pendingBatches.length === 0 && pendingProgress === undefined)\n return;\n const output = {\n lines: pendingLines,\n batches: pendingBatches,\n ...(pendingProgress ? { progress: pendingProgress } : {}),\n };\n pendingLines = [];\n pendingBatches = [];\n const progress = pendingProgress;\n pendingProgress = undefined;\n const written = interaction.runOutput(row.id, output);\n if (!written) return;\n publish(row.artifact_id, {\n runId: row.id,\n status: \"running\",\n ...(progress ? { progress } : {}),\n logFrom: written.logFrom,\n log: written.log,\n batchFrom: written.batchFrom,\n batches: written.batches,\n });\n };\n const soon = (): void => {\n timer ??= setTimeout(flush, FLUSH_MS);\n };\n const end = (\n status: \"succeeded\" | \"failed\" | \"cancelled\",\n reason?: string,\n error?: WireError,\n ): void => {\n flush();\n const state = interaction.endRun(row.id, {\n status,\n ...(reason ? { reason } : {}),\n ...(error ? { error: redactError(error) } : {}),\n });\n if (state) {\n publish(row.artifact_id, {\n runId: row.id,\n status: state.status,\n ...(state.reason ? { reason: state.reason } : {}),\n logFrom: state.log.length,\n log: [],\n batchFrom: state.batches.length,\n batches: [],\n ...(state.error ? { error: state.error } : {}),\n ...(state.finishedAt ? { finishedAt: state.finishedAt } : {}),\n });\n }\n };\n\n let ended = false;\n try {\n let handle: WorkerHandle;\n // A cancel while the worker starts (or backs off after a crash) ends the run at once.\n entry.endNow = () => {\n ended = true;\n end(\"cancelled\", \"cancelled\");\n };\n try {\n handle = await pool.acquire(versionOf(row.version_id));\n } catch (error) {\n delete entry.endNow;\n if (ended) return;\n const diagnostic = error instanceof RpcError ? error.diagnostic : undefined;\n end(\"failed\", diagnostic?.code === \"MOSTRA_RUNTIME_WORKER_PARKED\" ? \"parked\" : \"crashed\", {\n code: diagnostic?.code ?? \"MOSTRA_RUNTIME_WORKER_CRASHED\",\n message: diagnostic?.message ?? String(error),\n });\n return;\n }\n delete entry.endNow;\n if (ended) return;\n if (entry.cancelled) {\n end(\"cancelled\", \"cancelled\");\n return;\n }\n interaction.runRunning(row.id);\n publish(row.artifact_id, {\n runId: row.id,\n status: \"running\",\n logFrom: 0,\n log: [],\n batchFrom: 0,\n batches: [],\n });\n const viewer = row.viewer_id ? interaction.viewer(row.viewer_id) : undefined;\n const { callId, outcome } = handle.call(\n {\n fnId: row.action,\n args: JSON.parse(row.args_json) as Batches,\n context: {\n kind: \"run\",\n runId: row.id,\n ...(row.view_id ? { viewId: row.view_id } : {}),\n ...(viewer\n ? { viewer: { id: viewer.id, ...(viewer.name ? { name: viewer.name } : {}) } }\n : {}),\n dryRun: options.dryRun !== undefined,\n },\n ...(row.viewer_id ? { viewerId: row.viewer_id } : {}),\n },\n {\n onBatch(batch) {\n if (tooLarge) return;\n size += JSON.stringify(batch).length;\n if (size > ACTION_RESULT_MAX) {\n tooLarge = true;\n handle.cancel(callId, \"The result grew past 16 MiB.\");\n return;\n }\n pendingBatches.push(redactFrames([...batch], options.redactor));\n soon();\n },\n onProgress(progress) {\n pendingProgress = redactValue(progress, options.redactor);\n soon();\n },\n onLog(line) {\n pendingLines.push(redact(line));\n soon();\n },\n },\n );\n entry.handle = handle;\n entry.callId = callId;\n callRuns.set(callId, row.id);\n if (entry.cancelled) handle.cancel(callId, \"The run was cancelled.\");\n let result: Awaited<typeof outcome>;\n try {\n result = await outcome;\n } catch (error) {\n // The worker ended during the run (D24: interrupted, never retried by Mostra).\n const cause = crashCauses.get(row.id);\n crashCauses.delete(row.id);\n const message = cause\n ? `The run was interrupted: the artifact's server code stopped (${cause}).`\n : error instanceof RpcError\n ? error.diagnostic.message\n : String(error);\n end(\"failed\", \"interrupted\", { code: \"MOSTRA_ACTION_INTERRUPTED\", message });\n return;\n } finally {\n callRuns.delete(callId);\n }\n if (tooLarge) {\n end(\"failed\", \"too-large\", {\n code: \"MOSTRA_ACTION_TOO_LARGE\",\n message: \"The run's result grew past 16 MiB; the run was stopped.\",\n });\n } else if (result.status === \"succeeded\") {\n end(\"succeeded\");\n } else if (result.status === \"cancelled\") {\n end(\"cancelled\", \"cancelled\");\n } else {\n // The stack goes to the run's log, never to the page (INTERFACES §2.4).\n if (result.error.stack) pendingLines.push(...redact(result.error.stack).split(\"\\n\"));\n end(\n \"failed\",\n result.error.code === \"MOSTRA_ACTION_UNSERIALIZABLE\" ? \"unserializable\" : \"threw\",\n { code: result.error.code ?? \"MOSTRA_ACTION_THREW\", message: result.error.message },\n );\n }\n } catch (error) {\n log.error(\"action.run_failed\", { runId: row.id, error });\n end(\"failed\", \"interrupted\", {\n code: \"MOSTRA_ACTION_INTERRUPTED\",\n message: \"Mostra couldn't finish running this action.\",\n });\n } finally {\n executing.delete(row.id);\n }\n };\n\n /** A plain call's lines, from a worker that has it. */\n async function* stream(\n page: PageIdentity,\n input: { readonly viewId: string; readonly fnId: string; readonly args: Batches },\n signal: AbortSignal,\n handle: WorkerHandle,\n ): AsyncGenerator<CallLine> {\n const viewer = interaction.viewer(page.viewerId);\n const queue: CallLine[] = [];\n let wake: (() => void) | undefined;\n let size = 0;\n let tooLarge = false;\n const { callId, outcome } = handle.call(\n {\n fnId: input.fnId,\n args: input.args,\n context: {\n kind: \"call\",\n viewId: input.viewId,\n viewer: { id: viewer.id, ...(viewer.name ? { name: viewer.name } : {}) },\n dryRun: options.dryRun !== undefined,\n },\n viewerId: page.viewerId,\n },\n {\n onBatch(batch) {\n if (tooLarge) return;\n // The same bound as a run's result, so a call never buffers without limit (D131).\n size += JSON.stringify(batch).length;\n if (size > ACTION_RESULT_MAX) {\n tooLarge = true;\n handle.cancel(callId, \"The result grew past 16 MiB.\");\n return;\n }\n queue.push({ batch: redactFrames([...batch], options.redactor) });\n wake?.();\n },\n },\n );\n calls += 1;\n const abort = (): void => handle.cancel(callId, \"The page went away.\");\n signal.addEventListener(\"abort\", abort, { once: true });\n let ended: CallLine | undefined;\n void outcome.then(\n (result) => {\n ended = tooLarge\n ? {\n end: {\n status: \"failed\",\n error: {\n code: \"MOSTRA_ACTION_TOO_LARGE\",\n message: \"The call's result grew past 16 MiB; the call was stopped.\",\n },\n },\n }\n : result.status === \"succeeded\"\n ? { end: { status: \"succeeded\" } }\n : result.status === \"cancelled\"\n ? {\n end: {\n status: \"failed\",\n error: { code: \"MOSTRA_ACTION_CANCELLED\", message: \"The call was cancelled.\" },\n },\n }\n : {\n end: {\n status: \"failed\",\n error: redactError({\n message: result.error.message,\n code: result.error.code ?? \"MOSTRA_ACTION_THREW\",\n }),\n },\n };\n wake?.();\n },\n (error: unknown) => {\n const diagnostic = error instanceof RpcError ? error.diagnostic : undefined;\n ended = {\n end: {\n status: \"failed\",\n error: {\n code: diagnostic?.code ?? \"MOSTRA_RUNTIME_WORKER_CRASHED\",\n message: redact(diagnostic?.message ?? String(error)),\n },\n },\n };\n wake?.();\n },\n );\n try {\n for (;;) {\n if (queue.length > 0) {\n yield queue.shift() as CallLine;\n continue;\n }\n if (ended) {\n yield ended;\n return;\n }\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n wake = undefined;\n }\n } finally {\n calls -= 1;\n signal.removeEventListener(\"abort\", abort);\n // A reader that stopped early (the response failed) leaves nothing running.\n if (!ended) handle.cancel(callId, \"The page went away.\");\n }\n }\n\n const bridge: Actions[\"bridge\"] = {\n async request(worker, method, params, call) {\n const runId = call?.context.runId;\n switch (method) {\n case WORKER_METHODS.secret: {\n const { name } = ServerSecretParams.parse(params);\n return { value: await options.secrets.resolve(worker.artifactId, name) };\n }\n case WORKER_METHODS.signal: {\n const parsed = ServerSignalParams.parse(params);\n return {\n cursor: interaction.serverSignal(worker.artifactId, {\n name: parsed.name,\n ...(parsed.payload !== undefined ? { payload: parsed.payload } : {}),\n ...(runId !== undefined ? { runId } : {}),\n ...(call?.viewerId !== undefined ? { viewerId: call.viewerId } : {}),\n }),\n };\n }\n case WORKER_METHODS.emit: {\n const parsed = ServerEmitParams.parse(params);\n if (!/^host\\.[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(parsed.type)) {\n throw failed(\n \"MOSTRA_ACTION_EVENT_INVALID\",\n `${parsed.type.slice(0, 80)} isn't a host event type.`,\n );\n }\n return {\n cursor: interaction.serverEmit(worker.artifactId, {\n type: parsed.type,\n ...(parsed.payload !== undefined ? { payload: parsed.payload } : {}),\n ...(runId !== undefined ? { runId } : {}),\n ...(call?.viewerId !== undefined ? { viewerId: call.viewerId } : {}),\n }),\n };\n }\n case WORKER_METHODS.stateGet: {\n const parsed = ServerStateGetParams.parse(params);\n return interaction.serverState(worker.artifactId, parsed.ids);\n }\n case WORKER_METHODS.statePatch: {\n const parsed = ServerStatePatchParams.parse(params);\n return interaction.serverPatch(worker.artifactId, {\n ops: redactValue(parsed.ops, options.redactor),\n ...(parsed.mutationId !== undefined ? { mutationId: parsed.mutationId } : {}),\n ...(parsed.baseRevision !== undefined ? { baseRevision: parsed.baseRevision } : {}),\n ...(runId !== undefined ? { runId } : {}),\n });\n }\n default:\n throw failed(\"MOSTRA_HOST_METHOD_UNKNOWN\", `Mostra serves workers no method ${method}.`);\n }\n },\n log(worker, line) {\n log.info(\"worker.log\", { versionId: worker.versionId, line: redact(line) });\n },\n };\n\n return {\n async call(page, input, signal) {\n checkArgs(input.args);\n const versionId = interaction.viewVersion(page, input.viewId);\n const handle = await pool.acquire(functionOf(versionId, input.fnId));\n return stream(page, input, signal, handle);\n },\n\n startRun(page, input) {\n checkArgs(input.args);\n const versionId = interaction.viewVersion(page, input.viewId);\n functionOf(versionId, input.fnId);\n const { state, row, started } = interaction.startRun(page, input);\n bus.attachRuns(page.artifactId, input.viewId, [state.runId]);\n if (started) void execute(row);\n return state;\n },\n\n attach(page, input) {\n const states = interaction.runsFor(page, input);\n bus.attachRuns(\n page.artifactId,\n input.viewId,\n states.map((state) => state.runId),\n );\n return states;\n },\n\n cancel(page, viewId, runId) {\n const row = interaction.runFor(page, viewId, runId);\n const running = executing.get(row.id);\n if (running) {\n running.cancelled = true;\n if (running.handle && running.callId) {\n running.handle.cancel(running.callId, \"Cancelled from a page.\");\n } else running.endNow?.();\n } else if (row.status === \"queued\" || row.status === \"running\" || row.status === \"waiting\") {\n // Recorded but not in this instance (it restarted): nothing runs it, so it ends here.\n interaction.endRun(row.id, { status: \"cancelled\", reason: \"cancelled\" });\n }\n return interaction.runState(row.id) as RunState;\n },\n\n bridge,\n\n crashed(crash) {\n // The runs' own `execute` ends them, flushing what they logged first; this only says why.\n for (const callId of crash.callIds) {\n const runId = callRuns.get(callId);\n if (runId) crashCauses.set(runId, crash.cause);\n }\n },\n\n recover() {\n for (const row of interaction.openRuns()) {\n interaction.endRun(row.id, {\n status: \"failed\",\n reason: \"interrupted\",\n error: {\n code: \"MOSTRA_ACTION_INTERRUPTED\",\n message: \"The run was interrupted: Mostra stopped while it ran.\",\n },\n });\n }\n },\n\n activity() {\n return executing.size + calls;\n },\n };\n}\n","/**\n * Addressing (D21, D38, D70, D99): where the instance is reachable. It decides the bind address\n * and the URL host, forms each listener's origin and its exact `Host` allowlist, leases a stable\n * port per home for the shell and for each artifact, binds servers to their leased ports (leasing\n * a new one when another program took it), and picks the frame-session mode for a shell and\n * artifact origin pair. The gateway decides what is served on those ports.\n *\n * ```ts\n * const addressing = createAddressing({ ledger, log, bind: { address: \"127.0.0.1\" } });\n * const port = await addressing.listen(server, { purpose: \"artifact\", owner: artifactId });\n * addressing.origin(port); // \"http://127.0.0.1:23457\"\n * ```\n */\nimport { randomInt } from \"node:crypto\";\nimport type { Server } from \"node:net\";\nimport { isIP } from \"node:net\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\n\n/** The lowest port Mostra leases: below every ephemeral range (D99). */\nexport const LEASE_FIRST_PORT = 20000;\n/** The highest port Mostra leases: Linux's ephemeral range starts at 32768, macOS's at 49152. */\nexport const LEASE_LAST_PORT = 32767;\n/** How many free ports to try before giving up on a lease. */\nconst LEASE_ATTEMPTS = 64;\n\n/** What a lease is for (DATA_MODEL §3 `port_lease.purpose`); `face` from WP-13 (D158). */\nexport type LeasePurpose = \"shell\" | \"artifact\" | \"demo\" | \"face\";\n\n/** The address every face listens on: loopback, whatever `--bind` says (D158 item 1). */\nexport const FACE_BIND_ADDRESS = \"127.0.0.1\";\n\n/** Who holds a lease: the shell, an artifact ID, or a demo. */\nexport interface LeaseOwner {\n readonly purpose: LeasePurpose;\n /** `shell` for the shell; the artifact ID for an artifact. */\n readonly owner: string;\n}\n\n/** How the gateway binds (D99). */\nexport interface BindOptions {\n /** The address to listen on; `127.0.0.1` unless `--bind` names another. */\n readonly address: string;\n /** The host name URLs use and the Host allowlist accepts; required for a wildcard address. */\n readonly urlHost?: string;\n}\n\n/** How a frame authenticates for one shell and artifact origin pair (D70, D98). */\nexport type FrameMode = \"cookie\" | \"worker\";\n\n/** Where the instance is reachable. */\nexport interface Addressing {\n /** The address every listener binds. */\n readonly bindAddress: string;\n /** The host name in every URL, bracketed when it is an IPv6 literal. */\n readonly urlHost: string;\n /** The origin a listener on `port` serves: `http://<url host>:<port>`. */\n origin(port: number): string;\n /** The exact `Host` values a listener on `port` accepts, lowercase. */\n hosts(port: number): readonly string[];\n /** The leased port of an owner, if it has one. */\n leased(owner: LeaseOwner): number | undefined;\n /** Every lease, for binding them all at start. */\n leases(): readonly (LeaseOwner & { readonly port: number })[];\n /**\n * Binds `server` to the owner's leased port, or to a newly leased one when it has none or\n * another program holds it (`MOSTRA_ENV_PORT_TAKEN`). Resolves with the bound port.\n */\n listen(server: Server, owner: LeaseOwner): Promise<number>;\n /**\n * The frame-session mode for a shell and artifact origin pair: cookie mode when they share a\n * host (same site, D38), worker mode otherwise (cross-site, D70).\n */\n frameMode(shellOrigin: string, artifactOrigin: string): FrameMode;\n /**\n * Binds a face's listener on loopback (D158 item 1): on the port leased to `key` when `lease`\n * is set, so the face keeps its address across restarts, else on a port the operating system\n * picks. Resolves with the port.\n */\n listenFace(\n server: Server,\n face: { readonly key: string; readonly lease: boolean },\n ): Promise<number>;\n /** Releases a face's leased port, once the face is gone for good. */\n releaseFace(key: string): void;\n /** The loopback origin of a face listener on `port`: `http://127.0.0.1:<port>`. */\n faceLocal(port: number): string;\n}\n\n/**\n * The exact `Host` a browser sends for an origin: its host, with the port only when it isn't the\n * scheme's default (`https://a.ts.net` is `a.ts.net`, `https://a.ts.net:8443` is\n * `a.ts.net:8443`), lowercase. Registered tunnel addresses join the allowlist this way.\n */\nexport function hostOf(origin: string): string {\n return new URL(origin).host.toLowerCase();\n}\n\n/** The unspecified addresses, as {@link authorityHost} writes them: each listens everywhere. */\nconst WILDCARDS = new Set([\"0.0.0.0\", \"[::]\", \"[::ffff:0:0]\"]);\n\nfunction bindFailed(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_BIND_FAILED\", { message }));\n}\n\n/**\n * Validates the bind flags (D99) and returns the address and URL host. A wildcard address needs\n * `urlHost`; `urlHost` alone, without a wider bind, is refused, so a URL never names a host the\n * gateway doesn't listen on.\n */\nexport function resolveBind(options: {\n readonly bind?: string | undefined;\n readonly urlHost?: string | undefined;\n}): BindOptions {\n const address = options.bind ?? \"127.0.0.1\";\n const bare = address.replace(/^\\[(.*)\\]$/, \"$1\");\n if (isIP(bare) === 0) {\n throw bindFailed(`--bind takes an IP address, such as 127.0.0.1 or 0.0.0.0, not \"${address}\".`);\n }\n if (options.urlHost !== undefined && options.bind === undefined) {\n throw bindFailed(\"--url-host needs --bind: without it the gateway listens on 127.0.0.1 only.\");\n }\n // Compared in canonical form, so `0:0:0:0:0:0:0:0`, `::0` and `::ffff:0.0.0.0` count too.\n if (WILDCARDS.has(authorityHost(bare)) && options.urlHost === undefined) {\n throw bindFailed(\n `--bind ${address} listens on every interface; name the host viewers use with --url-host.`,\n );\n }\n if (\n options.urlHost !== undefined &&\n !/^(\\[[0-9a-f:.]+\\]|[a-z0-9.-]+|[0-9a-f:]+)$/i.test(options.urlHost)\n ) {\n throw bindFailed(`--url-host takes a host name or an IP address, not \"${options.urlHost}\".`);\n }\n if (options.urlHost !== undefined) {\n try {\n authorityHost(options.urlHost);\n } catch {\n throw bindFailed(`--url-host takes a host name or an IP address, not \"${options.urlHost}\".`);\n }\n }\n return { address: bare, ...(options.urlHost !== undefined ? { urlHost: options.urlHost } : {}) };\n}\n\n/**\n * A host as browsers write it in `Origin` and `Host`: lowercase, IPv6 compressed and bracketed\n * (`0:0:0:0:0:0:0:1` is `[::1]`). Origins and the Host allowlist use this form, so the exact\n * comparisons agree with what a browser sends however the flag spelled the address.\n */\nfunction authorityHost(host: string): string {\n const bare = host.replace(/^\\[(.*)\\]$/, \"$1\");\n return new URL(`http://${isIP(bare) === 6 ? `[${bare}]` : bare}/`).hostname;\n}\n\n/**\n * Binds `server` to `port` on `address`; resolves `false` when that port is taken. Every other\n * failure is about the address, so no port would do: it is `MOSTRA_ENV_BIND_FAILED`.\n */\nfunction tryListen(server: Server, port: number, address: string): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const onError = (error: NodeJS.ErrnoException): void => {\n server.off(\"listening\", onListening);\n if (error.code === \"EADDRINUSE\" || error.code === \"EACCES\") resolve(false);\n else if (error.code === \"EADDRNOTAVAIL\") {\n reject(bindFailed(`No network interface of this machine has the address ${address}.`));\n } else if (error.code === \"EAFNOSUPPORT\") {\n reject(\n bindFailed(\n `This machine has no ${isIP(address) === 6 ? \"IPv6\" : \"IPv4\"} support for ${address}.`,\n ),\n );\n } else {\n reject(\n bindFailed(`The gateway can't listen on ${address}: ${error.code ?? error.message}.`),\n );\n }\n };\n const onListening = (): void => {\n server.off(\"error\", onError);\n resolve(true);\n };\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen({ port, host: address, exclusive: true });\n });\n}\n\n/** Creates the addressing of one instance over its ledger's `port_lease` table. */\nexport function createAddressing(options: {\n readonly ledger: Ledger;\n readonly log: Log;\n readonly bind: BindOptions;\n /**\n * Listen on ports the operating system assigns and lease none: a `verify` run's short-lived\n * listeners (D138). Ephemeral ports lie above the lease range (D99), so they never take a port\n * leased to an artifact whose listener isn't bound yet (D132).\n */\n readonly ephemeral?: boolean;\n /** With `ephemeral`: the port the shell listens on instead of one assigned (`mostra dev --port`). */\n readonly shellPort?: number;\n}): Addressing {\n const { ledger, log } = options;\n const bindAddress = options.bind.address;\n const urlHost = authorityHost(options.bind.urlHost ?? bindAddress).toLowerCase();\n\n const leased = (owner: LeaseOwner): number | undefined =>\n ledger.read((db) =>\n db.get<{ port: number }>(\n \"SELECT port FROM port_lease WHERE purpose = ? AND owner_ref = ?\",\n owner.purpose,\n owner.owner,\n ),\n )?.port;\n\n const record = (owner: LeaseOwner, port: number): void => {\n ledger.write((db) => {\n db.run(\n \"DELETE FROM port_lease WHERE purpose = ? AND owner_ref = ?\",\n owner.purpose,\n owner.owner,\n );\n // A port another owner once held, but that this process could bind, is no longer theirs.\n db.run(\"DELETE FROM port_lease WHERE port = ?\", port);\n db.run(\n \"INSERT INTO port_lease (port, purpose, owner_ref, leased_at) VALUES (?, ?, ?, ?)\",\n port,\n owner.purpose,\n owner.owner,\n new Date().toISOString(),\n );\n });\n };\n\n const taken = (): Set<number> =>\n new Set(\n ledger\n .read((db) => db.all<{ port: number }>(\"SELECT port FROM port_lease\"))\n .map((row) => row.port),\n );\n\n /**\n * Binds `server` to the owner's leased port on `address`, or to a newly leased one when it has\n * none or another program holds it (`MOSTRA_ENV_PORT_TAKEN`).\n */\n const leaseAndListen = async (\n server: Server,\n owner: LeaseOwner,\n address: string,\n ): Promise<number> => {\n const previous = leased(owner);\n if (previous !== undefined) {\n if (await tryListen(server, previous, address)) return previous;\n log.warn(\"addressing.port_taken\", {\n code: \"MOSTRA_ENV_PORT_TAKEN\",\n purpose: owner.purpose,\n owner: owner.owner,\n port: previous,\n });\n }\n const others = taken();\n for (let attempt = 0; attempt < LEASE_ATTEMPTS; attempt++) {\n const port = randomInt(LEASE_FIRST_PORT, LEASE_LAST_PORT + 1);\n if (others.has(port)) continue;\n if (!(await tryListen(server, port, address))) continue;\n record(owner, port);\n if (previous !== undefined) {\n log.warn(\"addressing.port_released\", {\n purpose: owner.purpose,\n owner: owner.owner,\n from: previous,\n to: port,\n });\n }\n return port;\n }\n throw bindFailed(\n `No free port between ${LEASE_FIRST_PORT} and ${LEASE_LAST_PORT} on ${address} after ${LEASE_ATTEMPTS} attempts.`,\n );\n };\n\n return {\n bindAddress,\n urlHost,\n origin: (port) => `http://${urlHost}:${port}`,\n hosts: (port) => [`${urlHost}:${port}`],\n leased,\n leases: () =>\n ledger\n .read((db) =>\n db.all<{ port: number; purpose: LeasePurpose; owner_ref: string }>(\n \"SELECT port, purpose, owner_ref FROM port_lease ORDER BY purpose DESC, port\",\n ),\n )\n .map((row) => ({ port: row.port, purpose: row.purpose, owner: row.owner_ref })),\n async listen(server, owner) {\n if (options.ephemeral) {\n const wanted = owner.purpose === \"shell\" ? (options.shellPort ?? 0) : 0;\n if (!(await tryListen(server, wanted, bindAddress))) {\n throw bindFailed(\n wanted === 0\n ? `No ephemeral port is free on ${bindAddress}.`\n : `The port ${wanted} on ${bindAddress} is taken.`,\n );\n }\n const address = server.address();\n if (address === null || typeof address === \"string\") throw new Error(\"not a TCP listener\");\n return address.port;\n }\n return leaseAndListen(server, owner, bindAddress);\n },\n frameMode(shellOrigin, artifactOrigin) {\n return new URL(shellOrigin).hostname === new URL(artifactOrigin).hostname\n ? \"cookie\"\n : \"worker\";\n },\n async listenFace(server, face) {\n if (!face.lease) {\n if (!(await tryListen(server, 0, FACE_BIND_ADDRESS))) {\n throw bindFailed(`No port is free on ${FACE_BIND_ADDRESS}.`);\n }\n const address = server.address();\n if (address === null || typeof address === \"string\") throw new Error(\"not a TCP listener\");\n return address.port;\n }\n return leaseAndListen(server, { purpose: \"face\", owner: face.key }, FACE_BIND_ADDRESS);\n },\n releaseFace(key) {\n ledger.write((db) =>\n db.run(\"DELETE FROM port_lease WHERE purpose = 'face' AND owner_ref = ?\", key),\n );\n },\n faceLocal: (port) => `http://${FACE_BIND_ADDRESS}:${port}`,\n };\n}\n","/**\n * Field coverage (D109): which field IDs a version's code can use, as the builder's static scan\n * records them in `registry.json`, and the one matcher the supervisor judges orphans with. Pure\n * and free of the bundler, so the supervisor and `verify` (WP-09) can use it.\n */\n\n/** Where a field ID was found. */\nexport interface FieldLocation {\n readonly file: string;\n readonly line: number;\n readonly column: number;\n}\n\n/** The client-runtime call that names a field. */\nexport type FieldHook = \"useField\" | \"useChoice\" | \"useForm\" | \"storage\";\n\n/** One place the version's code names a field ID. */\nexport interface FieldEntry {\n /** A literal field ID. Exactly one of `id` and `template` is set. */\n readonly id?: string;\n /**\n * A template field ID: its literal parts around each `${…}` hole, so `reply.${m.id}` is\n * `[\"reply.\", \"\"]`. A hole stands for any text.\n */\n readonly template?: readonly string[];\n /** The call that names it. */\n readonly hook: FieldHook;\n /** Its scope, when the code gives it literally; absent when unknown or the default (`viewer`). */\n readonly scope?: \"viewer\" | \"artifact\";\n /** Its literal `label`, `required` and `sensitive` options, for `verify` and the shell. */\n readonly label?: string;\n readonly required?: boolean;\n readonly sensitive?: boolean;\n readonly location: FieldLocation;\n}\n\n/** The fields a version covers (D109). */\nexport interface FieldCoverage {\n /**\n * `true` when the version's code can use field IDs the scan couldn't know (a computed ID, a\n * hook passed around, a package that uses the hooks itself): the version then covers every\n * ID, so nothing is ever orphaned by a guess.\n */\n readonly open: boolean;\n /** Why the coverage is open, for `verify`'s hints; empty when it isn't. */\n readonly openReasons: readonly { readonly reason: string; readonly location?: FieldLocation }[];\n /** Every place a field ID is named, in source order. */\n readonly entries: readonly FieldEntry[];\n}\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Whether a version with this coverage covers a draft field ID (D109). A version without\n * coverage (built before WP-07) covers everything, as does an open one. Only entries that may be\n * viewer-scoped count: an artifact-scoped field never lives in a draft.\n */\nexport function coverageMatcher(coverage: FieldCoverage | undefined): (fieldId: string) => boolean {\n if (coverage === undefined || coverage.open) return () => true;\n const ids = new Set<string>();\n const templates: RegExp[] = [];\n for (const entry of coverage.entries) {\n if (entry.scope === \"artifact\") continue;\n if (entry.id !== undefined) ids.add(entry.id);\n else if (entry.template !== undefined) {\n templates.push(new RegExp(`^${entry.template.map(escapeRegExp).join(\"[\\\\s\\\\S]*\")}$`));\n }\n }\n return (fieldId) => ids.has(fieldId) || templates.some((pattern) => pattern.test(fieldId));\n}\n","/**\n * Process identity (DATA_MODEL §3 `child.start_time`, FAILURE_MODEL §2). A PID alone can be\n * reused, so a process is identified by its PID plus an opaque start time: the boot it started in\n * and when it started within that boot. Linux reads `/proc/<pid>/stat` (start ticks since boot)\n * and the boot ID; macOS reads `ps -o lstart` (seconds) and `kern.boottime` (VERIFIED_FACTS,\n * WP-02); Windows asks the helper for the creation time (`GetProcessTimes`, 100 ns units since\n * 1601, so absolute across boots), written `win/<creation time>` (VERIFIED_FACTS, WP-W1). Zombies,\n * and Windows processes that exited but whose object a handle still keeps, count as gone.\n *\n * Seconds are enough on macOS (issue #8): XNU hands out PIDs in order from the last one, up to\n * 99,999, then from 100, skipping any PID still used as a process, process group or session\n * (`forkproc` in `bsd/kern/kern_fork.c`). A PID comes back only after the whole range has been\n * handed out, about 99,900 forks, which takes this machine about 100 s at its measured 1,000\n * spawns a second, and never while its process group lives (VERIFIED_FACTS, WP-08).\n */\nimport { execFile } from \"node:child_process\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { runHelperAsync } from \"./helper.ts\";\n\n/** The boot part of every Windows start time: creation times are absolute. */\nconst WINDOWS_BOOT = \"win\";\n\n/** One running process as the operating system reports it. */\nexport interface ProcessInfo {\n readonly pid: number;\n /** Its process group; on Windows, where processes have none, its own PID. */\n readonly pgid: number;\n /** `<boot>/<start>`: opaque, but comparable with {@link startedNoEarlier} within one boot. */\n readonly startTime: string;\n}\n\n/** Splits a start time into its boot and its position within the boot. */\nfunction parts(startTime: string): { boot: string; at: bigint } | undefined {\n const slash = startTime.lastIndexOf(\"/\");\n if (slash <= 0) return undefined;\n const text = startTime.slice(slash + 1);\n // Seconds on macOS, ticks on Linux, 100 ns units since 1601 on Windows (past 2^53).\n if (!/^\\d+$/.test(text)) return undefined;\n return { boot: startTime.slice(0, slash), at: BigInt(text) };\n}\n\n/** Whether two start times belong to the same boot of the machine. */\nexport function sameBoot(a: string, b: string): boolean {\n const left = parts(a);\n const right = parts(b);\n return left !== undefined && right !== undefined && left.boot === right.boot;\n}\n\n/**\n * Whether `candidate` started in the same boot as `reference` and no earlier. On macOS the\n * resolution is one second, so a process started in the same second counts as no earlier.\n */\nexport function startedNoEarlier(candidate: string, reference: string): boolean {\n const c = parts(candidate);\n const r = parts(reference);\n return c !== undefined && r !== undefined && c.boot === r.boot && c.at >= r.at;\n}\n\n/** Parses one `/proc/<pid>/stat` line. `comm` may contain spaces and parentheses. */\nexport function parseProcStat(line: string, boot: string): ProcessInfo | undefined {\n const open = line.indexOf(\"(\");\n const close = line.lastIndexOf(\")\");\n if (open < 0 || close < open) return undefined;\n const pid = Number(line.slice(0, open).trim());\n // Fields after `comm` start at field 3 (state); pgrp is field 5 and starttime field 22.\n const rest = line\n .slice(close + 1)\n .trim()\n .split(/\\s+/);\n // A zombie has exited; only its parent's wait is missing. It runs nothing and is skipped.\n if (rest[0] === \"Z\") return undefined;\n const pgid = Number(rest[2]);\n const start = rest[19];\n if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(pgid) || start === undefined) {\n return undefined;\n }\n if (!/^\\d+$/.test(start)) return undefined;\n return { pid, pgid, startTime: `${boot}/${start}` };\n}\n\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n\n/**\n * Parses one line of `LC_ALL=C TZ=UTC ps -o pid=,pgid=,stat=,lstart=`, such as\n * ` 214 99444 Ss Tue Oct 6 13:53:19 2026`. Zombies (`stat` starting with `Z`) are skipped.\n */\nexport function parsePsLine(line: string, boot: string): ProcessInfo | undefined {\n const fields = line.trim().split(/\\s+/);\n if (fields.length < 8) return undefined;\n const [pidText, pgidText, stat, , monthText, dayText, timeText, yearText] = fields;\n if (stat?.startsWith(\"Z\")) return undefined;\n const pid = Number(pidText);\n const pgid = Number(pgidText);\n const month = MONTHS.indexOf(monthText ?? \"\");\n const [hours, minutes, seconds] = (timeText ?? \"\").split(\":\").map(Number);\n const millis = Date.UTC(\n Number(yearText),\n month,\n Number(dayText),\n hours ?? Number.NaN,\n minutes ?? Number.NaN,\n seconds ?? Number.NaN,\n );\n if (\n !Number.isSafeInteger(pid) ||\n !Number.isSafeInteger(pgid) ||\n month < 0 ||\n Number.isNaN(millis)\n ) {\n return undefined;\n }\n return { pid, pgid, startTime: `${boot}/${millis / 1000}` };\n}\n\nfunction run(file: string, args: readonly string[]): Promise<{ code: number; stdout: string }> {\n return new Promise((resolve, reject) => {\n execFile(\n file,\n args,\n {\n env: { LC_ALL: \"C\", TZ: \"UTC\", PATH: \"/usr/bin:/bin:/usr/sbin:/sbin\" },\n maxBuffer: 64 * 1024 * 1024,\n },\n (error, stdout) => {\n if (error && typeof error.code !== \"number\") {\n reject(error);\n return;\n }\n resolve({ code: typeof error?.code === \"number\" ? error.code : 0, stdout });\n },\n );\n });\n}\n\nlet cachedBoot: Promise<string> | undefined;\n\n/** The identity of the current boot of this machine (on Windows a constant: times are absolute). */\nexport function bootId(): Promise<string> {\n cachedBoot ??= (async () => {\n if (process.platform === \"win32\") return WINDOWS_BOOT;\n if (process.platform === \"linux\") {\n return (await readFile(\"/proc/sys/kernel/random/boot_id\", \"utf8\")).trim();\n }\n const { stdout } = await run(\"/usr/sbin/sysctl\", [\"-n\", \"kern.boottime\"]);\n const match = /sec = (\\d+), usec = (\\d+)/.exec(stdout);\n if (!match) throw new Error(\"Couldn't read kern.boottime.\");\n return `${match[1]}.${match[2]}`;\n })();\n return cachedBoot;\n}\n\ninterface WindowsProcess {\n readonly pid: number;\n readonly ppid?: number;\n readonly startTime?: string;\n}\n\n/** Reads one process, or `undefined` when no process has that PID. */\nexport async function readProcess(pid: number): Promise<ProcessInfo | undefined> {\n if (process.platform === \"win32\") {\n const [entry] = await runHelperAsync<WindowsProcess[]>([\"identity\", String(pid)]);\n return entry?.startTime === undefined\n ? undefined\n : { pid, pgid: pid, startTime: entry.startTime };\n }\n const boot = await bootId();\n if (process.platform === \"linux\") {\n try {\n return parseProcStat(await readFile(`/proc/${pid}/stat`, \"utf8\"), boot);\n } catch {\n return undefined;\n }\n }\n const { code, stdout } = await run(\"/bin/ps\", [\n \"-o\",\n \"pid=,pgid=,stat=,lstart=\",\n \"-p\",\n String(pid),\n ]);\n if (code !== 0) return undefined;\n const [line] = stdout.split(\"\\n\").filter((text) => text.trim() !== \"\");\n return line === undefined ? undefined : parsePsLine(line, boot);\n}\n\n/**\n * Lists every process the user can see. On Windows each carries its parent's PID (`ppid`), which\n * may name a process that has since exited and whose PID was reused.\n */\nexport async function listProcesses(): Promise<(ProcessInfo & { readonly ppid?: number })[]> {\n if (process.platform === \"win32\") {\n const entries = await runHelperAsync<WindowsProcess[]>([\"processes\"]);\n return entries.flatMap((entry) =>\n entry.startTime === undefined\n ? []\n : [{ pid: entry.pid, pgid: entry.pid, startTime: entry.startTime, ppid: entry.ppid ?? 0 }],\n );\n }\n const boot = await bootId();\n if (process.platform === \"linux\") {\n const entries = (await readdir(\"/proc\")).filter((name) => /^\\d+$/.test(name));\n const infos = await Promise.all(\n entries.map(async (name) => {\n try {\n return parseProcStat(await readFile(`/proc/${name}/stat`, \"utf8\"), boot);\n } catch {\n return undefined;\n }\n }),\n );\n return infos.filter((info): info is ProcessInfo => info !== undefined);\n }\n const { stdout } = await run(\"/bin/ps\", [\"-A\", \"-o\", \"pid=,pgid=,stat=,lstart=\"]);\n return stdout\n .split(\"\\n\")\n .map((line) => parsePsLine(line, boot))\n .filter((info): info is ProcessInfo => info !== undefined);\n}\n\n/** Whether the process recorded as `pid` and `startTime` is still the one running. */\nexport async function isSameProcess(pid: number, startTime: string): Promise<boolean> {\n const info = await readProcess(pid);\n return info !== undefined && info.startTime === startTime;\n}\n","/**\n * Starting, ending and reaping children on each operating system (RT-09, RT-10, issue #7, D93,\n * FAILURE_MODEL §2). The process manager keeps the policy (record a child before it runs, end its\n * descendants with it, reap what a crashed supervisor left); this module is how each system does\n * it.\n *\n * - **POSIX.** A child is started detached, as the leader of its own process group, behind a\n * `/bin/sh` gate that waits for \"go\" on descriptor 3 and then `exec`s the command, keeping its\n * PID, group and start time. It is ended by signalling its group (SIGTERM, then SIGKILL), and\n * the reaper signals a recorded group's members that started no earlier than its leader.\n * - **Windows.** A child is started behind `mostra-win gate`, which creates it suspended in a Job\n * Object of its own that ends every member when its last handle closes, reports its PID and\n * creation time on descriptor 3, and lets it run on \"go\". Descriptor 3 stays open as the\n * child's lifeline: closing it (a stop, or the supervisor's exit or crash) ends the job, child\n * and descendants at once. Windows has no signals to ask a process to stop, so a stop is that:\n * graceful work goes over the child's own channel first (D87). The reaper ends a recorded\n * child's job, which it opens by the name the gate gave it (`Local\\mostra-job-<pid>-<creation>`),\n * and the child itself if it still runs as the recorded process.\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport type { Readable, Writable } from \"node:stream\";\nimport { WINDOWS } from \"./directories.ts\";\nimport { helperPath, runHelperAsync } from \"./helper.ts\";\nimport {\n listProcesses,\n type ProcessInfo,\n readProcess,\n sameBoot,\n startedNoEarlier,\n} from \"./identity.ts\";\n\n/**\n * The POSIX gate (issue #7): `/bin/sh` waits for \"go\" on file descriptor 3 and only then replaces\n * itself with the real command. A supervisor killed in between leaves a gate that reads\n * end-of-file and exits 125 without running anything.\n */\nconst GATE_SCRIPT = 'IFS= read -r go <&3 && [ \"$go\" = go ] || exit 125; exec 3<&-; exec \"$@\"';\n\n/** How long reaping waits between SIGTERM and SIGKILL. */\nconst REAP_GRACE_MS = 2000;\n/** How long to wait for SIGKILLed processes to disappear before reporting them. */\nconst KILL_WAIT_MS = 5000;\n\n/** What a launch needs. */\nexport interface LaunchSpec {\n /** What the child is (`builder`, `install` …), shown in process listings. */\n readonly kind: string;\n /** The executable: an absolute path on Windows. */\n readonly command: string;\n readonly args: readonly string[];\n readonly cwd?: string | undefined;\n readonly env: NodeJS.ProcessEnv;\n /** Node's IPC channel or a plain byte channel on descriptor 4, or nothing. */\n readonly extra?: \"ipc\" | \"channel\" | undefined;\n}\n\n/** A child started behind its gate. */\nexport interface Launched {\n /** The process Node started (on Windows the gate, which ends when its child does). */\n readonly process: ChildProcess;\n /** The child's identity once known, `undefined` when it is already gone; rejects when unreadable. */\n identify(): Promise<{ readonly pid: number; readonly startTime: string } | undefined>;\n /** Lets the recorded child run. */\n release(): void;\n /** Whether the child or anything it started still runs. */\n running(): boolean;\n /**\n * Ends the child and everything it started: POSIX signals its group and `extraGroups` (SIGTERM,\n * SIGKILL after `graceMs`); Windows closes its lifeline and, after `graceMs`, kills the gate.\n */\n end(graceMs: number, extraGroups: readonly number[]): Promise<void>;\n /** After the child exited, ends what is left of its group (nothing on Windows: its job ended). */\n sweep(extraGroups: readonly number[]): Promise<void>;\n /** At the supervisor's own exit: ends everything at once, without waiting. */\n kill(): void;\n}\n\nconst delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction signalGroup(pgid: number, signal: NodeJS.Signals | 0): boolean {\n try {\n process.kill(-pgid, signal);\n return true;\n } catch {\n return false;\n }\n}\n\nconst groupAlive = (pgid: number): boolean => signalGroup(pgid, 0);\n\n/** Starts `spec` behind its gate. */\nexport function launch(\n spec: LaunchSpec,\n warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,\n): Launched {\n return WINDOWS ? launchWindows(spec) : launchPosix(spec, warn);\n}\n\nfunction stdioFor(extra: LaunchSpec[\"extra\"]): (\"ignore\" | \"pipe\" | \"ipc\" | \"overlapped\")[] {\n const base: (\"ignore\" | \"pipe\" | \"ipc\" | \"overlapped\")[] = [\"ignore\", \"pipe\", \"pipe\", \"pipe\"];\n // A byte channel is overlapped on Windows so both ends can read and write at once; the option\n // means \"pipe\" elsewhere.\n if (extra === \"ipc\") return [...base, \"ipc\"];\n if (extra === \"channel\") return [...base, \"overlapped\"];\n return base;\n}\n\nfunction launchPosix(\n spec: LaunchSpec,\n warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,\n): Launched {\n const child = spawn(\n \"/bin/sh\",\n [\"-c\", GATE_SCRIPT, `mostra-${spec.kind}`, spec.command, ...spec.args],\n {\n cwd: spec.cwd,\n env: spec.env,\n detached: true,\n stdio: stdioFor(spec.extra),\n serialization: \"json\",\n },\n );\n const gate = child.stdio[3] as Writable | null;\n gate?.on(\"error\", () => {\n // The child exited before reading \"go\"; its exit is reported through `exit`.\n });\n const pid = (): number => child.pid ?? 0;\n const end = async (pgids: readonly number[], graceMs: number): Promise<void> => {\n for (const pgid of pgids) signalGroup(pgid, \"SIGTERM\");\n const deadline = Date.now() + graceMs;\n while (Date.now() < deadline && pgids.some(groupAlive)) await delay(25);\n for (const pgid of pgids) if (groupAlive(pgid)) signalGroup(pgid, \"SIGKILL\");\n const killDeadline = Date.now() + KILL_WAIT_MS;\n while (Date.now() < killDeadline && pgids.some(groupAlive)) await delay(10);\n const left = pgids.filter(groupAlive);\n if (left.length > 0) warn(\"process.group_survived_sigkill\", { pgids: left });\n };\n return {\n process: child,\n async identify() {\n const info = await readProcess(pid());\n if (info) return { pid: info.pid, startTime: info.startTime };\n // Gone already: nothing is left to record or reap.\n if (child.exitCode !== null || child.signalCode !== null) return undefined;\n // Still waiting at its gate, so it can't have exited by itself: its identity just couldn't\n // be read (D80 Claude review finding 8).\n throw new Error(`Couldn't read the process identity of ${spec.kind} ${pid()}.`);\n },\n release() {\n gate?.end(\"go\\n\");\n },\n running: () => child.exitCode === null && child.signalCode === null,\n end: (graceMs, extraGroups) => end([pid(), ...extraGroups], graceMs),\n sweep: (extraGroups) => end([pid(), ...extraGroups], 2000),\n kill() {\n signalGroup(pid(), \"SIGKILL\");\n },\n };\n}\n\nfunction launchWindows(spec: LaunchSpec): Launched {\n // Node.js puts every child it starts, the gate too, into one kill-on-close job of its own\n // (libuv's global job), so a supervisor that dies takes its gates with it, and each gate's death\n // closes its child's job. A gate a test makes miss its lifeline (MOSTRA_TEST_GATE, a hung gate's\n // stand-in) is started outside that job, or nothing would be left for the reaper to find.\n const hung = (spec.env[\"MOSTRA_TEST_GATE\"] ?? \"\").split(\",\").includes(\"ignore-lifeline\");\n const child = spawn(helperPath(), [\"gate\", \"--\", spec.command, ...spec.args], {\n cwd: spec.cwd,\n env: spec.env,\n windowsHide: true,\n detached: hung,\n stdio: stdioFor(spec.extra),\n serialization: \"json\",\n });\n const lifeline = child.stdio[3] as (Readable & Writable) | null;\n lifeline?.on(\"error\", () => {});\n const report = new Promise<{ pid: number; startTime: string } | undefined>((resolve, reject) => {\n let text = \"\";\n const onData = (chunk: Buffer): void => {\n text += chunk.toString(\"utf8\");\n const end = text.indexOf(\"\\n\");\n if (end < 0) return;\n lifeline?.off(\"data\", onData);\n try {\n const line = JSON.parse(text.slice(0, end)) as {\n pid?: number;\n startTime?: string;\n error?: string;\n };\n if (line.pid !== undefined && line.startTime !== undefined) {\n resolve({ pid: line.pid, startTime: line.startTime });\n } else {\n reject(\n new Error(`The gate couldn't start ${spec.kind}: ${line.error ?? text.slice(0, end)}`),\n );\n }\n } catch {\n reject(new Error(`The gate of ${spec.kind} reported ${text.slice(0, 200)}`));\n }\n };\n lifeline?.on(\"data\", onData);\n child.once(\"exit\", () => resolve(undefined));\n child.once(\"error\", reject);\n });\n const exited = new Promise<void>((resolve) => {\n if (child.exitCode !== null) resolve();\n child.once(\"exit\", () => resolve());\n });\n const running = (): boolean => child.exitCode === null && child.signalCode === null;\n return {\n process: child,\n identify: () => report,\n release() {\n lifeline?.write(\"go\\n\");\n },\n running,\n async end(graceMs) {\n // Graceful work travels over the child's own channel before this (D87). Closing the\n // lifeline ends the job; a gate that doesn't exit by itself is killed, which closes the job\n // with its last handle.\n lifeline?.end();\n if (!running()) return;\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n exited,\n new Promise<void>((resolve) => (timer = setTimeout(resolve, graceMs))),\n ]);\n clearTimeout(timer);\n if (running()) child.kill();\n await Promise.race([exited, delay(KILL_WAIT_MS)]);\n },\n async sweep() {\n // The gate ended the child's job before it exited.\n },\n kill() {\n lifeline?.destroy();\n child.kill();\n },\n };\n}\n\n/** One recorded child, as the ledger's `child` table holds it. */\nexport interface RecordedChild {\n readonly pid: number;\n readonly start_time: string;\n readonly pgid: number;\n}\n\n/** What reaping did for one recorded child. */\nexport interface ReapOutcome {\n /** The processes it ended: the child if it still ran, and what its group or job held. */\n readonly ended: readonly number[];\n /** Why nothing was ended, when nothing was. */\n readonly skipped?: \"gone\" | \"pid reused\" | \"other boot\";\n}\n\n/**\n * Ends what a previous supervisor's children left running, by their recorded identities, and\n * leaves alone processes that only look like them (FAILURE_MODEL §2). Call it only while holding\n * the home's ledger lock.\n */\nexport function reapRecorded(\n rows: readonly RecordedChild[],\n warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,\n): Promise<ReapOutcome[]> {\n return WINDOWS ? reapWindows(rows, warn) : reapPosix(rows, warn);\n}\n\nasync function reapWindows(\n rows: readonly RecordedChild[],\n warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,\n): Promise<ReapOutcome[]> {\n if (rows.length === 0) return [];\n const answers = await runHelperAsync<\n { pid: number; job?: boolean; ended?: number[]; reused?: boolean; error?: string }[]\n >([\"reap\", ...rows.map((row) => `${row.pid}:${row.start_time}`)]);\n return rows.map((row, index): ReapOutcome => {\n const answer = answers[index];\n // A process the helper couldn't end (access, a protected process) is reported, never hidden.\n if (answer?.error !== undefined) {\n warn(\"process.reap_incomplete\", { pid: row.pid, error: answer.error });\n }\n const ended = answer?.ended ?? [];\n if (ended.length > 0) return { ended };\n return { ended: [], skipped: answer?.reused ? \"pid reused\" : \"gone\" };\n });\n}\n\n/** The processes of a recorded group that are provably the recorded child's. */\nfunction targetsFor(\n row: RecordedChild,\n processes: readonly ProcessInfo[],\n): number[] | NonNullable<ReapOutcome[\"skipped\"]> {\n const leader = processes.find((info) => info.pid === row.pid);\n if (leader && leader.startTime !== row.start_time) return \"pid reused\";\n if (!leader) {\n const boot = processes.find((info) => info.pid === process.pid)?.startTime;\n if (boot === undefined || !sameBoot(boot, row.start_time)) return \"other boot\";\n }\n const members = processes\n .filter((info) => info.pgid === row.pgid && info.pid !== process.pid)\n .filter((info) => startedNoEarlier(info.startTime, row.start_time))\n .map((info) => info.pid);\n return members.length > 0 ? members : \"gone\";\n}\n\nfunction signalAll(pids: readonly number[], signal: NodeJS.Signals): void {\n for (const pid of pids) {\n try {\n process.kill(pid, signal);\n } catch {\n // Already gone.\n }\n }\n}\n\nasync function reapPosix(\n rows: readonly RecordedChild[],\n warn: (event: string, fields: Readonly<Record<string, unknown>>) => void,\n): Promise<ReapOutcome[]> {\n if (rows.length === 0) return [];\n const before = await listProcesses();\n const plan = rows.map((row) => ({ row, targets: targetsFor(row, before) }));\n // Only groups proven to be the recorded children's are signalled, then watched until they are\n // empty: a member may start more processes in the group while it handles SIGTERM, so every\n // round re-lists the groups instead of trusting the first snapshot (RT-09).\n const owned = plan.filter((entry) => Array.isArray(entry.targets)).map((entry) => entry.row);\n const members = (processes: readonly ProcessInfo[]): number[] => [\n ...new Set(\n owned.flatMap((row) => {\n const targets = targetsFor(row, processes);\n return Array.isArray(targets) ? targets : [];\n }),\n ),\n ];\n // A listing is a series of reads, so a process that starts while another exits can slip\n // between them; the groups count as gone only when the kernel has no member left either.\n const groupsLeft = (): boolean => owned.some((row) => groupAlive(row.pgid));\n signalAll(members(before), \"SIGTERM\");\n const deadline = Date.now() + REAP_GRACE_MS;\n let remaining = members(await listProcesses());\n while ((remaining.length > 0 || groupsLeft()) && Date.now() < deadline) {\n await delay(100);\n remaining = members(await listProcesses());\n }\n const killDeadline = Date.now() + KILL_WAIT_MS;\n while ((remaining.length > 0 || groupsLeft()) && Date.now() < killDeadline) {\n signalAll(remaining, \"SIGKILL\");\n await delay(50);\n remaining = members(await listProcesses());\n }\n if (remaining.length > 0 || groupsLeft()) {\n warn(\"process.reap_incomplete\", { pids: remaining, pgids: owned.map((row) => row.pgid) });\n }\n return plan.map(({ targets }) =>\n Array.isArray(targets) ? { ended: targets } : { ended: [], skipped: targets },\n );\n}\n\n/**\n * Whether `pid` can be adopted by a child whose own group is `childPgid`: on POSIX a program the\n * child started in its own session (a PTY program), which only a group leader is; on Windows every\n * descendant is already in the child's job and ends with it, so a running process needs nothing\n * more (it isn't recorded again).\n */\nexport async function adoptable(\n pid: number,\n): Promise<{ info: ProcessInfo; record: boolean } | undefined> {\n const info = await readProcess(pid);\n if (!info) return undefined;\n if (WINDOWS) return { info, record: false };\n return info.pgid === info.pid ? { info, record: true } : undefined;\n}\n","/**\n * The home's control endpoint (D81, D82; RT-06, RT-10): how attached clients reach the\n * supervisor. On POSIX it is a Unix socket in the owner-only runtime directory; on Windows a named\n * pipe that only the user can open and that refuses remote clients, which the helper creates and\n * forwards to the supervisor over its descriptor 4 (`crates/mostra-win/src/win/pipe.rs`), because\n * Node.js's own pipes let any local user open them for reading (VERIFIED_FACTS, WP-W1).\n *\n * Either way the caller gets one stream per client and a listener it can check and replace: a\n * socket file that disappeared, or a pipe whose helper stopped, is bound again (D81 item 4).\n */\n\nimport { spawn } from \"node:child_process\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { chmodSync, mkdirSync, type Stats, statSync, unlinkSync } from \"node:fs\";\nimport { createConnection, createServer, type Server, type Socket } from \"node:net\";\nimport { dirname } from \"node:path\";\nimport { Duplex } from \"node:stream\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { type OperatingSystem, OS, pathsOf, socketPathLimit, WINDOWS } from \"./directories.ts\";\nimport { helperPath } from \"./helper.ts\";\nimport { launch } from \"./launch.ts\";\n\n/** Called once per client with the client's stream. */\nexport type OnConnection = (stream: Duplex) => void;\n\n/** A started helper pipe: its frame channel and its end. */\nexport interface PipeProcess {\n readonly channel: Duplex;\n readonly exited: Promise<unknown>;\n stop(): Promise<unknown>;\n}\n\n/** Starts `mostra-win pipe <name>` (through the process manager, so it is gated and recorded). */\nexport type LaunchPipe = (name: string) => Promise<PipeProcess>;\n\n/** A bound control endpoint. */\nexport interface ControlListener {\n /** What clients connect to, as `instance.json` records it. */\n readonly path: string;\n /** Whether it still serves; false when its socket file is gone or its pipe's helper stopped. */\n intact(): boolean;\n /**\n * Stops serving and removes what it created. Client streams the caller ended first are handed\n * over before the endpoint goes; any still open are ended here, after what they were sent.\n */\n close(): Promise<void>;\n}\n\n/**\n * The endpoint for a home. POSIX: `<runtime dir>/<home hash>.sock`, refused with\n * `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit. Windows: `\\\\.\\pipe\\mostra-<home hash>`,\n * to which each bind adds a random part, so no other program can create the name before the\n * supervisor does; clients learn the full name from `instance.json`.\n */\nexport function controlEndpoint(\n runtimeDir: string | undefined,\n hash: string,\n os: OperatingSystem = OS,\n): string {\n if (os === \"win32\" || runtimeDir === undefined) return `\\\\\\\\.\\\\pipe\\\\mostra-${hash}`;\n const path = pathsOf(os).join(runtimeDir, `${hash}.sock`);\n const limit = socketPathLimit(os);\n const length = Buffer.byteLength(path);\n if (length > limit) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOME_SOCKET_TOO_LONG\", {\n message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,\n fix: { kind: \"command\", command: \"export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER\" },\n }),\n );\n }\n return path;\n}\n\n/** What a listener reports besides its clients. */\nexport interface ListenOptions {\n /** Starts the pipe's helper (Windows); default: behind a gate, unrecorded. */\n readonly launchPipe?: LaunchPipe;\n /** Receives the listener's errors after it is bound (a socket's `error` events). */\n readonly onError?: (error: unknown) => void;\n}\n\n/** Binds `endpoint` and calls `onConnection` for every client. */\nexport function listenControl(\n endpoint: string,\n onConnection: OnConnection,\n options: ListenOptions = {},\n): Promise<ControlListener> {\n if (WINDOWS) return listenPipe(endpoint, onConnection, options.launchPipe ?? launchPipeDirectly);\n return listenSocket(endpoint, onConnection, options.onError ?? (() => {}));\n}\n\nconst PIPE_PREFIX = \"\\\\\\\\.\\\\pipe\\\\\";\n\n/**\n * Starts the pipe's helper behind its gate without a process manager to record it: for a\n * protocol server outside an instance (the instance always records its helper).\n */\nconst launchPipeDirectly: LaunchPipe = async (name) => {\n const launched = launch(\n {\n kind: \"control-pipe\",\n command: helperPath(),\n args: [\"pipe\", name],\n env: process.env,\n extra: \"channel\",\n },\n () => {},\n );\n const exited = new Promise((resolve) => launched.process.once(\"exit\", resolve));\n await launched.identify();\n launched.release();\n const channel = launched.process.stdio[4] as Duplex | null;\n if (!channel) throw new Error(\"The control pipe's helper has no channel.\");\n return { channel, exited, stop: () => launched.end(2000, []) };\n};\n\nasync function listenSocket(\n path: string,\n onConnection: OnConnection,\n onError: (error: unknown) => void,\n): Promise<ControlListener> {\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n try {\n unlinkSync(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n const server: Server = createServer((socket: Socket) => onConnection(socket));\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(path, () => {\n server.off(\"error\", reject);\n resolve();\n });\n });\n chmodSync(path, 0o600);\n server.on(\"error\", onError);\n const stats: Stats = statSync(path);\n const same = (): boolean => {\n try {\n const current = statSync(path);\n return current.ino === stats.ino && current.dev === stats.dev;\n } catch {\n return false;\n }\n };\n return {\n path,\n intact: same,\n async close() {\n // Node removes a Unix socket's file when its server closes, even a newer server's file at\n // the same path, so it closes first and removes only its own file.\n const ours = same();\n server.close();\n if (ours) {\n try {\n unlinkSync(path);\n } catch {\n // Already gone.\n }\n }\n },\n };\n}\n\n// The helper's frames: [connection u32 LE][kind u8][length u32 LE][payload].\nconst OPEN = 1;\nconst DATA = 2;\nconst CLOSE = 3;\nconst READY = 4;\nconst FATAL = 5;\n/** The largest payload the supervisor sends in one frame. */\nconst MAX_FRAME = 1 << 20;\n/** How long the helper may take to create the pipe. */\nconst READY_MS = 10_000;\n/** How long a closing listener waits for its helper to hand clients their bytes (its own 5 s). */\nconst DRAIN_MS = 6000;\n\nfunction frame(connection: number, kind: number, payload?: Uint8Array): Buffer {\n const header = Buffer.alloc(9);\n header.writeUInt32LE(connection, 0);\n header[4] = kind;\n header.writeUInt32LE(payload?.length ?? 0, 5);\n return payload ? Buffer.concat([header, payload]) : header;\n}\n\nasync function listenPipe(\n base: string,\n onConnection: OnConnection,\n launchPipe: LaunchPipe,\n): Promise<ControlListener> {\n // An endpoint that isn't a pipe name (a socket path a caller chose) names one by its hash.\n const stem = base.startsWith(PIPE_PREFIX)\n ? base.slice(PIPE_PREFIX.length)\n : `mostra-${createHash(\"sha256\").update(base).digest(\"hex\").slice(0, 16)}`;\n const name = `${stem}-${randomBytes(8).toString(\"hex\")}`;\n const helper = await launchPipe(name);\n const streams = new Map<number, Duplex>();\n let exited = false;\n let failed = false;\n // Set once READY arrived; a FATAL after it means the listener failed rather than never started.\n let path: string | undefined;\n void helper.exited.then(() => {\n exited = true;\n for (const stream of streams.values()) stream.destroy();\n streams.clear();\n });\n const send = (bytes: Buffer): void => {\n if (!exited && !helper.channel.destroyed) helper.channel.write(bytes);\n };\n\n const ready = new Promise<string>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(\"The control pipe's helper didn't create the pipe in time.\")),\n READY_MS,\n );\n let pending: Buffer = Buffer.alloc(0);\n helper.channel.on(\"data\", (chunk: Buffer) => {\n pending = pending.length === 0 ? chunk : Buffer.concat([pending, chunk]);\n while (pending.length >= 9) {\n const length = pending.readUInt32LE(5);\n if (pending.length < 9 + length) break;\n const id = pending.readUInt32LE(0);\n const kind = pending[4];\n const payload = pending.subarray(9, 9 + length);\n pending = pending.subarray(9 + length);\n if (kind === READY) {\n clearTimeout(timer);\n // Recorded here, not after the await: a FATAL in the same chunk must see it.\n path = payload.toString(\"utf8\");\n resolve(path);\n } else if (kind === FATAL) {\n clearTimeout(timer);\n const why = `The control pipe can't be served: ${payload.toString(\"utf8\")}`;\n if (path === undefined) {\n reject(new Error(why));\n } else {\n // Ready earlier, failed since (no further instance could be created): the endpoint\n // is unusable though the helper lives, so the listener is no longer intact and is\n // replaced by the server's next check (D81 item 4).\n failed = true;\n void helper.stop();\n }\n } else if (kind === OPEN) {\n const stream = clientStream(id, send, () => streams.delete(id));\n streams.set(id, stream);\n onConnection(stream);\n } else if (kind === DATA) {\n // A copy: the chunk's buffer is reused by later frames.\n streams.get(id)?.push(Buffer.from(payload));\n } else if (kind === CLOSE) {\n const stream = streams.get(id);\n streams.delete(id);\n if (stream) {\n stream.push(null);\n stream.end();\n }\n }\n }\n });\n void helper.exited.then(() => {\n clearTimeout(timer);\n reject(new Error(\"The control pipe's helper exited.\"));\n });\n });\n helper.channel.on(\"error\", () => {});\n let bound: string;\n try {\n bound = await ready;\n } catch (error) {\n await helper.stop();\n throw error;\n }\n return {\n path: bound,\n intact: () => !exited && !failed,\n async close() {\n // Every client's stream ends after what it was sent, in order on the one channel; then\n // connection 0's CLOSE asks the helper to hand all of it over and exit (at most its 5 s\n // drain). Only a helper that doesn't is stopped, which ends its job.\n for (const stream of streams.values()) stream.end();\n if (!exited) send(frame(0, CLOSE));\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n helper.exited,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, DRAIN_MS);\n }),\n ]);\n clearTimeout(timer);\n for (const stream of streams.values()) stream.destroy();\n streams.clear();\n await helper.stop();\n },\n };\n}\n\n/** One client's stream over the helper's channel. */\nfunction clientStream(id: number, send: (bytes: Buffer) => void, forget: () => void): Duplex {\n let closed = false;\n const close = (): void => {\n if (closed) return;\n closed = true;\n forget();\n send(frame(id, CLOSE));\n };\n return new Duplex({\n read() {},\n write(chunk: Buffer, _encoding, callback) {\n for (let offset = 0; offset < chunk.length; offset += MAX_FRAME) {\n send(frame(id, DATA, chunk.subarray(offset, offset + MAX_FRAME)));\n }\n callback();\n },\n final(callback) {\n close();\n callback();\n },\n destroy(error, callback) {\n close();\n callback(error);\n },\n });\n}\n\n/** Why a client couldn't open a control endpoint. */\nexport class ControlConnectError extends Error {\n /** `unreachable` (nothing serves it, or it timed out) or `not-owned` (another user's pipe). */\n readonly reason: \"unreachable\" | \"not-owned\";\n constructor(reason: \"unreachable\" | \"not-owned\", message: string) {\n super(message);\n this.name = \"ControlConnectError\";\n this.reason = reason;\n }\n}\n\n/**\n * Connects to a home's control endpoint as a client. On Windows through `mostra-win connect`,\n * which refuses a pipe another user created under the name (an old name `instance.json` still\n * names may be free for anyone to take), and never lets the server act as this process: Node.js\n * can check neither (Opus review of WP-W1). Rejects with a {@link ControlConnectError}.\n */\nexport function connectControl(endpoint: string, timeoutMs = 5000): Promise<Duplex> {\n return WINDOWS ? connectPipe(endpoint, timeoutMs) : connectSocket(endpoint, timeoutMs);\n}\n\nfunction connectSocket(path: string, timeoutMs: number): Promise<Duplex> {\n return new Promise((resolve, reject) => {\n const socket: Socket = createConnection(path);\n const timer = setTimeout(() => {\n socket.destroy();\n reject(new ControlConnectError(\"unreachable\", \"timed out\"));\n }, timeoutMs);\n socket.once(\"error\", (error: NodeJS.ErrnoException) => {\n clearTimeout(timer);\n reject(new ControlConnectError(\"unreachable\", error.code ?? \"failed\"));\n });\n socket.once(\"connect\", () => {\n clearTimeout(timer);\n resolve(socket);\n });\n });\n}\n\nfunction connectPipe(endpoint: string, timeoutMs: number): Promise<Duplex> {\n const name = endpoint.startsWith(PIPE_PREFIX) ? endpoint.slice(PIPE_PREFIX.length) : endpoint;\n return new Promise((resolve, reject) => {\n const child = spawn(helperPath(), [\"connect\", name], {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n let settled = false;\n const fail = (reason: \"unreachable\" | \"not-owned\", message: string): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.kill();\n reject(new ControlConnectError(reason, message));\n };\n const timer = setTimeout(() => fail(\"unreachable\", \"timed out\"), timeoutMs);\n child.once(\"error\", (error) => fail(\"unreachable\", error.message));\n child.once(\"exit\", (code) => fail(code === 3 ? \"not-owned\" : \"unreachable\", `exit ${code}`));\n let text = \"\";\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk: string) => {\n if (settled) return;\n text += chunk;\n const end = text.indexOf(\"\\n\");\n if (end < 0) return;\n let line: { connected?: boolean; code?: string; error?: string } = {};\n try {\n line = JSON.parse(text.slice(0, end)) as typeof line;\n } catch {\n // Treated as a failure below.\n }\n if (line.connected !== true) {\n fail(\n line.code === \"not-owned\" ? \"not-owned\" : \"unreachable\",\n line.error ?? text.slice(0, end),\n );\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolve(Duplex.from({ readable: child.stdout, writable: child.stdin }));\n });\n });\n}\n","/**\n * The smallest environment a child can run in (the builder's): `PATH`, `HOME` and `TMPDIR` on\n * POSIX. Windows programs need more of what Windows itself gives every program (without\n * `SystemRoot` Node.js can't load its cryptography, without `TEMP` it has no temporary folder),\n * and Windows compares variable names without case, so they are found that way.\n */\nimport { WINDOWS } from \"./directories.ts\";\n\ntype Environment = Readonly<Record<string, string | undefined>>;\n\n/**\n * What Windows itself gives every program and programs rely on, besides `Path`: the system's\n * directories, the user's profile folders, the shell and how it finds programs, who the user is\n * and the processor. None names a secret. The one list both the base and the artifact environment\n * pass on Windows (`processes/environment.ts`).\n */\nexport const WINDOWS_SYSTEM_VARIABLES: readonly string[] = [\n \"SystemRoot\",\n \"SystemDrive\",\n \"windir\",\n \"ComSpec\",\n \"PATHEXT\",\n \"TEMP\",\n \"TMP\",\n \"USERPROFILE\",\n \"HOMEDRIVE\",\n \"HOMEPATH\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"ProgramData\",\n \"ProgramFiles\",\n \"ProgramFiles(x86)\",\n \"ProgramW6432\",\n \"CommonProgramFiles\",\n \"CommonProgramFiles(x86)\",\n \"CommonProgramW6432\",\n \"USERNAME\",\n \"USERDOMAIN\",\n \"COMPUTERNAME\",\n \"OS\",\n \"NUMBER_OF_PROCESSORS\",\n \"PROCESSOR_ARCHITECTURE\",\n \"PROCESSOR_IDENTIFIER\",\n];\n\nconst WINDOWS_BASE = [\"Path\", ...WINDOWS_SYSTEM_VARIABLES];\n\n/** The base environment of a child, from the supervisor's `env`. */\nexport function baseEnvironment(env: Environment): Record<string, string> {\n if (!WINDOWS) {\n return {\n PATH: env[\"PATH\"] ?? \"/usr/bin:/bin\",\n HOME: env[\"HOME\"] ?? \"/\",\n ...(env[\"TMPDIR\"] ? { TMPDIR: env[\"TMPDIR\"] } : {}),\n };\n }\n const byName = new Map(Object.entries(env).map(([name, value]) => [name.toUpperCase(), value]));\n const result: Record<string, string> = {};\n for (const name of WINDOWS_BASE) {\n const value = byName.get(name.toUpperCase());\n if (value !== undefined) result[name] = value;\n }\n return result;\n}\n","/**\n * Where this system keeps the tunnel tools a share drives (D158 item 4): `tailscale` and\n * `cloudflared`, which Mostra never bundles or downloads. A daemon started by a login service may\n * run with a short `PATH`, so the tools' usual install locations are searched after it, and an\n * environment variable names one outright. How to install each is said here too, per system.\n */\nimport { accessSync, constants, statSync } from \"node:fs\";\nimport { delimiter, join } from \"node:path\";\nimport { OS, WINDOWS } from \"./directories.ts\";\n\n/** A tunnel tool. */\nexport type TunnelTool = \"tailscale\" | \"cloudflared\";\n\n/** The variable that names a tool's executable outright. */\nconst TOOL_VARIABLES: Readonly<Record<TunnelTool, string>> = {\n tailscale: \"MOSTRA_TAILSCALE\",\n cloudflared: \"MOSTRA_CLOUDFLARED\",\n};\n\n/** The usual install locations of each tool, per system, after `PATH`. */\nexport function usualLocations(\n tool: TunnelTool,\n env: Readonly<Record<string, string | undefined>>,\n): string[] {\n if (WINDOWS) {\n const programs = env[\"ProgramFiles\"] ?? \"C:\\\\Program Files\";\n const programs86 = env[\"ProgramFiles(x86)\"] ?? \"C:\\\\Program Files (x86)\";\n return tool === \"tailscale\"\n ? [join(programs, \"Tailscale\", \"tailscale.exe\")]\n : [\n join(programs86, \"cloudflared\", \"cloudflared.exe\"),\n join(programs, \"cloudflared\", \"cloudflared.exe\"),\n ];\n }\n if (OS === \"darwin\") {\n return tool === \"tailscale\"\n ? [\n \"/opt/homebrew/bin/tailscale\",\n \"/usr/local/bin/tailscale\",\n // Homebrew's formula left unlinked (beside the Mac app, which owns the name), as found on\n // a real Mac in WP-13: its prefix keeps the command line all the same.\n \"/opt/homebrew/opt/tailscale/bin/tailscale\",\n \"/usr/local/opt/tailscale/bin/tailscale\",\n // The Mac app's own executable is its command line too.\n \"/Applications/Tailscale.app/Contents/MacOS/Tailscale\",\n ]\n : [\n \"/opt/homebrew/bin/cloudflared\",\n \"/usr/local/bin/cloudflared\",\n \"/opt/homebrew/opt/cloudflared/bin/cloudflared\",\n \"/usr/local/opt/cloudflared/bin/cloudflared\",\n ];\n }\n return tool === \"tailscale\"\n ? [\"/usr/bin/tailscale\", \"/usr/local/bin/tailscale\", \"/usr/sbin/tailscale\"]\n : [\"/usr/bin/cloudflared\", \"/usr/local/bin/cloudflared\"];\n}\n\nfunction executable(path: string): boolean {\n try {\n if (!statSync(path).isFile()) return false;\n if (!WINDOWS) accessSync(path, constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * The tool's executable: the variable's (which must exist), else the first on `PATH`, else the\n * first usual location that exists; `undefined` when there is none.\n */\nfunction findTool(\n tool: TunnelTool,\n env: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n const named = env[TOOL_VARIABLES[tool]];\n if (named !== undefined && named !== \"\") return executable(named) ? named : undefined;\n const names = WINDOWS ? [`${tool}.exe`] : [tool];\n const path = (WINDOWS ? (env[\"Path\"] ?? env[\"PATH\"]) : env[\"PATH\"]) ?? \"\";\n for (const dir of path.split(delimiter)) {\n if (dir === \"\") continue;\n for (const name of names) {\n const candidate = join(dir, name);\n if (executable(candidate)) return candidate;\n }\n }\n return usualLocations(tool, env).find(executable);\n}\n\n/** How a tool runs: its executable and the arguments before the tool's own. */\nexport interface ToolCommand {\n readonly command: string;\n readonly args: readonly string[];\n /** Run by `MOSTRA_TEST_TUNNELS`: a local fake that forwards plain HTTP on loopback. */\n readonly fake: boolean;\n}\n\n/**\n * The variable that replaces both tools with local fakes for tests (`<dir>/tailscale.mjs` and\n * `<dir>/cloudflared.mjs`, run on this Node.js): the conformance kit's and the suites' own, which\n * forward on loopback as the real tools forward from their networks (STANDARDS: real side effects\n * in tests go to local fakes).\n */\nconst TEST_TUNNELS_VARIABLE = \"MOSTRA_TEST_TUNNELS\";\n\n/** How to run a tool: {@link findTool}'s executable, or the test fake; `undefined` when missing. */\nexport function toolCommand(\n tool: TunnelTool,\n env: Readonly<Record<string, string | undefined>>,\n): ToolCommand | undefined {\n const fakes = env[TEST_TUNNELS_VARIABLE];\n if (fakes !== undefined && fakes !== \"\") {\n const script = join(fakes, `${tool}.mjs`);\n return regularFile(script)\n ? { command: process.execPath, args: [script], fake: true }\n : undefined;\n }\n const found = findTool(tool, env);\n return found === undefined ? undefined : { command: found, args: [], fake: false };\n}\n\nfunction regularFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/** How to install a tool on this system, as one sentence. */\nexport function installHint(tool: TunnelTool): string {\n if (tool === \"tailscale\") {\n if (WINDOWS)\n return \"Install Tailscale from https://tailscale.com/download/windows (or `winget install tailscale.tailscale`) and sign in.\";\n if (OS === \"darwin\")\n return \"Install Tailscale from https://tailscale.com/download/mac (or `brew install tailscale`) and sign in.\";\n return \"Install Tailscale with `curl -fsSL https://tailscale.com/install.sh | sh` (https://tailscale.com/download/linux), then run `sudo tailscale up`.\";\n }\n if (WINDOWS)\n return \"Install cloudflared with `winget install --id Cloudflare.cloudflared` (https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/).\";\n if (OS === \"darwin\")\n return \"Install cloudflared with `brew install cloudflared` (https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/).\";\n return \"Install cloudflared from your distribution's Cloudflare package repository or https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/.\";\n}\n","/**\n * The builder (ARCHITECTURE §1, §3; ROUND-3 §7): the internal `RenderMode` contract with SPA as\n * its implementation (D19 seam 5), and the supervisor's side of the builder child. The supervisor\n * never loads the bundler: it starts a child per build through the process manager, which runs\n * `child/main.ts`, and turns a crash or a timeout into `MOSTRA_BUILD_CRASHED` or\n * `MOSTRA_BUILD_TIMEOUT` (FAILURE_MODEL §2, §9).\n *\n * ```ts\n * const spa = createSpaRenderMode({ processes, log });\n * const result = await spa.build({ stagingDir, entry: \"index.tsx\", entryHasDefault: true, manifest, nodeModules, … });\n * ```\n */\n\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { Faults } from \"../faults.ts\";\nimport type { Environment, Log } from \"../log.ts\";\nimport type { ProcessManager } from \"../processes/index.ts\";\nimport type { FieldCoverage } from \"./coverage.ts\";\nimport {\n BUILD_METHOD,\n type BuildRequest,\n type BuildResponse,\n DEV_CHANGED_METHOD,\n DEV_METHOD,\n DEV_RELOAD_METHOD,\n DEV_SERVER_NOTIFICATION,\n DEV_UPDATE_NOTIFICATION,\n type DevChange,\n type DevReady,\n type DevRequest,\n type DevServerBuild,\n STAGING_FILES,\n} from \"./types.ts\";\n\nexport { coverageMatcher, type FieldCoverage, type FieldEntry } from \"./coverage.ts\";\nexport {\n type BuildRequest,\n type BuildResponse,\n DEV_SECRET_HEADER,\n type DevChange,\n type DevReady,\n type DevRequest,\n type DevServerBuild,\n LIVE_DECLARATION,\n type VersionRegistry,\n} from \"./types.ts\";\n\nimport { baseEnvironment } from \"../platform/index.ts\";\n\n/** How long one build may take (FAILURE_MODEL §9). */\nexport const BUILD_TIMEOUT_MS = 180_000;\n\n/** Packages whose versions define the SPA build; they are part of `buildConfigDigest` (VR-01). */\nconst BUILD_PACKAGES = [\n \"vite\",\n \"@vitejs/plugin-react\",\n \"@mdx-js/mdx\",\n \"remark-frontmatter\",\n \"remark-gfm\",\n \"@tailwindcss/vite\",\n \"oxc-parser\",\n] as const;\n\n/** Bumped whenever the SPA build's settings change, so older versions aren't reused. */\nconst SPA_CONFIG_REVISION = 7;\n\n/** What a render mode can deliver for a manifest (ROUND-3 §7). */\nexport interface RenderCapabilities {\n readonly staticExport: boolean;\n readonly mcpApp: boolean;\n readonly needsWorker: boolean;\n}\n\n/**\n * The internal render-mode contract (ROUND-3 §7, D19 seam 5). SPA is v1's only mode; an `rsc`\n * mode implements the same interface later. `dev` arrives with `mostra dev` (WP-10).\n */\nexport interface RenderMode {\n readonly id: \"spa\";\n /** The settings that define the build, hashed into `buildConfigDigest`. */\n readonly buildConfig: Readonly<Record<string, unknown>>;\n capabilities(input: { readonly hasServerCode: boolean }): RenderCapabilities;\n /**\n * Builds the snapshot in `request.stagingDir` into `request.outDir`, resolving packages from\n * `request.nodeModules`: the warm layout or the artifact's lock layout (D95).\n */\n build(request: BuildRequest): Promise<BuildResponse>;\n /** The server bundle a worker loads from a version directory, when the version has one. */\n serverEntry(versionDir: string): string | undefined;\n /**\n * `mostra dev` (VR-08, D140 item 12): a dev server in a builder child of its own, over the dev\n * root's mirror of the source, until {@link DevChild.stop}. Throws `MOSTRA_BUILD_CRASHED` when\n * the child can't start it.\n */\n dev(request: DevRequest, events: DevEvents): Promise<DevChild>;\n}\n\n/** What a dev child tells the supervisor as the source changes. */\nexport interface DevEvents {\n /** The server bundle was built again, or failed to build; `files` changed. */\n server(build: DevServerBuild, files: readonly string[]): void;\n /** Client modules of `files` were updated in place. */\n update(files: readonly string[]): void;\n}\n\n/** A running dev child. */\nexport interface DevChild {\n readonly ready: DevReady;\n /** Tells every page to load again. */\n reload(): Promise<void>;\n /** These files of the mirror changed; resolves once the child acted on them. */\n changed(changes: readonly DevChange[]): Promise<void>;\n /** Resolves when the child ended, for whatever reason. */\n readonly exited: Promise<{ readonly stderrTail: readonly string[] }>;\n stop(): Promise<void>;\n}\n\n/** The directory of `@mostra/runtime`'s package.json. */\nfunction runtimeRoot(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n const manifest = join(dir, \"package.json\");\n if (existsSync(manifest)) {\n const { name } = JSON.parse(readFileSync(manifest, \"utf8\")) as { name?: string };\n if (name === \"@mostra/runtime\") return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(\"Couldn't find @mostra/runtime's package.json.\");\n dir = parent;\n }\n}\n\n/** Node's lookup of an installed package's directory, from `from` upwards. */\nfunction packageDir(name: string, from: string): string | undefined {\n let dir = from;\n for (;;) {\n const candidate = join(dir, \"node_modules\", name);\n if (existsSync(join(candidate, \"package.json\"))) return realpathSync(candidate);\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\nfunction versionOf(dir: string): string {\n return (JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\")) as { version: string })\n .version;\n}\n\n/** The builder child's entry: the compiled one beside the compiled supervisor, else the source. */\nfunction childEntry(root: string): string {\n return fileURLToPath(import.meta.url).endsWith(\".ts\")\n ? join(root, \"src/builder/child/main.ts\")\n : join(root, \"dist/builder/child/main.js\");\n}\n\n/** Options for {@link createSpaRenderMode}. */\nexport interface SpaRenderModeOptions {\n readonly processes: ProcessManager;\n readonly log: Log;\n /** Default {@link BUILD_TIMEOUT_MS}. */\n readonly timeoutMs?: number;\n /** The environment the builder's minimal environment takes `PATH` and `HOME` from. */\n readonly env?: Environment;\n /** Test fault points: `builder:build` with `hang` stops each build's child before it builds. */\n readonly faults?: Faults;\n}\n\n/** The SPA render mode (D19): every build in its own builder child. */\nexport function createSpaRenderMode(options: SpaRenderModeOptions): RenderMode {\n const root = runtimeRoot();\n const buildPackages: Record<string, string> = {};\n for (const name of BUILD_PACKAGES) {\n const dir = packageDir(name, root);\n if (!dir) throw new Error(`The runtime is missing its build dependency ${name}.`);\n buildPackages[name] = versionOf(dir);\n }\n const buildConfig = {\n mode: \"spa\",\n revision: SPA_CONFIG_REVISION,\n base: \"/\",\n sourcemap: true,\n packages: buildPackages,\n stagingFiles: STAGING_FILES,\n };\n const timeoutMs = options.timeoutMs ?? BUILD_TIMEOUT_MS;\n const env = options.env ?? process.env;\n // The builder gets only what it needs: no secrets, nothing that could reach a bundle.\n const childEnv: Environment = { ...baseEnvironment(env), NODE_ENV: \"production\" };\n\n return {\n id: \"spa\",\n buildConfig,\n capabilities: ({ hasServerCode }) => ({\n staticExport: !hasServerCode,\n mcpApp: true,\n needsWorker: hasServerCode,\n }),\n serverEntry(versionDir) {\n const entry = spaServerEntry(versionDir);\n return entry === undefined ? undefined : join(versionDir, entry);\n },\n async dev(request, events) {\n const child = await options.processes.spawn({\n kind: \"builder\",\n ownerRef: request.root,\n command: process.execPath,\n args: [childEntry(root)],\n cwd: request.root,\n // A dev server builds for development; nothing else of the supervisor's environment.\n env: { ...childEnv, NODE_ENV: \"development\" },\n ipc: {\n onNotification: (method, params) => {\n const body = (params ?? {}) as { build?: DevServerBuild; files?: string[] };\n if (method === DEV_SERVER_NOTIFICATION && body.build)\n events.server(body.build, body.files ?? []);\n if (method === DEV_UPDATE_NOTIFICATION) events.update(body.files ?? []);\n },\n },\n });\n const outcome = await Promise.race([\n child\n .request(DEV_METHOD, request as unknown as Record<string, unknown>, {\n timeoutMs: timeoutMs + 1000,\n })\n .then(\n (ready) => ({ kind: \"ready\" as const, ready: ready as DevReady }),\n (error: unknown) => ({ kind: \"error\" as const, error }),\n ),\n child.exited.then((exit) => ({ kind: \"exit\" as const, exit })),\n ]);\n if (outcome.kind !== \"ready\") {\n await child.stop(2000);\n const why =\n outcome.kind === \"error\"\n ? ((outcome.error as Error).message ?? String(outcome.error))\n : `it exited (${outcome.exit.signal ?? `code ${outcome.exit.code}`})${outcome.exit.stderrTail.length > 0 ? `\\n${outcome.exit.stderrTail.slice(-10).join(\"\\n\")}` : \"\"}`;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_BUILD_CRASHED\", {\n message: `The dev server couldn't start: ${why}`,\n }),\n );\n }\n return {\n ready: outcome.ready,\n reload: async () => {\n await child.request(DEV_RELOAD_METHOD, {}, { timeoutMs: 5000 });\n },\n changed: async (changes) => {\n await child.request(\n DEV_CHANGED_METHOD,\n { changes: changes as unknown as Record<string, unknown>[] },\n { timeoutMs: timeoutMs + 1000 },\n );\n },\n exited: child.exited,\n stop: async () => {\n await child.stop(3000);\n },\n };\n },\n async build(request) {\n const child = await options.processes.spawn({\n kind: \"builder\",\n ownerRef: request.stagingDir,\n command: process.execPath,\n args: [childEntry(root)],\n cwd: request.stagingDir,\n env: childEnv,\n ipc: {},\n });\n // A builder that hangs (issue #18): told to, so it never answers and the limit ends it. A\n // signal from outside raced a fast build; the child itself can't.\n const wire: BuildRequest = options.faults?.hangs(\"builder:build\")\n ? { ...request, hang: true }\n : request;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const outcome = await Promise.race([\n child\n .request(BUILD_METHOD, wire as unknown as Record<string, unknown>, {\n timeoutMs: timeoutMs + 1000,\n })\n .then(\n (result) => ({ kind: \"result\" as const, result: result as BuildResponse }),\n (error: unknown) => ({ kind: \"error\" as const, error }),\n ),\n child.exited.then((exit) => ({ kind: \"exit\" as const, exit })),\n new Promise<{ kind: \"timeout\" }>((done) => {\n timer = setTimeout(() => done({ kind: \"timeout\" }), timeoutMs);\n }),\n ]);\n if (outcome.kind === \"result\") return outcome.result;\n if (outcome.kind === \"timeout\") {\n return failed(\n \"MOSTRA_BUILD_TIMEOUT\",\n `The build took longer than ${Math.round(timeoutMs / 1000)} s and was stopped.`,\n );\n }\n let exit: Awaited<typeof child.exited> | undefined =\n outcome.kind === \"exit\" ? outcome.exit : undefined;\n if (outcome.kind === \"error\") {\n // A crash closes the IPC channel first; give the exit a moment to arrive.\n exit = await Promise.race([\n child.exited,\n new Promise<undefined>((done) => setTimeout(() => done(undefined), 1000)),\n ]);\n if (exit === undefined) {\n options.log.error(\"builder.failed\", { error: outcome.error });\n return failed(\n \"MOSTRA_BUILD_CRASHED\",\n `The builder failed unexpectedly: ${(outcome.error as Error).message ?? String(outcome.error)}`,\n );\n }\n }\n if (exit === undefined) throw new Error(\"unreachable\");\n const tail = exit.stderrTail.slice(-10).join(\"\\n\");\n options.log.warn(\"builder.crashed\", { code: exit.code, signal: exit.signal });\n return failed(\n \"MOSTRA_BUILD_CRASHED\",\n `The builder exited (${exit.signal ?? `code ${exit.code}`}) before it finished.${tail ? `\\n${tail}` : \"\"}`,\n );\n } finally {\n if (timer) clearTimeout(timer);\n await child.stop(2000);\n }\n },\n };\n}\n\nfunction failed(\n code: \"MOSTRA_BUILD_TIMEOUT\" | \"MOSTRA_BUILD_CRASHED\",\n message: string,\n): BuildResponse {\n return { ok: false, diagnostics: [createDiagnostic(code, { message })] };\n}\n\n/**\n * The SPA mode's server bundle of a built version, relative to it (`server/entry.mjs`), or\n * `undefined` for a version without server code, which never gets a worker (RT-05).\n */\nfunction spaServerEntry(versionDir: string): string | undefined {\n return existsSync(join(versionDir, \"server\", \"entry.mjs\")) ? \"server/entry.mjs\" : undefined;\n}\n\n/** The IDs of the server functions a version's `registry.json` lists, empty when it has none. */\nexport function readServerFunctions(versionDir: string): ReadonlySet<string> {\n try {\n const registry = JSON.parse(readFileSync(join(versionDir, \"registry.json\"), \"utf8\")) as {\n readonly actions?: unknown;\n };\n if (!Array.isArray(registry.actions)) return new Set();\n return new Set(\n registry.actions\n .map((entry) => (entry as { id?: unknown } | null)?.id)\n .filter((id): id is string => typeof id === \"string\"),\n );\n } catch {\n return new Set();\n }\n}\n\n/** The live sources a version's `registry.json` lists (D56), empty when it has none. */\nexport function readLiveSources(\n versionDir: string,\n): readonly { readonly key: string; readonly always?: boolean }[] {\n try {\n const registry = JSON.parse(readFileSync(join(versionDir, \"registry.json\"), \"utf8\")) as {\n readonly liveSources?: unknown;\n };\n if (!Array.isArray(registry.liveSources)) return [];\n return registry.liveSources.filter(\n (entry): entry is { key: string; always?: boolean } =>\n typeof entry === \"object\" &&\n entry !== null &&\n typeof (entry as { key?: unknown }).key === \"string\",\n );\n } catch {\n return [];\n }\n}\n\n/**\n * The field coverage a published version recorded in its `registry.json` (D109), or `undefined`\n * for a version built before WP-07 or one whose registry can't be read: such a version covers\n * every field ID, so nothing is orphaned by a guess.\n */\nexport function readFieldCoverage(versionDir: string): FieldCoverage | undefined {\n try {\n const registry = JSON.parse(readFileSync(join(versionDir, \"registry.json\"), \"utf8\")) as {\n readonly fields?: FieldCoverage;\n };\n const fields = registry.fields;\n if (fields === undefined || typeof fields.open !== \"boolean\" || !Array.isArray(fields.entries))\n return undefined;\n return fields;\n } catch {\n return undefined;\n }\n}\n","/**\n * Fault injection for tests (FAILURE_MODEL §3, VR-02, issue #7). A test that runs real Mostra\n * processes sets `MOSTRA_TEST_FAULTS` to a comma-separated list of `<point>:<action>` entries, and\n * the instance stops at those points: `throw` fails the operation there, `crash` kills the\n * supervisor with SIGKILL there, as a power cut or `kill -9` would, and `hang` makes the child the\n * point names hang (the module asks {@link Faults.hangs}; a builder told never to answer, so a test\n * of the build limit never races a fast build, issue #18). Without the variable every point\n * is a no-op. The points are named in the modules that call {@link Faults.at}.\n *\n * ```ts\n * faults.at(\"publish:after-promote\"); // a crash here leaves a version directory with no row\n * ```\n */\nimport type { Environment } from \"./log.ts\";\n\n/** What a fault point does. */\nexport type FaultAction = \"throw\" | \"throw-once\" | \"crash\" | \"hang\";\n\n/** The test fault points of one instance. */\nexport interface Faults {\n /** Runs the fault configured for `point`, if any (`hang` is the caller's to act on). */\n at(point: string): void;\n /** Whether `point` is configured to `hang`. */\n hangs(point: string): boolean;\n}\n\n/** The variable tests set. It carries no secrets and changes nothing when unset. */\nexport const FAULTS_VARIABLE = \"MOSTRA_TEST_FAULTS\";\n\n/** No faults: every point is a no-op. */\nexport const noFaults: Faults = { at() {}, hangs: () => false };\n\n/** The error a `throw` fault raises. */\nexport class InjectedFault extends Error {\n constructor(point: string) {\n super(`Injected fault at ${point} (${FAULTS_VARIABLE}).`);\n this.name = \"InjectedFault\";\n }\n}\n\n/** Reads the faults configured in `env`. Unknown actions are ignored. */\nexport function faultsFrom(env: Environment): Faults {\n const spec = env[FAULTS_VARIABLE];\n if (!spec) return noFaults;\n const configured = new Map<string, FaultAction>();\n for (const entry of spec.split(\",\")) {\n const separator = entry.lastIndexOf(\":\");\n const point = entry.slice(0, separator).trim();\n const action = entry.slice(separator + 1).trim();\n if (\n point &&\n (action === \"throw\" || action === \"throw-once\" || action === \"crash\" || action === \"hang\")\n )\n configured.set(point, action);\n }\n return {\n hangs: (point) => configured.get(point) === \"hang\",\n at(point) {\n const action = configured.get(point);\n if (action === \"throw\") throw new InjectedFault(point);\n if (action === \"throw-once\") {\n configured.delete(point);\n throw new InjectedFault(point);\n }\n if (action === \"crash\") {\n process.kill(process.pid, \"SIGKILL\");\n // The signal is delivered at once; block until it lands so no later step runs.\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10_000);\n }\n },\n };\n}\n","/**\n * The ledger's schema migrations (DATA_MODEL §3, §6), in order. Each package that adds tables adds\n * one migration at the end; a released migration never changes. Version 0 is the bootstrap every\n * ledger file is created with (`schema_migration` and `ledger_lock`).\n */\nimport type { MigrationDb } from \"./types.ts\";\n\n/** One forward step of the ledger schema. */\nexport interface Migration {\n /** 1, 2, 3 … with no gaps. */\n readonly version: number;\n /** A short name for logs and `schema_migration.name`. */\n readonly name: string;\n /** Applies the step. Runs inside the migration transaction. */\n up(db: MigrationDb): void;\n}\n\n/** The bootstrap schema, written into every new ledger file before it is linked into place. */\nexport const BOOTSTRAP_SQL = `\nCREATE TABLE schema_migration (\n version INTEGER PRIMARY KEY,\n name TEXT NOT NULL,\n runtime_version TEXT NOT NULL,\n applied_at TEXT NOT NULL\n);\nCREATE TABLE ledger_lock (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n pid INTEGER NOT NULL,\n start_time TEXT NOT NULL,\n acquired_at TEXT NOT NULL\n);\n`;\n\n/** Every migration of this runtime, in order. */\nexport const MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n name: \"child processes\",\n up(db) {\n // Every child process the supervisor started, so a restarted supervisor can reap them\n // (RT-09, FAILURE_MODEL §2). `start_time` is the opaque process identity of\n // processes/identity.ts; `pgid` is the group to signal.\n db.exec(`\n CREATE TABLE child (\n pid INTEGER NOT NULL,\n start_time TEXT NOT NULL,\n kind TEXT NOT NULL,\n owner_ref TEXT NOT NULL,\n pgid INTEGER NOT NULL,\n started_at TEXT NOT NULL,\n parent_pid INTEGER,\n PRIMARY KEY (pid, start_time)\n );\n `);\n },\n },\n {\n version: 2,\n name: \"artifacts, versions and events\",\n up(db) {\n // DATA_MODEL §3. `artifact` mirrors the latest version's manifest metadata; `version` rows\n // are immutable (VR-01, invariant 3) and the trigger refuses any UPDATE. `event` is\n // append-only; WP-03 appends `artifact.created` and `version.published`, WP-06 reads them.\n // `request` records the result of each mutating request with a `requestId` (H-03).\n db.exec(`\n CREATE TABLE artifact (\n id TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n family TEXT,\n links_json TEXT NOT NULL,\n policy_json TEXT,\n created_at TEXT NOT NULL,\n latest_version_id TEXT\n );\n CREATE TABLE source_binding (\n path TEXT PRIMARY KEY,\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n bound_at TEXT NOT NULL\n );\n CREATE INDEX source_binding_artifact ON source_binding (artifact_id);\n CREATE TABLE version (\n id TEXT PRIMARY KEY,\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n number INTEGER NOT NULL CHECK (number >= 1),\n source_digest TEXT NOT NULL,\n env_digest TEXT NOT NULL,\n output_digest TEXT NOT NULL,\n manifest_json TEXT NOT NULL,\n forced_codes_json TEXT,\n published_at TEXT NOT NULL,\n UNIQUE (artifact_id, number)\n );\n CREATE TRIGGER version_immutable BEFORE UPDATE ON version\n BEGIN\n SELECT RAISE(ABORT, 'published versions are immutable');\n END;\n CREATE TABLE event (\n cursor INTEGER PRIMARY KEY AUTOINCREMENT,\n artifact_id TEXT,\n seq INTEGER,\n type TEXT NOT NULL,\n actor_json TEXT NOT NULL,\n causation_json TEXT,\n payload_json TEXT NOT NULL,\n at TEXT NOT NULL,\n UNIQUE (artifact_id, seq)\n );\n CREATE TRIGGER event_append_only BEFORE UPDATE ON event\n BEGIN\n SELECT RAISE(ABORT, 'events are append-only');\n END;\n CREATE TABLE request (\n method TEXT NOT NULL,\n request_id TEXT NOT NULL,\n result_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (method, request_id)\n );\n `);\n },\n },\n {\n version: 3,\n name: \"dependencies\",\n up(db) {\n // D95. `dependency_lock` holds each artifact's working lockfile, keyed by its artifact ID,\n // or by `path:<real path>` until its first publish binds it (re-keyed in that publish's\n // transaction); `added_json` lists the packages added through deps/add, which stay in the\n // lockfile whether or not the source imports them. `dependency_package` indexes what the\n // home's package store holds, so an offline request for anything else fails at once (DP-04).\n db.exec(`\n CREATE TABLE dependency_lock (\n key TEXT PRIMARY KEY,\n lock_text TEXT NOT NULL,\n added_json TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE dependency_package (\n name TEXT NOT NULL,\n version TEXT NOT NULL,\n stored_at TEXT NOT NULL,\n PRIMARY KEY (name, version)\n );\n `);\n },\n },\n {\n version: 4,\n name: \"addressing, tokens and sessions\",\n up(db) {\n // DATA_MODEL §3, D97, D98, D99. `port_lease` gives the shell and each artifact a stable\n // port per home. `token` keeps only the SHA-256 of each capability secret; `is_default`\n // marks the artifact's default link (one live default per artifact, by the partial unique\n // index) and `pinned_version` the version number a link's URL names, so a rotation keeps\n // it. `shell_origin` is the address the link was minted for: a link works only there, so a\n // program that later holds an abandoned port can't use the secrets of old links (D97).\n // `session` keeps the SHA-256 of each session cookie, the origin it was issued for and, for\n // an artifact frame, the version it entered (D98 item 5). `request.params_digest` makes a\n // requestId replay only the request it recorded (H-03).\n db.exec(`\n CREATE TABLE port_lease (\n port INTEGER PRIMARY KEY CHECK (port BETWEEN 1 AND 65535),\n purpose TEXT NOT NULL CHECK (purpose IN ('shell', 'artifact', 'demo')),\n owner_ref TEXT NOT NULL,\n leased_at TEXT NOT NULL,\n UNIQUE (purpose, owner_ref)\n );\n CREATE TABLE token (\n id TEXT PRIMARY KEY,\n secret_hash TEXT NOT NULL UNIQUE,\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n scopes_json TEXT NOT NULL,\n viewer_id TEXT,\n expires_at TEXT,\n revoked_at TEXT,\n created_at TEXT NOT NULL,\n is_default INTEGER NOT NULL DEFAULT 0 CHECK (is_default IN (0, 1)),\n pinned_version INTEGER CHECK (pinned_version >= 1),\n shell_origin TEXT NOT NULL,\n replaced_by TEXT,\n CHECK (is_default = 0 OR (revoked_at IS NULL AND expires_at IS NULL))\n );\n CREATE UNIQUE INDEX token_default ON token (artifact_id) WHERE is_default = 1;\n CREATE INDEX token_artifact ON token (artifact_id);\n CREATE TRIGGER token_revocation_final BEFORE UPDATE ON token\n WHEN OLD.revoked_at IS NOT NULL OR NEW.secret_hash IS NOT OLD.secret_hash\n OR NEW.artifact_id IS NOT OLD.artifact_id OR NEW.scopes_json IS NOT OLD.scopes_json\n OR NEW.expires_at IS NOT OLD.expires_at OR NEW.pinned_version IS NOT OLD.pinned_version\n OR NEW.shell_origin IS NOT OLD.shell_origin\n BEGIN\n SELECT RAISE(ABORT, 'a token never changes its grant, and a revoked token stays revoked');\n END;\n CREATE TABLE session (\n id TEXT PRIMARY KEY,\n token_id TEXT NOT NULL REFERENCES token(id),\n origin TEXT NOT NULL,\n mode TEXT NOT NULL CHECK (mode IN ('cookie', 'worker')),\n -- The SHA-256 of the session's CSRF token, which is derived from the cookie (D98).\n csrf TEXT NOT NULL,\n version_id TEXT REFERENCES version(id),\n created_at TEXT NOT NULL,\n last_seen_at TEXT NOT NULL\n );\n CREATE INDEX session_token ON session (token_id);\n ALTER TABLE request ADD COLUMN params_digest TEXT;\n `);\n },\n },\n {\n version: 5,\n name: \"interaction ledger\",\n up(db) {\n // DATA_MODEL §3, D101 to D106. Viewers are people (one `local`, one `token` viewer per host\n // key); a view is one frame load of one version. A document is a viewer's draft or the\n // artifact's state: its revision and epoch only grow (trigger), and each field keeps the\n // revision that last wrote it, deletions included, so conflicts are exact. A mutation ID\n // replays its recorded result. Submissions are write-once (trigger); `position` is the\n // cursor of their `submission.created` event, the order deliveries replay in. A terminal\n // delivery never changes again (trigger). `subscriber` keeps durable acknowledged cursors.\n // A token's viewer joins its immutable grant. INSERT OR REPLACE would delete a row without\n // the DELETE and UPDATE triggers, so write-once tables also refuse an insert over an\n // existing row (Claude review finding 7). `artifact.policy_chosen_json` keeps the policy a\n // publish named explicitly, which later publishes keep until another names one (D102).\n db.exec(`\n CREATE TABLE viewer (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL CHECK (kind IN ('local', 'tailnet', 'token', 'host')),\n external_ref TEXT NOT NULL,\n name TEXT,\n created_at TEXT NOT NULL,\n UNIQUE (kind, external_ref)\n );\n CREATE TABLE view (\n id TEXT PRIMARY KEY,\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n version_id TEXT NOT NULL REFERENCES version(id),\n viewer_id TEXT NOT NULL REFERENCES viewer(id),\n token_id TEXT REFERENCES token(id),\n opened_cursor INTEGER,\n opened_at TEXT NOT NULL,\n closed_at TEXT,\n live_cursor_json TEXT\n );\n CREATE INDEX view_artifact ON view (artifact_id, viewer_id);\n CREATE TABLE document (\n id INTEGER PRIMARY KEY,\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n scope TEXT NOT NULL CHECK (scope IN ('viewer', 'artifact')),\n viewer_id TEXT REFERENCES viewer(id),\n revision INTEGER NOT NULL DEFAULT 0 CHECK (revision >= 0),\n epoch INTEGER NOT NULL DEFAULT 1 CHECK (epoch >= 1),\n size INTEGER NOT NULL DEFAULT 0 CHECK (size >= 0),\n CHECK ((scope = 'viewer') = (viewer_id IS NOT NULL)),\n UNIQUE (artifact_id, scope, viewer_id)\n );\n CREATE UNIQUE INDEX document_state ON document (artifact_id) WHERE scope = 'artifact';\n CREATE TRIGGER document_monotonic BEFORE UPDATE ON document\n WHEN NEW.revision < OLD.revision OR NEW.epoch < OLD.epoch\n OR NEW.artifact_id IS NOT OLD.artifact_id OR NEW.scope IS NOT OLD.scope\n OR NEW.viewer_id IS NOT OLD.viewer_id\n BEGIN\n SELECT RAISE(ABORT, 'a document''s revision and epoch only grow');\n END;\n CREATE TABLE field (\n document_id INTEGER NOT NULL REFERENCES document(id),\n field_id TEXT NOT NULL,\n value_json TEXT NOT NULL,\n deleted INTEGER NOT NULL DEFAULT 0 CHECK (deleted IN (0, 1)),\n field_rev INTEGER NOT NULL CHECK (field_rev >= 1),\n updated_by_json TEXT,\n updated_at TEXT NOT NULL,\n sensitive INTEGER NOT NULL DEFAULT 0 CHECK (sensitive IN (0, 1)),\n label TEXT,\n required INTEGER CHECK (required IN (0, 1)),\n orphaned_from_version INTEGER,\n PRIMARY KEY (document_id, field_id)\n );\n CREATE TABLE mutation (\n id TEXT PRIMARY KEY,\n document_id INTEGER NOT NULL REFERENCES document(id),\n params_digest TEXT NOT NULL,\n result_json TEXT NOT NULL,\n applied_at TEXT NOT NULL\n );\n CREATE TABLE submission (\n id TEXT PRIMARY KEY,\n position INTEGER NOT NULL UNIQUE,\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n version_id TEXT NOT NULL REFERENCES version(id),\n view_id TEXT NOT NULL REFERENCES view(id),\n viewer_id TEXT NOT NULL REFERENCES viewer(id),\n channel TEXT NOT NULL CHECK (channel IN ('shell', 'artifact')),\n policy_json TEXT NOT NULL,\n epoch INTEGER NOT NULL CHECK (epoch >= 1),\n scope_key TEXT NOT NULL,\n previous_id TEXT REFERENCES submission(id),\n draft_document_id INTEGER NOT NULL REFERENCES document(id),\n draft_revision INTEGER NOT NULL,\n state_revision INTEGER,\n latest_version_number INTEGER,\n snapshot_json TEXT NOT NULL,\n digest TEXT NOT NULL,\n stale_view INTEGER NOT NULL CHECK (stale_view IN (0, 1)),\n request_id TEXT UNIQUE,\n created_at TEXT NOT NULL,\n UNIQUE (artifact_id, scope_key, epoch)\n );\n CREATE INDEX submission_artifact ON submission (artifact_id, position);\n CREATE TRIGGER submission_write_once BEFORE UPDATE ON submission\n BEGIN\n SELECT RAISE(ABORT, 'submissions are immutable');\n END;\n CREATE TRIGGER submission_kept BEFORE DELETE ON submission\n BEGIN\n SELECT RAISE(ABORT, 'submissions are immutable');\n END;\n -- INSERT OR REPLACE deletes the old row without the DELETE trigger: refuse it at insert.\n CREATE TRIGGER submission_not_replaced BEFORE INSERT ON submission\n WHEN EXISTS (SELECT 1 FROM submission WHERE id = NEW.id OR position = NEW.position\n OR (artifact_id = NEW.artifact_id AND scope_key = NEW.scope_key AND epoch = NEW.epoch))\n BEGIN\n SELECT RAISE(ABORT, 'submissions are immutable');\n END;\n CREATE TABLE delivery (\n id TEXT PRIMARY KEY,\n submission_id TEXT NOT NULL REFERENCES submission(id),\n position INTEGER NOT NULL,\n port_owner TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('pending', 'delivered', 'rejected', 'undeliverable')),\n attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),\n next_attempt_at TEXT,\n last_error_json TEXT,\n reason TEXT,\n updated_at TEXT NOT NULL,\n UNIQUE (submission_id, port_owner)\n );\n CREATE INDEX delivery_owner ON delivery (port_owner, state, position);\n CREATE TRIGGER delivery_terminal BEFORE UPDATE ON delivery\n WHEN OLD.state <> 'pending' OR NEW.submission_id IS NOT OLD.submission_id\n OR NEW.port_owner IS NOT OLD.port_owner OR NEW.position IS NOT OLD.position\n BEGIN\n SELECT RAISE(ABORT, 'a delivery''s terminal state never changes');\n END;\n CREATE TRIGGER delivery_kept BEFORE DELETE ON delivery\n BEGIN\n SELECT RAISE(ABORT, 'deliveries are kept with their submissions');\n END;\n CREATE TRIGGER delivery_not_replaced BEFORE INSERT ON delivery\n WHEN EXISTS (SELECT 1 FROM delivery WHERE id = NEW.id\n OR (submission_id = NEW.submission_id AND port_owner = NEW.port_owner))\n BEGIN\n SELECT RAISE(ABORT, 'a delivery''s terminal state never changes');\n END;\n CREATE TRIGGER version_not_replaced BEFORE INSERT ON version\n WHEN EXISTS (SELECT 1 FROM version WHERE id = NEW.id\n OR (artifact_id = NEW.artifact_id AND number = NEW.number))\n BEGIN\n SELECT RAISE(ABORT, 'published versions are immutable');\n END;\n CREATE TRIGGER token_not_replaced BEFORE INSERT ON token\n WHEN EXISTS (SELECT 1 FROM token WHERE id = NEW.id OR secret_hash = NEW.secret_hash)\n BEGIN\n SELECT RAISE(ABORT, 'a token never changes its grant, and a revoked token stays revoked');\n END;\n CREATE TABLE subscriber (\n name TEXT PRIMARY KEY,\n filter_json TEXT NOT NULL,\n acked_cursor INTEGER NOT NULL DEFAULT 0 CHECK (acked_cursor >= 0),\n updated_at TEXT NOT NULL\n );\n ALTER TABLE artifact ADD COLUMN policy_chosen_json TEXT;\n CREATE INDEX event_artifact ON event (artifact_id, cursor);\n CREATE INDEX event_artifact_type ON event (artifact_id, type, cursor);\n DROP TRIGGER token_revocation_final;\n CREATE TRIGGER token_revocation_final BEFORE UPDATE ON token\n WHEN OLD.revoked_at IS NOT NULL OR NEW.secret_hash IS NOT OLD.secret_hash\n OR NEW.artifact_id IS NOT OLD.artifact_id OR NEW.scopes_json IS NOT OLD.scopes_json\n OR NEW.expires_at IS NOT OLD.expires_at OR NEW.pinned_version IS NOT OLD.pinned_version\n OR NEW.shell_origin IS NOT OLD.shell_origin OR NEW.viewer_id IS NOT OLD.viewer_id\n BEGIN\n SELECT RAISE(ABORT, 'a token never changes its grant, and a revoked token stays revoked');\n END;\n `);\n },\n },\n {\n version: 6,\n name: \"views, follows and field versions\",\n up(db) {\n // D108, D109, D63. A view records the submit channels and trusted controls in force when it\n // opened, so the shell, the page and the server judge it alike. `follow` keeps each viewer's\n // \"Always follow this artifact\". A field records the version whose view last wrote it (an\n // orphan's `fromVersion`): the column WP-06 reserved as `orphaned_from_version`, never set,\n // since orphans are derived per view and never stored.\n db.exec(`\n ALTER TABLE field RENAME COLUMN orphaned_from_version TO version_number;\n ALTER TABLE view ADD COLUMN controls_json TEXT;\n CREATE TABLE follow (\n viewer_id TEXT NOT NULL REFERENCES viewer(id),\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n followed_at TEXT NOT NULL,\n PRIMARY KEY (viewer_id, artifact_id)\n );\n `);\n // Fields written before: each draft change names the view it came from, so the newest\n // change of a field tells its version. Changes whose events were compacted stay unknown.\n const changes = db.all<{\n artifact_id: string;\n payload_json: string;\n version_number: number;\n }>(\n `SELECT event.artifact_id, event.payload_json, version.number AS version_number FROM event\n JOIN view ON view.id = json_extract(event.causation_json, '$.viewId')\n JOIN version ON version.id = view.version_id\n WHERE event.type = 'draft.changed' ORDER BY event.cursor`,\n );\n for (const change of changes) {\n const payload = JSON.parse(change.payload_json) as {\n viewerId?: string;\n changes?: { id: string }[];\n };\n for (const field of payload.changes ?? []) {\n db.run(\n `UPDATE field SET version_number = ? WHERE field_id = ? AND document_id IN\n (SELECT id FROM document WHERE artifact_id = ? AND scope = 'viewer' AND viewer_id = ?)`,\n change.version_number,\n field.id,\n change.artifact_id,\n payload.viewerId ?? null,\n );\n }\n }\n },\n },\n {\n version: 7,\n name: \"action runs and live values\",\n up(db) {\n // D24, D54, D47, AC-02, AC-03. A run is recorded before any worker starts it. An explicit\n // key allows one run per artifact, function and key, ever (SQLite treats NULL keys as\n // distinct, so keyless runs don't collide); a client key makes a retried request join the\n // run it started. `waiting` is reserved for WP-28's relay (D117, D124). A final run never\n // changes again, and its result batches only grow while it runs.\n db.exec(`\n CREATE TABLE action_run (\n id TEXT PRIMARY KEY,\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n version_id TEXT NOT NULL REFERENCES version(id),\n view_id TEXT REFERENCES view(id),\n viewer_id TEXT REFERENCES viewer(id),\n action TEXT NOT NULL,\n args_json TEXT NOT NULL,\n key TEXT,\n client_key TEXT NOT NULL,\n status TEXT NOT NULL\n CHECK (status IN ('queued', 'running', 'waiting', 'succeeded', 'failed', 'cancelled')),\n reason TEXT,\n error_json TEXT,\n progress_json TEXT,\n log_text TEXT NOT NULL DEFAULT '',\n log_lines INTEGER NOT NULL DEFAULT 0,\n log_truncated INTEGER NOT NULL DEFAULT 0,\n batches INTEGER NOT NULL DEFAULT 0,\n result_size INTEGER NOT NULL DEFAULT 0,\n started_at TEXT NOT NULL,\n finished_at TEXT,\n UNIQUE (artifact_id, action, key),\n UNIQUE (artifact_id, client_key)\n );\n CREATE INDEX action_run_view ON action_run(view_id);\n CREATE INDEX action_run_open ON action_run(status) WHERE status IN ('queued', 'running', 'waiting');\n CREATE TRIGGER action_run_final_update BEFORE UPDATE ON action_run\n WHEN OLD.status IN ('succeeded', 'failed', 'cancelled')\n BEGIN\n SELECT RAISE(ABORT, 'a finished action run never changes');\n END;\n CREATE TRIGGER action_run_no_delete BEFORE DELETE ON action_run\n BEGIN\n SELECT RAISE(ABORT, 'action runs are kept with their artifact');\n END;\n CREATE TABLE action_run_batch (\n run_id TEXT NOT NULL REFERENCES action_run(id),\n seq INTEGER NOT NULL,\n batch_json TEXT NOT NULL,\n PRIMARY KEY (run_id, seq)\n );\n CREATE TRIGGER action_run_batch_append BEFORE UPDATE ON action_run_batch\n BEGIN\n SELECT RAISE(ABORT, 'a run result batch never changes');\n END;\n -- Write-once like submissions and versions (DATA_MODEL §3): an INSERT OR REPLACE would\n -- delete the row it replaces without firing the DELETE trigger (Opus review 11).\n CREATE TRIGGER action_run_not_replaced BEFORE INSERT ON action_run\n WHEN EXISTS (SELECT 1 FROM action_run WHERE id = NEW.id\n OR (artifact_id = NEW.artifact_id AND client_key = NEW.client_key)\n OR (NEW.key IS NOT NULL AND artifact_id = NEW.artifact_id AND action = NEW.action\n AND key = NEW.key))\n BEGIN\n SELECT RAISE(ABORT, 'an action run is never replaced');\n END;\n CREATE TRIGGER action_run_batch_no_delete BEFORE DELETE ON action_run_batch\n BEGIN\n SELECT RAISE(ABORT, 'a run result batch is kept with its run');\n END;\n CREATE TRIGGER action_run_batch_once BEFORE INSERT ON action_run_batch\n WHEN EXISTS (SELECT 1 FROM action_run_batch WHERE run_id = NEW.run_id AND seq = NEW.seq)\n OR EXISTS (SELECT 1 FROM action_run WHERE id = NEW.run_id\n AND status IN ('succeeded', 'failed', 'cancelled'))\n BEGIN\n SELECT RAISE(ABORT, 'a finished run takes no more result batches');\n END;\n `);\n // D56, D63, LL-04. A live source keeps its latest value with a revision that only grows, and\n // in append mode a bounded ring of recent values. Updates are never events.\n db.exec(`\n CREATE TABLE live_value (\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n key TEXT NOT NULL,\n revision INTEGER NOT NULL,\n value_json TEXT NOT NULL,\n producer_version_id TEXT,\n at TEXT NOT NULL,\n PRIMARY KEY (artifact_id, key)\n );\n CREATE TRIGGER live_value_revision BEFORE UPDATE ON live_value\n WHEN NEW.revision <= OLD.revision\n BEGIN\n SELECT RAISE(ABORT, 'a live value revision only grows');\n END;\n CREATE TABLE live_ring (\n artifact_id TEXT NOT NULL,\n key TEXT NOT NULL,\n revision INTEGER NOT NULL,\n value_json TEXT NOT NULL,\n at TEXT NOT NULL,\n PRIMARY KEY (artifact_id, key, revision)\n );\n `);\n },\n },\n {\n version: 8,\n name: \"verify verdicts on versions\",\n up(db) {\n // D138 item 4: whether a version passed verify is a recorded fact, written with the version\n // (it is write-once like the rest of the row), so the regression baseline is the newest\n // version that passed even when its build is gone. NULL for versions published before\n // verify, which never count as passing.\n db.exec(`\n ALTER TABLE version ADD COLUMN verify_json TEXT;\n `);\n },\n },\n {\n version: 9,\n name: \"collected versions\",\n up(db) {\n // D140 item 14: `mostra gc` removes an unreferenced version's files and keeps its row, ID\n // and number forever, so a content-addressed ID never gets a second number. The collection\n // is a row here, never a change to `version`: inserted once, never updated, and deleted only\n // when a publish of the exact source restores the files.\n db.exec(`\n CREATE TABLE version_collected (\n version_id TEXT PRIMARY KEY REFERENCES version(id),\n collected_at TEXT NOT NULL\n );\n CREATE TRIGGER version_collected_write_once BEFORE UPDATE ON version_collected\n BEGIN\n SELECT RAISE(ABORT, 'a collection record never changes');\n END;\n CREATE TRIGGER version_collected_not_replaced BEFORE INSERT ON version_collected\n WHEN EXISTS (SELECT 1 FROM version_collected WHERE version_id = NEW.version_id)\n BEGIN\n SELECT RAISE(ABORT, 'a version is collected once');\n END;\n CREATE TRIGGER version_kept BEFORE DELETE ON version\n BEGIN\n SELECT RAISE(ABORT, 'a version row is kept forever, collected or not');\n END;\n `);\n },\n },\n {\n version: 10,\n name: \"session viewers\",\n up(db) {\n // D143 item 2: a link minted without a viewer acts as the person a host's identity port\n // names, decided once when the browser exchanges the link. The session keeps that viewer,\n // and a frame session made from its tickets keeps the same one. NULL: the link's own viewer,\n // or the home's local user.\n db.exec(`\n ALTER TABLE session ADD COLUMN viewer_id TEXT REFERENCES viewer(id);\n `);\n },\n },\n {\n version: 11,\n name: \"shares and faces\",\n up(db) {\n // D158. A face (an external address of the gateway: a tailnet or Funnel address, a quick\n // tunnel's, a host's external base) is a listener of its own on loopback; a face that must\n // keep its port across restarts (a tailnet address is `https://<device>:<port>`, a host's\n // tunnel forwards to a port it was told) leases it like the shell and the artifacts do, under\n // the purpose `face`. SQLite can't change a CHECK, so `port_lease` is rebuilt with its rows.\n // `share` records each share (DATA_MODEL §3) with its plan, the addresses it set up, so a\n // restart sets tailnet and Funnel shares up again; its row only ever ends (a trigger).\n // `external_base` keeps the faces a host's addressing port gave, so their links work after\n // a restart before the host answers again.\n db.exec(`\n CREATE TABLE port_lease_new (\n port INTEGER PRIMARY KEY CHECK (port BETWEEN 1 AND 65535),\n purpose TEXT NOT NULL CHECK (purpose IN ('shell', 'artifact', 'demo', 'face')),\n owner_ref TEXT NOT NULL,\n leased_at TEXT NOT NULL,\n UNIQUE (purpose, owner_ref)\n );\n INSERT INTO port_lease_new (port, purpose, owner_ref, leased_at)\n SELECT port, purpose, owner_ref, leased_at FROM port_lease;\n DROP TABLE port_lease;\n ALTER TABLE port_lease_new RENAME TO port_lease;\n CREATE TABLE share (\n id TEXT PRIMARY KEY,\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n via TEXT NOT NULL CHECK (via IN ('tailnet', 'funnel', 'cloudflare')),\n hostname TEXT NOT NULL,\n token_id TEXT NOT NULL REFERENCES token(id),\n mode TEXT NOT NULL CHECK (mode IN ('cookie', 'worker')),\n plan_json TEXT NOT NULL,\n started_at TEXT NOT NULL,\n expires_at TEXT,\n stopped_at TEXT,\n stop_reason TEXT,\n CHECK ((stopped_at IS NULL) = (stop_reason IS NULL))\n );\n CREATE INDEX share_artifact ON share (artifact_id);\n CREATE INDEX share_active ON share (stopped_at) WHERE stopped_at IS NULL;\n CREATE TRIGGER share_ends_once BEFORE UPDATE ON share\n WHEN OLD.stopped_at IS NOT NULL OR NEW.id IS NOT OLD.id\n OR NEW.artifact_id IS NOT OLD.artifact_id OR NEW.via IS NOT OLD.via\n OR NEW.token_id IS NOT OLD.token_id OR NEW.started_at IS NOT OLD.started_at\n OR NEW.expires_at IS NOT OLD.expires_at\n BEGIN\n SELECT RAISE(ABORT, 'a share only ever ends, once');\n END;\n CREATE TABLE external_base (\n key TEXT PRIMARY KEY,\n listener TEXT NOT NULL CHECK (listener IN ('shell', 'artifact')),\n artifact_id TEXT NOT NULL REFERENCES artifact(id),\n origin TEXT NOT NULL,\n mode TEXT CHECK (mode IN ('cookie', 'worker')),\n client TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n `);\n },\n },\n];\n","/**\n * Idempotent requests (H-03, FAILURE_MODEL §1 rule 3): a mutating method records its result under\n * the caller's `requestId`, with a digest of the parameters it was called with, in the same\n * transaction as its effect. A retry with the same parameters gets the recorded result; the same\n * `requestId` with other parameters is refused with `MOSTRA_HOST_REQUEST_ID_REUSED`, never answered\n * with a result for a request nobody made.\n */\nimport { createHash } from \"node:crypto\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { LedgerDb } from \"./types.ts\";\n\n/** A request to record or replay: its method, the caller's `requestId` and a digest of its params. */\nexport interface RequestKey {\n readonly method: string;\n readonly requestId: string;\n readonly digest: string;\n}\n\n/** JSON with object keys sorted at every depth, so equal parameters give equal text. */\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableJson).join(\",\")}]`;\n if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, item]) => item !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`).join(\",\")}}`;\n }\n return JSON.stringify(value);\n}\n\n/**\n * The key of a request, or `undefined` when the caller sent no `requestId`. The digest covers\n * every parameter but `requestId` itself.\n */\nexport function requestKey<P extends { readonly requestId?: string | undefined }>(\n method: string,\n params: P,\n): RequestKey | undefined {\n const { requestId, ...rest } = params as { requestId?: string } & Record<string, unknown>;\n if (requestId === undefined) return undefined;\n return {\n method,\n requestId,\n digest: createHash(\"sha256\").update(stableJson(rest), \"utf8\").digest(\"hex\"),\n };\n}\n\nfunction reused(key: RequestKey): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOST_REQUEST_ID_REUSED\", {\n message: `The requestId \"${key.requestId}\" was used for another ${key.method} request with other parameters.`,\n }),\n );\n}\n\n/**\n * The result recorded for `key`, or `undefined` when none is. Throws `MOSTRA_HOST_REQUEST_ID_REUSED`\n * when the `requestId` was recorded with other parameters. A row recorded before digests existed\n * replays as it always did.\n */\nexport function recordedResult<T>(db: LedgerDb, key: RequestKey): T | undefined {\n const row = db.get<{ result_json: string; params_digest: string | null }>(\n \"SELECT result_json, params_digest FROM request WHERE method = ? AND request_id = ?\",\n key.method,\n key.requestId,\n );\n if (!row) return undefined;\n if (row.params_digest !== null && row.params_digest !== key.digest) throw reused(key);\n return JSON.parse(row.result_json) as T;\n}\n\n/** Records `result` for `key` in the caller's transaction; a key already recorded is kept. */\nexport function recordResult(db: LedgerDb, key: RequestKey, result: unknown): void {\n db.run(\n \"INSERT OR IGNORE INTO request (method, request_id, result_json, params_digest, created_at) VALUES (?, ?, ?, ?, ?)\",\n key.method,\n key.requestId,\n JSON.stringify(result),\n key.digest,\n new Date().toISOString(),\n );\n}\n\n/**\n * Joins concurrent calls of one request, so a retry that arrives while the first attempt runs\n * waits for its result; the same `requestId` with other parameters is refused at once.\n */\nexport class InflightRequests {\n readonly #running = new Map<\n string,\n { readonly digest: string; readonly result: Promise<unknown> }\n >();\n\n run<T>(key: RequestKey, task: () => Promise<T>): Promise<T> {\n const id = `${key.method} ${key.requestId}`;\n const running = this.#running.get(id);\n if (running) {\n if (running.digest !== key.digest) return Promise.reject(reused(key));\n return running.result as Promise<T>;\n }\n const result = task().finally(() => this.#running.delete(id));\n this.#running.set(id, { digest: key.digest, result });\n return result;\n }\n}\n","/**\n * The ledger (D58, D71, D81; DATA_MODEL §3, §6): the home's one SQLite database, in WAL mode with\n * `synchronous=FULL`, opened with an exclusive lock that decides who owns the home. The\n * supervisor is its only reader and writer; every other module reaches it through\n * {@link Ledger.write} and {@link Ledger.read}, and nothing else in the process opens the file\n * (POSIX drops a process's locks on a file when any descriptor for it closes).\n *\n * ```ts\n * const opened = openLedger({ storeDir, runtimeVersion, owner, log });\n * if (!opened.ok) return attachToOwner(); // another supervisor holds the lock\n * opened.ledger.write((db) => db.run(\"INSERT INTO child …\", …));\n * ```\n */\nimport { existsSync, linkSync, mkdirSync, readdirSync, rmSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type BetterSqlite3 from \"better-sqlite3\";\nimport type { Log } from \"../log.ts\";\nimport { fsyncPath } from \"../platform/index.ts\";\nimport { BOOTSTRAP_SQL, MIGRATIONS, type Migration } from \"./migrations.ts\";\nimport type { LedgerDb, MigrationDb, RunResult, SqlValue } from \"./types.ts\";\n\nexport { MIGRATIONS, type Migration } from \"./migrations.ts\";\nexport {\n InflightRequests,\n type RequestKey,\n recordedResult,\n recordResult,\n requestKey,\n} from \"./requests.ts\";\nexport type { LedgerDb } from \"./types.ts\";\n\n/** The ledger's file name inside `<home>/store`. */\nexport const LEDGER_FILE = \"ledger.sqlite\";\n\n/** The process that holds the ledger's lock. */\nexport interface LedgerOwner {\n readonly pid: number;\n /** Its start time (processes/identity.ts). */\n readonly startTime: string;\n}\n\n/** Options for {@link openLedger}. */\nexport interface OpenLedgerOptions {\n /** `<home>/store`, created with mode 0700 when missing. */\n readonly storeDir: string;\n /** This runtime's release, recorded with each migration and named by `MOSTRA_HOME_TOO_NEW`. */\n readonly runtimeVersion: string;\n /** Who takes the lock, recorded in `ledger_lock`. */\n readonly owner: LedgerOwner;\n readonly log: Log;\n /** The migrations to apply. Default: this runtime's {@link MIGRATIONS}. */\n readonly migrations?: readonly Migration[];\n}\n\n/** The open ledger. Holding this object holds the home's lock. */\nexport interface Ledger {\n /** The ledger file. */\n readonly file: string;\n /** The schema version after migrations. */\n readonly schemaVersion: number;\n /** The migrations applied while opening, with the backup taken first (when any). */\n readonly migrated:\n | { readonly from: number; readonly to: number; readonly backup?: string }\n | undefined;\n /**\n * Runs `fn` in one write transaction (`BEGIN IMMEDIATE`) and commits it, durably\n * (`synchronous=FULL`), before returning (FAILURE_MODEL §1 rule 1). A full disk throws\n * `MOSTRA_HOME_DISK_FULL`; a removed ledger throws `MOSTRA_HOME_GONE`. Nothing partial commits.\n */\n write<T>(fn: (db: LedgerDb) => T): T;\n /** Runs `fn` in one read transaction, so it sees a single consistent state. */\n read<T>(fn: (db: LedgerDb) => T): T;\n /**\n * Calls `listener` after every write transaction that committed, so readers waiting for new\n * events (`wait`, subscriptions, event streams) look again. Returns the unsubscribe function.\n * A listener's exception is swallowed: it never undoes or fails the commit.\n */\n onCommit(listener: () => void): () => void;\n /** Runs SQLite's full integrity check: `ok`, or the problems it reports. */\n checkIntegrity(): { readonly ok: boolean; readonly problems: readonly string[] };\n /** Closes the ledger and releases the home's lock. Idempotent. */\n close(): void;\n}\n\n/** The outcome of {@link openLedger}. */\nexport type LedgerOpening =\n | { readonly ok: true; readonly ledger: Ledger }\n | { readonly ok: false; readonly reason: \"locked\" };\n\ntype Database = BetterSqlite3.Database;\ntype DatabaseConstructor = typeof BetterSqlite3;\n\nlet driver: DatabaseConstructor | undefined;\n/** Loads the native driver on first use, so importing this module loads no native code. */\nfunction loadDriver(): DatabaseConstructor {\n driver ??= createRequire(import.meta.url)(\"better-sqlite3\") as DatabaseConstructor;\n return driver;\n}\n\nconst sqliteCode = (error: unknown): string | undefined =>\n typeof error === \"object\" && error !== null && \"code\" in error && typeof error.code === \"string\"\n ? error.code\n : undefined;\n\n/**\n * Turns a SQLite failure into the diagnostic the caller can act on, or `undefined` for failures\n * that are defects (they stay internal errors).\n */\nfunction diagnose(error: unknown, file: string): RpcError | undefined {\n const code = sqliteCode(error);\n if (code === undefined) return undefined;\n if (code === \"SQLITE_FULL\") {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOME_DISK_FULL\", {\n message: `The disk holding ${file} is full; the change was rolled back.`,\n }),\n );\n }\n if (code === \"SQLITE_READONLY_DBMOVED\") {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOME_GONE\", {\n message: `The ledger ${file} was moved or deleted while the instance was running.`,\n }),\n );\n }\n if (code === \"SQLITE_NOTADB\" || code.startsWith(\"SQLITE_CORRUPT\") || code === \"SQLITE_CANTOPEN\") {\n return unreadable(file, describe(code));\n }\n return undefined;\n}\n\nfunction describe(code: string): string {\n if (code === \"SQLITE_NOTADB\") return \"it isn't a SQLite database\";\n if (code === \"SQLITE_CANTOPEN\") return \"it can't be opened\";\n return \"it is damaged\";\n}\n\nfunction unreadable(file: string, why: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOME_LEDGER_UNREADABLE\", {\n message: `The ledger ${file} can't be read: ${why}.`,\n }),\n );\n}\n\n/** Builds a new ledger file at `file` without ever replacing an existing one (DATA_MODEL §6). */\nfunction createLedgerFile(storeDir: string, file: string, log: Log): void {\n const Driver = loadDriver();\n const temp = join(storeDir, `${LEDGER_FILE}.${process.pid}.${Date.now()}.creating`);\n const db = new Driver(temp);\n try {\n db.pragma(\"journal_mode = WAL\");\n db.pragma(\"synchronous = FULL\");\n db.exec(BOOTSTRAP_SQL);\n } finally {\n db.close();\n }\n fsyncPath(temp);\n try {\n linkSync(temp, file);\n log.info(\"ledger.created\", { file });\n } catch (error) {\n // Another starter created it first; theirs is the ledger.\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n } finally {\n rmSync(temp, { force: true });\n }\n syncDirectory(storeDir);\n}\n\nfunction syncDirectory(dir: string): void {\n // Some file systems can't fsync a directory; the data itself is synced.\n fsyncPath(dir, true);\n}\n\n/**\n * Removes `*.creating` files left by starters that died while building a ledger. A file whose\n * creator still runs is another starter's work in progress and stays.\n */\nfunction removeAbandonedFiles(storeDir: string): void {\n for (const name of readdirSync(storeDir)) {\n const match = /^ledger\\.sqlite\\.(\\d+)\\.\\d+\\.creating(-wal|-shm|-journal)?$/.exec(name);\n if (match && !processExists(Number(match[1]))) rmSync(join(storeDir, name), { force: true });\n }\n}\n\nfunction processExists(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nfunction queries(db: Database): MigrationDb {\n const cache = new Map<string, BetterSqlite3.Statement>();\n const prepare = (sql: string): BetterSqlite3.Statement => {\n let statement = cache.get(sql);\n if (!statement) {\n statement = db.prepare(sql);\n cache.set(sql, statement);\n }\n return statement;\n };\n return {\n run(sql: string, ...params: readonly SqlValue[]): RunResult {\n const result = prepare(sql).run(...params);\n return { changes: result.changes, lastInsertRowid: result.lastInsertRowid };\n },\n get<T>(sql: string, ...params: readonly SqlValue[]): T | undefined {\n return prepare(sql).get(...params) as T | undefined;\n },\n all<T>(sql: string, ...params: readonly SqlValue[]): T[] {\n return prepare(sql).all(...params) as T[];\n },\n exec(sql: string): void {\n db.exec(sql);\n },\n };\n}\n\n/**\n * Opens the home's ledger and takes its exclusive lock (D81). Returns `{ ok: false, reason:\n * \"locked\" }` when another process holds it. Throws an `RpcError` with `MOSTRA_HOME_TOO_NEW`,\n * `MOSTRA_HOME_LEDGER_UNREADABLE` or `MOSTRA_HOME_DISK_FULL` when the ledger can't be used.\n *\n * Opening creates a missing ledger, applies pending migrations in one transaction after an\n * integrity check and a `VACUUM INTO` backup (`ledger.sqlite.bak-<from>-<to>`), and records the\n * owner in `ledger_lock`.\n */\nexport function openLedger(options: OpenLedgerOptions): LedgerOpening {\n const { storeDir, log } = options;\n const migrations = options.migrations ?? MIGRATIONS;\n const latest = migrations.at(-1)?.version ?? 0;\n mkdirSync(storeDir, { recursive: true, mode: 0o700 });\n const file = join(storeDir, LEDGER_FILE);\n if (!existsSync(file)) createLedgerFile(storeDir, file, log);\n\n const Driver = loadDriver();\n let db: Database;\n try {\n db = new Driver(file, { timeout: 0, fileMustExist: true });\n } catch (error) {\n throw diagnose(error, file) ?? error;\n }\n\n try {\n // EXCLUSIVE before the first WAL access: no shared-memory index, and no other connection.\n db.pragma(\"locking_mode = EXCLUSIVE\");\n const mode = db.pragma(\"journal_mode = WAL\", { simple: true });\n if (mode !== \"wal\") throw unreadable(file, `its journal mode is ${String(mode)}, not WAL`);\n db.pragma(\"synchronous = FULL\");\n db.pragma(\"foreign_keys = ON\");\n // A write transaction takes and keeps the exclusive lock from the start (D81).\n db.prepare(\"BEGIN EXCLUSIVE\").run();\n try {\n db.prepare(\n \"INSERT OR REPLACE INTO ledger_lock (id, pid, start_time, acquired_at) VALUES (1, ?, ?, ?)\",\n ).run(options.owner.pid, options.owner.startTime, new Date().toISOString());\n db.prepare(\"COMMIT\").run();\n } catch (error) {\n if (db.inTransaction) db.prepare(\"ROLLBACK\").run();\n throw error;\n }\n } catch (error) {\n db.close();\n if (sqliteCode(error) === \"SQLITE_BUSY\") return { ok: false, reason: \"locked\" };\n if (error instanceof RpcError) throw error;\n if (/no such table/.test((error as Error).message)) {\n throw unreadable(file, \"it isn't a Mostra ledger\");\n }\n throw diagnose(error, file) ?? error;\n }\n\n try {\n removeAbandonedFiles(storeDir);\n const migrated = migrate(db, file, storeDir, latest, migrations, options);\n return { ok: true, ledger: wrap(db, file, latest, migrated) };\n } catch (error) {\n db.close();\n throw diagnose(error, file) ?? error;\n }\n}\n\nfunction migrate(\n db: Database,\n file: string,\n storeDir: string,\n latest: number,\n migrations: readonly Migration[],\n options: OpenLedgerOptions,\n): Ledger[\"migrated\"] {\n const current = db\n .prepare(\"SELECT version, runtime_version FROM schema_migration ORDER BY version DESC LIMIT 1\")\n .get() as { version: number; runtime_version: string } | undefined;\n const from = current?.version ?? 0;\n if (from > latest) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOME_TOO_NEW\", {\n message: `This home's ledger is at schema version ${from}, written by Mostra ${current?.runtime_version ?? \"unknown\"}; this runtime (${options.runtimeVersion}) understands schema versions up to ${latest}.`,\n }),\n );\n }\n if (from === latest) return undefined;\n\n let backup: string | undefined;\n if (from > 0) {\n const check = db.pragma(\"quick_check\") as { quick_check: string }[];\n const problems = check.map((row) => row.quick_check).filter((text) => text !== \"ok\");\n if (problems.length > 0) {\n throw unreadable(\n file,\n `SQLite's integrity check failed (${problems.slice(0, 3).join(\"; \")})`,\n );\n }\n backup = join(storeDir, `${LEDGER_FILE}.bak-${from}-${latest}`);\n rmSync(backup, { force: true });\n // VACUUM INTO writes a consistent copy through SQLite, fsynced under synchronous=FULL;\n // copying the file with fs would drop this process's lock (DATA_MODEL §1).\n db.prepare(\"VACUUM INTO ?\").run(backup);\n options.log.info(\"ledger.backup\", { file: backup, from, to: latest });\n }\n\n const pending = migrations.filter((migration) => migration.version > from);\n const apply = db.transaction(() => {\n const target = queries(db);\n for (const migration of pending) {\n migration.up(target);\n target.run(\n \"INSERT INTO schema_migration (version, name, runtime_version, applied_at) VALUES (?, ?, ?, ?)\",\n migration.version,\n migration.name,\n options.runtimeVersion,\n new Date().toISOString(),\n );\n }\n });\n apply.immediate();\n options.log.info(\"ledger.migrated\", { from, to: latest });\n return backup === undefined ? { from, to: latest } : { from, to: latest, backup };\n}\n\nfunction inodeOf(file: string): string | undefined {\n try {\n const stats = statSync(file);\n return `${stats.dev}:${stats.ino}`;\n } catch {\n return undefined;\n }\n}\n\nfunction wrap(\n db: Database,\n file: string,\n schemaVersion: number,\n migrated: Ledger[\"migrated\"],\n): Ledger {\n const target = queries(db);\n let open = true;\n const listeners = new Set<() => void>();\n // SQLite keeps writing to a ledger whose file was removed (its open descriptors outlive the\n // name), and the data would be lost on close. Every write checks that the file is still the one\n // it opened, before and after the commit, and fails closed otherwise (FAILURE_MODEL §3).\n const opened = inodeOf(file);\n const assertInPlace = (): void => {\n if (inodeOf(file) === opened) return;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOME_GONE\", {\n message: `The ledger ${file} was moved or deleted while the instance was running.`,\n }),\n );\n };\n const guarded = <T>(run: () => T): T => {\n try {\n return run();\n } catch (error) {\n throw diagnose(error, file) ?? error;\n }\n };\n return {\n file,\n schemaVersion,\n migrated,\n write<T>(fn: (db: LedgerDb) => T): T {\n assertInPlace();\n const result = guarded(() => db.transaction(() => fn(target)).immediate());\n assertInPlace();\n // A write nested in another commits with the outer one; listeners hear of that one.\n if (db.inTransaction) return result;\n for (const listener of listeners) {\n try {\n listener();\n } catch {\n // A listener's failure is its own; the commit stands.\n }\n }\n return result;\n },\n onCommit(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n read<T>(fn: (db: LedgerDb) => T): T {\n return guarded(() => db.transaction(() => fn(target)).deferred());\n },\n checkIntegrity() {\n const rows = db.pragma(\"integrity_check\") as { integrity_check: string }[];\n const problems = rows.map((row) => row.integrity_check).filter((text) => text !== \"ok\");\n return { ok: problems.length === 0, problems };\n },\n close() {\n if (!open) return;\n open = false;\n db.close();\n },\n };\n}\n","/**\n * The artifact environment (D95, DP-05): what a child that runs an artifact's own code, or code\n * the artifact chose such as a package's lifecycle script, receives from the supervisor's\n * environment. It is an allowlist, so the supervisor's own settings and a host's credentials\n * (anything a spawning host put into Mostra's environment) never reach artifact code by accident.\n * Install children use it from WP-04 on; workers (WP-08) start from it too.\n */\nimport { delimiter, dirname } from \"node:path\";\nimport type { Environment } from \"../log.ts\";\nimport { WINDOWS, WINDOWS_SYSTEM_VARIABLES } from \"../platform/index.ts\";\n\n/** Variables an artifact's processes need to work like an ordinary shell's programs. */\nconst PASSED: ReadonlySet<string> = new Set([\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TZ\",\n // Who the user is, and the toolchain a package's native build (node-gyp, prebuilds) uses.\n \"USER\",\n \"LOGNAME\",\n \"SHELL\",\n \"TERM\",\n \"XDG_CACHE_HOME\",\n \"XDG_CONFIG_HOME\",\n \"XDG_DATA_HOME\",\n \"CC\",\n \"CXX\",\n \"MAKE\",\n \"PYTHON\",\n \"DEVELOPER_DIR\",\n \"SDKROOT\",\n // Network access through the user's proxy and certificate authorities.\n \"HTTP_PROXY\",\n \"HTTPS_PROXY\",\n \"NO_PROXY\",\n \"http_proxy\",\n \"https_proxy\",\n \"no_proxy\",\n \"NODE_EXTRA_CA_CERTS\",\n \"SSL_CERT_FILE\",\n \"SSL_CERT_DIR\",\n]);\n\n/** What Windows programs need besides the variables above (`platform`'s one list). */\nconst PASSED_WINDOWS: ReadonlySet<string> = new Set(\n WINDOWS_SYSTEM_VARIABLES.map((name) => name.toUpperCase()),\n);\nconst PASSED_UPPER: ReadonlySet<string> = new Set([...PASSED].map((name) => name.toUpperCase()));\n\n/** npm's own configuration channel: the user's registry, scopes and proxies for installs. */\nconst NPM_CONFIG = /^npm_config_/i;\n\n/**\n * The artifact environment derived from the supervisor's `env`. Its `PATH` starts with the\n * directory of the Node.js the runtime runs on (D142): a lifecycle script or server code that runs\n * `node` gets the runtime bundle's private Node.js, on a machine with no other Node.js too.\n */\nexport function artifactEnvironment(env: Environment): Environment {\n const result: Record<string, string> = {};\n // On Windows `Path` and `PATH` are one variable; the one given keeps its own name.\n let pathName = \"PATH\";\n for (const [name, value] of Object.entries(env)) {\n if (value === undefined) continue;\n if (WINDOWS) {\n const upper = name.toUpperCase();\n if (upper === \"PATH\") pathName = name;\n if (PASSED_UPPER.has(upper) || PASSED_WINDOWS.has(upper) || NPM_CONFIG.test(name)) {\n result[name] = value;\n }\n } else if (PASSED.has(name) || NPM_CONFIG.test(name)) {\n result[name] = value;\n }\n }\n const own = dirname(process.execPath);\n const path = result[pathName] ?? (WINDOWS ? \"\" : \"/usr/bin:/bin\");\n const first = path.split(delimiter)[0] ?? \"\";\n const already = WINDOWS ? first.toLowerCase() === own.toLowerCase() : first === own;\n result[pathName] = already ? path : path === \"\" ? own : `${own}${delimiter}${path}`;\n return result;\n}\n","/**\n * The process manager (RT-09, RT-10, ARCHITECTURE §4, FAILURE_MODEL §2). Every child starts\n * behind a gate in a group of its own (a process group on POSIX, a Job Object on Windows,\n * `platform/launch.ts`) and is recorded in the ledger's `child` table with its PID and start\n * time before it may run. A child's group dies with it, and a supervisor that starts after a\n * crash reaps every recorded group that is still running.\n */\nimport { createInterface } from \"node:readline\";\nimport type { Duplex } from \"node:stream\";\nimport { type JsonRpcParams, RpcPeer } from \"@mostra/protocol\";\nimport * as z from \"zod\";\nimport { type Faults, noFaults } from \"../faults.ts\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Environment, Log, Redactor } from \"../log.ts\";\nimport { adoptable, launch, reapRecorded } from \"../platform/index.ts\";\n\n/** How long a stopping child gets between SIGTERM and SIGKILL, by default. */\nconst DEFAULT_GRACE_MS = 5000;\n/** How many stderr lines a child's exit report keeps. */\nconst STDERR_TAIL = 50;\n\n/** How a child ended. */\nexport interface ChildExit {\n /** The exit code, or `null` when a signal ended it. */\n readonly code: number | null;\n /** The signal that ended it, if any. */\n readonly signal: string | null;\n /** Its last stderr lines, for diagnostics such as `MOSTRA_BUILD_CRASHED`. */\n readonly stderrTail: readonly string[];\n}\n\n/** What to start. */\nexport interface SpawnSpec {\n /** What the child is: `builder`, `verify`, `worker`, `pty-host`, `demo`, `install` … */\n readonly kind: string;\n /** What it serves, such as an artifact or version ID. */\n readonly ownerRef: string;\n /** The executable. */\n readonly command: string;\n /** Its arguments. */\n readonly args?: readonly string[];\n /** Its working directory. Default: the supervisor's. */\n readonly cwd?: string;\n /** The child's whole environment. Default: the supervisor's. */\n readonly env?: Environment;\n /**\n * Values the child receives that must never appear in logs or reports, such as secrets.\n * Variables whose names look like secrets (`*_TOKEN`, `*_SECRET` …) are redacted as well.\n */\n readonly redact?: readonly string[];\n /**\n * Receives each line the child writes to stdout, redacted, instead of the log: for children\n * whose output is data, such as the installer's NDJSON report. Every line has arrived before\n * `exited` resolves.\n */\n readonly onStdout?: (line: string) => void;\n /**\n * Receives each line the child writes to stderr, redacted, instead of the log (the exit's\n * `stderrTail` keeps the last ones as always): for a tool that reports its state there, such as\n * `cloudflared`'s tunnel address (D158).\n */\n readonly onStderr?: (line: string) => void;\n /**\n * Opens a JSON-RPC channel over Node IPC; the command must then be a Node.js executable. The\n * handlers answer the child's requests besides the built-in `child/adopt` and `child/release`.\n */\n readonly ipc?: {\n readonly onRequest?: (method: string, params: unknown) => unknown;\n readonly onNotification?: (method: string, params: unknown) => void;\n };\n /**\n * Opens a plain byte channel as the child's fd 4 (an artifact's worker, D124): a pipe the child\n * reads and writes as it likes, unlike `ipc`, which is Node's own channel on the main thread.\n * The two exclude each other.\n */\n readonly channel?: true;\n}\n\n/** A running child. */\nexport interface ChildHandle {\n /** Its process ID, which is also its process group ID. */\n readonly pid: number;\n /** What it is (`SpawnSpec.kind`). */\n readonly kind: string;\n /** What it serves (`SpawnSpec.ownerRef`). */\n readonly ownerRef: string;\n /** When it was started (RFC 3339). */\n readonly startedAt: string;\n /** Sends requests to the child, when it was started with `ipc`. */\n request(\n method: string,\n params?: JsonRpcParams,\n options?: { timeoutMs?: number },\n ): Promise<unknown>;\n /** The child's fd 4, when it was started with `channel`. */\n readonly channel?: Duplex;\n /** Resolves when the child has exited and its process groups are gone. */\n readonly exited: Promise<ChildExit>;\n /** Stops the child: SIGTERM to its group, SIGKILL after `graceMs`. */\n stop(graceMs?: number): Promise<ChildExit>;\n}\n\n/** What reaping found for one recorded child. */\nexport interface ReapedChild {\n /** The recorded process ID. */\n readonly pid: number;\n /** The recorded kind; a program a child adopted has its parent's kind plus \"/adopted\". */\n readonly kind: string;\n /** What it served. */\n readonly ownerRef: string;\n /** The processes that were signalled: the leader if it still ran, and its group's members. */\n readonly signalled: readonly number[];\n /** Why nothing was signalled, when nothing was. */\n readonly skipped?: \"gone\" | \"pid reused\" | \"other boot\";\n}\n\ninterface ChildRow {\n pid: number;\n start_time: string;\n kind: string;\n owner_ref: string;\n pgid: number;\n started_at: string;\n parent_pid: number | null;\n}\n\nconst AdoptParams = z.object({ pid: z.int().min(2) });\n\n/** The process manager of one supervisor. */\nexport interface ProcessManager {\n /** Starts a child in its own process group and records it. */\n spawn(spec: SpawnSpec): Promise<ChildHandle>;\n /** The children running now, for `instance/status`. */\n list(): readonly { pid: number; kind: string; ownerRef: string; startedAt: string }[];\n /** Stops every child; used when the supervisor stops. */\n stopAll(graceMs?: number): Promise<void>;\n /** Ends every child at once without waiting: the last resort at the supervisor's exit. */\n killAll(): void;\n}\n\n/** Options for {@link openProcessManager}. */\nexport interface ProcessManagerOptions {\n readonly ledger: Ledger;\n readonly log: Log;\n /** Learns the secrets children receive, so their output is redacted wherever it goes. */\n readonly redactor: Redactor;\n /** Test fault points (`spawn:before-record`). Default: none. */\n readonly faults?: Faults;\n}\n\n/**\n * Opens the process manager: first reaps every child a previous supervisor of this home left\n * running (FAILURE_MODEL §2), then accepts new children. Call it only while holding the home's\n * ledger lock, so no live supervisor's children are touched.\n */\nexport async function openProcessManager(\n options: ProcessManagerOptions,\n): Promise<{ manager: ProcessManager; reaped: readonly ReapedChild[] }> {\n const reaped = await reap(options.ledger, options.log);\n return { manager: createManager(options), reaped };\n}\n\n/** Waits for `promise` to settle, or `ms` at most, leaving no timer behind. */\nasync function settleWithin(promise: Promise<unknown>, ms: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n promise.then(\n () => undefined,\n () => undefined,\n ),\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, ms);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nasync function reap(ledger: Ledger, log: Log): Promise<ReapedChild[]> {\n const rows = ledger.read((db) => db.all<ChildRow>(\"SELECT * FROM child ORDER BY started_at\"));\n if (rows.length === 0) return [];\n const outcomes = await reapRecorded(rows, (event, fields) => log.warn(event, fields));\n ledger.write((db) => {\n for (const row of rows) {\n db.run(\"DELETE FROM child WHERE pid = ? AND start_time = ?\", row.pid, row.start_time);\n }\n });\n const report = rows.map((row, index): ReapedChild => {\n const base = { pid: row.pid, kind: row.kind, ownerRef: row.owner_ref };\n const outcome = outcomes[index];\n return outcome?.skipped === undefined\n ? { ...base, signalled: outcome?.ended ?? [] }\n : { ...base, signalled: [], skipped: outcome.skipped };\n });\n for (const entry of report) log.info(\"process.reaped\", { ...entry });\n return report;\n}\n\nfunction createManager({\n ledger,\n log,\n redactor,\n faults = noFaults,\n}: ProcessManagerOptions): ProcessManager {\n const running = new Map<number, { handle: ChildHandle; kill(): void }>();\n let stopping = false;\n\n const record = (row: ChildRow): void => {\n ledger.write((db) =>\n db.run(\n \"INSERT OR REPLACE INTO child (pid, start_time, kind, owner_ref, pgid, started_at, parent_pid) VALUES (?, ?, ?, ?, ?, ?, ?)\",\n row.pid,\n row.start_time,\n row.kind,\n row.owner_ref,\n row.pgid,\n row.started_at,\n row.parent_pid,\n ),\n );\n };\n const forget = (pid: number): void => {\n ledger.write((db) => db.run(\"DELETE FROM child WHERE pid = ? OR parent_pid = ?\", pid, pid));\n };\n const warn = (event: string, fields: Readonly<Record<string, unknown>>): void =>\n log.warn(event, fields);\n\n const spawnChild = async (spec: SpawnSpec): Promise<ChildHandle> => {\n if (stopping) throw new Error(\"The process manager is stopping.\");\n if (spec.ipc && spec.channel) throw new Error(\"A child takes ipc or a channel, not both.\");\n for (const value of spec.redact ?? []) redactor.protect(value);\n redactor.protectEnvironment(spec.env ?? process.env);\n // fd 3 is the gate; the IPC channel or the byte channel, when there is one, is fd 4.\n const launched = launch(\n {\n kind: spec.kind,\n command: spec.command,\n args: spec.args ?? [],\n cwd: spec.cwd,\n env: spec.env ?? process.env,\n extra: spec.ipc ? \"ipc\" : spec.channel ? \"channel\" : undefined,\n },\n warn,\n );\n const child = launched.process;\n const startedAt = new Date().toISOString();\n await new Promise<void>((resolve, reject) => {\n child.once(\"spawn\", () => resolve());\n child.once(\"error\", reject);\n });\n // The gate's process ID until the child's own is known (the same one on POSIX).\n let pid = child.pid ?? 0;\n // After the spawn, errors (a failed signal or IPC send) are reported, never thrown: an\n // unhandled 'error' event would take the supervisor down.\n child.on(\"error\", (error) => log.warn(\"process.error\", { kind: spec.kind, pid, error }));\n const adopted = new Map<number, number>(); // adopted pid → its pgid\n const stderrTail: string[] = [];\n const exit = new Promise<{ code: number | null; signal: string | null }>((resolve) => {\n child.once(\"exit\", (code, signal) => resolve({ code, signal }));\n });\n // Output can still be in the pipes when the process exits; `exited` waits for it.\n const drained: Promise<unknown>[] = [];\n\n if (child.stdout) {\n const lines = createInterface({ input: child.stdout });\n drained.push(new Promise((resolve) => lines.once(\"close\", resolve)));\n lines.on(\"line\", (line) => {\n if (spec.onStdout) spec.onStdout(redactor.redact(line));\n else log.info(\"process.stdout\", { kind: spec.kind, pid, line });\n });\n }\n if (child.stderr) {\n const lines = createInterface({ input: child.stderr });\n drained.push(new Promise((resolve) => lines.once(\"close\", resolve)));\n lines.on(\"line\", (line) => {\n // The log redacts what it writes; the tail feeds diagnostics, so it is redacted here.\n const redacted = redactor.redact(line);\n stderrTail.push(redacted);\n if (stderrTail.length > STDERR_TAIL) stderrTail.shift();\n if (spec.onStderr) spec.onStderr(redacted);\n else log.info(\"process.stderr\", { kind: spec.kind, pid, line });\n });\n }\n\n let peer: RpcPeer | undefined;\n if (spec.ipc) {\n const ipc = spec.ipc;\n peer = new RpcPeer({\n send: (message) => {\n if (!child.connected) throw new Error(\"The IPC channel is closed.\");\n child.send(message);\n },\n onRequest: async (method, params) => {\n if (method === \"child/adopt\" || method === \"child/release\") {\n const parsed = AdoptParams.safeParse(params);\n if (!parsed.success) throw new Error(`Invalid params for ${method}.`);\n if (method === \"child/release\") {\n adopted.delete(parsed.data.pid);\n ledger.write((db) =>\n db.run(\"DELETE FROM child WHERE pid = ? AND parent_pid = ?\", parsed.data.pid, pid),\n );\n return {};\n }\n // Only a group leader (a program in its own session, such as a PTY program) can be\n // adopted on POSIX: its whole group is then signalled, and no foreign group ever is.\n // On Windows every descendant already ends with the child's job.\n const found = await adoptable(parsed.data.pid);\n if (!found) return { adopted: false };\n if (!found.record) return { adopted: true };\n adopted.set(found.info.pid, found.info.pgid);\n record({\n pid: found.info.pid,\n start_time: found.info.startTime,\n kind: `${spec.kind}/adopted`,\n owner_ref: spec.ownerRef,\n pgid: found.info.pgid,\n started_at: new Date().toISOString(),\n parent_pid: pid,\n });\n return { adopted: true };\n }\n if (!ipc.onRequest) throw new Error(`No handler for ${method}.`);\n return ipc.onRequest(method, params);\n },\n ...(ipc.onNotification ? { onNotification: ipc.onNotification } : {}),\n onInternalError: (error, method) =>\n log.error(\"process.ipc_error\", { kind: spec.kind, pid, method, error }),\n });\n const connected = peer;\n child.on(\"message\", (message) => connected.receive(message));\n child.on(\"disconnect\", () => connected.close());\n }\n\n // Record the child before it may run its command (RT-09, issue #7), then open its gate. If it\n // already exited, nothing is left to reap.\n const registered = (async () => {\n const info = await launched.identify();\n faults.at(\"spawn:before-record\");\n // The same point for one kind of child (`spawn:before-record:demo`), for an instance whose\n // start already spawns children of its own (on Windows the control pipe's helper).\n faults.at(`spawn:before-record:${spec.kind}`);\n // A supervisor stalled here (a test's `hang`) shows the child waiting at its gate, unrecorded.\n if (faults.hangs(`spawn:before-record:${spec.kind}`)) await new Promise(() => {});\n if (!info) return;\n pid = info.pid;\n record({\n pid: info.pid,\n start_time: info.startTime,\n kind: spec.kind,\n owner_ref: spec.ownerRef,\n pgid: info.pid,\n started_at: startedAt,\n parent_pid: null,\n });\n launched.release();\n })();\n\n // From here on, the child's group ends with it, whatever happens to its registration.\n const exited = exit.then(async ({ code, signal }) => {\n // The child's lifetime bounds its group and the groups it adopted.\n await launched.sweep([...adopted.values()]);\n // The group is gone, so nothing holds the pipes open any more; the bound covers a\n // descendant that left the group with them.\n await settleWithin(Promise.all(drained), 2000);\n await registered.catch(() => {});\n running.delete(child.pid ?? 0);\n try {\n forget(pid);\n } catch (error) {\n log.warn(\"process.forget_failed\", { pid, error });\n }\n log.info(\"process.exited\", { kind: spec.kind, pid, code, signal });\n return { code, signal, stderrTail: [...stderrTail] };\n });\n\n const channel = spec.channel ? (child.stdio[4] as Duplex | null) : null;\n channel?.on(\"error\", (error) =>\n log.warn(\"process.channel_error\", { kind: spec.kind, pid, error }),\n );\n const stop = async (graceMs = DEFAULT_GRACE_MS): Promise<ChildExit> => {\n if (launched.running()) await launched.end(graceMs, [...adopted.values()]);\n return exited;\n };\n const handle = {\n get pid() {\n return pid;\n },\n kind: spec.kind,\n ownerRef: spec.ownerRef,\n startedAt,\n ...(channel ? { channel } : {}),\n exited,\n request(method: string, params?: JsonRpcParams, options?: { timeoutMs?: number }) {\n if (!peer) return Promise.reject(new Error(`${spec.kind} was started without IPC.`));\n return peer.request(method, params, options);\n },\n stop,\n } satisfies ChildHandle;\n // Tracked from the spawn on, so stopAll reaches a child whose registration is still running.\n running.set(child.pid ?? 0, { handle, kill: () => launched.kill() });\n\n try {\n await registered;\n } catch (error) {\n // A child that can't be recorded can't be reaped after a crash: don't keep it.\n log.error(\"process.record_failed\", { kind: spec.kind, pid, error });\n await handle.stop(500);\n throw error;\n }\n log.info(\"process.started\", { kind: spec.kind, ownerRef: spec.ownerRef, pid });\n return handle;\n };\n\n /** Spawns in progress, so stopAll waits for them before it stops the children. */\n const inflight = new Set<Promise<unknown>>();\n const trackedSpawn = (spec: SpawnSpec): Promise<ChildHandle> => {\n const spawning = spawnChild(spec);\n const settled = spawning.then(\n () => undefined,\n () => undefined,\n );\n inflight.add(settled);\n void settled.then(() => inflight.delete(settled));\n return spawning;\n };\n\n return {\n spawn: trackedSpawn,\n list: () =>\n [...running.values()].map(({ handle }) => ({\n pid: handle.pid,\n kind: handle.kind,\n ownerRef: handle.ownerRef,\n startedAt: handle.startedAt,\n })),\n async stopAll(graceMs = DEFAULT_GRACE_MS) {\n stopping = true;\n // Spawns already under way finish first, so their children are tracked and stopped too.\n await Promise.all(inflight);\n await Promise.all([...running.values()].map(({ handle }) => handle.stop(graceMs)));\n },\n killAll() {\n for (const { kill } of running.values()) kill();\n },\n };\n}\n","/**\n * The warm set (D91, D95): the pre-built, read-only layout every artifact resolves without an\n * install. `@mostra/warm`'s `dependencies` are the warm packages; its `node_modules` is the layout.\n */\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { Environment } from \"../log.ts\";\nimport { runtimeRoot } from \"../platform/index.ts\";\n\n/** The warm set: where its layout is and what versions it holds. */\nexport interface WarmSet {\n /** The real path of its `node_modules`, the layout builds link to. */\n readonly nodeModules: string;\n /** Package name → installed version, sorted by name; written into every `lock.yaml`. */\n readonly packages: Readonly<Record<string, string>>;\n}\n\nexport { runtimeRoot };\n\nfunction warmMissing(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_WARM_MISSING\", { message }));\n}\n\n/**\n * Finds the warm set: `MOSTRA_WARM_DIR`, else the `warm` directory beside the runtime package, as\n * the runtime bundle and this repository lay it out. Every listed package must be installed.\n */\nexport function locateWarmSet(env: Environment): WarmSet {\n const dir = env[\"MOSTRA_WARM_DIR\"] ?? resolve(runtimeRoot(), \"..\", \"warm\");\n const manifestFile = join(dir, \"package.json\");\n if (!existsSync(manifestFile)) throw warmMissing(`No warm package set at ${dir}.`);\n const { dependencies = {} } = JSON.parse(readFileSync(manifestFile, \"utf8\")) as {\n dependencies?: Record<string, string>;\n };\n const nodeModules = join(dir, \"node_modules\");\n const packages: Record<string, string> = {};\n for (const name of Object.keys(dependencies).sort()) {\n const installed = join(nodeModules, name, \"package.json\");\n if (!existsSync(installed)) throw warmMissing(`The warm package set at ${dir} lacks ${name}.`);\n packages[name] = (JSON.parse(readFileSync(installed, \"utf8\")) as { version: string }).version;\n }\n return { nodeModules: realpathSync(nodeModules), packages };\n}\n","/**\n * The install child (D94, D95, DP-05): pnpm 10 run by the process manager in the artifact's\n * context, never inside the supervisor. Every run is one child, `node pnpm.cjs …`, started in the\n * artifact's source directory with the artifact environment, against the home's store, metadata\n * cache and state, and stopped after 300 s (FAILURE_MODEL §9). Its NDJSON report becomes the\n * outcome: success, or one diagnostic from the DEP area.\n */\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createDiagnostic, type Diagnostic } from \"@mostra/protocol\";\nimport type { Environment, Log } from \"../log.ts\";\nimport { artifactEnvironment, type ProcessManager } from \"../processes/index.ts\";\nimport { runtimeRoot } from \"./warm.ts\";\n\n/** How long one install may take (FAILURE_MODEL §9). */\nexport const INSTALL_TIMEOUT_MS = 300_000;\n\n/** The release age of an unpinned resolution, in minutes (D95): one day. */\nexport const MINIMUM_RELEASE_AGE_MINUTES = 1440;\n\n/** Where the installer keeps its state inside the home (DATA_MODEL §1). */\nexport interface InstallerDirs {\n /** `deps/store`: the shared content-addressed store. */\n readonly store: string;\n /** `deps/cache`: registry metadata, read when offline. */\n readonly cache: string;\n /** `deps/state`: the installer's own state. */\n readonly state: string;\n}\n\n/** One installer run. */\nexport interface InstallRun {\n /** The pnpm command and its own arguments, such as `[\"install\", \"--frozen-lockfile\"]`. */\n readonly command: readonly string[];\n /** The project directory pnpm works on (`--dir`). */\n readonly dir: string;\n /** The artifact's source directory: the child's working directory (DP-05). */\n readonly cwd: string;\n /** Use only what the store and the metadata cache hold. */\n readonly offline: boolean;\n /**\n * Resolution applies the release age (D95), exempting packages named with an exact version.\n * `false` for an install of a lockfile already resolved: its pins are exact and were checked\n * when they were chosen.\n */\n readonly releaseAge: { readonly exempt: readonly string[] } | false;\n /** What the child serves, for `instance/status` and reaping. */\n readonly ownerRef: string;\n}\n\n/** What a run ended with. */\nexport type InstallOutcome =\n | { readonly ok: true }\n | { readonly ok: false; readonly diagnostic: Diagnostic };\n\n/** The installer of one instance. */\nexport interface Installer {\n readonly version: string;\n run(run: InstallRun): Promise<InstallOutcome>;\n /**\n * `pnpm store prune` (gc, D140 item 14): removes what no layout links from the store. `dir` is\n * an empty scratch directory the prune works in, and its registry metadata cache: pnpm's prune\n * empties the metadata cache it is given, and the home's (`deps/cache`) is what offline\n * resolution reads (D95), so it never sees that one. A store command takes no network flag.\n */\n prune(input: { readonly dir: string; readonly ownerRef: string }): Promise<InstallOutcome>;\n}\n\n/** Connection failures: the registry can't be reached at all, so Mostra is offline (D95). */\nconst UNREACHABLE =\n /\\b(?:ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|ENETDOWN|EHOSTDOWN|ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT)\\b/;\n\n/** The package a pnpm error names, from its record or its message. */\nfunction packageNamed(record: Record<string, unknown>, message: string): string | undefined {\n const fromRecord = (record[\"package\"] as { name?: unknown } | undefined)?.name;\n if (typeof fromRecord === \"string\") return fromRecord;\n const fromSpec = (record[\"spec\"] as { name?: unknown } | undefined)?.name;\n if (typeof fromSpec === \"string\") return fromSpec;\n return /(?:for|resolve|GET \\S+?\\/)(@?[^\\s@/:]+(?:\\/[^\\s@/:]+)?)/.exec(message)?.[1];\n}\n\n/** The install child's entry: the compiled one beside the compiled supervisor, else the source. */\nfunction childEntry(): string {\n return fileURLToPath(import.meta.url).endsWith(\".ts\")\n ? join(runtimeRoot(), \"src/deps/child/install.ts\")\n : join(runtimeRoot(), \"dist/deps/child/install.js\");\n}\n\n/** Finds pnpm 10 beside the runtime; anything else is refused (D94). */\nfunction locatePnpm(): { entry: string; version: string } {\n let dir = runtimeRoot();\n for (;;) {\n const candidate = join(dir, \"node_modules\", \"pnpm\");\n if (existsSync(join(candidate, \"package.json\"))) {\n const real = realpathSync(candidate);\n const { version } = JSON.parse(readFileSync(join(real, \"package.json\"), \"utf8\")) as {\n version: string;\n };\n if (!version.startsWith(\"10.\")) {\n throw new Error(`The runtime found pnpm ${version}; its installer must be pnpm 10 (D94).`);\n }\n return { entry: join(real, \"dist\", \"pnpm.cjs\"), version };\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(\"The runtime is missing its installer, pnpm 10.\");\n dir = parent;\n }\n}\n\n/** The project settings of a run: the release age, and the packages named exactly (D95). */\nexport function workspaceSettings(releaseAge: InstallRun[\"releaseAge\"]): string {\n if (releaseAge === false) return \"minimumReleaseAge: 0\\n\";\n const lines = [`minimumReleaseAge: ${MINIMUM_RELEASE_AGE_MINUTES}`];\n if (releaseAge.exempt.length > 0) {\n lines.push(\"minimumReleaseAgeExclude:\");\n for (const name of [...new Set(releaseAge.exempt)].sort()) {\n lines.push(` - ${JSON.stringify(name)}`);\n }\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/** Options for {@link createInstaller}. */\nexport interface InstallerOptions {\n readonly processes: ProcessManager;\n readonly log: Log;\n readonly dirs: InstallerDirs;\n /** The supervisor's environment; the child gets the artifact environment derived from it. */\n readonly env: Environment;\n /** Default {@link INSTALL_TIMEOUT_MS}. */\n readonly timeoutMs?: number;\n}\n\n/** Creates the installer. */\nexport function createInstaller(options: InstallerOptions): Installer {\n const pnpm = locatePnpm();\n const entry = childEntry();\n const timeoutMs = options.timeoutMs ?? INSTALL_TIMEOUT_MS;\n // The artifact environment passes no CI variable, which would switch pnpm to frozen installs on\n // its own; every run says what it wants.\n const env = artifactEnvironment(options.env);\n\n /** The arguments every pnpm run takes; `network` is absent for a store command. */\n const argsFor = (spec: {\n readonly command: readonly string[];\n readonly dir: string;\n readonly cacheDir: string;\n readonly network?: \"--offline\" | \"--prefer-offline\";\n }): string[] => [\n // The install child connects to the supervisor and runs pnpm in its own process group.\n entry,\n pnpm.entry,\n ...spec.command,\n \"--dir\",\n spec.dir,\n `--config.store-dir=${options.dirs.store}`,\n `--config.cache-dir=${spec.cacheDir}`,\n `--config.state-dir=${options.dirs.state}`,\n // Settings a user's .npmrc could change, which these layouts depend on.\n \"--config.lockfile=true\",\n \"--config.modules-dir=node_modules\",\n \"--config.virtual-store-dir=node_modules/.pnpm\",\n \"--config.shamefully-hoist=false\",\n \"--config.enable-global-virtual-store=false\",\n \"--reporter=ndjson\",\n ...(spec.network ? [spec.network] : []),\n \"--config.update-notifier=false\",\n // Every on-demand package's lifecycle scripts run, here in the install child (D95).\n \"--config.dangerously-allow-all-builds=true\",\n \"--config.ignore-scripts=false\",\n \"--config.auto-install-peers=true\",\n \"--config.strict-peer-dependencies=false\",\n \"--config.node-linker=isolated\",\n \"--config.fetch-retries=2\",\n \"--config.fetch-retry-mintimeout=1000\",\n \"--config.fetch-retry-maxtimeout=8000\",\n ];\n\n /** Runs pnpm in an install child, bounded by the install limit. */\n const execute = async (run: {\n readonly args: readonly string[];\n readonly dir: string;\n readonly cwd: string;\n readonly releaseAge: InstallRun[\"releaseAge\"];\n readonly ownerRef: string;\n }): Promise<InstallOutcome> => {\n const args = [...run.args];\n // pnpm 10 reads the release age's exemptions only from the project's pnpm-workspace.yaml, and\n // reads that file only when the project is its own workspace root (VERIFIED_FACTS, WP-04);\n // being the root also stops pnpm's upward search for a workspace above the home.\n await writeFile(join(run.dir, \"pnpm-workspace.yaml\"), workspaceSettings(run.releaseAge));\n const errors: { code: string; message: string; record: Record<string, unknown> }[] = [];\n const scriptLines: string[] = [];\n const child = await options.processes.spawn({\n kind: \"install\",\n ownerRef: run.ownerRef,\n command: process.execPath,\n args,\n cwd: run.cwd,\n env,\n // The IPC channel is the child's lifeline: when the supervisor dies, it ends its group.\n ipc: {},\n onStdout: (line) => {\n let record: Record<string, unknown>;\n try {\n record = JSON.parse(line) as Record<string, unknown>;\n } catch {\n return;\n }\n if (record[\"name\"] === \"pnpm:lifecycle\" && typeof record[\"line\"] === \"string\") {\n scriptLines.push(record[\"line\"]);\n if (scriptLines.length > 20) scriptLines.shift();\n }\n if (record[\"level\"] !== \"error\") return;\n const err = (record[\"err\"] ?? {}) as { code?: unknown; message?: unknown };\n const code = String(record[\"code\"] ?? err.code ?? \"\");\n const message = String(err.message ?? record[\"message\"] ?? \"\");\n errors.push({ code, message, record });\n },\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const outcome = await Promise.race([\n child.exited.then((exit) => ({ kind: \"exit\" as const, exit })),\n new Promise<{ kind: \"timeout\" }>((done) => {\n timer = setTimeout(() => done({ kind: \"timeout\" }), timeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (outcome.kind === \"timeout\") {\n await child.stop(2000);\n return {\n ok: false,\n diagnostic: createDiagnostic(\"MOSTRA_DEP_TIMEOUT\", {\n message: `Installing packages took longer than ${Math.round(timeoutMs / 1000)} s and was stopped.`,\n }),\n };\n }\n if (outcome.exit.code === 0) return { ok: true };\n options.log.warn(\"deps.install_failed\", {\n code: outcome.exit.code,\n signal: outcome.exit.signal,\n errors: errors.map(({ code, message }) => ({ code, message })),\n });\n return { ok: false, diagnostic: diagnose(errors, scriptLines, outcome.exit.stderrTail) };\n };\n\n return {\n version: pnpm.version,\n run: (run) =>\n execute({\n args: argsFor({\n command: run.command,\n dir: run.dir,\n cacheDir: options.dirs.cache,\n network: run.offline ? \"--offline\" : \"--prefer-offline\",\n }),\n dir: run.dir,\n cwd: run.cwd,\n releaseAge: run.releaseAge,\n ownerRef: run.ownerRef,\n }),\n prune: (input) =>\n execute({\n args: argsFor({\n command: [\"store\", \"prune\"],\n dir: input.dir,\n cacheDir: join(input.dir, \"metadata-cache\"),\n }),\n dir: input.dir,\n cwd: input.dir,\n releaseAge: false,\n ownerRef: input.ownerRef,\n }),\n };\n}\n\n/** Turns the installer's errors into one diagnostic. */\nfunction diagnose(\n errors: readonly { code: string; message: string; record: Record<string, unknown> }[],\n scriptLines: readonly string[],\n stderr: readonly string[],\n): Diagnostic {\n const first = errors[0];\n const output = [...scriptLines, ...stderr].slice(-12).join(\"\\n\");\n if (!first) {\n return createDiagnostic(\"MOSTRA_DEP_INSTALL_FAILED\", {\n message: `The package installer failed.${output ? `\\n${output}` : \"\"}`,\n });\n }\n const named = packageNamed(first.record, first.message);\n const subject = named ? `the package ${named}` : \"a package\";\n if (first.code === \"ERR_PNPM_NO_OFFLINE_META\" || first.code === \"ERR_PNPM_NO_OFFLINE_TARBALL\") {\n return createDiagnostic(\"MOSTRA_DEP_OFFLINE\", {\n message: `Mostra is offline and the home's package store doesn't hold ${subject}.`,\n });\n }\n if (UNREACHABLE.test(first.message)) {\n return createDiagnostic(\"MOSTRA_DEP_OFFLINE\", {\n message: `The package registry can't be reached, so ${subject} can't be installed: ${first.message}`,\n });\n }\n if (\n first.code === \"ERR_PNPM_FETCH_404\" ||\n first.code === \"ERR_PNPM_NO_MATCHING_VERSION\" ||\n first.code === \"ERR_PNPM_NO_MATURE_MATCHING_VERSION\"\n ) {\n // pnpm reports a range whose only matches are too new either way (D95's release age).\n const mature =\n first.code === \"ERR_PNPM_FETCH_404\"\n ? \"\"\n : \" Without an exact version, only releases at least a day old match; a release less than a day old installs when named exactly.\";\n return createDiagnostic(\"MOSTRA_DEP_NOT_FOUND\", {\n message: `The registry has no match for ${subject}: ${first.message}.${mature}`,\n });\n }\n return createDiagnostic(\"MOSTRA_DEP_INSTALL_FAILED\", {\n message: `Installing ${subject} failed: ${first.message}${output ? `\\n${output}` : \"\"}`,\n });\n}\n","/**\n * The lockfile (`lock.yaml`, D20, D95): what a version was built with, frozen at publish, and the\n * form of every artifact's working lockfile. WP-03's form lists the warm set; an artifact with\n * on-demand packages adds `packages` (each direct one at its exact version) and `pnpm` (the\n * installer's lockfile, which pins the whole graph). `lockDigest` is the SHA-256 of the text, so\n * any change to either changes `envDigest` and the version (DP-03).\n */\nimport { createHash } from \"node:crypto\";\nimport { parse } from \"yaml\";\n\n/** A lockfile's content. */\nexport interface Lock {\n /** Every warm package and its version. */\n readonly warm: Readonly<Record<string, string>>;\n /** Each direct on-demand package and its exact version; empty without any. */\n readonly packages: Readonly<Record<string, string>>;\n /** The installer's lockfile (pnpm's `pnpm-lock.yaml`), present exactly when `packages` isn't empty. */\n readonly pnpm?: string;\n}\n\nconst HEADER = \"# Mostra lockfile: the packages this version was built with. Frozen at publish.\";\n\nconst sorted = (record: Readonly<Record<string, string>>): [string, string][] =>\n Object.entries(record).sort(([a], [b]) => (a < b ? -1 : 1));\n\n/** The canonical text of `lock`. */\nexport function lockText(lock: Lock): string {\n const lines = [HEADER, \"lockfileVersion: 1\", \"warm:\"];\n for (const [name, version] of sorted(lock.warm)) {\n lines.push(` ${JSON.stringify(name)}: ${JSON.stringify(version)}`);\n }\n const packages = sorted(lock.packages);\n if (packages.length > 0) {\n if (lock.pnpm === undefined)\n throw new Error(\"A lockfile with packages needs its pnpm lockfile.\");\n lines.push(\"packages:\");\n for (const [name, version] of packages) {\n lines.push(` ${JSON.stringify(name)}: ${JSON.stringify(version)}`);\n }\n lines.push(\"pnpm: |\");\n const pnpm = lock.pnpm.replace(/\\s+$/, \"\");\n for (const line of pnpm.split(\"\\n\")) lines.push(line === \"\" ? \"\" : ` ${line}`);\n }\n const text = `${lines.join(\"\\n\")}\\n`;\n // The block scalar must hold the installer's lockfile exactly; anything else is a bug here.\n const back = parseLock(text);\n if (packages.length > 0 && back.pnpm !== `${lock.pnpm?.replace(/\\s+$/, \"\")}\\n`) {\n throw new Error(\"The pnpm lockfile doesn't round-trip through lock.yaml.\");\n }\n return text;\n}\n\n/** Reads a lockfile's text. */\nexport function parseLock(text: string): Lock {\n const data = (parse(text) ?? {}) as {\n warm?: Record<string, string> | null;\n packages?: Record<string, string> | null;\n pnpm?: string;\n };\n return {\n warm: data.warm ?? {},\n packages: data.packages ?? {},\n ...(typeof data.pnpm === \"string\" ? { pnpm: data.pnpm } : {}),\n };\n}\n\n/** The SHA-256 of a lockfile's text, as lowercase hex. */\nexport function lockDigest(text: string): string {\n return createHash(\"sha256\").update(text).digest(\"hex\");\n}\n\n/** Every package, direct or transitive, an installer lockfile pins: `{ name, version }`. */\nexport function pinnedPackages(pnpm: string): { name: string; version: string }[] {\n const data = (parse(pnpm) ?? {}) as { packages?: Record<string, unknown> | null };\n const result: { name: string; version: string }[] = [];\n for (const key of Object.keys(data.packages ?? {})) {\n const at = key.lastIndexOf(\"@\");\n if (at <= 0) continue;\n result.push({ name: key.slice(0, at), version: key.slice(at + 1) });\n }\n return result;\n}\n","/**\n * Package names and specs (D95): what an import specifier names, and what `deps/add` accepts.\n */\nimport { builtinModules } from \"node:module\";\nimport semver from \"semver\";\n\n/** npm's package-name rules, with the capitals that packages published before 2017 may have. */\nconst NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\\/)?[a-zA-Z0-9][a-zA-Z0-9._~-]*$/;\nconst BUILTINS: ReadonlySet<string> = new Set(builtinModules);\n\n/** Packages an artifact imports that are provided outside its lockfile. */\nconst PROVIDED: ReadonlySet<string> = new Set([\n // The worker provides it to server code (WP-08); the server bundle keeps it external.\n \"@mostra/server\",\n]);\n\n/** Whether `name` is a valid npm package name. */\nexport function isPackageName(name: string): boolean {\n return name.length <= 214 && NAME.test(name);\n}\n\n/**\n * The npm package an import specifier names, or `undefined` for a specifier that isn't a package\n * import: relative and absolute paths, the `@/` alias, URLs and other schemes, subpath imports\n * (`#…`), Node built-ins, Vite's virtual modules and packages provided outside the lockfile.\n */\nexport function packageOf(specifier: string): string | undefined {\n const bare = specifier.split(\"?\")[0] ?? specifier;\n if (bare === \"\" || bare.startsWith(\".\") || bare.startsWith(\"/\") || bare.startsWith(\"#\")) {\n return undefined;\n }\n if (bare.startsWith(\"@/\") || bare.startsWith(\"\\0\") || /^[a-z][a-z0-9+.-]*:/i.test(bare)) {\n return undefined;\n }\n const parts = bare.split(\"/\");\n const name = bare.startsWith(\"@\") ? parts.slice(0, 2).join(\"/\") : (parts[0] ?? \"\");\n if (BUILTINS.has(name) || PROVIDED.has(name) || !isPackageName(name)) return undefined;\n return name;\n}\n\n/** A parsed registry spec: `name`, `name@version`, `name@range` or `name@tag`. */\nexport interface PackageSpec {\n readonly name: string;\n /** The version, range or tag after `@`; absent for a bare name. */\n readonly range?: string;\n /** Set when `range` is one exact version, which installs whatever its age (D95). */\n readonly exact?: string;\n}\n\n/** Parses a `deps/add` spec, or returns `undefined` when it isn't a registry spec. */\nexport function parseSpec(spec: string): PackageSpec | undefined {\n const text = spec.trim();\n const at = text.indexOf(\"@\", text.startsWith(\"@\") ? 1 : 0);\n const name = at === -1 ? text : text.slice(0, at);\n const range = at === -1 ? undefined : text.slice(at + 1);\n if (!isPackageName(name)) return undefined;\n if (range === undefined) return { name };\n if (range === \"\") return undefined;\n const exact = semver.valid(range);\n if (exact !== null) return { name, range: exact, exact };\n // A semver range, or a dist-tag (`latest`, `next`, `beta`).\n if (semver.validRange(range) === null && !/^[a-z][a-z0-9._-]*$/i.test(range)) return undefined;\n return { name, range };\n}\n","/**\n * The static import scan (D95): which npm packages an artifact's snapshot imports, found by\n * parsing, never by running anything (RT-02). It reads every script (static, dynamic and\n * `require` imports, `export … from` and `@jsxImportSource` pragmas), the ESM blocks of MDX files, and the `@import`,\n * `@plugin` and `@reference` rules of CSS files. Type-only imports are skipped: the build erases\n * them. What the scan misses (a computed `import()`, say) still meets the build, which refuses a\n * package outside the warm set and the lockfile, and `deps/add` adds it explicitly.\n */\n\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { extname, join } from \"node:path\";\nimport type * as Oxc from \"oxc-parser\";\nimport { packageOf } from \"./specifier.ts\";\n\nlet oxc: typeof Oxc | undefined;\n/** Loads the native parser on first use, so the platform gate answers first (RT-07). */\nfunction parser(): typeof Oxc {\n oxc ??= createRequire(import.meta.url)(\"oxc-parser\") as typeof Oxc;\n return oxc;\n}\n\n/** Where an import is, inside the artifact. */\nexport interface ImportSite {\n readonly file: string;\n readonly line: number;\n readonly column: number;\n}\n\nconst SCRIPT = new Set([\".ts\", \".tsx\", \".mts\", \".cts\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\n\ninterface Node {\n readonly type: string;\n readonly start: number;\n readonly end: number;\n readonly [key: string]: unknown;\n}\n\nfunction langOf(file: string): \"ts\" | \"tsx\" | \"js\" | \"jsx\" {\n const ext = extname(file);\n if (ext === \".tsx\") return \"tsx\";\n if (ext === \".jsx\" || ext === \".mdx\") return \"jsx\";\n if (ext === \".ts\" || ext === \".mts\" || ext === \".cts\") return \"ts\";\n return \"js\";\n}\n\nfunction position(text: string, offset: number): { line: number; column: number } {\n const before = text.slice(0, offset);\n const newline = before.lastIndexOf(\"\\n\");\n return { line: before.split(\"\\n\").length, column: offset - newline };\n}\n\n/** A string literal's value, or `undefined` for anything computed. */\nfunction literal(source: string): string | undefined {\n const quote = source[0];\n if ((quote !== '\"' && quote !== \"'\" && quote !== \"`\") || source.at(-1) !== quote)\n return undefined;\n const body = source.slice(1, -1);\n if (quote === \"`\" && body.includes(\"${\")) return undefined;\n return body;\n}\n\n/** The specifiers a script imports, with their offsets in `text`. */\nfunction scriptImports(file: string, text: string): { specifier: string; offset: number }[] {\n const parsed = parser().parseSync(file, text, { lang: langOf(file), sourceType: \"module\" });\n if (parsed.errors.length > 0 && !parsed.program) return [];\n const found: { specifier: string; offset: number }[] = [];\n const { module } = parsed;\n for (const entry of module.staticImports) {\n if (entry.entries.length > 0 && entry.entries.every((item) => item.isType)) continue;\n found.push({ specifier: entry.moduleRequest.value, offset: entry.moduleRequest.start });\n }\n for (const entry of module.staticExports) {\n for (const item of entry.entries) {\n if (!item.moduleRequest || (item as { isType?: boolean }).isType) continue;\n found.push({ specifier: item.moduleRequest.value, offset: item.moduleRequest.start });\n }\n }\n for (const entry of module.dynamicImports) {\n const value = literal(text.slice(entry.moduleRequest.start, entry.moduleRequest.end));\n if (value !== undefined) found.push({ specifier: value, offset: entry.moduleRequest.start });\n }\n // A JSX pragma makes the compiled file import `<package>/jsx-runtime`.\n for (const comment of parsed.comments) {\n const pragma = /@jsxImportSource\\s+(\\S+)/.exec(comment.value);\n if (pragma?.[1]) found.push({ specifier: pragma[1], offset: comment.start });\n }\n // `require(\"x\")` in CommonJS files and in code that keeps it.\n if (text.includes(\"require\")) {\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const child of node) visit(child);\n return;\n }\n if (node === null || typeof node !== \"object\") return;\n const current = node as Node;\n if (current.type === \"CallExpression\") {\n const callee = current[\"callee\"] as Node | undefined;\n const [first] = (current[\"arguments\"] as Node[] | undefined) ?? [];\n if (\n callee?.type === \"Identifier\" &&\n (callee as unknown as { name: string }).name === \"require\" &&\n first?.type === \"Literal\" &&\n typeof (first as unknown as { value: unknown }).value === \"string\"\n ) {\n found.push({\n specifier: (first as unknown as { value: string }).value,\n offset: first.start,\n });\n }\n }\n for (const [key, value] of Object.entries(current)) {\n if (key !== \"type\" && key !== \"start\" && key !== \"end\" && typeof value === \"object\") {\n visit(value);\n }\n }\n };\n visit(parsed.program);\n }\n return found;\n}\n\n/**\n * The ESM blocks of an MDX file (MDX 3): paragraphs outside code fences and frontmatter whose\n * first line starts with `import` or `export`, each running to the next blank line.\n */\nfunction mdxImports(file: string, text: string): { specifier: string; offset: number }[] {\n const lines = text.split(\"\\n\");\n const offsets: number[] = [];\n let at = 0;\n for (const line of lines) {\n offsets.push(at);\n at += line.length + 1;\n }\n const found: { specifier: string; offset: number }[] = [];\n let index = 0;\n if (lines[0]?.trim() === \"---\") {\n index = lines.findIndex((line, i) => i > 0 && line.trim() === \"---\") + 1;\n if (index === 0) return found;\n }\n let fence: string | undefined;\n while (index < lines.length) {\n const line = lines[index] ?? \"\";\n const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];\n if (fence !== undefined) {\n if (marker !== undefined && marker[0] === fence[0] && marker.length >= fence.length) {\n fence = undefined;\n }\n index++;\n continue;\n }\n if (marker !== undefined) {\n fence = marker;\n index++;\n continue;\n }\n if (/^(import|export)\\b/.test(line)) {\n let end = index;\n while (end + 1 < lines.length && (lines[end + 1] ?? \"\").trim() !== \"\") end++;\n const start = offsets[index] ?? 0;\n const block = lines.slice(index, end + 1).join(\"\\n\");\n try {\n for (const entry of scriptImports(`${file}.jsx`, block)) {\n found.push({ specifier: entry.specifier, offset: start + entry.offset });\n }\n } catch {\n // Not ESM after all: the MDX compiler reports it.\n }\n index = end + 1;\n continue;\n }\n index++;\n }\n return found;\n}\n\n/**\n * `text` with every CSS comment blanked to spaces (newlines kept), so offsets still point into the\n * original. Strings are copied as they are: a `/*` inside one doesn't start a comment.\n */\nfunction withoutCssComments(text: string): string {\n let out = \"\";\n let index = 0;\n while (index < text.length) {\n const char = text[index] as string;\n if (char === '\"' || char === \"'\") {\n let end = index + 1;\n while (end < text.length && text[end] !== char && text[end] !== \"\\n\") {\n end += text[end] === \"\\\\\" ? 2 : 1;\n }\n out += text.slice(index, end + 1);\n index = end + 1;\n } else if (char === \"/\" && text[index + 1] === \"*\") {\n const close = text.indexOf(\"*/\", index + 2);\n const end = close === -1 ? text.length : close + 2;\n out += text.slice(index, end).replace(/[^\\n]/g, \" \");\n index = end;\n } else {\n out += char;\n index++;\n }\n }\n return out;\n}\n\n/** The packages a CSS file loads: `@import`, Tailwind's `@plugin` and `@reference`. */\nfunction cssImports(source: string): { specifier: string; offset: number }[] {\n const text = withoutCssComments(source);\n const found: { specifier: string; offset: number }[] = [];\n const rule = /@(?:import|plugin|reference)\\s+(?:url\\(\\s*)?([\"'])([^\"'\\n]+)\\1/g;\n for (const match of text.matchAll(rule)) {\n found.push({\n specifier: match[2] ?? \"\",\n offset: (match.index ?? 0) + match[0].indexOf(match[1] ?? \"\"),\n });\n }\n return found;\n}\n\nasync function listFiles(dir: string, prefix: string, out: string[]): Promise<void> {\n for (const entry of await readdir(dir, { withFileTypes: true })) {\n const path = prefix ? `${prefix}/${entry.name}` : entry.name;\n // `public/` is served as-is and never bundled (INTERFACES §2.1).\n if (entry.isDirectory()) {\n if (path !== \"public\") await listFiles(join(dir, entry.name), path, out);\n } else if (entry.isFile()) out.push(path);\n }\n}\n\n/**\n * The npm packages the artifact in `sourceDir` imports, each with its first import site, sorted by\n * name. Warm packages are included; the caller tells them apart.\n */\nexport async function scanImports(sourceDir: string): Promise<Map<string, ImportSite>> {\n const files: string[] = [];\n await listFiles(sourceDir, \"\", files);\n files.sort();\n const found = new Map<string, ImportSite>();\n for (const file of files) {\n const ext = extname(file);\n // Declaration files hold types only; the build never loads them.\n if (/\\.d\\.[cm]?ts$/.test(file)) continue;\n const kind = SCRIPT.has(ext) ? \"script\" : ext === \".mdx\" ? \"mdx\" : ext === \".css\" ? \"css\" : \"\";\n if (kind === \"\") continue;\n const text = await readFile(join(sourceDir, file), \"utf8\");\n let imports: { specifier: string; offset: number }[];\n try {\n imports =\n kind === \"script\"\n ? scriptImports(file, text)\n : kind === \"mdx\"\n ? mdxImports(file, text)\n : cssImports(text);\n } catch {\n // A file that doesn't parse is the build's to report.\n continue;\n }\n for (const { specifier, offset } of imports) {\n const name = packageOf(specifier);\n if (name !== undefined && !found.has(name)) {\n found.set(name, { file, ...position(text, offset) });\n }\n }\n }\n return new Map([...found].sort(([a], [b]) => (a < b ? -1 : 1)));\n}\n","/**\n * Dependencies (D20, D43, D94, D95; DP-01 to DP-05): which packages an artifact's build resolves.\n *\n * - The **warm set** is a pre-built, read-only layout. An artifact that imports only warm packages\n * builds against it with no install.\n * - **On-demand packages** install through pnpm 10 into the home's shared, content-addressed store\n * (`deps/store`) and are linked into one layout per lockfile (`deps/locks/<lockDigest>`), whose\n * `package.json` links every warm package through one `warm` symlink. pnpm resolves each peer\n * dependency to the warm copy, so React exists once.\n * - Each artifact has a **working lockfile** in the ledger, keyed by its artifact ID (or source\n * path before its first publish). Every pin is exact, and the lockfile seeds each resolution, so\n * a republish is reproducible and works offline; publish freezes it into the version.\n * - Installs run in an **install child** in the artifact's source directory with the artifact\n * environment; lifecycle scripts run there, never in the supervisor.\n *\n * ```ts\n * const deps = createDependencies({ home, ledger, processes, log, env, warm });\n * const resolved = await deps.resolve({ key, sourceDir, artifactDir, artifactPath });\n * // resolved.lock → versions/<id>/lock.yaml; resolved.lockDigest → envDigest; resolved.nodeModules → the build\n * ```\n */\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { lstat, mkdir, readdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { networkInterfaces } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n type AddedPackage,\n createDiagnostic,\n type DependencyPolicy,\n type DepsAddResult,\n type Diagnostic,\n RpcError,\n} from \"@mostra/protocol\";\nimport semver from \"semver\";\nimport { type Faults, noFaults } from \"../faults.ts\";\nimport type { Gate } from \"../gate.ts\";\nimport {\n type Ledger,\n type LedgerDb,\n type RequestKey,\n recordedResult,\n recordResult,\n} from \"../ledger/index.ts\";\nimport type { Environment, Log } from \"../log.ts\";\nimport {\n linkDirectory,\n linkTarget,\n replaceDirectoryLink,\n samePath,\n WINDOWS,\n} from \"../platform/index.ts\";\nimport type { ProcessManager } from \"../processes/index.ts\";\nimport { createInstaller, INSTALL_TIMEOUT_MS, type Installer } from \"./installer.ts\";\nimport { type Lock, lockDigest, lockText, parseLock, pinnedPackages } from \"./lock.ts\";\nimport { scanImports } from \"./scan.ts\";\nimport { type PackageSpec, parseSpec } from \"./specifier.ts\";\nimport type { WarmSet } from \"./warm.ts\";\n\nexport { lockDigest, lockText, parseLock } from \"./lock.ts\";\nexport { scanImports } from \"./scan.ts\";\nexport { packageOf, parseSpec } from \"./specifier.ts\";\nexport { locateWarmSet, runtimeRoot, type WarmSet } from \"./warm.ts\";\n\n/** The marker a complete lock layout carries; a layout without it is rebuilt. */\nconst LAYOUT_MARKER = \".mostra-layout\";\n\n/** Options for {@link createDependencies}. */\nexport interface DependenciesOptions {\n /** The instance's gate: layout installs hold it shared, so gc never runs beside one (D140). */\n readonly gate?: Gate;\n /** The home's real path; `deps/` lives in it. */\n readonly home: string;\n readonly ledger: Ledger;\n readonly processes: ProcessManager;\n readonly log: Log;\n /** The supervisor's environment: `MOSTRA_OFFLINE`, and the source of the artifact environment. */\n readonly env: Environment;\n readonly warm: WarmSet;\n /** The home's dependency policy, read when it is needed. */\n readonly policy: () => DependencyPolicy;\n /** Default 300 s (FAILURE_MODEL §9). */\n readonly installTimeoutMs?: number;\n /** Test fault points `deps:*`. */\n readonly faults?: Faults;\n}\n\n/** What a build resolves its packages from. */\nexport interface ResolvedDependencies {\n /** The lockfile's text, written into the version as `lock.yaml`. */\n readonly lock: string;\n /** Its SHA-256, part of `envDigest` (DP-03). */\n readonly lockDigest: string;\n /** The `node_modules` the build links: the warm layout, or the lock's layout. */\n readonly nodeModules: string;\n}\n\n/** A resolution, and the step that makes it the artifact's working lockfile. */\nexport interface Resolution extends ResolvedDependencies {\n /**\n * Inside the transaction that commits the publish: records the lockfile as the working\n * lockfile of `artifactId`, moving a path-keyed one to it. Nothing is recorded when the publish\n * fails, and a working lockfile changed since the resolution read it (by `deps/add`) is kept.\n */\n save(db: LedgerDb, artifactId: string): void;\n}\n\n/** One artifact, as dependencies see it. */\nexport interface DependencyTarget {\n /** The working lockfile's key: {@link lockKey}. */\n readonly key: string;\n /** The artifact's source directory: the install child's working directory (DP-05). */\n readonly artifactDir: string;\n /** The artifact's source path as callers name it, for the `mostra add` command in diagnostics. */\n readonly artifactPath: string;\n}\n\n/** What gc collects of the dependency state (D140 item 14). */\nexport interface DependencyCollection {\n /** The lock layouts, and the bytes only they hold (files the store doesn't share). */\n readonly lockLayouts: {\n readonly count: number;\n readonly bytes: number;\n readonly names: readonly string[];\n };\n /**\n * The store packages no kept lockfile needs. `bytes` is what the store shrank by in a real run\n * (its files are shared between packages, so a dry run can't attribute them) and 0 in a dry run.\n */\n readonly storePackages: {\n readonly count: number;\n readonly bytes: number;\n readonly packages: readonly string[];\n /** Why the store couldn't be pruned; its packages then stay, still indexed. */\n readonly failed?: Diagnostic;\n };\n}\n\n/** The dependencies of one instance. */\nexport interface Dependencies {\n readonly warm: WarmSet;\n /**\n * Resolves the packages the snapshot in `sourceDir` imports into a lockfile and a layout to\n * build with, installing what's missing (or, under the `explicit` policy, refusing it with\n * `MOSTRA_DEP_MISSING`). The caller records it with {@link Resolution.save}.\n */\n resolve(target: DependencyTarget & { readonly sourceDir: string }): Promise<Resolution>;\n /**\n * The `node_modules` a version's server code resolves its packages from at run time (D135):\n * the warm set when the version has no on-demand packages, else the layout of its frozen\n * lockfile, installed again from the store if it was removed. When the warm set moved since the\n * version was built (a runtime with other warm versions), a pinned layout installs the warm\n * packages the version locked at their exact versions, so its server code runs against what it\n * was built with.\n *\n * @throws RpcError `MOSTRA_DEP_OFFLINE`, `MOSTRA_DEP_INSTALL_FAILED` … when a layout can't be made.\n */\n runtimeModules(target: {\n readonly artifactId: string;\n /** The version's directory, holding its `lock.yaml`. */\n readonly versionDir: string;\n /** The artifact's source directory, when it still exists: lifecycle scripts run there. */\n readonly sourceDir?: string;\n }): Promise<string>;\n /**\n * gc's part (D95, D135, D140 item 14): the lock layouts in `deps/locks` that no working\n * lockfile and no lock text in `keep` names (a `pinned-*` layout counts as named by the\n * `lockDigest` its marker records), and the store packages only they need. A dry run lists them;\n * a real run removes the layouts, drops the packages from the store index and runs\n * `pnpm store prune` in the install child. The caller holds the instance's gate alone, so no\n * install runs meanwhile.\n */\n collect(input: {\n /** The `lock.yaml` texts of every version gc keeps. */\n readonly keep: readonly string[];\n readonly dryRun: boolean;\n }): Promise<DependencyCollection>;\n /** `deps/add`: adds packages to the artifact's working lockfile and installs them. */\n add(\n target: DependencyTarget & {\n readonly packages: readonly string[];\n readonly request?: RequestKey | undefined;\n },\n ): Promise<DepsAddResult>;\n}\n\n/**\n * At start-up, before any request: removes resolutions and lock layouts a crash left unfinished\n * (a layout is complete only once it carries its marker).\n */\nexport async function recoverDependencies(options: {\n readonly home: string;\n readonly log: Log;\n}): Promise<void> {\n const root = join(options.home, \"deps\");\n await rm(join(root, \"tmp\"), { recursive: true, force: true });\n let entries: string[];\n try {\n entries = await readdir(join(root, \"locks\"));\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!existsSync(join(root, \"locks\", entry, LAYOUT_MARKER))) {\n options.log.info(\"deps.layout_removed\", { lockDigest: entry, reason: \"incomplete\" });\n await rm(join(root, \"locks\", entry), { recursive: true, force: true });\n }\n }\n}\n\n/** The working lockfile's key: the artifact ID when there is one, else its source path. */\nexport function lockKey(artifactId: string | undefined, bindingPath: string): string {\n return artifactId ?? `path:${bindingPath}`;\n}\n\n/**\n * Whether Mostra is offline (D95): `MOSTRA_OFFLINE` is set, or no network interface has a\n * routable address (link-local addresses don't reach a registry).\n */\nexport function isOffline(env: Environment): boolean {\n const flag = env[\"MOSTRA_OFFLINE\"];\n if (flag !== undefined && flag !== \"\" && !/^(?:0|false|no)$/i.test(flag)) return true;\n return !Object.values(networkInterfaces()).some((addresses) =>\n (addresses ?? []).some(\n (address) =>\n !address.internal &&\n !address.address.startsWith(\"169.254.\") &&\n !/^fe[89ab]/i.test(address.address),\n ),\n );\n}\n\n/**\n * A shell-safe rendering of `value`, for the commands in diagnostics: POSIX shell quoting, or on\n * Windows the double quotes PowerShell and `cmd` both read (a Windows path holds no `\"`), and a\n * plain path with backslashes as it is.\n */\nfunction shellQuote(value: string): string {\n if (WINDOWS) return /^[\\w@%+=:,./\\\\-]+$/.test(value) ? value : `\"${value}\"`;\n return /^[\\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/** Serializes work per key; one supervisor, so in-process order is the order. */\nclass KeyedQueue {\n readonly #tails = new Map<string, Promise<unknown>>();\n run<T>(key: string, task: () => Promise<T>): Promise<T> {\n const next = (this.#tails.get(key) ?? Promise.resolve()).then(task, task);\n const tail = next.then(\n () => undefined,\n () => undefined,\n );\n this.#tails.set(key, tail);\n void tail.then(() => {\n if (this.#tails.get(key) === tail) this.#tails.delete(key);\n });\n return next;\n }\n}\n\ninterface WorkingLock {\n readonly lock: Lock;\n /** Packages added through `deps/add`, kept whether or not the source imports them. */\n readonly added: readonly string[];\n}\n\nconst fail = (code: Parameters<typeof createDiagnostic>[0], message: string): RpcError =>\n new RpcError(createDiagnostic(code, { message }));\n\n/** Creates the dependencies of one instance. */\nexport function createDependencies(options: DependenciesOptions): Dependencies {\n const { ledger, log, warm } = options;\n const faults = options.faults ?? noFaults;\n const root = join(options.home, \"deps\");\n const dirs = {\n store: join(root, \"store\"),\n cache: join(root, \"cache\"),\n state: join(root, \"state\"),\n locks: join(root, \"locks\"),\n tmp: join(root, \"tmp\"),\n };\n let installer: Installer | undefined;\n const install = (): Installer =>\n (installer ??= createInstaller({\n processes: options.processes,\n log,\n dirs,\n env: options.env,\n timeoutMs: options.installTimeoutMs ?? INSTALL_TIMEOUT_MS,\n }));\n const byArtifact = new KeyedQueue();\n const byLayout = new KeyedQueue();\n const offline = (): boolean => isOffline(options.env);\n\n // Every warm package as a link through the layout's `warm` symlink (D95).\n const warmLinks = Object.fromEntries(\n Object.keys(warm.packages).map((name) => [name, `link:warm/${name}`]),\n );\n const manifestOf = (packages: Readonly<Record<string, string>>): string =>\n `${JSON.stringify(\n {\n name: \"mostra-artifact-dependencies\",\n private: true,\n dependencies: Object.fromEntries(\n Object.entries({ ...warmLinks, ...packages }).sort(([a], [b]) => (a < b ? -1 : 1)),\n ),\n },\n null,\n 2,\n )}\\n`;\n\n const readWorking = (key: string): WorkingLock | undefined => {\n const row = ledger.read((db) =>\n db.get<{ lock_text: string; added_json: string }>(\n \"SELECT lock_text, added_json FROM dependency_lock WHERE key = ?\",\n key,\n ),\n );\n return row\n ? { lock: parseLock(row.lock_text), added: JSON.parse(row.added_json) as string[] }\n : undefined;\n };\n const writeWorking = (key: string, text: string, added: readonly string[]): void => {\n ledger.write((db) =>\n db.run(\n \"INSERT INTO dependency_lock (key, lock_text, added_json, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET lock_text = excluded.lock_text, added_json = excluded.added_json, updated_at = excluded.updated_at\",\n key,\n text,\n JSON.stringify([...new Set(added)].sort()),\n new Date().toISOString(),\n ),\n );\n };\n /** A working lockfile's stored text, or `null` without one. */\n const rowText = (key: string): string | null =>\n ledger.read(\n (db) =>\n db.get<{ lock_text: string }>(\"SELECT lock_text FROM dependency_lock WHERE key = ?\", key)\n ?.lock_text ?? null,\n );\n /** Versions of `name` the home's store holds, from the store index. */\n const stored = (name: string): string[] =>\n ledger\n .read((db) =>\n db.all<{ version: string }>(\"SELECT version FROM dependency_package WHERE name = ?\", name),\n )\n .map((row) => row.version);\n\n const sameRecord = (a: Readonly<Record<string, string>>, b: Readonly<Record<string, string>>) =>\n JSON.stringify(Object.entries(a).sort()) === JSON.stringify(Object.entries(b).sort());\n\n /**\n * Resolves a new lockfile in a scratch project: the pins stay exactly as they are, `additions`\n * resolve through `pnpm add --save-exact`, and the previous installer lockfile seeds the graph.\n * Packages without a pin or an addition leave the lockfile.\n */\n const resolveLock = async (input: {\n readonly key: string;\n readonly artifactDir: string;\n readonly pins: Readonly<Record<string, string>>;\n readonly additions: readonly PackageSpec[];\n readonly previous: string | undefined;\n }): Promise<Lock> => {\n const isOff = offline();\n const additions = input.additions;\n if (isOff) {\n // Offline, only the store can answer (DP-04). When no version it holds can match, say so at\n // once; otherwise pnpm resolves the spec as given from its metadata cache, so tags and the\n // release age still mean what they mean online.\n for (const spec of additions) {\n const versions = stored(spec.name);\n const range = spec.range !== undefined && semver.validRange(spec.range) ? spec.range : \"*\";\n if (semver.maxSatisfying(versions, range) === null) {\n throw fail(\n \"MOSTRA_DEP_OFFLINE\",\n `Mostra is offline and the home's package store doesn't hold ${spec.name}${spec.range ? `@${spec.range}` : \"\"}.`,\n );\n }\n }\n }\n await mkdir(dirs.tmp, { recursive: true });\n const work = join(dirs.tmp, `resolve-${randomBytes(6).toString(\"hex\")}`);\n await mkdir(work);\n try {\n await linkDirectory(warm.nodeModules, join(work, \"warm\"));\n await writeFile(join(work, \"package.json\"), manifestOf(input.pins));\n if (input.previous !== undefined)\n await writeFile(join(work, \"pnpm-lock.yaml\"), input.previous);\n const outcome = await install().run({\n command:\n additions.length > 0\n ? [\n \"add\",\n ...additions.map((spec) => (spec.range ? `${spec.name}@${spec.range}` : spec.name)),\n \"--save-exact\",\n \"--lockfile-only\",\n ]\n : [\"install\", \"--lockfile-only\", \"--no-frozen-lockfile\"],\n dir: work,\n cwd: input.artifactDir,\n offline: isOff,\n releaseAge: {\n exempt: additions.filter((spec) => spec.exact !== undefined).map((spec) => spec.name),\n },\n ownerRef: input.key,\n });\n if (!outcome.ok) throw new RpcError(outcome.diagnostic);\n const manifest = JSON.parse(await readFile(join(work, \"package.json\"), \"utf8\")) as {\n dependencies?: Record<string, string>;\n };\n const packages = Object.fromEntries(\n Object.entries(manifest.dependencies ?? {}).filter(([name]) => !(name in warm.packages)),\n );\n if (Object.keys(packages).length === 0) return { warm: warm.packages, packages: {} };\n return {\n warm: warm.packages,\n packages,\n pnpm: await readFile(join(work, \"pnpm-lock.yaml\"), \"utf8\"),\n };\n } finally {\n await rm(work, { recursive: true, force: true });\n }\n };\n\n /** Points a layout's `warm` symlink at the current warm set (the runtime may have moved). */\n const relinkWarm = async (dir: string): Promise<void> => {\n const link = join(dir, \"warm\");\n const target = await linkTarget(link);\n if (target !== undefined && samePath(target, warm.nodeModules)) return;\n await replaceDirectoryLink(warm.nodeModules, link);\n };\n\n /**\n * The layout of `lock`, installed from the store (and the registry for what the store lacks)\n * into `deps/locks/<lockDigest>` unless it is already complete.\n */\n const ensureLayout = (\n lock: Lock,\n digest: string,\n target: { readonly key: string; readonly artifactDir: string },\n ): Promise<string> =>\n byLayout.run(digest, async () => {\n const dir = join(dirs.locks, digest);\n const nodeModules = join(dir, \"node_modules\");\n if (existsSync(join(dir, LAYOUT_MARKER))) {\n await relinkWarm(dir);\n return nodeModules;\n }\n const pnpm = lock.pnpm as string;\n const isOff = offline();\n if (isOff) {\n const missing = pinnedPackages(pnpm).find(\n ({ name, version }) => !stored(name).includes(version),\n );\n if (missing) {\n throw fail(\n \"MOSTRA_DEP_OFFLINE\",\n `Mostra is offline and the home's package store doesn't hold ${missing.name}@${missing.version}.`,\n );\n }\n }\n await rm(dir, { recursive: true, force: true });\n await mkdir(dir, { recursive: true });\n try {\n await linkDirectory(warm.nodeModules, join(dir, \"warm\"));\n await writeFile(join(dir, \"package.json\"), manifestOf(lock.packages));\n await writeFile(join(dir, \"pnpm-lock.yaml\"), pnpm);\n const outcome = await install().run({\n command: [\"install\", \"--frozen-lockfile\"],\n dir,\n cwd: target.artifactDir,\n offline: isOff,\n releaseAge: false,\n ownerRef: target.key,\n });\n if (!outcome.ok) throw new RpcError(outcome.diagnostic);\n // The store index first, then the marker: a crash between them leaves an incomplete\n // layout (removed at the next start) over packages the store does hold, never a complete\n // layout whose packages the index doesn't know (D80 review finding 5).\n const now = new Date().toISOString();\n ledger.write((db) => {\n for (const { name, version } of pinnedPackages(pnpm)) {\n db.run(\n \"INSERT OR IGNORE INTO dependency_package (name, version, stored_at) VALUES (?, ?, ?)\",\n name,\n version,\n now,\n );\n }\n });\n faults.at(\"deps:before-marker\");\n await writeFile(\n join(dir, LAYOUT_MARKER),\n `${JSON.stringify({ lockDigest: digest, installer: install().version })}\\n`,\n );\n } catch (error) {\n await rm(dir, { recursive: true, force: true });\n throw error;\n }\n log.info(\"deps.layout_installed\", {\n lockDigest: digest,\n packages: Object.keys(lock.packages),\n });\n return nodeModules;\n });\n\n /**\n * A layout for a version whose locked warm packages the current warm set no longer holds at\n * those versions: each such package installs at its locked version, the others link to the warm\n * set as usual, and the version's installer lockfile seeds the rest of the graph.\n */\n const ensurePinnedLayout = (\n lock: Lock,\n digest: string,\n drifted: readonly string[],\n target: { readonly key: string; readonly artifactDir: string },\n ): Promise<string> => {\n const name = `pinned-${lockDigest(`${digest}\\n${JSON.stringify(warm.packages)}`)}`;\n return byLayout.run(name, async () => {\n const dir = join(dirs.locks, name);\n const nodeModules = join(dir, \"node_modules\");\n if (existsSync(join(dir, LAYOUT_MARKER))) {\n await relinkWarm(dir);\n return nodeModules;\n }\n const pinnedWarm = Object.fromEntries(\n Object.keys(lock.warm).map((pkg) => [\n pkg,\n drifted.includes(pkg) ? (lock.warm[pkg] as string) : `link:warm/${pkg}`,\n ]),\n );\n const isOff = offline();\n if (isOff) {\n const missing = drifted.find((pkg) => !stored(pkg).includes(lock.warm[pkg] as string));\n if (missing) {\n throw fail(\n \"MOSTRA_DEP_OFFLINE\",\n `Mostra is offline, and this version's server code needs ${missing}@${lock.warm[missing]}, which the warm set no longer holds and the home's package store doesn't.`,\n );\n }\n }\n await rm(dir, { recursive: true, force: true });\n await mkdir(dir, { recursive: true });\n try {\n await linkDirectory(warm.nodeModules, join(dir, \"warm\"));\n await writeFile(\n join(dir, \"package.json\"),\n `${JSON.stringify(\n {\n name: \"mostra-artifact-dependencies\",\n private: true,\n dependencies: Object.fromEntries(\n Object.entries({ ...pinnedWarm, ...lock.packages }).sort(([a], [b]) =>\n a < b ? -1 : 1,\n ),\n ),\n },\n null,\n 2,\n )}\\n`,\n );\n if (lock.pnpm !== undefined) await writeFile(join(dir, \"pnpm-lock.yaml\"), lock.pnpm);\n const outcome = await install().run({\n command: [\"install\", \"--no-frozen-lockfile\"],\n dir,\n cwd: target.artifactDir,\n offline: isOff,\n // Every version here was accepted when the version was published.\n releaseAge: false,\n ownerRef: target.key,\n });\n if (!outcome.ok) throw new RpcError(outcome.diagnostic);\n const now = new Date().toISOString();\n const pinned = await readFile(join(dir, \"pnpm-lock.yaml\"), \"utf8\").catch(() => \"\");\n ledger.write((db) => {\n for (const { name: pkg, version } of pinnedPackages(pinned)) {\n db.run(\n \"INSERT OR IGNORE INTO dependency_package (name, version, stored_at) VALUES (?, ?, ?)\",\n pkg,\n version,\n now,\n );\n }\n });\n await writeFile(\n join(dir, LAYOUT_MARKER),\n `${JSON.stringify({ lockDigest: digest, pinned: drifted, installer: install().version })}\\n`,\n );\n } catch (error) {\n await rm(dir, { recursive: true, force: true });\n throw error;\n }\n log.info(\"deps.pinned_layout_installed\", { lockDigest: digest, pinned: drifted });\n return nodeModules;\n });\n };\n\n /** Settles a lockfile: its text, digest and layout. */\n const settle = async (\n lock: Lock,\n target: { readonly key: string; readonly artifactDir: string },\n ): Promise<ResolvedDependencies> => {\n const text = lockText(lock);\n const digest = lockDigest(text);\n const nodeModules =\n Object.keys(lock.packages).length === 0\n ? warm.nodeModules\n : await ensureLayout(lock, digest, target);\n return { lock: text, lockDigest: digest, nodeModules };\n };\n\n const runtimeModules = async (target: {\n readonly artifactId: string;\n readonly versionDir: string;\n readonly sourceDir?: string;\n }): Promise<string> => {\n const text = await readFile(join(target.versionDir, \"lock.yaml\"), \"utf8\");\n const lock = parseLock(text);\n const digest = lockDigest(text);\n const where = { key: target.artifactId, artifactDir: target.sourceDir ?? target.versionDir };\n // Mostra's own packages always come from this runtime: they aren't on a registry to pin.\n const drifted = Object.keys(lock.warm)\n .filter((pkg) => !pkg.startsWith(\"@mostra/\"))\n .filter((pkg) => warm.packages[pkg] !== lock.warm[pkg]);\n if (drifted.length > 0) return ensurePinnedLayout(lock, digest, drifted, where);\n if (Object.keys(lock.packages).length === 0) return warm.nodeModules;\n return ensureLayout(lock, digest, where);\n };\n\n /** gc's part (D140 item 14); see {@link Dependencies.collect}. */\n const collect = async (input: {\n readonly keep: readonly string[];\n readonly dryRun: boolean;\n }): Promise<DependencyCollection> => {\n const working = ledger.read((db) =>\n db\n .all<{ lock_text: string }>(\"SELECT lock_text FROM dependency_lock\")\n .map((row) => row.lock_text),\n );\n const texts = [...working, ...input.keep];\n const named = new Set(texts.map((text) => lockDigest(text)));\n const needed = new Set<string>();\n const need = (pnpm: string | undefined): void => {\n if (pnpm === undefined) return;\n for (const { name, version } of pinnedPackages(pnpm)) needed.add(`${name}@${version}`);\n };\n for (const text of texts) {\n try {\n need(parseLock(text).pnpm);\n } catch {\n // A lockfile Mostra can't read names no package it could keep.\n }\n }\n const entries = await readdir(dirs.locks).catch(() => [] as string[]);\n const layouts: string[] = [];\n let layoutBytes = 0;\n for (const name of entries.sort()) {\n const dir = join(dirs.locks, name);\n let digest = name;\n try {\n const marker = JSON.parse(await readFile(join(dir, LAYOUT_MARKER), \"utf8\")) as {\n lockDigest?: unknown;\n };\n if (typeof marker.lockDigest === \"string\") digest = marker.lockDigest;\n } catch {\n // Unfinished: recovery at start removes it, never gc.\n continue;\n }\n if (named.has(digest)) {\n // A kept pinned layout needs its own installer lockfile's packages too.\n need(await readFile(join(dir, \"pnpm-lock.yaml\"), \"utf8\").catch(() => undefined));\n continue;\n }\n layouts.push(name);\n layoutBytes += await unsharedBytes(dir);\n }\n const unneeded = ledger\n .read((db) =>\n db.all<{ name: string; version: string }>(\"SELECT name, version FROM dependency_package\"),\n )\n .map((row) => `${row.name}@${row.version}`)\n .filter((id) => !needed.has(id))\n .sort();\n let storeBytes = 0;\n let failed: Diagnostic | undefined;\n let pruned = unneeded;\n if (!input.dryRun) {\n for (const name of layouts) {\n await rm(join(dirs.locks, name), { recursive: true, force: true });\n log.info(\"deps.layout_collected\", { layout: name });\n }\n if (existsSync(dirs.store) && (layouts.length > 0 || unneeded.length > 0)) {\n const before = await apparentBytes(dirs.store);\n const scratch = join(dirs.tmp, `prune-${randomBytes(6).toString(\"hex\")}`);\n await mkdir(scratch, { recursive: true });\n try {\n const outcome = await install().prune({ dir: scratch, ownerRef: \"gc\" });\n if (!outcome.ok) failed = outcome.diagnostic;\n } finally {\n await rm(scratch, { recursive: true, force: true });\n }\n storeBytes = Math.max(0, before - (await apparentBytes(dirs.store)));\n }\n // The index says what the store holds (offline answers, DP-04): a package leaves it only\n // once the prune that removed it succeeded.\n if (failed) {\n log.warn(\"deps.prune_failed\", { diagnostic: failed });\n pruned = [];\n } else if (unneeded.length > 0) {\n ledger.write((db) => {\n for (const id of unneeded) {\n const at = id.lastIndexOf(\"@\");\n db.run(\n \"DELETE FROM dependency_package WHERE name = ? AND version = ?\",\n id.slice(0, at),\n id.slice(at + 1),\n );\n }\n });\n }\n }\n return {\n lockLayouts: { count: layouts.length, bytes: layoutBytes, names: layouts },\n storePackages: {\n count: pruned.length,\n bytes: storeBytes,\n packages: pruned,\n ...(failed ? { failed } : {}),\n },\n };\n };\n\n return {\n warm,\n\n runtimeModules: (target) =>\n options.gate ? options.gate.shared(() => runtimeModules(target)) : runtimeModules(target),\n\n collect,\n\n resolve: (target) =>\n byArtifact.run(target.key, async () => {\n const imports = await scanImports(target.sourceDir);\n const working = readWorking(target.key);\n const added = (working?.added ?? []).filter((name) => !(name in warm.packages));\n const needed = [\n ...new Set([...[...imports.keys()].filter((name) => !(name in warm.packages)), ...added]),\n ].sort();\n const pinned = working?.lock.packages ?? {};\n const missing = needed.filter((name) => pinned[name] === undefined);\n if (missing.length > 0 && options.policy() === \"explicit\") {\n const first = missing[0] as string;\n const site = imports.get(first);\n const command = `mostra add ${missing.join(\" \")} --artifact ${shellQuote(target.artifactPath)}`;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_DEP_MISSING\", {\n message: `${missing.join(\", \")} ${missing.length === 1 ? \"isn't\" : \"aren't\"} in the warm set or the artifact's lockfile, and this home's dependency policy is explicit.`,\n ...(site ? { location: site } : {}),\n fix: { kind: \"command\", command },\n }),\n );\n }\n const pins = Object.fromEntries(\n needed\n .filter((name) => pinned[name] !== undefined)\n .map((name) => [name, pinned[name] as string]),\n );\n let lock: Lock;\n if (needed.length === 0) {\n lock = { warm: warm.packages, packages: {} };\n } else if (\n missing.length === 0 &&\n working?.lock.pnpm !== undefined &&\n sameRecord(pins, pinned) &&\n sameRecord(working.lock.warm, warm.packages)\n ) {\n // Exactly the working lockfile: nothing to resolve, and it works offline.\n lock = working.lock;\n } else {\n lock = await resolveLock({\n key: target.key,\n artifactDir: target.artifactDir,\n pins,\n additions: missing.map((name) => ({ name })),\n previous: working?.lock.pnpm,\n });\n }\n const resolved = await settle(lock, target);\n const seen = rowText(target.key);\n return {\n ...resolved,\n save(db, artifactId) {\n const current = db.get<{ lock_text: string; added_json: string }>(\n \"SELECT lock_text, added_json FROM dependency_lock WHERE key = ?\",\n target.key,\n );\n // deps/add changed it after this resolution read it: the newer lockfile stays.\n if ((current?.lock_text ?? null) !== seen) return;\n const now = new Date().toISOString();\n if (target.key !== artifactId) {\n db.run(\"DELETE FROM dependency_lock WHERE key = ?\", target.key);\n }\n db.run(\n \"INSERT INTO dependency_lock (key, lock_text, added_json, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET lock_text = excluded.lock_text, added_json = excluded.added_json, updated_at = excluded.updated_at\",\n artifactId,\n resolved.lock,\n JSON.stringify([...new Set(added)].sort()),\n now,\n );\n },\n };\n }),\n\n add: (target) =>\n byArtifact.run(target.key, async () => {\n const request = target.request;\n const recorded =\n request === undefined\n ? undefined\n : ledger.read((db) => recordedResult<DepsAddResult>(db, request));\n if (recorded !== undefined) return recorded;\n const specs: PackageSpec[] = [];\n for (const text of target.packages) {\n const spec = parseSpec(text);\n if (!spec) {\n throw fail(\n \"MOSTRA_DEP_SPEC_INVALID\",\n `\"${text}\" isn't a registry package spec (name, name@version, name@range or name@tag).`,\n );\n }\n specs.push(spec);\n }\n for (const spec of specs) {\n const version = warm.packages[spec.name];\n if (version === undefined || spec.range === undefined) continue;\n const fits = semver.validRange(spec.range)\n ? semver.satisfies(version, spec.range)\n : spec.range === \"latest\";\n if (!fits) {\n throw fail(\n \"MOSTRA_DEP_WARM_CONFLICT\",\n `${spec.name} is in the warm set at ${version}, which every artifact uses; ${spec.name}@${spec.range} can't replace it.`,\n );\n }\n }\n const working = readWorking(target.key);\n const pinned = working?.lock.packages ?? {};\n const onDemand = specs.filter((spec) => !(spec.name in warm.packages));\n // A bare name that is already pinned keeps its pin; anything else resolves now.\n const additions = onDemand.filter(\n (spec) => spec.range !== undefined || pinned[spec.name] === undefined,\n );\n const additionNames = new Set(additions.map((spec) => spec.name));\n const pins = Object.fromEntries(\n Object.entries(pinned).filter(\n ([name]) => !additionNames.has(name) && !(name in warm.packages),\n ),\n );\n const lock: Lock =\n additions.length === 0 &&\n working !== undefined &&\n sameRecord(working.lock.warm, warm.packages)\n ? working.lock\n : Object.keys(pins).length === 0 && additions.length === 0\n ? { warm: warm.packages, packages: {} }\n : await resolveLock({\n key: target.key,\n artifactDir: target.artifactDir,\n pins,\n additions,\n previous: working?.lock.pnpm,\n });\n const resolved = await settle(lock, target);\n const added = [...(working?.added ?? []), ...onDemand.map((spec) => spec.name)];\n writeWorking(target.key, resolved.lock, added);\n const packages: AddedPackage[] = specs.map((spec) => {\n const warmVersion = warm.packages[spec.name];\n return warmVersion !== undefined\n ? { name: spec.name, version: warmVersion, warm: true }\n : { name: spec.name, version: lock.packages[spec.name] as string, warm: false };\n });\n const result: DepsAddResult = { packages, lockDigest: resolved.lockDigest };\n if (request !== undefined) ledger.write((db) => recordResult(db, request, result));\n return result;\n }),\n };\n}\n\n/** The bytes of the files under `dir` that nothing else links to (a layout's own files). */\nasync function unsharedBytes(dir: string): Promise<number> {\n let total = 0;\n for (const info of await files(dir)) if (info.nlink <= 1) total += info.size;\n return total;\n}\n\n/** The apparent size of a tree, counting each inode once. */\nasync function apparentBytes(dir: string): Promise<number> {\n const seen = new Set<number>();\n let total = 0;\n for (const info of await files(dir)) {\n if (seen.has(info.ino)) continue;\n seen.add(info.ino);\n total += info.size;\n }\n return total;\n}\n\n/** The regular files under `dir`, as `lstat` sees them; symbolic links are never followed. */\nasync function files(dir: string): Promise<{ size: number; nlink: number; ino: number }[]> {\n const found: { size: number; nlink: number; ino: number }[] = [];\n const walk = async (path: string): Promise<void> => {\n const entries = await readdir(path, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const child = join(path, entry.name);\n if (entry.isDirectory()) await walk(child);\n else if (entry.isFile()) {\n const info = await lstat(child).catch(() => undefined);\n if (info) found.push({ size: info.size, nlink: info.nlink, ino: info.ino });\n }\n }\n };\n await walk(dir);\n return found;\n}\n","/**\n * Newline-delimited JSON-RPC over byte streams (INTERFACES §6): stdio for `mostra-runtime host`,\n * Unix sockets for attached clients. Both feed the same {@link RpcPeer}.\n */\nimport type { Readable, Writable } from \"node:stream\";\nimport {\n createDiagnostic,\n encodeLine,\n LineSplitter,\n MAX_LINE_LENGTH,\n RpcError,\n type RpcPeer,\n} from \"@mostra/protocol\";\n\n/** A connection's raw ends. */\nexport interface StreamEnds {\n readonly input: Readable;\n readonly output: Writable;\n}\n\n/**\n * Connects `peer` to a stream pair: lines in, encoded messages out. Calls `onEnd` once when the\n * input ends or fails. A line longer than the limit is answered with `MOSTRA_HOST_MALFORMED` and\n * ends the connection, so a client can't make the instance buffer without bound.\n */\nexport function pump(ends: StreamEnds, peer: () => RpcPeer, onEnd: () => void): void {\n const splitter = new LineSplitter();\n let ended = false;\n const end = (): void => {\n if (ended) return;\n ended = true;\n onEnd();\n };\n ends.input.setEncoding(\"utf8\");\n ends.input.on(\"data\", (chunk: string) => {\n let lines: string[];\n try {\n lines = splitter.push(chunk);\n } catch (error) {\n const diagnostic = createDiagnostic(\"MOSTRA_HOST_MALFORMED\", {\n message: (error as Error).message,\n });\n writeLine(ends.output, {\n jsonrpc: \"2.0\",\n id: null,\n error: new RpcError(diagnostic).toErrorObject(),\n });\n ends.input.destroy();\n end();\n return;\n }\n for (const line of lines) peer().receiveLine(line);\n });\n ends.input.on(\"end\", end);\n ends.input.on(\"close\", end);\n ends.input.on(\"error\", end);\n}\n\n/**\n * Writes one message as a line. Returns false when the stream can't take it any more. A message\n * longer than the line limit would make the reader drop the connection, so it is never written:\n * an answer becomes `MOSTRA_HOST_MESSAGE_TOO_LARGE` for its request, and anything else is dropped\n * (Mostra's own requests and notifications are bounded well below the limit).\n */\nexport function writeLine(output: Writable, message: Parameters<typeof encodeLine>[0]): boolean {\n if (output.destroyed || output.writableEnded) throw new Error(\"The connection is closed.\");\n let line = encodeLine(message);\n if (line.length > MAX_LINE_LENGTH) {\n if (!(\"id\" in message) || \"method\" in message || message.id === null) return true;\n line = encodeLine({\n jsonrpc: \"2.0\",\n id: message.id,\n error: new RpcError(\n createDiagnostic(\"MOSTRA_HOST_MESSAGE_TOO_LARGE\", {\n message: `The answer is ${line.length} characters, longer than one protocol message carries (${MAX_LINE_LENGTH}).`,\n }),\n ).toErrorObject(),\n });\n }\n return output.write(line);\n}\n","/**\n * The host protocol server (D59, INTERFACES §6, HO-02): one dispatcher for every connection,\n * whether `mostra-runtime host`'s stdio or an attached client's Unix socket. It owns the session\n * rules (initialize first and once, revision negotiation, the home check, port registration on\n * the registering connection) and routes every other method to the handler a module registered.\n */\nimport type { Readable, Writable } from \"node:stream\";\nimport {\n CLI_CLIENT_NAME,\n type ClientInfo,\n createDiagnostic,\n type Diagnostic,\n HOST_PROTOCOL_REVISIONS,\n type HomeConfig,\n type InstanceInfo,\n type JsonRpcParams,\n type MethodDefinition,\n type MostraInitializeResult,\n mostraInitializeMethod,\n negotiateRevision,\n parseParams,\n type Revision,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport type { Log } from \"../log.ts\";\nimport { type ControlListener, type LaunchPipe, listenControl } from \"../platform/index.ts\";\nimport { pump, writeLine } from \"./streams.ts\";\n\n/** How a connection reached the instance. */\nexport type ConnectionKind = \"stdio\" | \"socket\";\n\n/** One connection's session, as handlers see it. */\nexport interface Session {\n /** A per-instance sequence number, for logs. */\n readonly id: number;\n readonly kind: ConnectionKind;\n /** The client, once initialized. */\n readonly client: ClientInfo | undefined;\n /** The negotiated revision, once initialized. */\n readonly revision: Revision | undefined;\n /** The ports this connection registered and the instance supports. */\n readonly ports: ReadonlySet<string>;\n /** The notifications the client accepts (D84); the instance sends no others. */\n readonly notifications: ReadonlySet<string>;\n /** Aborts when the connection closes, so long requests (`wait`) end with it. */\n readonly signal: AbortSignal;\n}\n\n/** A method a module serves. */\nexport interface MethodHandler<P = unknown, R = unknown> {\n readonly definition: MethodDefinition<P, R>;\n handle(params: P, session: Session): R | Promise<R>;\n}\n\n/** Builds a handler with its types checked against the method definition. */\nexport function handler<P, R>(\n definition: MethodDefinition<P, R>,\n handle: (params: P, session: Session) => R | Promise<R>,\n): MethodHandler {\n return { definition, handle } as unknown as MethodHandler;\n}\n\n/** Options for {@link ProtocolServer}. */\nexport interface ProtocolServerOptions {\n readonly log: Log;\n /** Describes the instance for `mostra/initialize`. */\n describe(): InstanceInfo;\n /** Whether a client's `home.path` names this instance's home (D84). */\n servesHome(path: string): boolean;\n /**\n * Applies a client's home settings (`HomeConfig` without `path`), such as the dependency policy\n * (D95). Runs during `mostra/initialize`, after the home check; a throw refuses the session.\n */\n configureHome?(home: HomeConfig, client: ClientInfo): void;\n /**\n * Marks the home as configured by a host (D140 item 4): called when a client other than the\n * standalone CLI sends `home` or `ports` in `mostra/initialize`.\n */\n markHostConfigured?(client: ClientInfo): void;\n /** Every method besides `mostra/initialize`. */\n readonly handlers: readonly MethodHandler[];\n /** The ports this instance calls when a client registers them. */\n readonly supportedPorts: readonly string[];\n /** The revisions this instance speaks. Default: `HOST_PROTOCOL_REVISIONS`. */\n readonly revisions?: readonly Revision[];\n /**\n * Applied to the text of every diagnostic a response carries, so secrets and capability\n * material that reach an error (a bundler message quoting an import, say) never leave the\n * instance (STANDARDS security). Default: the identity.\n */\n readonly redact?: (text: string) => string;\n /** Runs after a connection initialized, with its registered ports. */\n onInitialized?(session: Session): void;\n /** Runs once when a connection closes. */\n onClosed?(session: Session): void;\n /** The notifications this instance may send, for `capabilities.notifications`. */\n readonly notifications?: readonly string[];\n}\n\ninterface Connection {\n readonly session: MutableSession;\n readonly peer: RpcPeer;\n readonly output: Writable;\n close(): void;\n}\n\ninterface MutableSession {\n id: number;\n kind: ConnectionKind;\n client: ClientInfo | undefined;\n revision: Revision | undefined;\n ports: Set<string>;\n notifications: Set<string>;\n readonly signal: AbortSignal;\n initialized: boolean;\n}\n\n/** The host protocol server of one instance. */\nexport class ProtocolServer {\n readonly #options: ProtocolServerOptions;\n readonly #handlers: ReadonlyMap<string, MethodHandler>;\n readonly #connections = new Set<Connection>();\n #nextId = 1;\n #refusal: Diagnostic | undefined;\n #listener: ControlListener | undefined;\n #endpoint: string | undefined;\n #listenOptions: { launchPipe?: LaunchPipe; onMoved?: (path: string) => void } = {};\n #healTimer: ReturnType<typeof setInterval> | undefined;\n /** A heal under way: one at a time, and `close` waits for it (Opus review of WP-W1). */\n #healing: Promise<void> | undefined;\n /** An endpoint that moved but whose `onMoved` failed: announced again by every heal until it holds. */\n #unannounced: string | undefined;\n #closed = false;\n\n constructor(options: ProtocolServerOptions) {\n this.#options = options;\n this.#handlers = new Map(options.handlers.map((entry) => [entry.definition.method, entry]));\n }\n\n /** How many connections are open. */\n get connections(): number {\n return this.#connections.size;\n }\n\n /** The methods this server serves, for `capabilities.methods`. */\n get methods(): readonly string[] {\n return [mostraInitializeMethod.method, ...this.#handlers.keys()];\n }\n\n /**\n * Serves one stream connection (stdio, or an accepted socket). `onClose` runs once when it\n * ends.\n */\n serve(kind: ConnectionKind, input: Readable, output: Writable, onClose?: () => void): Session {\n const closed = new AbortController();\n const session: MutableSession = {\n id: this.#nextId++,\n kind,\n client: undefined,\n revision: undefined,\n ports: new Set(),\n notifications: new Set(),\n signal: closed.signal,\n initialized: false,\n };\n const peer = new RpcPeer({\n send: (message) => {\n writeLine(output, message);\n },\n onRequest: (method, params) => this.#dispatch(session, method, params),\n onInternalError: (error, method) =>\n this.#options.log.error(\"protocol.internal_error\", { session: session.id, method, error }),\n });\n const connection: Connection = {\n session,\n peer,\n output,\n close: () => {\n peer.close();\n output.end();\n },\n };\n this.#connections.add(connection);\n this.#options.log.info(\"protocol.connected\", { session: session.id, kind });\n pump(\n { input, output },\n () => peer,\n () => {\n peer.close();\n this.#connections.delete(connection);\n closed.abort();\n this.#options.log.info(\"protocol.disconnected\", { session: session.id, kind });\n if (session.initialized) {\n try {\n this.#options.onClosed?.(session);\n } catch (error) {\n this.#options.log.error(\"protocol.close_hook_failed\", { session: session.id, error });\n }\n }\n onClose?.();\n },\n );\n return session;\n }\n\n /**\n * Listens on the home's control endpoint (D81, D82): a Unix socket, replacing any leftover file\n * (only the lock holder calls this) and owner-only; on Windows the helper's owner-only pipe\n * (`launchPipe`). Every `healMs` (at most 10 s) it checks that the endpoint still serves and\n * binds it again when it doesn't, calling `onMoved` when the new endpoint has another name.\n */\n async listen(\n path: string,\n healMs = 5000,\n options: { launchPipe?: LaunchPipe; onMoved?: (path: string) => void } = {},\n ): Promise<void> {\n this.#endpoint = path;\n this.#listenOptions = options;\n this.#listener = await this.#bind();\n this.#healTimer = setInterval(() => void this.#heal(), Math.min(healMs, 10_000));\n this.#healTimer.unref();\n }\n\n /** The endpoint the server listens on, as clients connect to it. */\n get socketPath(): string | undefined {\n return this.#listener?.path;\n }\n\n #bind(): Promise<ControlListener> {\n return listenControl(\n this.#endpoint ?? \"\",\n (stream) => {\n this.serve(\"socket\", stream, stream);\n },\n {\n ...(this.#listenOptions.launchPipe ? { launchPipe: this.#listenOptions.launchPipe } : {}),\n onError: (error) => this.#options.log.error(\"protocol.listener_error\", { error }),\n },\n );\n }\n\n #heal(): Promise<void> {\n if (this.#closed) return Promise.resolve();\n // A bind on Windows (a gated helper and its READY) can outlast the interval: one heal at a time.\n this.#healing ??= this.#healOnce().finally(() => {\n this.#healing = undefined;\n });\n return this.#healing;\n }\n\n async #healOnce(): Promise<void> {\n if (this.#unannounced !== undefined) this.#announce(this.#unannounced);\n const listener = this.#listener;\n if (!listener || listener.intact()) return;\n // Close the old listener first: Node removes a Unix socket's file when its server closes, so\n // closing it after binding would remove the new socket.\n await listener.close();\n if (this.#closed) return;\n try {\n const replacement = await this.#bind();\n if (this.#closed) {\n // The server closed while this bind ran: the endpoint is never served or announced.\n await replacement.close();\n return;\n }\n this.#listener = replacement;\n this.#options.log.warn(\"protocol.socket_recreated\", { path: replacement.path });\n if (replacement.path !== listener.path) this.#announce(replacement.path);\n } catch (error) {\n this.#options.log.warn(\"protocol.socket_recreate_failed\", { path: listener.path, error });\n }\n }\n\n /**\n * Tells the instance the endpoint moved (it rewrites `instance.json`); when that fails, every\n * later heal tries again, so starters are never left with a record naming a dead pipe.\n */\n #announce(path: string): void {\n try {\n this.#listenOptions.onMoved?.(path);\n this.#unannounced = undefined;\n } catch (error) {\n this.#unannounced = path;\n this.#options.log.warn(\"protocol.endpoint_announce_failed\", { path, error });\n }\n }\n\n /**\n * Answers every request from now on with `diagnostic`, for an instance that can no longer serve\n * (`MOSTRA_HOME_GONE`).\n */\n refuse(diagnostic: Diagnostic): void {\n this.#refusal = diagnostic;\n }\n\n /**\n * Calls a port method on the connection that registered the port most recently (D59: port\n * callbacks reach only the registering connection).\n */\n callPort(\n port: string,\n method: string,\n params: JsonRpcParams,\n options: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n const registrant = [...this.#connections]\n .reverse()\n .find((connection) => connection.session.ports.has(port));\n if (!registrant) return Promise.reject(new Error(`No connection registered the ${port} port.`));\n return registrant.peer.request(method, params, options);\n }\n\n /** The names of the clients connected now (initialized sessions). */\n connectedClients(): ReadonlySet<string> {\n return new Set(\n [...this.#connections]\n .filter((connection) => connection.session.initialized)\n .map((connection) => connection.session.client?.name ?? \"\"),\n );\n }\n\n /**\n * The initialized connections that registered `port`, oldest first, with their clients' names:\n * the hosts a port call can reach (D105).\n */\n registrants(port: string): { readonly session: number; readonly owner: string }[] {\n return [...this.#connections]\n .filter((connection) => connection.session.initialized && connection.session.ports.has(port))\n .map((connection) => ({\n session: connection.session.id,\n owner: connection.session.client?.name ?? \"\",\n }));\n }\n\n /**\n * Calls a method on one connection (a port call, D59); rejects with `MOSTRA_HOST_CONNECTION_CLOSED`\n * when that connection is gone, and `MOSTRA_HOST_TIMEOUT` past `timeoutMs`.\n */\n callSession(\n session: number,\n method: string,\n params: JsonRpcParams,\n timeoutMs: number,\n ): Promise<unknown> {\n const connection = [...this.#connections].find((entry) => entry.session.id === session);\n if (!connection) {\n return Promise.reject(\n new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `The connection that registered for ${method} has closed.`,\n }),\n ),\n );\n }\n return connection.peer.request(method, params, { timeoutMs });\n }\n\n /**\n * When a connection's output is full (its client reads slower than the instance writes), a\n * promise that settles once it drained or closed; `undefined` when it can take more now. Senders\n * of long streams of notifications wait on it, so a slow client never makes the instance buffer\n * without bound.\n */\n drained(session: number): Promise<void> | undefined {\n const connection = [...this.#connections].find((entry) => entry.session.id === session);\n const output = connection?.output;\n if (!output?.writableNeedDrain) return undefined;\n return new Promise((resolve) => {\n const done = (): void => {\n output.off(\"drain\", done);\n output.off(\"close\", done);\n resolve();\n };\n output.once(\"drain\", done);\n output.once(\"close\", done);\n });\n }\n\n /**\n * Sends a notification on one connection, if its client accepted that notification (D84).\n * Returns `false` when the connection is gone or didn't accept it.\n */\n notify(session: number, method: string, params: JsonRpcParams): boolean {\n const connection = [...this.#connections].find((entry) => entry.session.id === session);\n if (!connection || connection.peer.closed || !connection.session.notifications.has(method)) {\n return false;\n }\n connection.peer.notify(method, params);\n return true;\n }\n\n /**\n * Stops listening, removes the socket file if it is still this server's, and closes every\n * connection. Responses already sent are flushed first: the connections end before the\n * listener, which on Windows lets the pipe's helper hand them over before it exits.\n */\n async close(): Promise<void> {\n this.#closed = true;\n if (this.#healTimer) clearInterval(this.#healTimer);\n await this.#healing;\n for (const connection of this.#connections) connection.close();\n const listener = this.#listener;\n this.#listener = undefined;\n await listener?.close();\n }\n\n async #dispatch(session: MutableSession, method: string, params: unknown): Promise<unknown> {\n try {\n return await this.#route(session, method, params);\n } catch (error) {\n const redact = this.#options.redact;\n if (!redact || !(error instanceof RpcError)) throw error;\n const { diagnostic } = error;\n throw new RpcError(\n {\n ...diagnostic,\n message: redact(diagnostic.message),\n ...(diagnostic.hint !== undefined ? { hint: redact(diagnostic.hint) } : {}),\n ...(diagnostic.fix?.text !== undefined\n ? { fix: { ...diagnostic.fix, text: redact(diagnostic.fix.text) } }\n : {}),\n },\n error.code,\n );\n }\n }\n\n async #route(session: MutableSession, method: string, params: unknown): Promise<unknown> {\n if (this.#refusal) throw new RpcError(this.#refusal);\n if (method === mostraInitializeMethod.method) return this.#initialize(session, params);\n if (!session.initialized) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INITIALIZE_ORDER\", {\n message: `${method} arrived before mostra/initialize on this connection.`,\n }),\n );\n }\n const entry = this.#handlers.get(method);\n if (!entry) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_METHOD_UNKNOWN\", {\n message: `This instance serves no method ${method}.`,\n }),\n );\n }\n const parsed = parseParams(entry.definition, params);\n const result = await entry.handle(parsed, session);\n const checked = entry.definition.result.safeParse(result);\n if (!checked.success) {\n this.#options.log.error(\"protocol.invalid_result\", { method, issues: checked.error.issues });\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: `${method} failed unexpectedly.`,\n }),\n );\n }\n return checked.data;\n }\n\n #initialize(session: MutableSession, raw: unknown): MostraInitializeResult {\n if (session.initialized) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INITIALIZE_ORDER\", {\n message: \"This connection is already initialized; mostra/initialize is sent once.\",\n }),\n );\n }\n const params = parseParams(mostraInitializeMethod, raw);\n const negotiation = negotiateRevision(\n params.revisions,\n this.#options.revisions ?? HOST_PROTOCOL_REVISIONS,\n );\n if (!negotiation.ok) throw new RpcError(negotiation.diagnostic);\n const instance = this.#options.describe();\n if (params.home?.path !== undefined && !this.#options.servesHome(params.home.path)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOME_MISMATCH\", {\n message: `The client expects the home ${params.home.path}; this instance serves ${instance.home}.`,\n }),\n );\n }\n if (params.home !== undefined) this.#options.configureHome?.(params.home, params.client);\n if (\n (params.home !== undefined || params.ports.length > 0) &&\n params.client.name !== CLI_CLIENT_NAME\n ) {\n this.#options.markHostConfigured?.(params.client);\n }\n const supported = new Set(this.#options.supportedPorts);\n const warnings: Diagnostic[] = [];\n for (const port of new Set(params.ports)) {\n if (supported.has(port)) {\n session.ports.add(port);\n } else {\n warnings.push(\n createDiagnostic(\"MOSTRA_HOST_PORT_UNSUPPORTED\", {\n message:\n port === \"ai\"\n ? \"The ai port is reserved for a later release (D46); this instance doesn't call it.\"\n : `This instance doesn't call the ${port} port; the session continues without it.`,\n }),\n );\n }\n }\n session.initialized = true;\n session.client = params.client;\n session.revision = negotiation.revision;\n const offered = new Set(this.#options.notifications ?? []);\n for (const name of params.capabilities.notifications ?? []) {\n if (offered.has(name)) session.notifications.add(name);\n }\n this.#options.log.info(\"protocol.initialized\", {\n session: session.id,\n client: params.client,\n revision: negotiation.revision,\n ports: [...session.ports],\n });\n // After the answer is on its way: a port call it starts never precedes the response.\n setImmediate(() => {\n if (session.signal.aborted) return;\n try {\n this.#options.onInitialized?.(session);\n } catch (error) {\n this.#options.log.error(\"protocol.initialized_hook_failed\", { session: session.id, error });\n }\n });\n return {\n revision: negotiation.revision,\n instance,\n capabilities: {\n methods: this.methods,\n notifications: [...(this.#options.notifications ?? [])],\n ports: [...this.#options.supportedPorts],\n },\n warnings,\n };\n }\n}\n","/**\n * The client end of the home socket, used by a starter that finds another supervisor holding the\n * home (D81) and by tests. SDKs and the CLI implement the same few steps in their own packages.\n */\nimport {\n type ClientInfo,\n createDiagnostic,\n HOST_PROTOCOL_REVISIONS,\n type MostraInitializeResult,\n mostraInitializeMethod,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport { ControlConnectError, connectControl } from \"../platform/index.ts\";\nimport { pump, writeLine } from \"./streams.ts\";\n\n/** An open client connection to an instance's socket. */\nexport interface SocketClient {\n readonly peer: RpcPeer;\n /** Resolves when the connection has closed. */\n readonly closed: Promise<void>;\n close(): void;\n}\n\n/**\n * Connects to a control socket. Rejects with `MOSTRA_HOST_CONNECTION_CLOSED` when nothing\n * listens there (the file is missing or stale), the connection doesn't open within `timeoutMs`,\n * or, on Windows, the pipe under that name is another user's.\n */\nexport function connectSocket(path: string, timeoutMs = 5000): Promise<SocketClient> {\n return connectControl(path, timeoutMs).then(\n (socket) => {\n const peer = new RpcPeer({ send: (message) => void writeLine(socket, message) });\n let markClosed: () => void = () => {};\n const closed = new Promise<void>((done) => {\n markClosed = done;\n });\n socket.on(\"error\", () => socket.destroy());\n pump(\n { input: socket, output: socket },\n () => peer,\n () => {\n peer.close();\n markClosed();\n },\n );\n return {\n peer,\n closed,\n close: () => {\n peer.close();\n socket.end();\n },\n };\n },\n (error: unknown) => {\n // Another user's pipe under the name is no instance of this home, like no instance at all.\n const why =\n error instanceof ControlConnectError && error.reason === \"not-owned\"\n ? \"it belongs to another user\"\n : error instanceof Error\n ? error.message\n : \"failed\";\n throw refused(path, why);\n },\n );\n}\n\nfunction refused(path: string, why: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `Couldn't connect to the instance socket ${path} (${why}).`,\n }),\n );\n}\n\n/** Connects to a socket and opens a session. The caller closes the returned client. */\nexport async function attach(\n path: string,\n client: ClientInfo,\n timeoutMs = 5000,\n): Promise<{ client: SocketClient; result: MostraInitializeResult }> {\n const connection = await connectSocket(path, timeoutMs);\n try {\n const result = await connection.peer.call(\n mostraInitializeMethod,\n { client, revisions: [...HOST_PROTOCOL_REVISIONS], capabilities: {}, ports: [] },\n { timeoutMs },\n );\n return { client: connection, result };\n } catch (error) {\n connection.close();\n throw error;\n }\n}\n","/**\n * The host protocol server (HO-02, D59): one dispatcher for stdio and the home socket, the\n * session methods, and the socket client a starter uses to attach.\n */\nimport {\n type ChildProcessStatus,\n createDiagnostic,\n type DeliveryCounts,\n type GatewayStatus,\n type InstanceCheck,\n type InstanceInfo,\n type InstanceStatusResult,\n instanceCheckMethod,\n instanceStatusMethod,\n mostraShutdownMethod,\n RpcError,\n type Share,\n type WorkerStatus,\n} from \"@mostra/protocol\";\nimport { handler, type MethodHandler } from \"./server.ts\";\n\nexport { attach, type SocketClient } from \"./client.ts\";\nexport { handler, type MethodHandler, ProtocolServer, type Session } from \"./server.ts\";\n\n/** What the session methods need from the instance. */\nexport interface SessionMethodsOptions {\n describe(): InstanceInfo;\n /** When the instance took ownership of its home. */\n readonly startedAt: string;\n socketPath(): string;\n connections(): number;\n processes(): readonly ChildProcessStatus[];\n /** Where the gateway listens, once it has started. */\n gateway?(): GatewayStatus | undefined;\n /** The outbox per host (WP-06). */\n deliveries?(): readonly DeliveryCounts[];\n /** The artifact workers (WP-08). */\n workers?(): readonly WorkerStatus[];\n /** When an idle daemon exits (WP-08); `undefined` while busy or for an instance that never does. */\n idleExitAt?(): string | undefined;\n /** The active shares (WP-13, D158). */\n shares?(): readonly Share[];\n /**\n * The supervisor's own checks of its home (`instance/check`, D140 item 18), in order; `deep`\n * also hashes every version against its output digest.\n */\n checks?(deep: boolean): Promise<readonly InstanceCheck[]>;\n /**\n * Stops the instance. Called after the `mostra/shutdown` response is on its way (D87).\n */\n shutdown(reason: string): void;\n}\n\n/** The handlers of `instance/status` and `mostra/shutdown`. */\nexport function sessionMethods(options: SessionMethodsOptions): MethodHandler[] {\n return [\n handler(instanceStatusMethod, (): InstanceStatusResult => {\n const gateway = options.gateway?.();\n return {\n instance: options.describe(),\n startedAt: options.startedAt,\n socket: options.socketPath(),\n connections: options.connections(),\n processes: [...options.processes()],\n ...(gateway ? { gateway } : {}),\n ...(options.deliveries ? { deliveries: [...options.deliveries()] } : {}),\n ...(options.workers ? { workers: [...options.workers()] } : {}),\n ...(options.shares ? { shares: [...options.shares()] } : {}),\n ...(() => {\n const at = options.idleExitAt?.();\n return at === undefined ? {} : { idleExitAt: at };\n })(),\n };\n }),\n handler(instanceCheckMethod, async (params) => ({\n checks: [...((await options.checks?.(params.deep === true)) ?? [])],\n })),\n handler(mostraShutdownMethod, (_params, session) => {\n // A host-spawned instance lives as long as its host's stdio; attached clients can't end it\n // (D87). A daemon stops for any attached client: its socket is owner-only.\n if (options.describe().mode === \"host\" && session.kind !== \"stdio\") {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_SHUTDOWN_REFUSED\", {\n message: \"This instance was spawned by a host over stdio; only that host can stop it.\",\n }),\n );\n }\n // Answer first: the response is written before the stop begins.\n setImmediate(() =>\n options.shutdown(`mostra/shutdown from ${session.client?.name ?? \"a client\"}`),\n );\n return {};\n }),\n ];\n}\n","/**\n * The event log (IN-08, DATA_MODEL §3, §4): every durable change appends one event in the same\n * ledger transaction as the change, with a home-wide cursor and a per-artifact sequence. Readers\n * take events after a cursor, in cursor order, through one filter; since the supervisor is the\n * only writer and every commit is serialized, a reader can never see a later cursor before an\n * earlier one commits, so reading on from the last cursor never skips an event.\n *\n * ```ts\n * ledger.write((db) => {\n * db.run(\"INSERT INTO version …\");\n * const cursor = appendEvent(db, { artifactId, type: \"version.published\", payload: { … } });\n * });\n * const { events, cursor } = ledger.read((db) => readEvents(db, { filter, after: \"41\" }));\n * ```\n */\nimport {\n type Actor,\n type Cursor,\n createDiagnostic,\n type Diagnostic,\n type EventFilter,\n type EventRecord,\n RpcError,\n} from \"@mostra/protocol\";\nimport type { LedgerDb } from \"../ledger/index.ts\";\n\n/** Who caused an event (DATA_MODEL §4). */\nexport type EventActor = Actor;\n\n/** One event to append. */\nexport interface NewEvent {\n /** The artifact the event belongs to, or `null` for a home-wide event. */\n readonly artifactId: string | null;\n /** The event type from DATA_MODEL §4's catalog (`version.published` …). */\n readonly type: string;\n /** Who caused it. Default: an agent, the publisher of versions. */\n readonly actor?: EventActor;\n /** What caused it: a run, a mutation, a submission. */\n readonly causation?: Readonly<Record<string, string>>;\n /** The event's data, JSON. Never a sensitive field's value (D52). */\n readonly payload: Readonly<Record<string, unknown>>;\n}\n\n/** Redactors whose secrets no event may carry (D44, AC-06): the instances of this process. */\nconst redactors = new Set<{ redact(text: string): string }>();\n\n/**\n * Makes every event payload pass through `redactor` before it is stored: a secret that server\n * code put into a signal, a host event or a state value never enters the event log. Returns the\n * function that stops it (an instance's stop).\n */\nexport function redactEvents(redactor: { redact(text: string): string }): () => void {\n redactors.add(redactor);\n return () => redactors.delete(redactor);\n}\n\n/** `value` with every string (keys too) redacted, its structure kept. */\nfunction redacted(value: unknown): unknown {\n if (redactors.size === 0) return value;\n const text = (input: string): string => {\n let out = input;\n for (const redactor of redactors) out = redactor.redact(out);\n return out;\n };\n const walk = (item: unknown): unknown => {\n if (typeof item === \"string\") return text(item);\n if (Array.isArray(item)) return item.map(walk);\n if (item !== null && typeof item === \"object\") {\n return Object.fromEntries(\n Object.entries(item).map(([key, entry]) => [text(key), walk(entry)]),\n );\n }\n return item;\n };\n return walk(value);\n}\n\n/**\n * Appends one event inside the caller's write transaction and returns its cursor (a decimal\n * string, INTERFACES §1). The per-artifact sequence continues from the artifact's last event.\n * Secrets the instance knows are redacted from its payload.\n */\nexport function appendEvent(db: LedgerDb, event: NewEvent): string {\n const seq =\n event.artifactId === null\n ? null\n : (db.get<{ next: number }>(\n \"SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM event WHERE artifact_id = ?\",\n event.artifactId,\n )?.next ?? 1);\n const result = db.run(\n \"INSERT INTO event (artifact_id, seq, type, actor_json, causation_json, payload_json, at) VALUES (?, ?, ?, ?, ?, ?, ?)\",\n event.artifactId,\n seq,\n event.type,\n JSON.stringify(event.actor ?? { kind: \"agent\" }),\n event.causation === undefined ? null : JSON.stringify(event.causation),\n JSON.stringify(redacted(event.payload)),\n new Date().toISOString(),\n );\n return String(result.lastInsertRowid);\n}\n\n/** An `event` row. */\nexport interface EventRow {\n readonly cursor: number;\n readonly artifact_id: string | null;\n readonly seq: number | null;\n readonly type: string;\n readonly actor_json: string;\n readonly causation_json: string | null;\n readonly payload_json: string;\n readonly at: string;\n}\n\n/** An event row as the wire carries it. */\nexport function eventRecord(row: EventRow): EventRecord {\n return {\n cursor: String(row.cursor) as Cursor,\n artifactId: row.artifact_id,\n seq: row.seq,\n type: row.type,\n at: row.at,\n actor: JSON.parse(row.actor_json) as Actor,\n ...(row.causation_json !== null\n ? { causation: JSON.parse(row.causation_json) as Record<string, string> }\n : {}),\n payload: JSON.parse(row.payload_json) as Record<string, unknown>,\n };\n}\n\n/** The newest cursor in the home, or 0 before the first event. */\nexport function latestCursor(db: LedgerDb): number {\n return db.get<{ cursor: number }>(\"SELECT COALESCE(MAX(cursor), 0) AS cursor FROM event\")\n ?.cursor as number;\n}\n\n/** The type of the event compaction leaves behind (DATA_MODEL §4). */\nexport const COMPACTED = \"artifact.compacted\";\n\n/** The SQL condition and parameters of a filter, applied before any row is parsed. */\nfunction filterSql(filter: EventFilter | undefined): {\n where: string;\n params: (string | number)[];\n} {\n const clauses: string[] = [];\n const params: (string | number)[] = [];\n if (filter?.artifacts) {\n if (filter.artifacts.length === 0) return { where: \"0\", params: [] };\n clauses.push(`artifact_id IN (${filter.artifacts.map(() => \"?\").join(\", \")})`);\n params.push(...filter.artifacts);\n }\n if (filter?.types) {\n const alternatives = [`type = '${COMPACTED}'`];\n for (const pattern of filter.types) {\n if (pattern.endsWith(\".*\")) {\n const prefix = pattern.slice(0, -1);\n alternatives.push(\"substr(type, 1, ?) = ?\");\n params.push(prefix.length, prefix);\n } else {\n alternatives.push(\"type = ?\");\n params.push(pattern);\n }\n }\n clauses.push(`(${alternatives.join(\" OR \")})`);\n }\n return { where: clauses.length === 0 ? \"1\" : clauses.join(\" AND \"), params };\n}\n\n/**\n * The compaction summary whose range holds `after` for an artifact the filter covers: the reader\n * already had events of that range (`from <= after`), and the ones after its cursor are gone\n * (`after < through`, the summary's own cursor). A reader before the range receives the summary in\n * its place, in order, and continues after it (DATA_MODEL §4).\n */\nexport function compactionCovering(\n db: LedgerDb,\n filter: EventFilter | undefined,\n after: number,\n): EventRow | undefined {\n const { where, params } = filterSql(filter?.artifacts ? { artifacts: filter.artifacts } : {});\n return db.get<EventRow>(\n `SELECT * FROM event WHERE type = '${COMPACTED}' AND ${where} AND json_extract(payload_json, '$.from') <= ? AND cursor > ? ORDER BY cursor LIMIT 1`,\n ...params,\n after,\n after,\n );\n}\n\n/** Refuses a read whose cursor falls inside a compacted range (`MOSTRA_HOST_CURSOR_COMPACTED`). */\nexport function checkCompaction(\n db: LedgerDb,\n filter: EventFilter | undefined,\n after: number,\n): void {\n const hit = compactionCovering(db, filter, after);\n if (hit) {\n const from = (JSON.parse(hit.payload_json) as CompactionSummary).from;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CURSOR_COMPACTED\", {\n message: `Events after cursor ${after} were compacted into a summary at cursor ${hit.cursor}; read again after cursor ${from - 1} to receive it (events of other artifacts in between may repeat).`,\n }),\n );\n }\n}\n\n/** The most a page of events carries, as JSON: well inside every framing limit (D83). */\nexport const READ_MAX_BYTES: number = 8 * 1024 * 1024;\n\n/** Options for {@link readEvents}. */\nexport interface ReadOptions {\n readonly filter?: EventFilter | undefined;\n /** Events after this cursor. */\n readonly after: number;\n /** At most this many events. */\n readonly limit: number;\n /** At most about this many bytes of events; one event always fits. Default {@link READ_MAX_BYTES}. */\n readonly maxBytes?: number;\n /**\n * Read on through a compacted range that holds `after` instead of refusing it: the summary\n * arrives in cursor order among other artifacts' events, so nothing between is skipped, and the\n * page that carries it says so (`compacted`).\n */\n readonly acceptCompacted?: boolean;\n}\n\n/**\n * Reads matching events after a cursor, in order, inside the caller's read transaction. The\n * returned cursor is where the next read continues: the last event returned when the page is full\n * (by count or by size), else the newest cursor examined, so non-matching events are never\n * examined twice and an event left out is never skipped.\n */\nexport function readEvents(\n db: LedgerDb,\n options: ReadOptions,\n): { readonly events: EventRecord[]; readonly cursor: string; readonly compacted?: Diagnostic } {\n let covering: EventRow | undefined;\n if (options.acceptCompacted) covering = compactionCovering(db, options.filter, options.after);\n else checkCompaction(db, options.filter, options.after);\n const upTo = latestCursor(db);\n const { where, params } = filterSql(options.filter);\n const rows = db.all<EventRow>(\n `SELECT * FROM event WHERE cursor > ? AND cursor <= ? AND ${where} ORDER BY cursor LIMIT ?`,\n options.after,\n upTo,\n ...params,\n options.limit,\n );\n const maxBytes = options.maxBytes ?? READ_MAX_BYTES;\n const events: EventRecord[] = [];\n let bytes = 0;\n let full = rows.length === options.limit;\n for (const row of rows) {\n const size =\n row.payload_json.length + row.actor_json.length + (row.causation_json?.length ?? 0) + 256;\n if (events.length > 0 && bytes + size > maxBytes) {\n full = true;\n break;\n }\n bytes += size;\n events.push(eventRecord(row));\n }\n const last = events.at(-1)?.cursor;\n const cursor = full && last !== undefined ? Number(last) : Math.max(upTo, options.after);\n // The page that carries the summary says that events after `after` were lost.\n const compacted =\n covering !== undefined && events.some((event) => Number(event.cursor) === covering.cursor)\n ? createDiagnostic(\"MOSTRA_HOST_CURSOR_COMPACTED\", {\n message: `Events after cursor ${options.after} were compacted; the summary at cursor ${covering.cursor} stands in for them.`,\n })\n : undefined;\n return { events, cursor: String(cursor), ...(compacted ? { compacted } : {}) };\n}\n\n/** What compaction left behind: the `artifact.compacted` event's payload (DATA_MODEL §4). */\nexport interface CompactionSummary {\n /** The first cursor the summary covers. */\n readonly from: number;\n /** The last cursor it covers, which is its own: the artifact's events in between were replaced. */\n readonly through: number;\n /** How many events it replaced. */\n readonly removed: number;\n /** How many of each type. */\n readonly types: Readonly<Record<string, number>>;\n /** The latest version published within the range. */\n readonly latestVersion?: {\n readonly versionId: unknown;\n readonly number: unknown;\n readonly cursor: number;\n };\n}\n\n/**\n * Compacts an artifact's events before `before` (`mostra gc --compact-events`, D47): they are\n * replaced, in this transaction, by one `artifact.compacted` event at the last replaced cursor and\n * sequence, whose payload summarizes them (an earlier summary in the range folds in). Cursors and\n * per-artifact sequences therefore never move back, and a reader who receives the summary\n * continues after it. Returns the summary, or `undefined` when there was nothing to replace.\n */\nexport function compactEvents(\n db: LedgerDb,\n artifactId: string,\n before: number,\n): CompactionSummary | undefined {\n const rows = db.all<EventRow>(\n \"SELECT * FROM event WHERE artifact_id = ? AND cursor < ? ORDER BY cursor\",\n artifactId,\n before,\n );\n const first = rows[0];\n const last = rows.at(-1);\n if (!first || !last) return undefined;\n if (rows.length === 1 && first.type === COMPACTED) return undefined;\n const types: Record<string, number> = {};\n let removed = 0;\n let from = first.cursor;\n let latestVersion: CompactionSummary[\"latestVersion\"];\n for (const row of rows) {\n if (row.type === COMPACTED) {\n // An earlier summary folds into this one, with everything it covered.\n const earlier = JSON.parse(row.payload_json) as CompactionSummary;\n from = Math.min(from, earlier.from);\n removed += earlier.removed;\n for (const [type, count] of Object.entries(earlier.types))\n types[type] = (types[type] ?? 0) + count;\n if (earlier.latestVersion) latestVersion = earlier.latestVersion;\n continue;\n }\n removed += 1;\n types[row.type] = (types[row.type] ?? 0) + 1;\n if (row.type === \"version.published\") {\n const payload = JSON.parse(row.payload_json) as { versionId?: unknown; number?: unknown };\n latestVersion = { versionId: payload.versionId, number: payload.number, cursor: row.cursor };\n }\n }\n const summary: CompactionSummary = {\n from,\n through: last.cursor,\n removed,\n types,\n ...(latestVersion ? { latestVersion } : {}),\n };\n db.run(\"DELETE FROM event WHERE artifact_id = ? AND cursor < ?\", artifactId, before);\n db.run(\n \"INSERT INTO event (cursor, artifact_id, seq, type, actor_json, causation_json, payload_json, at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?)\",\n last.cursor,\n artifactId,\n last.seq,\n COMPACTED,\n JSON.stringify({ kind: \"mostra\" }),\n JSON.stringify(summary),\n new Date().toISOString(),\n );\n return summary;\n}\n","/**\n * Fields and documents (D22, D52, D63, D106; ARCHITECTURE §6). A document is a viewer's draft or\n * an artifact's shared state: a map from field ID to value, each field carrying the document\n * revision that last wrote it, under a revision that only grows. A mutation applies its ops\n * together: an op whose field changed after the mutation's base revision is a conflict and leaves\n * the field alone, the others apply under one new revision, and the result is recorded under the\n * mutation's ID so a retry replays it.\n */\nimport { createHash } from \"node:crypto\";\nimport {\n type Actor,\n canonicalJson,\n createDiagnostic,\n type FieldConflict,\n type FieldOp,\n type FieldScope,\n type FieldState,\n isFieldId,\n type MutationResult,\n RpcError,\n} from \"@mostra/protocol\";\nimport type { LedgerDb } from \"../ledger/index.ts\";\nimport { appendEvent } from \"./events.ts\";\n\n/** The largest field value, as UTF-8 JSON (DATA_MODEL §5). */\nexport const FIELD_VALUE_MAX_BYTES: number = 1024 * 1024;\n\n/** The largest document: every live field value together (DATA_MODEL §5). */\nexport const DOCUMENT_MAX_BYTES: number = 16 * 1024 * 1024;\n\n/** A `document` row. */\nexport interface DocumentRow {\n readonly id: number;\n readonly artifact_id: string;\n readonly scope: FieldScope;\n readonly viewer_id: string | null;\n readonly revision: number;\n readonly epoch: number;\n readonly size: number;\n}\n\n/** A `field` row. */\nexport interface FieldRow {\n readonly document_id: number;\n readonly field_id: string;\n readonly value_json: string;\n readonly deleted: number;\n readonly field_rev: number;\n readonly updated_by_json: string | null;\n readonly updated_at: string;\n readonly sensitive: number;\n readonly label: string | null;\n readonly required: number | null;\n /** The number of the version whose view last wrote the field (D109); null for agents and hosts. */\n readonly version_number: number | null;\n}\n\n/**\n * The document for an artifact's state (`viewerId` null) or a viewer's draft, created when\n * `create` is set and it doesn't exist yet.\n */\nexport function documentFor(\n db: LedgerDb,\n artifactId: string,\n viewerId: string | null,\n create: true,\n): DocumentRow;\nexport function documentFor(\n db: LedgerDb,\n artifactId: string,\n viewerId: string | null,\n create?: false,\n): DocumentRow | undefined;\nexport function documentFor(\n db: LedgerDb,\n artifactId: string,\n viewerId: string | null,\n create = false,\n): DocumentRow | undefined {\n const find = (): DocumentRow | undefined =>\n viewerId === null\n ? db.get<DocumentRow>(\n \"SELECT * FROM document WHERE artifact_id = ? AND scope = 'artifact'\",\n artifactId,\n )\n : db.get<DocumentRow>(\n \"SELECT * FROM document WHERE artifact_id = ? AND scope = 'viewer' AND viewer_id = ?\",\n artifactId,\n viewerId,\n );\n const found = find();\n if (found || !create) return found;\n db.run(\n \"INSERT INTO document (artifact_id, scope, viewer_id) VALUES (?, ?, ?)\",\n artifactId,\n viewerId === null ? \"artifact\" : \"viewer\",\n viewerId,\n );\n return find() as DocumentRow;\n}\n\n/** A live field as the wire carries it. */\nexport function fieldState(row: FieldRow): FieldState {\n return {\n value: JSON.parse(row.value_json) as unknown,\n revision: String(row.field_rev),\n ...(row.updated_by_json !== null\n ? { updatedBy: JSON.parse(row.updated_by_json) as Actor }\n : {}),\n updatedAt: row.updated_at,\n ...(row.label !== null ? { label: row.label } : {}),\n ...(row.required !== null ? { required: row.required === 1 } : {}),\n ...(row.sensitive === 1 ? { sensitive: true } : {}),\n };\n}\n\n/**\n * A document's live fields (deleted ones left out), by ID. A draft field the page's version\n * doesn't cover is still live: orphans are derived per view, never stored (D109).\n */\nexport function liveFields(\n db: LedgerDb,\n documentId: number | undefined,\n): Record<string, FieldState> {\n if (documentId === undefined) return {};\n const rows = db.all<FieldRow>(\n \"SELECT * FROM field WHERE document_id = ? AND deleted = 0 ORDER BY field_id\",\n documentId,\n );\n return Object.fromEntries(rows.map((row) => [row.field_id, fieldState(row)]));\n}\n\n/** What a mutation needs besides its ops. */\nexport interface MutationInput {\n readonly artifactId: string;\n readonly scope: FieldScope;\n /** The draft's viewer, for `scope: \"viewer\"`. */\n readonly viewerId?: string;\n readonly mutationId: string;\n /** The revision the writer last saw; absent writes unconditionally (agents and hosts, D106). */\n readonly baseRevision?: number;\n readonly ops: readonly FieldOp[];\n readonly actor: Actor;\n /** The view a viewer's mutation came from, recorded as its cause. */\n readonly viewId?: string;\n /** The number of that view's version, recorded on each field it writes (D109). */\n readonly versionNumber?: number;\n /** The submit channel a choice came through (D40, D108), recorded as its cause. */\n readonly channel?: \"shell\" | \"artifact\";\n}\n\n/** What {@link applyMutation} did, for the caller's follow-ups (mirrors, streams). */\nexport interface MutationOutcome {\n readonly result: MutationResult;\n /** Whether the document changed (a new revision committed). */\n readonly changed: boolean;\n /** Whether the result was replayed from an earlier attempt. */\n readonly replayed: boolean;\n}\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", { message }), -32602);\n}\n\nfunction tooLarge(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_FIELD_TOO_LARGE\", { message }));\n}\n\n/** Checks the ops before anything is read: IDs, one change each, JSON values within limits. */\nfunction checkOps(ops: readonly FieldOp[]): Map<string, string | undefined> {\n if (ops.length === 0) throw invalid(\"A mutation needs at least one op.\");\n const encoded = new Map<string, string | undefined>();\n for (const op of ops) {\n if (!isFieldId(op.id)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_FIELD_ID_INVALID\", {\n message: `${JSON.stringify(op.id).slice(0, 80)} isn't a field ID.`,\n }),\n );\n }\n if (encoded.has(op.id)) throw invalid(`The field ${op.id} appears twice in one mutation.`);\n const deletes = op.delete === true;\n if (deletes === (op.value !== undefined)) {\n throw invalid(`The op for ${op.id} needs exactly one of value and delete.`);\n }\n if (deletes) {\n encoded.set(op.id, undefined);\n continue;\n }\n let json: string;\n try {\n // The canonical form checks it is JSON that I-JSON can hold; the stored text keeps the\n // writer's order, which reads back as the same value.\n canonicalJson(op.value);\n json = JSON.stringify(op.value);\n } catch {\n throw invalid(`The value of ${op.id} isn't JSON.`);\n }\n if (Buffer.byteLength(json, \"utf8\") > FIELD_VALUE_MAX_BYTES) {\n throw tooLarge(`The value of ${op.id} is larger than 1 MiB of JSON.`);\n }\n encoded.set(op.id, json);\n }\n return encoded;\n}\n\n/** The digest a mutation ID is recorded with: everything the mutation asked, as canonical JSON. */\nfunction mutationDigest(input: MutationInput): string {\n return createHash(\"sha256\")\n .update(\n canonicalJson({\n artifactId: input.artifactId,\n scope: input.scope,\n viewerId: input.viewerId ?? null,\n baseRevision: input.baseRevision ?? null,\n ops: input.ops,\n }),\n )\n .digest(\"hex\");\n}\n\nfunction conflictOf(row: FieldRow): FieldConflict {\n return {\n id: row.field_id,\n revision: String(row.field_rev),\n ...(row.deleted === 1 ? { deleted: true as const } : { value: JSON.parse(row.value_json) }),\n ...(row.updated_by_json !== null\n ? { updatedBy: JSON.parse(row.updated_by_json) as Actor }\n : {}),\n updatedAt: row.updated_at,\n };\n}\n\n/**\n * The result a mutation ID recorded, when this exact mutation was applied before, or `undefined`\n * for a new one; the same ID with other contents is `MOSTRA_FIELD_MUTATION_ID_REUSED` (D106).\n * Callers check it before any other rule, so a retry of a committed mutation always replays.\n */\nexport function replayedMutation(db: LedgerDb, input: MutationInput): MutationResult | undefined {\n const recorded = db.get<{ params_digest: string; result_json: string }>(\n \"SELECT params_digest, result_json FROM mutation WHERE id = ?\",\n input.mutationId,\n );\n if (!recorded) return undefined;\n if (recorded.params_digest !== mutationDigest(input)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_FIELD_MUTATION_ID_REUSED\", {\n message: `The mutation ID ${input.mutationId} was used for another change.`,\n }),\n );\n }\n return JSON.parse(recorded.result_json) as MutationResult;\n}\n\n/**\n * Applies a mutation inside the caller's write transaction (D22, IN-01, LL-01). The mutation ID\n * replays its recorded result; the same ID with other contents is\n * `MOSTRA_FIELD_MUTATION_ID_REUSED`. Each changed field takes the new revision; each conflict\n * names what the field holds now. Changes append `draft.changed` or `state.changed`, conflicts\n * `draft.conflict` or `state.conflict`, with sensitive values left out (D52).\n */\nexport function applyMutation(db: LedgerDb, input: MutationInput): MutationOutcome {\n if ((input.scope === \"viewer\") !== (input.viewerId !== undefined)) {\n throw new Error(\"A draft mutation names its viewer, and only a draft mutation does.\");\n }\n const encoded = checkOps(input.ops);\n const digest = mutationDigest(input);\n const replay = replayedMutation(db, input);\n if (replay) return { result: replay, changed: false, replayed: true };\n\n const document = documentFor(db, input.artifactId, input.viewerId ?? null, true);\n const revision = document.revision + 1;\n const now = new Date().toISOString();\n const applied: string[] = [];\n const conflicts: FieldConflict[] = [];\n const changes: Record<string, unknown>[] = [];\n let size = document.size;\n const writes: (() => void)[] = [];\n for (const op of input.ops) {\n const row = db.get<FieldRow>(\n \"SELECT * FROM field WHERE document_id = ? AND field_id = ?\",\n document.id,\n op.id,\n );\n if (input.baseRevision !== undefined && row && row.field_rev > input.baseRevision) {\n conflicts.push(conflictOf(row));\n continue;\n }\n applied.push(op.id);\n const json = encoded.get(op.id);\n const oldSize = row && row.deleted === 0 ? Buffer.byteLength(row.value_json, \"utf8\") : 0;\n const sensitive = op.sensitive ?? (row ? row.sensitive === 1 : false);\n if (json === undefined) {\n // Deleting what isn't there changes nothing and needs no new revision.\n if (!row || row.deleted === 1) continue;\n size -= oldSize;\n writes.push(() =>\n db.run(\n \"UPDATE field SET value_json = 'null', deleted = 1, field_rev = ?, updated_by_json = ?, updated_at = ?, version_number = ? WHERE document_id = ? AND field_id = ?\",\n revision,\n JSON.stringify(input.actor),\n now,\n input.versionNumber ?? null,\n document.id,\n op.id,\n ),\n );\n changes.push({ id: op.id, deleted: true });\n continue;\n }\n size += Buffer.byteLength(json, \"utf8\") - oldSize;\n const label = op.label ?? row?.label ?? null;\n const required = op.required !== undefined ? (op.required ? 1 : 0) : (row?.required ?? null);\n writes.push(() =>\n db.run(\n `INSERT INTO field (document_id, field_id, value_json, deleted, field_rev, updated_by_json, updated_at, sensitive, label, required, version_number)\n VALUES (?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (document_id, field_id) DO UPDATE SET value_json = excluded.value_json, deleted = 0,\n field_rev = excluded.field_rev, updated_by_json = excluded.updated_by_json,\n updated_at = excluded.updated_at, sensitive = excluded.sensitive, label = excluded.label,\n required = excluded.required, version_number = excluded.version_number`,\n document.id,\n op.id,\n json,\n revision,\n JSON.stringify(input.actor),\n now,\n sensitive ? 1 : 0,\n label,\n required,\n input.versionNumber ?? null,\n ),\n );\n changes.push(\n sensitive\n ? { id: op.id, sensitive: true }\n : { id: op.id, value: JSON.parse(json) as unknown },\n );\n }\n if (size > DOCUMENT_MAX_BYTES) {\n throw tooLarge(\n `This change would make the ${input.scope === \"viewer\" ? \"draft\" : \"artifact state\"} larger than 16 MiB.`,\n );\n }\n\n const changed = writes.length > 0;\n for (const write of writes) write();\n if (changed) {\n db.run(\"UPDATE document SET revision = ?, size = ? WHERE id = ?\", revision, size, document.id);\n }\n const current = changed ? revision : document.revision;\n const causation = {\n mutationId: input.mutationId,\n ...(input.viewId !== undefined ? { viewId: input.viewId } : {}),\n ...(input.channel !== undefined ? { channel: input.channel } : {}),\n };\n const subject =\n input.scope === \"viewer\" ? { viewerId: input.viewerId as string, epoch: document.epoch } : {};\n if (changed) {\n appendEvent(db, {\n artifactId: input.artifactId,\n type: input.scope === \"viewer\" ? \"draft.changed\" : \"state.changed\",\n actor: input.actor,\n causation,\n payload: { ...subject, revision: String(current), changes },\n });\n }\n if (conflicts.length > 0) {\n appendEvent(db, {\n artifactId: input.artifactId,\n type: input.scope === \"viewer\" ? \"draft.conflict\" : \"state.conflict\",\n actor: input.actor,\n causation,\n payload: {\n ...subject,\n revision: String(current),\n base: String(input.baseRevision),\n fields: conflicts.map((conflict) => ({ id: conflict.id, revision: conflict.revision })),\n },\n });\n }\n const result: MutationResult = { revision: String(current), applied, conflicts };\n db.run(\n \"INSERT INTO mutation (id, document_id, params_digest, result_json, applied_at) VALUES (?, ?, ?, ?, ?)\",\n input.mutationId,\n document.id,\n digest,\n JSON.stringify(result),\n now,\n );\n return { result, changed, replayed: false };\n}\n","/**\n * The submission policy in force (D10, D39, D63, D102): the first of the publish's `policy`, the\n * home's `HomeConfig.submission` and the manifest's request, else `once` per-artifact. It is\n * resolved at publish and stored on the artifact; `once` always carries its scope.\n */\nimport type { SubmissionPolicy } from \"@mostra/protocol\";\n\n/** The policy when nobody asked for one: exactly one submission per artifact (D39). */\nexport const DEFAULT_POLICY: SubmissionPolicy = { policy: \"once\", scope: \"per-artifact\" };\n\n/** The policy in force, from the sources in D102's order, with `once`'s scope filled in. */\nexport function policyInForce(\n ...sources: readonly (SubmissionPolicy | undefined)[]\n): SubmissionPolicy {\n const chosen = sources.find((source) => source !== undefined) ?? DEFAULT_POLICY;\n return chosen.policy === \"once\"\n ? { policy: \"once\", scope: chosen.scope ?? \"per-artifact\" }\n : { policy: chosen.policy };\n}\n\n/** The stored policy of an artifact row; artifacts published before WP-06 get the default. */\nexport function storedPolicy(policyJson: string | null): SubmissionPolicy {\n return policyInForce(\n policyJson === null ? undefined : (JSON.parse(policyJson) as SubmissionPolicy),\n );\n}\n","/**\n * Signals (IN-09, D10, D106): named, non-terminal requests for a host's attention, raised by the\n * artifact (`useSignal`), by server code (`signal()`, WP-08) or by a submission (`submit`). Each\n * is one durable `signal.raised` event and nothing more: Mostra never decides on its own what a\n * signal wakes. Hosts filter events and decide.\n */\nimport {\n type Actor,\n canonicalJson,\n createDiagnostic,\n RpcError,\n SIGNAL_NAME_PATTERN,\n SIGNAL_PAYLOAD_MAX_BYTES,\n} from \"@mostra/protocol\";\nimport type { LedgerDb } from \"../ledger/index.ts\";\nimport { appendEvent } from \"./events.ts\";\n\n/** Who raised a signal (DATA_MODEL §4). */\nexport type SignalSource = \"shell\" | \"artifact\" | \"action\";\n\n/** The signal every submission raises (D106); no one else may raise it. */\nexport const SUBMIT_SIGNAL = \"submit\";\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_SUBMIT_SIGNAL_INVALID\", { message }));\n}\n\n/** Checks a signal's name and payload (D106). */\nexport function checkSignal(name: unknown, payload: unknown): void {\n if (typeof name !== \"string\" || !SIGNAL_NAME_PATTERN.test(name)) {\n throw invalid(\n `${JSON.stringify(name).slice(0, 80)} isn't a signal name: 1 to 64 letters, digits, \".\", \"_\" and \"-\".`,\n );\n }\n if (name === SUBMIT_SIGNAL) {\n throw invalid('The signal name \"submit\" is reserved: a submission raises it.');\n }\n if (payload === undefined) return;\n let text: string;\n try {\n text = canonicalJson(payload);\n } catch {\n throw invalid(`The payload of the signal ${name} isn't JSON.`);\n }\n if (Buffer.byteLength(text, \"utf8\") > SIGNAL_PAYLOAD_MAX_BYTES) {\n throw invalid(`The payload of the signal ${name} is larger than 64 KiB of JSON.`);\n }\n}\n\n/**\n * Appends `signal.raised` inside the caller's transaction and returns its cursor, after checking\n * the name and payload. No caller may raise `submit`: only a submission does (D106).\n */\nexport function raiseSignal(\n db: LedgerDb,\n input: {\n readonly artifactId: string;\n readonly name: string;\n readonly payload?: unknown;\n readonly source: SignalSource;\n readonly actor: Actor;\n readonly viewId?: string;\n /** The viewer whose call raised it, for a signal of server code (D104: theirs alone). */\n readonly viewerId?: string;\n readonly causation?: Readonly<Record<string, string>>;\n },\n): string {\n checkSignal(input.name, input.payload);\n return appendSignal(db, input);\n}\n\n/** The `submit` signal a submission raises, in its transaction (D106). */\nexport function raiseSubmitSignal(\n db: LedgerDb,\n input: {\n readonly artifactId: string;\n readonly submissionId: string;\n readonly channel: \"shell\" | \"artifact\";\n readonly actor: Actor;\n readonly viewId: string;\n },\n): string {\n return appendSignal(db, {\n artifactId: input.artifactId,\n name: SUBMIT_SIGNAL,\n payload: { submissionId: input.submissionId },\n source: input.channel,\n actor: input.actor,\n viewId: input.viewId,\n causation: { submissionId: input.submissionId },\n });\n}\n\nfunction appendSignal(\n db: LedgerDb,\n input: {\n readonly artifactId: string;\n readonly name: string;\n readonly payload?: unknown;\n readonly source: SignalSource;\n readonly actor: Actor;\n readonly viewId?: string;\n readonly viewerId?: string;\n readonly causation?: Readonly<Record<string, string>>;\n },\n): string {\n return appendEvent(db, {\n artifactId: input.artifactId,\n type: \"signal.raised\",\n actor: input.actor,\n ...(input.causation ? { causation: input.causation } : {}),\n payload: {\n name: input.name,\n source: input.source,\n ...(input.viewId !== undefined ? { viewId: input.viewId } : {}),\n ...(input.viewerId !== undefined ? { viewerId: input.viewerId } : {}),\n ...(input.payload !== undefined ? { payload: input.payload } : {}),\n },\n });\n}\n","/**\n * Viewers and views (D104, DATA_MODEL §3). A viewer is a person: the home's local user, or the\n * person a capability link was minted for (`view/url`'s `viewer`), mapped idempotently by the\n * host's key. A view is one frame load of one version by one viewer; mutations and submits name\n * it, and a submission takes its version from it.\n */\nimport {\n type ControlsPolicy,\n createDiagnostic,\n RpcError,\n type Viewer,\n ViewerId,\n type ViewerKind,\n type ViewerSpec,\n ViewId,\n} from \"@mostra/protocol\";\nimport type { LedgerDb } from \"../ledger/index.ts\";\nimport { appendEvent } from \"./events.ts\";\n\ninterface ViewerRow {\n id: string;\n kind: ViewerKind;\n external_ref: string;\n name: string | null;\n}\n\n/** A `view` row. */\nexport interface ViewRow {\n readonly id: string;\n readonly artifact_id: string;\n readonly version_id: string;\n readonly viewer_id: string;\n readonly token_id: string | null;\n readonly opened_cursor: number | null;\n /** The channels and controls in force for the view (D108); null for views from before them. */\n readonly controls_json: string | null;\n}\n\n/** Both channels, every control: D40's standalone default. */\nexport const OPEN_CONTROLS: ControlsPolicy = { submitChannels: [\"shell\", \"artifact\"] };\n\n/** The channels and controls a view was opened with (D108). */\nexport function viewControls(view: ViewRow): ControlsPolicy {\n return view.controls_json === null\n ? OPEN_CONTROLS\n : (JSON.parse(view.controls_json) as ControlsPolicy);\n}\n\n/** The `external_ref` of the home's one local user. */\nconst LOCAL_REF = \"local\";\n\nfunction viewerOf(row: ViewerRow): Viewer {\n return {\n id: row.id,\n kind: row.kind,\n ...(row.name !== null ? { name: row.name } : {}),\n ...(row.kind === \"token\" || row.kind === \"host\" || row.kind === \"tailnet\"\n ? { ref: row.external_ref }\n : {}),\n };\n}\n\n/** The home's local user (created on first use): who every session acts as without a viewer. */\nexport function localViewerId(db: LedgerDb): string {\n const found = db.get<{ id: string }>(\n \"SELECT id FROM viewer WHERE kind = 'local' AND external_ref = ?\",\n LOCAL_REF,\n );\n if (found) return found.id;\n const id = ViewerId.create();\n db.run(\n \"INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, 'local', ?, NULL, ?)\",\n id,\n LOCAL_REF,\n new Date().toISOString(),\n );\n return id;\n}\n\n/**\n * The viewer a link minted with `viewer` acts for: the same `ref` always gives the same viewer, and\n * a `name` given again replaces the stored one.\n */\nexport function viewerForSpec(db: LedgerDb, spec: ViewerSpec): string {\n return viewerByRef(db, \"token\", spec);\n}\n\n/**\n * The viewer a host's identity port named (D143 item 2): one viewer of kind `host` per `ref`,\n * kept apart from `view/url`'s viewers, which a host names for links it mints.\n */\nexport function viewerForHost(db: LedgerDb, spec: ViewerSpec): string {\n return viewerByRef(db, \"host\", spec);\n}\n\n/**\n * A tailnet person (D158 item 2): one viewer of kind `tailnet` per Tailscale login, named by the\n * display name Tailscale Serve sends.\n */\nexport function viewerForTailnet(db: LedgerDb, spec: ViewerSpec): string {\n return viewerByRef(db, \"tailnet\", spec);\n}\n\n/**\n * A link's own viewer (D158 item 2): whoever opens a link over a tunnel without being named (a\n * public share, a tagged tailnet device) acts as one viewer per link, never as the home's local\n * user, so a visitor's answers never mix into the owner's draft.\n */\nexport function viewerForLink(db: LedgerDb, tokenId: string, name: string): string {\n return viewerByRef(db, \"token\", { ref: `link:${tokenId}`, name });\n}\n\nfunction viewerByRef(db: LedgerDb, kind: \"token\" | \"host\" | \"tailnet\", spec: ViewerSpec): string {\n const found = db.get<ViewerRow>(\n \"SELECT * FROM viewer WHERE kind = ? AND external_ref = ?\",\n kind,\n spec.ref,\n );\n if (found) {\n if (spec.name !== undefined && spec.name !== found.name) {\n db.run(\"UPDATE viewer SET name = ? WHERE id = ?\", spec.name, found.id);\n }\n return found.id;\n }\n const id = ViewerId.create();\n db.run(\n \"INSERT INTO viewer (id, kind, external_ref, name, created_at) VALUES (?, ?, ?, ?, ?)\",\n id,\n kind,\n spec.ref,\n spec.name ?? null,\n new Date().toISOString(),\n );\n return id;\n}\n\n/** A viewer by ID; throws for an unknown one, which would be a defect. */\nexport function viewer(db: LedgerDb, id: string): Viewer {\n const row = db.get<ViewerRow>(\"SELECT * FROM viewer WHERE id = ?\", id);\n if (!row) throw new Error(`No viewer ${id}.`);\n return viewerOf(row);\n}\n\n/** Records one frame load of a version (D104) and appends `view.opened`. */\nexport function openView(\n db: LedgerDb,\n input: {\n readonly artifactId: string;\n readonly versionId: string;\n readonly viewerId: string;\n readonly tokenId?: string | undefined;\n /** The channels and controls in force for this view (D108). */\n readonly controls?: ControlsPolicy;\n },\n): string {\n const id = ViewId.create();\n const cursor = appendEvent(db, {\n artifactId: input.artifactId,\n type: \"view.opened\",\n actor: { kind: \"viewer\", id: input.viewerId },\n payload: { viewId: id, versionId: input.versionId, viewerId: input.viewerId },\n });\n db.run(\n \"INSERT INTO view (id, artifact_id, version_id, viewer_id, token_id, opened_cursor, opened_at, controls_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\",\n id,\n input.artifactId,\n input.versionId,\n input.viewerId,\n input.tokenId ?? null,\n Number(cursor),\n new Date().toISOString(),\n JSON.stringify(input.controls ?? OPEN_CONTROLS),\n );\n return id;\n}\n\n/**\n * The view a request names, checked against the artifact and the viewer it must belong to, and,\n * for a page, the link it was opened through: a page can't name a view another link opened, such\n * as one of a version its own link may not open (Claude review finding 11).\n * `MOSTRA_SUBMIT_VIEW_INVALID` otherwise (D104).\n */\nexport function viewFor(\n db: LedgerDb,\n viewId: string,\n artifactId: string,\n viewerId: string,\n tokenId?: string,\n): ViewRow {\n const row = ViewId.is(viewId)\n ? db.get<ViewRow>(\"SELECT * FROM view WHERE id = ?\", viewId)\n : undefined;\n if (\n !row ||\n row.artifact_id !== artifactId ||\n row.viewer_id !== viewerId ||\n (tokenId !== undefined && row.token_id !== tokenId)\n ) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SUBMIT_VIEW_INVALID\", {\n message: `The view ${viewId} isn't one this page's link opened for this artifact.`,\n }),\n );\n }\n return row;\n}\n","/**\n * The submit transaction (IN-05, IN-07, IN-12; ARCHITECTURE §6, D39, D40, D103, D106). One ledger\n * transaction resolves the view to its exact version, checks the policy in force and the draft\n * revision the viewer saw, reads the canonical persisted draft and artifact state, computes the\n * snapshot's digest, inserts the immutable submission, enqueues one delivery per host, and\n * appends `submission.created` and the `submit` signal. A submission is never made from content\n * the page sent: only from what the ledger holds (IN-06).\n */\nimport { createHash } from \"node:crypto\";\nimport {\n canonicalJson,\n createDiagnostic,\n DeliveryId,\n type DeliveryState,\n type DeliveryStatus,\n type OrphanedField,\n RpcError,\n SubmissionId,\n type SubmissionPolicy,\n type SubmissionSummary,\n type SubmitChannel,\n type Viewer,\n} from \"@mostra/protocol\";\nimport type { LedgerDb } from \"../ledger/index.ts\";\nimport { appendEvent } from \"./events.ts\";\nimport { documentFor, type FieldRow } from \"./fields.ts\";\nimport { storedPolicy } from \"./policy.ts\";\nimport { raiseSubmitSignal, SUBMIT_SIGNAL } from \"./signals.ts\";\nimport { type ViewRow, viewControls, viewer as viewerById, viewFor } from \"./viewers.ts\";\n\n/** The most signals a snapshot keeps: the view's newest. */\nexport const SNAPSHOT_SIGNALS_MAX = 100;\n\n/** The most signal payload text a snapshot keeps. */\nexport const SNAPSHOT_SIGNAL_BYTES_MAX: number = 1024 * 1024;\n\n/**\n * The longest snapshot, in characters: the two 16 MiB documents, labels and signals fit, and the\n * results built from it stay well inside one 64 Mi-character protocol message.\n */\nexport const SNAPSHOT_MAX_LENGTH: number = 40 * 1024 * 1024;\n\n/**\n * The owner of the built-in adapter's deliveries, which accepts at once (D58, D105): empty, since\n * a client name never is, so no host can be taken for it.\n */\nexport const BUILT_IN_OWNER = \"\";\n\n/** One field as a snapshot keeps it. */\nexport interface SnapshotField {\n readonly value: unknown;\n readonly label?: string;\n readonly required?: boolean;\n readonly sensitive?: boolean;\n}\n\n/**\n * The canonical answer document of a submission (DATA_MODEL §3 `snapshot_json`): everything the\n * results are made of, frozen at submit. Its digest is the SHA-256 of its RFC 8785 form.\n */\nexport interface Snapshot {\n readonly schema: 1;\n readonly submissionId: string;\n readonly at: string;\n readonly artifactId: string;\n readonly versionId: string;\n readonly version: number;\n readonly viewId: string;\n readonly viewer: Viewer;\n readonly channel: SubmitChannel;\n readonly policy: SubmissionPolicy;\n readonly epoch: number;\n readonly previous?: string;\n readonly staleView: boolean;\n readonly latestVersion?: number;\n readonly draft: { readonly revision: string; readonly fields: Record<string, SnapshotField> };\n readonly state?: { readonly revision: string; readonly fields: Record<string, SnapshotField> };\n readonly orphaned: readonly {\n readonly id: string;\n readonly label?: string;\n readonly value: unknown;\n readonly fromVersion: number;\n }[];\n readonly signals: readonly {\n readonly name: string;\n readonly at: string;\n readonly payload?: unknown;\n }[];\n readonly signalsOmitted?: number;\n readonly signalsCompacted?: true;\n /**\n * The action runs started in the view before the submission, with their state then (WP-08):\n * at most 100, oldest first. Snapshots made before WP-08 have none.\n */\n readonly actions?: readonly {\n readonly runId: string;\n readonly action: string;\n readonly status: string;\n readonly at: string;\n }[];\n}\n\n/** The most action runs a snapshot lists. */\nconst SNAPSHOT_ACTIONS_MAX = 100;\n\n/** A `submission` row. */\nexport interface SubmissionRow {\n readonly id: string;\n readonly position: number;\n readonly artifact_id: string;\n readonly version_id: string;\n readonly view_id: string;\n readonly viewer_id: string;\n readonly channel: SubmitChannel;\n readonly policy_json: string;\n readonly epoch: number;\n readonly scope_key: string;\n readonly previous_id: string | null;\n readonly draft_document_id: number;\n readonly draft_revision: number;\n readonly state_revision: number | null;\n readonly latest_version_number: number | null;\n readonly snapshot_json: string;\n readonly digest: string;\n readonly stale_view: number;\n readonly created_at: string;\n}\n\ninterface DeliveryRow {\n readonly id: string;\n readonly port_owner: string;\n readonly state: DeliveryState;\n readonly attempts: number;\n readonly reason: string | null;\n readonly last_error_json: string | null;\n readonly updated_at: string;\n}\n\n/**\n * A refused submit that carries the submission already made (H-02): `MOSTRA_SUBMIT_ALREADY` under\n * `once`. The gateway answers it with the submission beside the diagnostic.\n */\nexport class SubmitConflict extends RpcError {\n readonly submission: SubmissionSummary;\n\n constructor(message: string, submission: SubmissionSummary) {\n super(createDiagnostic(\"MOSTRA_SUBMIT_ALREADY\", { message }));\n this.submission = submission;\n }\n}\n\nconst SEVERITY: Readonly<Record<DeliveryState, number>> = {\n delivered: 0,\n pending: 1,\n rejected: 2,\n undeliverable: 3,\n};\n\n/** A submission's deliveries. */\nexport function deliveriesOf(db: LedgerDb, submissionId: string): DeliveryStatus[] {\n return db\n .all<DeliveryRow>(\n \"SELECT * FROM delivery WHERE submission_id = ? ORDER BY port_owner\",\n submissionId,\n )\n .map((row) => ({\n deliveryId: row.id,\n owner: row.port_owner,\n state: row.state,\n attempts: row.attempts,\n ...(row.reason !== null ? { reason: row.reason } : {}),\n ...(row.state === \"pending\" && row.last_error_json !== null\n ? { waiting: true as const }\n : {}),\n updatedAt: row.updated_at,\n }));\n}\n\n/** Every delivery's state summed up: the worst of them (`delivered` when there are none). */\nexport function overallDelivery(deliveries: readonly DeliveryStatus[]): DeliveryState {\n let worst: DeliveryState = \"delivered\";\n for (const delivery of deliveries)\n if (SEVERITY[delivery.state] > SEVERITY[worst]) worst = delivery.state;\n return worst;\n}\n\n/** A submission as a submit answers it. */\nexport function submissionSummary(db: LedgerDb, row: SubmissionRow): SubmissionSummary {\n const snapshot = JSON.parse(row.snapshot_json) as Snapshot;\n return {\n id: row.id,\n at: row.created_at,\n epoch: row.epoch,\n channel: row.channel,\n versionId: row.version_id,\n version: snapshot.version,\n viewId: row.view_id,\n staleView: row.stale_view === 1,\n draftRevision: String(row.draft_revision),\n digest: row.digest,\n ...(() => {\n const deliveries = deliveriesOf(db, row.id);\n return { delivery: overallDelivery(deliveries), deliveries };\n })(),\n };\n}\n\n/** The submission that closes a viewer's draft under `once`, if any (D106). */\nexport function closingSubmission(\n db: LedgerDb,\n artifactId: string,\n viewerId: string,\n): SubmissionRow | undefined {\n const artifact = db.get<{ policy_json: string | null }>(\n \"SELECT policy_json FROM artifact WHERE id = ?\",\n artifactId,\n );\n if (!artifact) return undefined;\n const policy = storedPolicy(artifact.policy_json);\n if (policy.policy !== \"once\") return undefined;\n return policy.scope === \"per-viewer\"\n ? db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE artifact_id = ? AND viewer_id = ? ORDER BY position LIMIT 1\",\n artifactId,\n viewerId,\n )\n : db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE artifact_id = ? ORDER BY position LIMIT 1\",\n artifactId,\n );\n}\n\n/** Refuses a write to a draft that a `once` submission closed (D106). */\nexport function assertDraftOpen(db: LedgerDb, artifactId: string, viewerId: string): void {\n const closing = closingSubmission(db, artifactId, viewerId);\n if (closing) {\n throw new SubmitConflict(\n `A submission made at ${closing.created_at} closed this draft: the artifact takes one submission.`,\n submissionSummary(db, closing),\n );\n }\n}\n\nfunction snapshotFields(rows: readonly FieldRow[]): Record<string, SnapshotField> {\n // fromEntries defines own properties, so a field ID such as `__proto__` stays a field.\n return Object.fromEntries(\n rows.map((row) => [\n row.field_id,\n {\n value: JSON.parse(row.value_json) as unknown,\n ...(row.label !== null ? { label: row.label } : {}),\n ...(row.required !== null ? { required: row.required === 1 } : {}),\n ...(row.sensitive === 1 ? { sensitive: true } : {}),\n },\n ]),\n );\n}\n\n/**\n * Refuses a submit through a channel the view doesn't accept (D40, D108):\n * `MOSTRA_SUBMIT_CHANNEL_DENIED`.\n */\nexport function assertChannel(view: ViewRow, channel: SubmitChannel): void {\n if (viewControls(view).submitChannels.includes(channel)) return;\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SUBMIT_CHANNEL_DENIED\", {\n message:\n channel === \"artifact\"\n ? \"This view takes submissions and choices from the shell's trusted controls only.\"\n : \"This view takes submissions and choices from the artifact's own code only.\",\n }),\n );\n}\n\n/**\n * Draft fields a view's version doesn't cover, as results deliver them (D42, D109). A field\n * records the version whose view last wrote it; one written before Mostra kept that (an\n * unreleased ledger of WP-06's time, which migration 6 fills from its events where it can) is\n * attributed to version 1, the earliest it can have come from.\n */\nexport function orphansOf(rows: readonly FieldRow[]): OrphanedField[] {\n return rows.map((row) => ({\n id: row.field_id,\n ...(row.label !== null ? { label: row.label } : {}),\n value: JSON.parse(row.value_json) as unknown,\n fromVersion: row.version_number ?? 1,\n }));\n}\n\n/** What a submit names. */\nexport interface SubmitInput {\n readonly artifactId: string;\n /** The viewer whose session submits. */\n readonly viewerId: string;\n /** The link the page's session came from: the view must be one it opened. */\n readonly tokenId?: string;\n /** The view the page was opened as; its version is what the submission names (D104). */\n readonly viewId: string;\n /** The draft revision the viewer saw. */\n readonly expectedRevision: number;\n readonly channel: SubmitChannel;\n /** The hosts to deliver to (D105): registered or expected now; empty for the built-in adapter. */\n readonly owners: readonly string[];\n /** Whether the view's version covers a field ID (D109); the others are the orphans. */\n readonly covers: (versionId: string) => (fieldId: string) => boolean;\n}\n\n/** What a submit did. */\nexport interface SubmitOutcome {\n readonly submission: SubmissionSummary;\n /** `false` when it returned an earlier submission of the same view and revision (D22). */\n readonly created: boolean;\n}\n\n/**\n * Submits a viewer's draft, in the caller's write transaction (ARCHITECTURE §6). Refusals:\n * `MOSTRA_SUBMIT_VIEW_INVALID` for a view of another viewer or artifact,\n * `MOSTRA_SUBMIT_POLICY_NONE`, `MOSTRA_SUBMIT_ALREADY` (a {@link SubmitConflict}) under `once`,\n * `MOSTRA_SUBMIT_REVISION_MOVED` when the draft changed since the viewer saw it.\n */\nexport function submit(db: LedgerDb, input: SubmitInput): SubmitOutcome {\n // 1. The view, and through it the exact version the viewer saw, and the channels it accepts.\n const view = viewFor(db, input.viewId, input.artifactId, input.viewerId, input.tokenId);\n assertChannel(view, input.channel);\n const draft = documentFor(db, input.artifactId, input.viewerId, true);\n // A repeat of the same submit (double click, retry, a second request in flight) gets the\n // submission it made (D22), whatever has happened since.\n const repeat = db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE view_id = ? AND draft_document_id = ? AND draft_revision = ? ORDER BY position DESC LIMIT 1\",\n view.id,\n draft.id,\n input.expectedRevision,\n );\n if (repeat)\n return { submission: { ...submissionSummary(db, repeat), duplicate: true }, created: false };\n\n // 2. The policy in force.\n const artifact = db.get<{ policy_json: string | null; latest_version_id: string | null }>(\n \"SELECT policy_json, latest_version_id FROM artifact WHERE id = ?\",\n input.artifactId,\n );\n if (!artifact) throw new Error(`No artifact ${input.artifactId}.`);\n const policy = storedPolicy(artifact.policy_json);\n if (policy.policy === \"none\") {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SUBMIT_POLICY_NONE\", {\n message: \"This artifact's submission policy is none: it takes no submissions.\",\n }),\n );\n }\n const closing = closingSubmission(db, input.artifactId, input.viewerId);\n if (closing) {\n throw new SubmitConflict(\n `This artifact takes one submission ${policy.policy === \"once\" && policy.scope === \"per-viewer\" ? \"per viewer\" : \"in all\"}, and it was made at ${closing.created_at}.`,\n submissionSummary(db, closing),\n );\n }\n\n // 3. The draft revision the viewer saw.\n if (draft.revision !== input.expectedRevision) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SUBMIT_REVISION_MOVED\", {\n message: `The draft is at revision ${draft.revision}, not ${input.expectedRevision}: it changed after the viewer saw it.`,\n }),\n );\n }\n\n // 4. The canonical persisted draft and the artifact state at its current revision.\n const draftRows = db.all<FieldRow>(\n \"SELECT * FROM field WHERE document_id = ? AND deleted = 0 ORDER BY field_id\",\n draft.id,\n );\n const state = documentFor(db, input.artifactId, null);\n const stateRows = state\n ? db.all<FieldRow>(\n \"SELECT * FROM field WHERE document_id = ? AND deleted = 0 ORDER BY field_id\",\n state.id,\n )\n : [];\n const version = db.get<{ number: number }>(\n \"SELECT number FROM version WHERE id = ?\",\n view.version_id,\n ) as { number: number };\n const covered = input.covers(view.version_id);\n const latest =\n artifact.latest_version_id === null\n ? undefined\n : db.get<{ id: string; number: number }>(\n \"SELECT id, number FROM version WHERE id = ?\",\n artifact.latest_version_id,\n );\n const staleView = latest !== undefined && latest.id !== view.version_id;\n\n // Epochs (D103): the viewer's next round; once: the one submission of its scope.\n const scopeKey =\n policy.policy === \"once\" && policy.scope === \"per-artifact\" ? \"\" : input.viewerId;\n const previous =\n policy.policy === \"epochs\"\n ? db.get<{ id: string; epoch: number }>(\n \"SELECT id, epoch FROM submission WHERE artifact_id = ? AND viewer_id = ? ORDER BY position DESC LIMIT 1\",\n input.artifactId,\n input.viewerId,\n )\n : undefined;\n const epoch =\n policy.policy === \"epochs\"\n ? Math.max(\n draft.epoch,\n (db.get<{ epoch: number | null }>(\n \"SELECT MAX(epoch) AS epoch FROM submission WHERE artifact_id = ? AND scope_key = ?\",\n input.artifactId,\n scopeKey,\n )?.epoch ?? 0) + 1,\n )\n : 1;\n\n const submissionId = SubmissionId.create();\n const at = new Date().toISOString();\n const viewerRecord = viewerById(db, input.viewerId);\n // The view's signals, newest first up to the limits, so a snapshot stays bounded however many\n // a page raised (Claude review finding 2); the count left out is recorded.\n const signalRows = db.all<{ at: string; payload_json: string }>(\n \"SELECT at, payload_json FROM event WHERE artifact_id = ? AND type = 'signal.raised' AND json_extract(payload_json, '$.viewId') = ? AND json_extract(payload_json, '$.name') != ? ORDER BY cursor DESC LIMIT ?\",\n input.artifactId,\n view.id,\n SUBMIT_SIGNAL,\n SNAPSHOT_SIGNALS_MAX,\n );\n const signals: { name: string; at: string; payload?: unknown }[] = [];\n let signalBytes = 0;\n for (const row of signalRows) {\n signalBytes += row.payload_json.length;\n if (signalBytes > SNAPSHOT_SIGNAL_BYTES_MAX) break;\n const payload = JSON.parse(row.payload_json) as { name: string; payload?: unknown };\n signals.unshift({\n name: payload.name,\n at: row.at,\n ...(payload.payload !== undefined ? { payload: payload.payload } : {}),\n });\n }\n const signalCount =\n db.get<{ n: number }>(\n \"SELECT COUNT(*) AS n FROM event WHERE artifact_id = ? AND type = 'signal.raised' AND json_extract(payload_json, '$.viewId') = ? AND json_extract(payload_json, '$.name') != ?\",\n input.artifactId,\n view.id,\n SUBMIT_SIGNAL,\n )?.n ?? 0;\n const signalsOmitted = signalCount - signals.length;\n // Compaction may have removed some of the view's signals; the snapshot says so (finding 10).\n const signalsCompacted =\n view.opened_cursor !== null &&\n db.get(\n \"SELECT 1 FROM event WHERE artifact_id = ? AND type = 'artifact.compacted' AND cursor >= ? AND json_extract(payload_json, '$.types.\\\"signal.raised\\\"') > 0\",\n input.artifactId,\n view.opened_cursor,\n ) !== undefined;\n // The view's action runs, as they stood when the viewer submitted (D101: results list them).\n const actions = db\n .all<{ id: string; action: string; status: string; started_at: string }>(\n \"SELECT id, action, status, started_at FROM action_run WHERE view_id = ? ORDER BY started_at, id LIMIT ?\",\n view.id,\n SNAPSHOT_ACTIONS_MAX,\n )\n .map((run) => ({ runId: run.id, action: run.action, status: run.status, at: run.started_at }));\n const snapshot: Snapshot = {\n schema: 1,\n submissionId,\n at,\n artifactId: input.artifactId,\n versionId: view.version_id,\n version: version.number,\n viewId: view.id,\n viewer: viewerRecord,\n channel: input.channel,\n policy,\n epoch,\n ...(previous ? { previous: previous.id } : {}),\n staleView,\n ...(staleView && latest ? { latestVersion: latest.number } : {}),\n draft: {\n revision: String(draft.revision),\n fields: snapshotFields(draftRows.filter((row) => covered(row.field_id))),\n },\n ...(state\n ? { state: { revision: String(state.revision), fields: snapshotFields(stateRows) } }\n : {}),\n // Fields the view's version doesn't cover are delivered too, labelled (D42, D109).\n orphaned: orphansOf(draftRows.filter((row) => !covered(row.field_id))),\n signals,\n ...(signalsOmitted > 0 ? { signalsOmitted } : {}),\n ...(signalsCompacted ? { signalsCompacted: true as const } : {}),\n actions,\n };\n\n // 5. The digest of the canonical snapshot, which must fit one protocol message with room to\n // spare, or no host could ever receive it.\n const snapshotJson = canonicalJson(snapshot);\n if (snapshotJson.length > SNAPSHOT_MAX_LENGTH) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_FIELD_TOO_LARGE\", {\n message: `This submission would be ${snapshotJson.length} characters, more than a submission may hold (${SNAPSHOT_MAX_LENGTH}).`,\n }),\n );\n }\n const digest = createHash(\"sha256\").update(snapshotJson, \"utf8\").digest(\"hex\");\n\n // 8 (first, for its cursor). `submission.created`; its cursor is the submission's position,\n // the order deliveries replay in.\n const actor = { kind: \"viewer\" as const, id: input.viewerId };\n const causation = { submissionId };\n const position = Number(\n appendEvent(db, {\n artifactId: input.artifactId,\n type: \"submission.created\",\n actor,\n causation,\n payload: {\n submissionId,\n versionId: view.version_id,\n version: version.number,\n viewId: view.id,\n viewerId: input.viewerId,\n channel: input.channel,\n epoch,\n staleView,\n digest,\n },\n }),\n );\n // 6. The immutable submission.\n db.run(\n `INSERT INTO submission (id, position, artifact_id, version_id, view_id, viewer_id, channel, policy_json, epoch, scope_key,\n previous_id, draft_document_id, draft_revision, state_revision, latest_version_number, snapshot_json, digest, stale_view, request_id, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)`,\n submissionId,\n position,\n input.artifactId,\n view.version_id,\n view.id,\n input.viewerId,\n input.channel,\n JSON.stringify(policy),\n epoch,\n scopeKey,\n previous?.id ?? null,\n draft.id,\n draft.revision,\n state?.revision ?? null,\n staleView && latest ? latest.number : null,\n snapshotJson,\n digest,\n staleView ? 1 : 0,\n at,\n );\n // The next round starts with the same values (D103).\n if (policy.policy === \"epochs\") {\n db.run(\"UPDATE document SET epoch = ? WHERE id = ?\", epoch + 1, draft.id);\n }\n // 7. One delivery per host, durable with the submission (IN-12).\n const owners = input.owners.length > 0 ? [...new Set(input.owners)].sort() : [BUILT_IN_OWNER];\n for (const owner of owners) {\n db.run(\n \"INSERT INTO delivery (id, submission_id, position, port_owner, state, attempts, next_attempt_at, updated_at) VALUES (?, ?, ?, ?, 'pending', 0, ?, ?)\",\n DeliveryId.create(),\n submissionId,\n position,\n owner,\n at,\n at,\n );\n }\n // Submit is the standard signal (D106).\n raiseSubmitSignal(db, {\n artifactId: input.artifactId,\n submissionId,\n channel: input.channel,\n actor,\n viewId: view.id,\n });\n const row = db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE id = ?\",\n submissionId,\n ) as SubmissionRow;\n return { submission: submissionSummary(db, row), created: true };\n}\n","/**\n * Results (IN-11, INTERFACES §8): the complete submission as JSON and as Markdown for agents.\n * Everything comes from the immutable submission row, its snapshot and the version it names, plus\n * the deliveries' current states; never from the live draft (IN-06).\n */\nimport type { ArtifactLink, ArtifactManifest, DeliveryStatus, Results } from \"@mostra/protocol\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { LedgerDb } from \"../ledger/index.ts\";\nimport {\n deliveriesOf,\n overallDelivery,\n type Snapshot,\n type SnapshotField,\n type SubmissionRow,\n} from \"./submissions.ts\";\n\n/** The field ID a review set's choice is kept under (D65): `review.<set>.choice`. */\nexport const CHOICE: RegExp = /^review\\.(.+)\\.choice$/;\n\n/**\n * Nests dotted field IDs into objects (D52): `reply.m1` becomes `{ reply: { m1 } }`. A value never\n * gets keys merged into it: when `a` holds a value and `a.b` exists too, `a.b` stays a literal key\n * beside it, so no answer is lost or altered.\n */\nexport function nestFields(\n fields: Readonly<Record<string, SnapshotField>>,\n): Record<string, unknown> {\n // Objects without a prototype, written with defineProperty, so a field ID such as `__proto__`\n // is an ordinary key.\n const make = (): Record<string, unknown> => Object.create(null) as Record<string, unknown>;\n const set = (node: Record<string, unknown>, key: string, value: unknown): void => {\n Object.defineProperty(node, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n };\n const root = make();\n const made = new Set<object>([root]);\n for (const id of Object.keys(fields).sort()) {\n const value = (fields[id] as SnapshotField).value;\n const parts = id.split(\".\");\n let node = root;\n let index = 0;\n for (; index < parts.length - 1; index++) {\n const key = parts[index] as string;\n const next = Object.hasOwn(node, key) ? node[key] : undefined;\n if (next === undefined) {\n const child = make();\n made.add(child);\n set(node, key, child);\n node = child;\n } else if (typeof next === \"object\" && next !== null && made.has(next)) {\n node = next as Record<string, unknown>;\n } else {\n break;\n }\n }\n const rest = parts.slice(index).join(\".\");\n if (!Object.hasOwn(node, rest)) set(node, rest, value);\n else set(root, id, value);\n }\n return root;\n}\n\nfunction notFound(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_SUBMIT_NOT_FOUND\", { message }));\n}\n\n/**\n * The submission an artifact's results are read from: the one named, or the latest. Throws\n * `MOSTRA_SUBMIT_NOT_FOUND` when there is none.\n */\nexport function submissionFor(\n db: LedgerDb,\n artifactId: string,\n submissionId: string | undefined,\n): SubmissionRow {\n const row =\n submissionId === undefined\n ? db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE artifact_id = ? ORDER BY position DESC LIMIT 1\",\n artifactId,\n )\n : db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE id = ? AND artifact_id = ?\",\n submissionId,\n artifactId,\n );\n if (!row) {\n throw notFound(\n submissionId === undefined\n ? `The artifact ${artifactId} has no submission yet.`\n : `The artifact ${artifactId} has no submission ${submissionId}.`,\n );\n }\n return row;\n}\n\n/** The complete results of a submission (INTERFACES §8). */\nexport function buildResults(db: LedgerDb, row: SubmissionRow): Results {\n const snapshot = JSON.parse(row.snapshot_json) as Snapshot;\n const version = db.get<{ manifest_json: string }>(\n \"SELECT manifest_json FROM version WHERE id = ?\",\n row.version_id,\n );\n const manifest = version ? (JSON.parse(version.manifest_json) as ArtifactManifest) : undefined;\n const artifactRow = db.get<{ title: string; family: string | null; links_json: string }>(\n \"SELECT title, family, links_json FROM artifact WHERE id = ?\",\n row.artifact_id,\n );\n const family = manifest ? manifest.family : (artifactRow?.family ?? undefined);\n const links = manifest\n ? (manifest.links ?? [])\n : (JSON.parse(artifactRow?.links_json ?? \"[]\") as ArtifactLink[]);\n const deliveries: DeliveryStatus[] = deliveriesOf(db, row.id);\n const draftFields = snapshot.draft.fields;\n const stateFields = snapshot.state?.fields;\n const describe = (id: string, field: SnapshotField, scope: \"viewer\" | \"artifact\") => ({\n id,\n ...(field.label !== undefined ? { label: field.label } : {}),\n ...(field.required !== undefined ? { required: field.required } : {}),\n ...(field.sensitive ? { sensitive: true } : {}),\n scope,\n });\n return {\n artifact: {\n id: row.artifact_id,\n title: manifest?.title ?? artifactRow?.title ?? row.artifact_id,\n ...(manifest?.description !== undefined ? { description: manifest.description } : {}),\n ...(family !== undefined && family !== null ? { family } : {}),\n links,\n },\n submission: {\n id: row.id,\n at: row.created_at,\n epoch: row.epoch,\n ...(row.previous_id !== null ? { previous: row.previous_id } : {}),\n policy: snapshot.policy,\n channel: row.channel,\n viewer: snapshot.viewer,\n versionId: row.version_id,\n version: snapshot.version,\n viewId: row.view_id,\n staleView: row.stale_view === 1,\n ...(row.latest_version_number !== null ? { latestVersion: row.latest_version_number } : {}),\n draftRevision: String(row.draft_revision),\n ...(row.state_revision !== null ? { stateRevision: String(row.state_revision) } : {}),\n digest: row.digest,\n delivery: overallDelivery(deliveries),\n deliveries,\n },\n answers: nestFields(draftFields),\n fields: [\n ...Object.keys(draftFields)\n .sort()\n .map((id) => describe(id, draftFields[id] as SnapshotField, \"viewer\")),\n ...Object.keys(stateFields ?? {})\n .sort()\n .map((id) =>\n describe(\n id,\n (stateFields as Record<string, SnapshotField>)[id] as SnapshotField,\n \"artifact\",\n ),\n ),\n ],\n ...(stateFields ? { state: nestFields(stateFields) } : {}),\n choices: Object.keys(draftFields)\n .sort()\n .flatMap((id) => {\n const match = CHOICE.exec(id);\n const field = draftFields[id] as SnapshotField;\n // The trusted Choose keeps the candidate's label as the field's (D113).\n return match && typeof field.value === \"string\"\n ? [\n {\n reviewSetId: match[1] as string,\n candidateId: field.value,\n ...(field.label !== undefined ? { label: field.label } : {}),\n },\n ]\n : [];\n }),\n comments: [],\n orphaned: snapshot.orphaned,\n actions: snapshot.actions ?? [],\n signals: snapshot.signals,\n ...(snapshot.signalsOmitted !== undefined ? { signalsOmitted: snapshot.signalsOmitted } : {}),\n ...(snapshot.signalsCompacted ? { signalsCompacted: true as const } : {}),\n };\n}\n\n/**\n * Text from viewers and hosts is data in the Markdown, never structure (Claude review finding 4):\n * labels and string values are JSON strings, identifiers and JSON are code spans whose delimiters\n * outrun any backticks inside, multi-line text sits in a fence longer than any backtick run in it,\n * and everything else is folded onto one line.\n */\nconst LINE_BREAKS = /\\r\\n|\\r|\\n|\\u2028|\\u2029/;\n\n/** Control characters and line separators as spaces: the text stays on its line. */\nfunction oneLine(text: string): string {\n // biome-ignore lint/suspicious/noControlCharactersInRegex: replacing them is the point.\n return text.replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g, \" \");\n}\n\n/** The longest run of backticks in `text`. */\nfunction longestBacktickRun(text: string): number {\n let longest = 0;\n for (const run of text.match(/`+/g) ?? []) longest = Math.max(longest, run.length);\n return longest;\n}\n\n/** `text` as an inline code span that nothing inside can close. */\nexport function code(text: string): string {\n const line = oneLine(text);\n const ticks = \"`\".repeat(longestBacktickRun(line) + 1);\n const pad = line.startsWith(\"`\") || line.endsWith(\"`\") || line.trim() === \"\" ? \" \" : \"\";\n return `${ticks}${pad}${line}${pad}${ticks}`;\n}\n\n/** `text` as a JSON string: quoted, with its line breaks and controls escaped. */\nfunction quoted(text: string): string {\n return oneLine(JSON.stringify(text));\n}\n\n/** A value as one Markdown line, or a fenced block for text with line breaks. */\nfunction markdownValue(value: unknown): string {\n if (typeof value === \"string\") {\n if (!LINE_BREAKS.test(value)) return quoted(value);\n const fence = \"`\".repeat(Math.max(3, longestBacktickRun(value) + 1));\n const body = value\n .split(LINE_BREAKS)\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n return `\\n\\n ${fence}text\\n${body}\\n ${fence}\\n`;\n }\n return code(JSON.stringify(value));\n}\n\n/** A field's name: its label as a JSON string, then its ID as code. */\nfunction fieldName(id: string, label: string | undefined): string {\n return label !== undefined ? `${quoted(label)} (${code(id)})` : code(id);\n}\n\nfunction fieldLines(fields: Readonly<Record<string, SnapshotField>>): string[] {\n const ids = Object.keys(fields).sort();\n if (ids.length === 0) return [\"- (none)\"];\n return ids.map((id) => {\n const field = fields[id] as SnapshotField;\n return `- ${fieldName(id, field.label)}: ${markdownValue(field.value)}`;\n });\n}\n\n/**\n * Results as Markdown for agents (ROUND-2 §1.1): a header with the IDs, then answers by label,\n * the artifact state, choices, comments with their crop paths, actions, signals, and what didn't\n * carry over. Every section is present, with \"(none)\" when empty, so an agent never wonders\n * whether a section was dropped. Viewers' and hosts' text is rendered as data, so no answer,\n * label or reason can forge a section.\n */\nexport function resultsMarkdown(results: Results, snapshot: Snapshot): string {\n const { submission } = results;\n const viewer = submission.viewer.name ?? submission.viewer.ref ?? submission.viewer.id;\n const signalNotes = [\n ...(results.signalsOmitted !== undefined\n ? [`- (${results.signalsOmitted} older signals of this view left out)`]\n : []),\n ...(results.signalsCompacted ? [\"- (some signals may have been removed by compaction)\"] : []),\n ];\n const lines = [\n `# ${oneLine(results.artifact.title)}: submission ${submission.id}`,\n \"\",\n `- Artifact: ${results.artifact.id}${results.artifact.family ? ` (${code(results.artifact.family)})` : \"\"}`,\n `- Version: ${submission.versionId} (version ${submission.version})${submission.staleView ? `, a stale view: version ${submission.latestVersion ?? \"?\"} was the latest` : \"\"}`,\n `- View: ${submission.viewId}, channel ${submission.channel}, viewer ${quoted(viewer)} (${submission.viewer.id})`,\n `- Submitted: ${submission.at}, epoch ${submission.epoch}${submission.previous ? ` (after ${submission.previous})` : \"\"}, policy ${submission.policy.policy}${submission.policy.policy === \"once\" ? ` ${submission.policy.scope ?? \"per-artifact\"}` : \"\"}`,\n `- Draft revision ${submission.draftRevision}${submission.stateRevision !== undefined ? `, artifact state revision ${submission.stateRevision}` : \"\"}, digest ${submission.digest}`,\n `- Delivery: ${submission.delivery}${submission.deliveries.length > 0 ? ` (${submission.deliveries.map((delivery) => `${delivery.owner === \"\" ? \"built-in\" : quoted(delivery.owner)}: ${delivery.state}${delivery.reason ? `, ${quoted(delivery.reason)}` : \"\"}`).join(\"; \")})` : \"\"}`,\n ...(results.artifact.links.length > 0\n ? [\n `- Links: ${results.artifact.links.map((link) => `${code(link.rel)} ${code(link.artifact)}`).join(\", \")}`,\n ]\n : []),\n \"\",\n \"## Answers\",\n ...fieldLines(snapshot.draft.fields),\n \"\",\n \"## Artifact state\",\n ...(snapshot.state ? fieldLines(snapshot.state.fields) : [\"- (none)\"]),\n \"\",\n \"## Choices\",\n ...(results.choices.length > 0\n ? results.choices.map(\n (choice) =>\n `- ${code(choice.reviewSetId)}: ${quoted(choice.candidateId)}${choice.label ? ` (${quoted(choice.label)})` : \"\"}`,\n )\n : [\"- (none)\"]),\n \"\",\n \"## Comments\",\n ...(results.comments.length > 0\n ? results.comments.flatMap((comment) => [\n `- Thread ${comment.threadId} (${comment.status}), crop ${code(comment.crop.path)}${comment.anchor.reviewId ? `, on ${code(comment.anchor.reviewId)}` : \"\"}${comment.anchor.page ? `, page ${code(comment.anchor.page)}` : \"\"}`,\n ...comment.messages.map(\n (message) =>\n ` - ${quoted(message.author.name ?? message.author.id)} at ${message.at}: ${quoted(message.text)}`,\n ),\n ])\n : [\"- (none)\"]),\n \"\",\n \"## Actions run in this view\",\n ...(results.actions.length > 0\n ? results.actions.map(\n (run) => `- ${code(run.action)}: ${run.status} at ${run.at} (run ${run.runId})`,\n )\n : [\"- (none)\"]),\n \"\",\n \"## Signals raised in this view\",\n ...(results.signals.length > 0 || signalNotes.length > 0\n ? [\n ...signalNotes,\n ...results.signals.map(\n (signal) =>\n `- ${code(signal.name)} at ${signal.at}${signal.payload !== undefined ? `: ${code(JSON.stringify(signal.payload))}` : \"\"}`,\n ),\n ]\n : [\"- (none)\"]),\n \"\",\n \"## Not carried over from an earlier version\",\n ...(results.orphaned.length > 0\n ? results.orphaned.map(\n (orphan) =>\n `- ${fieldName(orphan.id, orphan.label)} from version ${orphan.fromVersion}: ${markdownValue(orphan.value)}`,\n )\n : [\"- (none)\"]),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n","/**\n * The outbox (IN-12, H-04, D105; FAILURE_MODEL §4): delivers each submission, after it is\n * durable, to every host it was enqueued for, through the host's `submissions` port, and mirrors\n * drafts to hosts with a `drafts` port. Each host's deliveries go out one at a time in submission\n * order; a retryable failure keeps the head pending with backoff (1 s doubling to 5 min) and a host\n * that isn't connected gets its deliveries when it registers again, in order. A host's terminal\n * answer is recorded once and never retried. The delivery row is the state: after a crash, a\n * delivery the host acknowledged but Mostra didn't record goes out again with the same ID.\n */\nimport {\n type DeliveryState,\n type DraftMirror,\n MAX_LINE_LENGTH,\n portDraftsMirrorMethod,\n portSubmissionsDeliverMethod,\n type SubmissionEnvelope,\n type SubmissionsDeliverResult,\n} from \"@mostra/protocol\";\nimport type { Faults } from \"../faults.ts\";\nimport type { Ledger, LedgerDb } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { appendEvent } from \"./events.ts\";\nimport { documentFor, liveFields } from \"./fields.ts\";\nimport { buildResults } from \"./results.ts\";\nimport { BUILT_IN_OWNER, type SubmissionRow } from \"./submissions.ts\";\n\n/** How long a host has to answer one port call (FAILURE_MODEL §9). */\nexport const PORT_CALL_TIMEOUT_MS = 30_000;\n\n/** Room for the JSON-RPC request around an envelope (`jsonrpc`, `id`, `method`, newline). */\nconst ENVELOPE_FRAME_SLACK = 1024;\n\n/** The first retry's delay; each later one doubles, up to {@link MAX_BACKOFF_MS}. */\nexport const FIRST_BACKOFF_MS = 1_000;\n\n/** The longest delay between retries (FAILURE_MODEL §4). */\nexport const MAX_BACKOFF_MS: number = 5 * 60_000;\n\n/** The delay before retry number `attempts` + 1. */\nexport function backoffMs(attempts: number): number {\n return Math.min(MAX_BACKOFF_MS, FIRST_BACKOFF_MS * 2 ** Math.max(0, attempts - 1));\n}\n\n/** The connections that registered ports, as the outbox sees them. */\nexport interface HostConnections {\n /** The connections that registered `port`, newest last, with their hosts' client names. */\n registrants(port: string): readonly { readonly session: number; readonly owner: string }[];\n /** Calls a port method on one connection; rejects on a transport failure or the timeout. */\n call(session: number, method: string, params: unknown, timeoutMs: number): Promise<unknown>;\n}\n\n/** Options for {@link Outbox}. */\nexport interface OutboxOptions {\n readonly ledger: Ledger;\n readonly log: Log;\n readonly hosts: HostConnections;\n /** The hosts that always provide the submissions port (`HomeConfig.ports`, D105). */\n readonly expected: () => readonly string[];\n readonly faults: Faults;\n /** The clock (tests move it). */\n readonly now?: () => number;\n /** How long a host has to answer a port call; default {@link PORT_CALL_TIMEOUT_MS}. */\n readonly portTimeoutMs?: number;\n}\n\ninterface DeliveryRow {\n readonly id: string;\n readonly submission_id: string;\n readonly position: number;\n readonly port_owner: string;\n readonly state: DeliveryState;\n readonly attempts: number;\n readonly next_attempt_at: string | null;\n readonly last_error_json: string | null;\n}\n\ntype Outcome =\n | { readonly kind: \"delivered\"; readonly reason?: string }\n | {\n readonly kind: \"terminal\";\n readonly state: \"rejected\" | \"undeliverable\";\n readonly reason: string;\n }\n | { readonly kind: \"retry\"; readonly error: string };\n\n/** The outbox of one instance. */\nexport class Outbox {\n readonly #options: OutboxOptions;\n readonly #now: () => number;\n readonly #running = new Set<string>();\n readonly #again = new Set<string>();\n readonly #timers = new Map<string, ReturnType<typeof setTimeout>>();\n readonly #mirroring = new Map<string, { dirty: boolean }>();\n #unsubscribe: (() => void) | undefined;\n #stopped = false;\n\n constructor(options: OutboxOptions) {\n this.#options = options;\n this.#now = options.now ?? Date.now;\n }\n\n /** The hosts a submission made now is delivered to: registered or expected (D105). */\n owners(): string[] {\n const registered = this.#options.hosts\n .registrants(\"submissions\")\n .map((registrant) => registrant.owner);\n return [...new Set([...registered, ...this.#options.expected()])].sort();\n }\n\n /** Starts delivering: every commit may have enqueued something. */\n start(): void {\n this.#unsubscribe = this.#options.ledger.onCommit(() => this.kick());\n this.kick();\n }\n\n /** Stops delivering; a call in flight finishes but nothing new starts. */\n stop(): void {\n this.#stopped = true;\n this.#unsubscribe?.();\n for (const timer of this.#timers.values()) clearTimeout(timer);\n this.#timers.clear();\n }\n\n /**\n * A host registered its submissions port (again): its pending deliveries are due now, and replay\n * in submission order (FAILURE_MODEL §4).\n */\n registered(owner: string): void {\n const now = new Date(this.#now()).toISOString();\n this.#options.ledger.write((db) =>\n db.run(\n \"UPDATE delivery SET next_attempt_at = ? WHERE port_owner = ? AND state = 'pending'\",\n now,\n owner,\n ),\n );\n this.kick();\n }\n\n /** Looks for work for every host with pending deliveries. */\n kick(): void {\n if (this.#stopped) return;\n const owners = this.#options.ledger.read((db) =>\n db.all<{ port_owner: string }>(\n \"SELECT DISTINCT port_owner FROM delivery WHERE state = 'pending'\",\n ),\n );\n for (const { port_owner: owner } of owners) void this.#pump(owner);\n }\n\n /** Each host's deliveries by state, for `instance/status`. */\n counts(): {\n owner: string;\n connected: boolean;\n pending: number;\n delivered: number;\n rejected: number;\n undeliverable: number;\n }[] {\n const rows = this.#options.ledger.read((db) =>\n db.all<{ port_owner: string; state: DeliveryState; count: number }>(\n \"SELECT port_owner, state, COUNT(*) AS count FROM delivery GROUP BY port_owner, state\",\n ),\n );\n const connected = new Set(\n this.#options.hosts.registrants(\"submissions\").map((registrant) => registrant.owner),\n );\n const byOwner = new Map<\n string,\n {\n owner: string;\n connected: boolean;\n pending: number;\n delivered: number;\n rejected: number;\n undeliverable: number;\n }\n >();\n for (const row of rows) {\n const entry = byOwner.get(row.port_owner) ?? {\n owner: row.port_owner,\n connected: row.port_owner === BUILT_IN_OWNER || connected.has(row.port_owner),\n pending: 0,\n delivered: 0,\n rejected: 0,\n undeliverable: 0,\n };\n entry[row.state] = row.count;\n byOwner.set(row.port_owner, entry);\n }\n return [...byOwner.values()].sort((a, b) => (a.owner < b.owner ? -1 : 1));\n }\n\n async #pump(owner: string): Promise<void> {\n if (this.#running.has(owner)) {\n this.#again.add(owner);\n return;\n }\n this.#running.add(owner);\n try {\n do {\n this.#again.delete(owner);\n while (!this.#stopped && (await this.#step(owner))) {\n // One delivery at a time, in order.\n }\n } while (this.#again.has(owner) && !this.#stopped);\n } catch (error) {\n this.#options.log.error(\"outbox.failed\", { owner, error });\n } finally {\n this.#running.delete(owner);\n }\n }\n\n /** Delivers the owner's next pending delivery; `false` when there is nothing to do now. */\n async #step(owner: string): Promise<boolean> {\n const { ledger, hosts, log, faults } = this.#options;\n const head = ledger.read((db) =>\n db.get<DeliveryRow>(\n \"SELECT * FROM delivery WHERE port_owner = ? AND state = 'pending' ORDER BY position LIMIT 1\",\n owner,\n ),\n );\n if (!head) return false;\n if (owner === BUILT_IN_OWNER) {\n this.#record(head, { kind: \"delivered\" });\n return true;\n }\n const due = head.next_attempt_at === null ? 0 : Date.parse(head.next_attempt_at);\n const wait = due - this.#now();\n if (wait > 0) {\n this.#schedule(owner, wait);\n return false;\n }\n const registrant = hosts\n .registrants(\"submissions\")\n .filter((entry) => entry.owner === owner)\n .at(-1);\n // Not connected: its deliveries wait for it to register again, and the viewer learns that\n // the submission is waiting (IN-13).\n if (!registrant) {\n if (head.last_error_json === null) this.#waiting(head, \"The host isn't connected.\");\n return false;\n }\n const attempt = head.attempts + 1;\n const envelope = ledger.write((db) => {\n db.run(\n \"UPDATE delivery SET attempts = ?, updated_at = ? WHERE id = ?\",\n attempt,\n new Date(this.#now()).toISOString(),\n head.id,\n );\n const submission = db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE id = ?\",\n head.submission_id,\n ) as SubmissionRow;\n const envelope: SubmissionEnvelope = {\n kind: \"submission\",\n deliveryId: head.id,\n submissionId: submission.id,\n artifactId: submission.artifact_id,\n attempt,\n results: buildResults(db, submission),\n };\n return envelope;\n });\n let outcome: Outcome;\n // An envelope no host could read would be retried forever and hold back every later delivery\n // to this host: it is undeliverable, with the reason, and never sent (Claude review finding 2).\n const length = JSON.stringify(envelope).length + ENVELOPE_FRAME_SLACK;\n if (length > MAX_LINE_LENGTH) {\n log.error(\"outbox.too_large\", { owner, deliveryId: head.id, length });\n this.#record(\n { ...head, attempts: attempt },\n {\n kind: \"terminal\",\n state: \"undeliverable\",\n reason: `too-large: the submission's envelope is ${length} characters; one protocol message carries ${MAX_LINE_LENGTH}`,\n },\n );\n return true;\n }\n try {\n const answer = await hosts.call(\n registrant.session,\n portSubmissionsDeliverMethod.method,\n envelope,\n this.#options.portTimeoutMs ?? PORT_CALL_TIMEOUT_MS,\n );\n const parsed = portSubmissionsDeliverMethod.result.safeParse(answer);\n outcome = parsed.success\n ? outcomeOf(parsed.data)\n : {\n kind: \"retry\",\n error: \"The host's answer doesn't match port/submissions.deliver's result.\",\n };\n } catch (error) {\n outcome = { kind: \"retry\", error: (error as Error).message };\n }\n // A crash here, after the host answered and before Mostra records it, redelivers the same\n // delivery ID on the next start (FAILURE_MODEL §4).\n faults.at(\"deliver:after-answer\");\n this.#record({ ...head, attempts: attempt }, outcome);\n if (outcome.kind === \"retry\") {\n log.warn(\"outbox.retry\", { owner, deliveryId: head.id, attempt, error: outcome.error });\n return false;\n }\n return true;\n }\n\n #schedule(owner: string, delayMs: number): void {\n if (this.#timers.has(owner) || this.#stopped) return;\n const timer = setTimeout(() => {\n this.#timers.delete(owner);\n void this.#pump(owner);\n }, delayMs);\n timer.unref?.();\n this.#timers.set(owner, timer);\n }\n\n #record(head: DeliveryRow, outcome: Outcome): void {\n const now = new Date(this.#now()).toISOString();\n const { ledger } = this.#options;\n ledger.write((db) => {\n const current = db.get<{ state: DeliveryState }>(\n \"SELECT state FROM delivery WHERE id = ?\",\n head.id,\n );\n if (current?.state !== \"pending\") return;\n const submission = db.get<{ artifact_id: string }>(\n \"SELECT artifact_id FROM submission WHERE id = ?\",\n head.submission_id,\n ) as { artifact_id: string };\n if (outcome.kind === \"retry\") {\n const first = db.get<{ last_error_json: string | null }>(\n \"SELECT last_error_json FROM delivery WHERE id = ?\",\n head.id,\n );\n db.run(\n \"UPDATE delivery SET next_attempt_at = ?, last_error_json = ?, updated_at = ? WHERE id = ?\",\n new Date(this.#now() + backoffMs(head.attempts)).toISOString(),\n JSON.stringify({ message: outcome.error.slice(0, 500), at: now }),\n now,\n head.id,\n );\n if (first?.last_error_json === null) {\n appendRetrying(db, submission.artifact_id, head, outcome.error);\n }\n return;\n }\n const state = outcome.kind === \"delivered\" ? \"delivered\" : outcome.state;\n const reason = outcome.reason ?? null;\n db.run(\n \"UPDATE delivery SET state = ?, reason = ?, next_attempt_at = NULL, updated_at = ? WHERE id = ?\",\n state,\n reason,\n now,\n head.id,\n );\n appendEvent(db, {\n artifactId: submission.artifact_id,\n type: `submission.${state}`,\n actor:\n head.port_owner === BUILT_IN_OWNER\n ? { kind: \"mostra\" }\n : { kind: \"host\", id: head.port_owner },\n causation: { submissionId: head.submission_id },\n payload: {\n submissionId: head.submission_id,\n deliveryId: head.id,\n owner: head.port_owner,\n attempts: head.attempts,\n ...(reason !== null ? { reason } : {}),\n },\n });\n });\n }\n\n /**\n * Records that a delivery waits for a host that isn't connected, once: the viewer sees \"Pending\n * delivery\" instead of a submission that looks merely slow (IN-13, D47).\n */\n #waiting(head: DeliveryRow, reason: string): void {\n const now = new Date(this.#now()).toISOString();\n this.#options.ledger.write((db) => {\n const current = db.get<{ state: DeliveryState; last_error_json: string | null }>(\n \"SELECT state, last_error_json FROM delivery WHERE id = ?\",\n head.id,\n );\n if (current?.state !== \"pending\" || current.last_error_json !== null) return;\n db.run(\n \"UPDATE delivery SET last_error_json = ?, updated_at = ? WHERE id = ?\",\n JSON.stringify({ message: reason, at: now }),\n now,\n head.id,\n );\n const submission = db.get<{ artifact_id: string }>(\n \"SELECT artifact_id FROM submission WHERE id = ?\",\n head.submission_id,\n ) as { artifact_id: string };\n appendRetrying(db, submission.artifact_id, head, reason);\n });\n }\n\n /**\n * Mirrors a viewer's draft to every connection with a `drafts` port (D105): best effort, the\n * latest revision only, coalesced while one is in flight, never retried. A mirror is labelled\n * `kind: \"draft\"` and never goes through the submissions port (IN-06).\n */\n mirror(artifactId: string, viewerId: string): void {\n for (const registrant of this.#options.hosts.registrants(\"drafts\")) {\n const key = `${registrant.session} ${artifactId} ${viewerId}`;\n const running = this.#mirroring.get(key);\n if (running) {\n running.dirty = true;\n continue;\n }\n const entry = { dirty: false };\n this.#mirroring.set(key, entry);\n void (async () => {\n try {\n do {\n entry.dirty = false;\n const mirror = this.#options.ledger.read((db): DraftMirror | undefined => {\n const draft = documentFor(db, artifactId, viewerId);\n if (!draft) return undefined;\n const fields = liveFields(db, draft.id);\n return {\n kind: \"draft\",\n artifactId,\n viewerId,\n epoch: draft.epoch,\n revision: String(draft.revision),\n fields: Object.fromEntries(\n Object.entries(fields).map(([id, field]) => [id, field.value]),\n ),\n };\n });\n if (!mirror || this.#stopped) break;\n try {\n await this.#options.hosts.call(\n registrant.session,\n portDraftsMirrorMethod.method,\n mirror,\n this.#options.portTimeoutMs ?? PORT_CALL_TIMEOUT_MS,\n );\n } catch (error) {\n this.#options.log.warn(\"outbox.mirror_failed\", {\n artifactId,\n owner: registrant.owner,\n error: (error as Error).message,\n });\n }\n } while (entry.dirty && !this.#stopped);\n } finally {\n this.#mirroring.delete(key);\n }\n })();\n }\n }\n}\n\n/**\n * `submission.retrying`: a delivery is waiting, its host away or its first attempt failed (D47's\n * \"Pending delivery\"). Appended once per delivery, so a long outage never fills the event log;\n * `submission.delivered` and the terminal events end it.\n */\nfunction appendRetrying(db: LedgerDb, artifactId: string, head: DeliveryRow, reason: string): void {\n appendEvent(db, {\n artifactId,\n type: \"submission.retrying\",\n actor: { kind: \"mostra\" },\n causation: { submissionId: head.submission_id },\n payload: {\n submissionId: head.submission_id,\n deliveryId: head.id,\n owner: head.port_owner,\n attempts: head.attempts,\n reason: reason.slice(0, 500),\n },\n });\n}\n\n/** What a host's answer means (D105). */\nfunction outcomeOf(answer: SubmissionsDeliverResult): Outcome {\n if (answer.accepted) return { kind: \"delivered\" };\n if (answer.retry) return { kind: \"retry\", error: `The host asked to retry: ${answer.reason}` };\n if (answer.reason === \"duplicate\") return { kind: \"delivered\", reason: \"duplicate\" };\n return {\n kind: \"terminal\",\n state: answer.reason === \"undeliverable\" ? \"undeliverable\" : \"rejected\",\n reason: answer.reason,\n };\n}\n","/**\n * Action runs in the ledger (D24, D54, AC-02, AC-03; ARCHITECTURE §7): each invocation through\n * `useAction` is recorded before any worker starts it, keyed so a double click, a second tab or a\n * reload joins the run that exists, and every change of state appends its event in the same\n * transaction. The log is capped at 1 MB with a marker (D47); the result's batches only grow while\n * the run runs, and a finished run never changes again (a trigger refuses it).\n */\nimport {\n type Actor,\n type Batches,\n createDiagnostic,\n type Frame,\n isFinalRunStatus,\n RpcError,\n RUN_LOG_MAX,\n RUN_LOG_TRUNCATED,\n RunId,\n type RunProgress,\n type RunState,\n type RunStatus,\n type WireError,\n} from \"@mostra/protocol\";\nimport type { LedgerDb } from \"../ledger/index.ts\";\nimport { appendEvent } from \"./events.ts\";\n\n/** An `action_run` row. */\nexport interface RunRow {\n readonly id: string;\n readonly artifact_id: string;\n readonly version_id: string;\n readonly view_id: string | null;\n readonly viewer_id: string | null;\n readonly action: string;\n readonly args_json: string;\n readonly key: string | null;\n readonly client_key: string;\n readonly status: RunStatus;\n readonly reason: string | null;\n readonly error_json: string | null;\n readonly progress_json: string | null;\n readonly log_text: string;\n readonly log_lines: number;\n readonly log_truncated: number;\n readonly batches: number;\n readonly result_size: number;\n readonly started_at: string;\n readonly finished_at: string | null;\n}\n\n/** A run to record. */\nexport interface NewRun {\n readonly artifactId: string;\n readonly versionId: string;\n readonly viewId: string;\n readonly viewerId: string;\n readonly fnId: string;\n readonly args: Batches;\n readonly key?: string;\n readonly clientKey: string;\n readonly actor: Actor;\n}\n\n/** The run a request names, by ID, of one artifact. */\nexport function runById(db: LedgerDb, artifactId: string, runId: string): RunRow | undefined {\n return db.get<RunRow>(\n \"SELECT * FROM action_run WHERE id = ? AND artifact_id = ?\",\n runId,\n artifactId,\n );\n}\n\n/** The run of an artifact, function and key, if one was ever started. */\nexport function runByKey(\n db: LedgerDb,\n artifactId: string,\n fnId: string,\n key: string,\n): RunRow | undefined {\n return db.get<RunRow>(\n \"SELECT * FROM action_run WHERE artifact_id = ? AND action = ? AND key = ?\",\n artifactId,\n fnId,\n key,\n );\n}\n\n/**\n * Records a run as `queued` and appends `action.started`, or returns the run the request joins:\n * the one its client key already started (a retried request), or the one its key names (AC-03).\n */\nexport function createOrJoinRun(db: LedgerDb, input: NewRun): { row: RunRow; joined: boolean } {\n const retried = db.get<RunRow>(\n \"SELECT * FROM action_run WHERE artifact_id = ? AND client_key = ?\",\n input.artifactId,\n input.clientKey,\n );\n if (retried) {\n // A client key is one page's request: another viewer's never joins it, nor a request for\n // another function (whose run its link may not be allowed to see, Opus review 9).\n if (retried.viewer_id !== input.viewerId || retried.action !== input.fnId) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", {\n message: \"This clientKey belongs to another request; send a new one.\",\n }),\n );\n }\n return { row: retried, joined: true };\n }\n if (input.key !== undefined) {\n const keyed = runByKey(db, input.artifactId, input.fnId, input.key);\n if (keyed) return { row: keyed, joined: true };\n }\n const id = RunId.create();\n const startedAt = new Date().toISOString();\n db.run(\n `INSERT INTO action_run (id, artifact_id, version_id, view_id, viewer_id, action, args_json, key,\n client_key, status, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?)`,\n id,\n input.artifactId,\n input.versionId,\n input.viewId,\n input.viewerId,\n input.fnId,\n JSON.stringify(input.args),\n input.key ?? null,\n input.clientKey,\n startedAt,\n );\n appendEvent(db, {\n artifactId: input.artifactId,\n type: \"action.started\",\n actor: input.actor,\n causation: { runId: id, viewId: input.viewId },\n payload: {\n runId: id,\n action: input.fnId,\n ...(input.key !== undefined ? { key: input.key } : {}),\n viewId: input.viewId,\n },\n });\n return {\n row: db.get<RunRow>(\"SELECT * FROM action_run WHERE id = ?\", id) as RunRow,\n joined: false,\n };\n}\n\n/** Moves a queued run to `running`, when its worker has it. */\nexport function markRunning(db: LedgerDb, runId: string): void {\n db.run(\"UPDATE action_run SET status = 'running' WHERE id = ? AND status = 'queued'\", runId);\n}\n\n/** What a running run produced since the last flush. */\nexport interface RunOutput {\n readonly lines: readonly string[];\n readonly batches: readonly (readonly Frame[])[];\n readonly progress?: RunProgress;\n}\n\n/** The counts after a flush, and the lines and batches actually kept. */\nexport interface RunFlush {\n readonly logFrom: number;\n readonly log: readonly string[];\n readonly batchFrom: number;\n readonly batches: readonly (readonly Frame[])[];\n readonly resultSize: number;\n}\n\n/**\n * Appends a run's new log lines (until the 1 MB cap, then one marker line) and result batches,\n * and keeps its latest progress. Does nothing to a finished run.\n */\nexport function appendRunOutput(\n db: LedgerDb,\n runId: string,\n output: RunOutput,\n): RunFlush | undefined {\n const row = db.get<RunRow>(\"SELECT * FROM action_run WHERE id = ?\", runId);\n if (!row || isFinalRunStatus(row.status)) return undefined;\n const kept: string[] = [];\n let text = row.log_text;\n let lines = row.log_lines;\n let truncated = row.log_truncated === 1;\n for (const raw of output.lines) {\n for (const line of raw.split(/\\r?\\n/)) {\n if (truncated) break;\n if (text.length + line.length + 1 > RUN_LOG_MAX) {\n truncated = true;\n kept.push(RUN_LOG_TRUNCATED);\n text += `${lines > 0 ? \"\\n\" : \"\"}${RUN_LOG_TRUNCATED}`;\n lines += 1;\n break;\n }\n kept.push(line);\n text += `${lines > 0 ? \"\\n\" : \"\"}${line}`;\n lines += 1;\n }\n }\n let size = row.result_size;\n output.batches.forEach((batch, index) => {\n const json = JSON.stringify(batch);\n size += json.length;\n db.run(\n \"INSERT INTO action_run_batch (run_id, seq, batch_json) VALUES (?, ?, ?)\",\n runId,\n row.batches + index,\n json,\n );\n });\n db.run(\n `UPDATE action_run SET log_text = ?, log_lines = ?, log_truncated = ?, batches = ?, result_size = ?,\n progress_json = COALESCE(?, progress_json) WHERE id = ?`,\n text,\n lines,\n truncated ? 1 : 0,\n row.batches + output.batches.length,\n size,\n output.progress === undefined ? null : JSON.stringify(output.progress),\n runId,\n );\n return {\n logFrom: row.log_lines,\n log: kept,\n batchFrom: row.batches,\n batches: output.batches,\n resultSize: size,\n };\n}\n\n/** How a run ended. */\nexport interface RunEnd {\n readonly status: \"succeeded\" | \"failed\" | \"cancelled\";\n readonly reason?: string;\n readonly error?: WireError;\n}\n\n/** Ends a run and appends `action.succeeded`, `action.failed` or `action.cancelled`. */\nexport function finishRun(db: LedgerDb, runId: string, end: RunEnd): RunRow | undefined {\n const row = db.get<RunRow>(\"SELECT * FROM action_run WHERE id = ?\", runId);\n if (!row || isFinalRunStatus(row.status)) return row;\n const finishedAt = new Date().toISOString();\n db.run(\n \"UPDATE action_run SET status = ?, reason = ?, error_json = ?, finished_at = ? WHERE id = ?\",\n end.status,\n end.reason ?? null,\n end.error === undefined ? null : JSON.stringify(end.error),\n finishedAt,\n runId,\n );\n appendEvent(db, {\n artifactId: row.artifact_id,\n type: `action.${end.status}`,\n actor: { kind: \"mostra\" },\n causation: { runId },\n payload: {\n runId,\n action: row.action,\n ...(end.reason !== undefined ? { reason: end.reason } : {}),\n ...(end.error?.code !== undefined ? { code: end.error.code } : {}),\n },\n });\n return db.get<RunRow>(\"SELECT * FROM action_run WHERE id = ?\", runId);\n}\n\n/** The runs still open (queued, running or waiting), optionally of one version. */\nexport function openRuns(db: LedgerDb, versionId?: string): RunRow[] {\n return versionId === undefined\n ? db.all<RunRow>(\"SELECT * FROM action_run WHERE status IN ('queued', 'running', 'waiting')\")\n : db.all<RunRow>(\n \"SELECT * FROM action_run WHERE status IN ('queued', 'running', 'waiting') AND version_id = ?\",\n versionId,\n );\n}\n\n/** A run as a page reads it: state, progress, the whole log and every batch so far. */\nexport function runState(\n db: LedgerDb,\n row: RunRow,\n joined?: boolean,\n held?: { readonly log: number; readonly batches: number },\n): RunState {\n // What the page holds already isn't read again (Opus review 14).\n const batchFrom = Math.min(held?.batches ?? 0, row.batches);\n const batches = db\n .all<{ batch_json: string }>(\n \"SELECT batch_json FROM action_run_batch WHERE run_id = ? AND seq >= ? ORDER BY seq\",\n row.id,\n batchFrom,\n )\n .map((entry) => JSON.parse(entry.batch_json) as Frame[]);\n const lines = row.log_text === \"\" && row.log_lines === 0 ? [] : row.log_text.split(\"\\n\");\n const logFrom = Math.min(held?.log ?? 0, lines.length);\n const error = row.error_json === null ? undefined : (JSON.parse(row.error_json) as WireError);\n return {\n runId: row.id,\n fnId: row.action,\n ...(row.key !== null ? { key: row.key } : {}),\n status: row.status,\n ...(row.reason !== null ? { reason: row.reason } : {}),\n ...(row.progress_json !== null\n ? { progress: JSON.parse(row.progress_json) as RunProgress }\n : {}),\n log: logFrom === 0 ? lines : lines.slice(logFrom),\n batches,\n ...(logFrom > 0 ? { logFrom } : {}),\n ...(batchFrom > 0 ? { batchFrom } : {}),\n ...(error\n ? { error: { message: error.message, ...(error.code ? { code: error.code } : {}) } }\n : {}),\n startedAt: row.started_at,\n ...(row.finished_at !== null ? { finishedAt: row.finished_at } : {}),\n ...(joined === undefined ? {} : { joined }),\n };\n}\n","/**\n * Event subscriptions (IN-08, H-09; INTERFACES §6): `events/subscribe` delivers a connection the\n * events that pass its filter, as `events/notify` notifications in cursor order without gaps;\n * `events/ack` records how far a named subscriber got, durably, so its next subscription with the\n * same name resumes there after any disconnect or restart. Delivery follows every commit.\n */\nimport {\n createDiagnostic,\n EVENTS_NOTIFY,\n type EventFilter,\n type EventsNotifyParams,\n type EventsSubscribeParams,\n type EventsSubscribeResult,\n RpcError,\n} from \"@mostra/protocol\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { latestCursor, readEvents } from \"./events.ts\";\n\n/** Events per notification. */\nconst PAGE = 100;\n\n/** Pages one pump sends before yielding, so a long backlog never blocks the instance. */\nconst PAGES_PER_TURN = 10;\n\n/** Bytes one pump sends before yielding. */\nconst BYTES_PER_TURN: number = 8 * 1024 * 1024;\n\n/** A connection as subscriptions see it. */\nexport interface SubscriberSession {\n readonly id: number;\n /** The notifications the client accepted in `mostra/initialize` (D84). */\n readonly notifications: ReadonlySet<string>;\n}\n\ninterface Subscription {\n readonly id: string;\n readonly session: number;\n readonly filter: EventFilter | undefined;\n readonly name: string | undefined;\n /** Every event up to here was examined and the matching ones sent. */\n cursor: number;\n /** Whether the pump waits for the connection to drain. */\n waiting: boolean;\n}\n\n/** Options for {@link Subscriptions}. */\nexport interface SubscriptionsOptions {\n readonly ledger: Ledger;\n readonly log: Log;\n /** Sends a notification on a connection; `false` when the connection is gone. */\n readonly notify: (session: number, method: string, params: EventsNotifyParams) => boolean;\n /** A promise that settles when the connection can take more, or `undefined` when it can now. */\n readonly drained: (session: number) => Promise<void> | undefined;\n}\n\n/** The event subscriptions of one instance. */\nexport class Subscriptions {\n readonly #options: SubscriptionsOptions;\n readonly #all = new Map<string, Subscription>();\n #next = 1;\n #unsubscribe: (() => void) | undefined;\n #scheduled = false;\n\n constructor(options: SubscriptionsOptions) {\n this.#options = options;\n }\n\n /** Delivers after every commit. */\n start(): void {\n this.#unsubscribe = this.#options.ledger.onCommit(() => this.#pumpAll());\n }\n\n /**\n * The artifacts some host subscription names in its filter (`artifacts`): their live producers\n * run while it lasts (LL-04). A subscription without an artifacts filter starts none.\n */\n subscribedArtifacts(): Set<string> {\n const artifacts = new Set<string>();\n for (const subscription of this.#all.values()) {\n for (const artifact of subscription.filter?.artifacts ?? []) artifacts.add(artifact);\n }\n return artifacts;\n }\n\n /** How many subscriptions are open: the daemon stays while hosts listen (D62). */\n get size(): number {\n return this.#all.size;\n }\n\n stop(): void {\n this.#unsubscribe?.();\n this.#all.clear();\n }\n\n /** `events/subscribe` on a connection. */\n subscribe(session: SubscriberSession, params: EventsSubscribeParams): EventsSubscribeResult {\n if (!session.notifications.has(EVENTS_NOTIFY)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_NOTIFICATION_UNSUPPORTED\", {\n message: `events/subscribe sends ${EVENTS_NOTIFY}, which this connection didn't accept in mostra/initialize.`,\n }),\n );\n }\n const { ledger } = this.#options;\n const cursor = ledger.write((db) => {\n const latest = latestCursor(db);\n let start: number;\n if (params.after !== undefined) start = Number(params.after);\n else {\n // A known name resumes after its acknowledged cursor; a new one, like an unnamed\n // subscription, starts now (the history stays readable through events/read).\n const known =\n params.name === undefined\n ? undefined\n : db.get<{ acked_cursor: number }>(\n \"SELECT acked_cursor FROM subscriber WHERE name = ?\",\n params.name,\n );\n start = known?.acked_cursor ?? latest;\n }\n if (params.name !== undefined) {\n db.run(\n `INSERT INTO subscriber (name, filter_json, acked_cursor, updated_at) VALUES (?, ?, ?, ?)\n ON CONFLICT (name) DO UPDATE SET filter_json = excluded.filter_json, updated_at = excluded.updated_at`,\n params.name,\n JSON.stringify(params.filter ?? {}),\n start,\n new Date().toISOString(),\n );\n }\n // A cursor inside a compacted range isn't refused: the subscription delivers the summary\n // in order, flagged `compacted`, and goes on.\n return start;\n });\n const subscription: Subscription = {\n id: `sub-${session.id}-${this.#next++}`,\n session: session.id,\n filter: params.filter,\n name: params.name,\n cursor,\n waiting: false,\n };\n this.#all.set(subscription.id, subscription);\n // The answer goes out first; the backlog follows it.\n setImmediate(() => this.#pump(subscription));\n return { subscriptionId: subscription.id, cursor: String(cursor) };\n }\n\n /** `events/unsubscribe`. */\n unsubscribe(session: SubscriberSession, subscriptionId: string): void {\n this.#owned(session, subscriptionId);\n this.#all.delete(subscriptionId);\n }\n\n /** `events/ack`: durable for a named subscriber; an earlier cursor changes nothing. */\n ack(session: SubscriberSession, subscriptionId: string, cursor: number): void {\n const subscription = this.#owned(session, subscriptionId);\n if (subscription.name === undefined) return;\n this.#options.ledger.write((db) =>\n db.run(\n \"UPDATE subscriber SET acked_cursor = MAX(acked_cursor, MIN(?, ?)), updated_at = ? WHERE name = ?\",\n cursor,\n latestCursor(db),\n new Date().toISOString(),\n subscription.name as string,\n ),\n );\n }\n\n /** Ends a closed connection's subscriptions; named cursors stay. */\n closed(session: number): void {\n for (const [id, subscription] of this.#all)\n if (subscription.session === session) this.#all.delete(id);\n }\n\n #owned(session: SubscriberSession, subscriptionId: string): Subscription {\n const subscription = this.#all.get(subscriptionId);\n if (!subscription || subscription.session !== session.id) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_SUBSCRIPTION_UNKNOWN\", {\n message: `No subscription ${subscriptionId} exists on this connection.`,\n }),\n );\n }\n return subscription;\n }\n\n #pumpAll(): void {\n if (this.#scheduled) return;\n this.#scheduled = true;\n // After the committing call returns: a commit inside a request is answered first.\n setImmediate(() => {\n this.#scheduled = false;\n for (const subscription of this.#all.values()) this.#pump(subscription);\n });\n }\n\n #pump(subscription: Subscription): void {\n const { ledger, log, notify, drained } = this.#options;\n // While the host's connection is full, the pump waits for it to drain (flow control).\n if (subscription.waiting) return;\n let bytes = 0;\n for (let page = 0; page < PAGES_PER_TURN && bytes < BYTES_PER_TURN; page++) {\n if (!this.#all.has(subscription.id)) return;\n let read: ReturnType<typeof readEvents>;\n try {\n // Through a compacted range, not past it: the summary arrives in cursor order among the\n // other artifacts' events, flagged `compacted`, and nothing between is skipped (DATA_MODEL §4).\n read = ledger.read((db) =>\n readEvents(db, {\n filter: subscription.filter,\n after: subscription.cursor,\n limit: PAGE,\n acceptCompacted: true,\n }),\n );\n } catch (error) {\n log.error(\"events.subscription_failed\", { subscriptionId: subscription.id, error });\n this.#all.delete(subscription.id);\n return;\n }\n const next = Number(read.cursor);\n if (read.events.length > 0) {\n if (read.compacted) {\n log.warn(\"events.subscription_compacted\", {\n subscriptionId: subscription.id,\n after: subscription.cursor,\n });\n }\n const sent = notify(subscription.session, EVENTS_NOTIFY, {\n subscriptionId: subscription.id,\n events: read.events,\n cursor: read.cursor,\n ...(read.compacted ? { compacted: read.compacted } : {}),\n });\n if (!sent) {\n this.#all.delete(subscription.id);\n return;\n }\n bytes += read.events.reduce((sum, event) => sum + JSON.stringify(event).length, 0);\n }\n subscription.cursor = next;\n const waiting = drained(subscription.session);\n if (waiting) {\n subscription.waiting = true;\n void waiting.then(() => {\n subscription.waiting = false;\n this.#pump(subscription);\n });\n return;\n }\n // A page cut short by size (READ_MAX_BYTES) ends before the newest cursor: read on.\n if (read.events.length < PAGE && next >= ledger.read((db) => latestCursor(db))) return;\n }\n setImmediate(() => this.#pump(subscription));\n }\n}\n","/**\n * `wait` (IN-10, ARCHITECTURE §6, D103): blocks until a condition holds or the timeout passes.\n * `submitted` is level-triggered under `once` (any submission satisfies it, whatever the cursor) and\n * edge-triggered under `epochs`; `signal:`, `state:` and `event:` are edge-triggered after the\n * cursor, which defaults to the artifact's latest publish. A timeout answers `still_waiting` with\n * the newest cursor examined, so a later wait from it misses nothing: every condition is a query of\n * durable events, so nothing that happened while no one waited is lost.\n */\nimport {\n type Cursor,\n createDiagnostic,\n type EventRecord,\n RpcError,\n type WaitResult,\n} from \"@mostra/protocol\";\nimport type { Ledger, LedgerDb } from \"../ledger/index.ts\";\nimport { COMPACTED, checkCompaction, type EventRow, eventRecord, latestCursor } from \"./events.ts\";\nimport { storedPolicy } from \"./policy.ts\";\nimport type { SubmissionRow } from \"./submissions.ts\";\n\n/** The cursor a wait starts from by default: the artifact's latest publish (D103). */\nexport function defaultWaitCursor(db: LedgerDb, artifactId: string): number {\n const published =\n db.get<{ cursor: number | null }>(\n \"SELECT MAX(cursor) AS cursor FROM event WHERE artifact_id = ? AND type = 'version.published'\",\n artifactId,\n )?.cursor ?? 0;\n // A publish that was compacted away is still known by its cursor, which its summary records:\n // waiting after the summary instead would skip what happened between (Claude review finding 9).\n const compacted =\n db.get<{ cursor: number | null }>(\n `SELECT MAX(json_extract(payload_json, '$.latestVersion.cursor')) AS cursor FROM event WHERE artifact_id = ? AND type = '${COMPACTED}'`,\n artifactId,\n )?.cursor ?? 0;\n return Math.max(published, compacted);\n}\n\n/** Builds a `submission.created` record from its row, when compaction removed the event. */\nfunction submissionEvent(db: LedgerDb, row: SubmissionRow): EventRecord {\n const event = db.get<EventRow>(\"SELECT * FROM event WHERE cursor = ?\", row.position);\n if (event && event.type === \"submission.created\") return eventRecord(event);\n return {\n cursor: String(row.position) as Cursor,\n artifactId: row.artifact_id,\n seq: null,\n type: \"submission.created\",\n at: row.created_at,\n actor: { kind: \"viewer\", id: row.viewer_id },\n causation: { submissionId: row.id },\n payload: {\n submissionId: row.id,\n versionId: row.version_id,\n version: (JSON.parse(row.snapshot_json) as { version: number }).version,\n viewId: row.view_id,\n viewerId: row.viewer_id,\n channel: row.channel,\n epoch: row.epoch,\n staleView: row.stale_view === 1,\n digest: row.digest,\n },\n };\n}\n\n/**\n * Checks a condition once, inside the caller's read transaction: the event that satisfies it, or\n * the newest cursor examined. Throws `MOSTRA_SUBMIT_POLICY_NONE` for `submitted` on an artifact\n * without submissions, and `MOSTRA_HOST_CURSOR_COMPACTED` for a cursor inside a compacted range.\n */\nexport function checkCondition(\n db: LedgerDb,\n artifactId: string,\n until: string,\n after: number,\n explicitAfter = true,\n): { readonly event: EventRecord } | { readonly cursor: number } {\n const upTo = latestCursor(db);\n const first = (sql: string, ...params: (string | number)[]): EventRow | undefined =>\n db.get<EventRow>(\n `SELECT * FROM event WHERE artifact_id = ? AND cursor > ? AND cursor <= ? AND ${sql} ORDER BY cursor LIMIT 1`,\n artifactId,\n after,\n upTo,\n ...params,\n );\n let found: EventRow | undefined;\n if (until === \"submitted\") {\n const artifact = db.get<{ policy_json: string | null }>(\n \"SELECT policy_json FROM artifact WHERE id = ?\",\n artifactId,\n );\n const policy = storedPolicy(artifact?.policy_json ?? null);\n if (policy.policy === \"none\") {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SUBMIT_POLICY_NONE\", {\n message:\n \"This artifact's submission policy is none: nothing will be submitted to wait for.\",\n }),\n );\n }\n // Level-triggered under once per-artifact, and under once per-viewer while no cursor was\n // given: any submission satisfies it. After an explicit cursor, per-viewer is edge-triggered,\n // so a survey's agent can wait for the next respondent (D107).\n const level = policy.policy === \"once\" && (policy.scope !== \"per-viewer\" || !explicitAfter);\n const row = level\n ? db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE artifact_id = ? ORDER BY position LIMIT 1\",\n artifactId,\n )\n : db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE artifact_id = ? AND position > ? AND position <= ? ORDER BY position LIMIT 1\",\n artifactId,\n after,\n upTo,\n );\n if (row) return { event: submissionEvent(db, row) };\n checkCompaction(db, { artifacts: [artifactId] }, after);\n return { cursor: Math.max(upTo, after) };\n }\n checkCompaction(db, { artifacts: [artifactId] }, after);\n const separator = until.indexOf(\":\");\n const kind = until.slice(0, separator);\n const subject = until.slice(separator + 1);\n if (kind === \"signal\") {\n found = first(\"type = 'signal.raised' AND json_extract(payload_json, '$.name') = ?\", subject);\n } else if (kind === \"state\") {\n found = first(\n \"type = 'state.changed' AND EXISTS (SELECT 1 FROM json_each(payload_json, '$.changes') WHERE json_extract(json_each.value, '$.id') = ?)\",\n subject,\n );\n } else if (kind === \"event\") {\n found = subject.endsWith(\".*\")\n ? first(\"substr(type, 1, ?) = ?\", subject.length - 1, subject.slice(0, -1))\n : first(\"type = ?\", subject);\n } else {\n throw new Error(`Unknown wait condition ${until}.`);\n }\n return found ? { event: eventRecord(found) } : { cursor: Math.max(upTo, after) };\n}\n\n/** Options for {@link waitFor}. */\nexport interface WaitOptions {\n readonly ledger: Ledger;\n readonly artifactId: string;\n readonly until: string;\n /** The cursor to wait after; absent: the artifact's latest publish. */\n readonly after?: number | undefined;\n readonly timeoutMs: number;\n /** Ends the wait early (the connection closed, the instance stops): it answers `still_waiting`. */\n readonly signal?: AbortSignal | undefined;\n}\n\n/**\n * Waits for a condition: checks it now, then again after every commit, until it holds, the timeout\n * passes or `signal` aborts.\n */\nexport async function waitFor(options: WaitOptions): Promise<WaitResult> {\n const { ledger, artifactId, until } = options;\n const after = options.after ?? ledger.read((db) => defaultWaitCursor(db, artifactId));\n const explicit = options.after !== undefined;\n const check = () => ledger.read((db) => checkCondition(db, artifactId, until, after, explicit));\n const answer = (outcome: ReturnType<typeof check>): WaitResult =>\n \"event\" in outcome\n ? { status: \"satisfied\", event: outcome.event, cursor: outcome.event.cursor }\n : { status: \"still_waiting\", cursor: String(outcome.cursor) };\n const now = check();\n if (\"event\" in now || options.timeoutMs === 0 || options.signal?.aborted) return answer(now);\n return new Promise<WaitResult>((resolve, reject) => {\n let last: ReturnType<typeof check> = now;\n let settled = false;\n const finish = (result: WaitResult | Error): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n options.signal?.removeEventListener(\"abort\", onAbort);\n if (result instanceof Error) reject(result);\n else resolve(result);\n };\n const onCommit = (): void => {\n try {\n last = check();\n } catch (error) {\n finish(error as Error);\n return;\n }\n if (\"event\" in last) finish(answer(last));\n };\n const onAbort = (): void => finish(answer(last));\n const unsubscribe = ledger.onCommit(onCommit);\n const timer = setTimeout(() => {\n // One last look, so a commit at the deadline isn't missed.\n try {\n finish(answer(check()));\n } catch (error) {\n finish(error as Error);\n }\n }, options.timeoutMs);\n timer.unref?.();\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * Ephemeral traffic to pages (D47, D63, LL-04): run progress, log lines and result items, and live\n * values. None of it is an event: it reaches the views that asked for it within the last minute\n * (a run they started or attached to, a live source they read) and is lost by anyone who isn't\n * listening, because what it reports is also readable on demand (`runs/attach`, `live`). A view's\n * open event stream hears it at once; a view that long-polls collects it in a bounded queue\n * between polls.\n */\nimport type { EphemeralMessage } from \"@mostra/protocol\";\n\n/** How long a view's interest in a run or a live source lasts without being renewed. */\nexport const INTEREST_LEASE_MS: number = 60_000;\n\n/** The most messages a polling view keeps between polls; older ones are dropped. */\nconst POLL_QUEUE_MAX = 1000;\n\n/** What a view listens to. */\ninterface ViewInterest {\n readonly artifactId: string;\n readonly runs: Map<string, number>;\n readonly live: Map<string, { until: number; window?: number }>;\n readonly listeners: Set<(message: EphemeralMessage) => void>;\n queue?: EphemeralMessage[];\n queueUntil?: number;\n wake?: () => void;\n}\n\ntype RunMessage = Extract<EphemeralMessage, { kind: \"run\" }>;\n\n/**\n * Adds `message` to a view's queue of messages not yet sent, coalesced (D130, FAILURE_MODEL §6;\n * Opus review 12), so a fast source can't make a slow reader fall behind:\n * - a live value in latest mode replaces the values of its source still queued: the page shows\n * only the newest (append mode keeps every value, for the ring);\n * - a run's delta that continues the one queued for the run merges into it, losing nothing.\n */\nfunction coalesceInto(\n view: ViewInterest,\n queue: EphemeralMessage[],\n message: EphemeralMessage,\n): void {\n if (message.kind === \"live\") {\n const latestMode = view.live.get(message.live.key)?.window === undefined;\n if (latestMode && message.live.value !== undefined) {\n for (let index = queue.length - 1; index >= 0; index--) {\n const queued = queue[index] as EphemeralMessage;\n if (\n queued.kind === \"live\" &&\n queued.live.key === message.live.key &&\n queued.live.value !== undefined\n ) {\n queue.splice(index, 1);\n }\n }\n }\n queue.push(message);\n return;\n }\n const delta = message.run;\n for (let index = queue.length - 1; index >= 0; index--) {\n const queued = queue[index] as EphemeralMessage;\n if (queued.kind !== \"run\" || queued.run.runId !== delta.runId) continue;\n const prior = queued.run;\n if (\n delta.logFrom === prior.logFrom + prior.log.length &&\n delta.batchFrom === prior.batchFrom + prior.batches.length\n ) {\n const merged: RunMessage = {\n kind: \"run\",\n run: {\n ...prior,\n ...delta,\n logFrom: prior.logFrom,\n log: [...prior.log, ...delta.log],\n batchFrom: prior.batchFrom,\n batches: [...prior.batches, ...delta.batches],\n ...((delta.progress ?? prior.progress)\n ? { progress: delta.progress ?? prior.progress }\n : {}),\n },\n };\n queue[index] = merged;\n return;\n }\n break;\n }\n queue.push(message);\n}\n\n/** A live source some view, host or `always` keeps alive. */\nexport interface LiveInterest {\n readonly artifactId: string;\n readonly key: string;\n}\n\n/** The bus. */\nexport interface EphemeralBus {\n /**\n * Adds `message` to `queue`, a reader's messages not yet sent, coalescing it with what the\n * queue holds for the same source or run as the view's interest allows.\n */\n coalesce(\n artifactId: string,\n viewId: string,\n queue: EphemeralMessage[],\n message: EphemeralMessage,\n ): void;\n /** The view follows these runs for the next minute. */\n attachRuns(artifactId: string, viewId: string, runIds: readonly string[]): void;\n /** The view reads these live sources for the next minute. */\n watchLive(\n artifactId: string,\n viewId: string,\n keys: readonly { readonly key: string; readonly window?: number }[],\n ): void;\n /** Sends a run's change to every view following it. */\n publishRun(artifactId: string, message: Extract<EphemeralMessage, { kind: \"run\" }>): void;\n /** Sends a live update to every view reading the source. */\n publishLive(artifactId: string, message: Extract<EphemeralMessage, { kind: \"live\" }>): void;\n /** Hears the view's messages as they come (an open event stream); returns the stop. */\n listen(\n artifactId: string,\n viewId: string,\n listener: (message: EphemeralMessage) => void,\n ): () => void;\n /** Takes what the view collected since its last poll, starting its queue on the first. */\n drain(artifactId: string, viewId: string): EphemeralMessage[];\n /** Resolves when the polling view has something, or after `ms`. */\n wait(artifactId: string, viewId: string, ms: number, signal?: AbortSignal): Promise<void>;\n /** The live sources views read now. */\n liveInterest(): LiveInterest[];\n /** Hears every change of {@link liveInterest}; returns the stop. */\n onLiveInterest(listener: () => void): () => void;\n /** How many views listen or poll now: the daemon stays while any do (D62). */\n activeViews(): number;\n /** Stops the lease timer. */\n close(): void;\n}\n\n/** Creates the bus. */\nexport function createEphemeralBus(\n options: { readonly now?: () => number; readonly leaseMs?: number } = {},\n): EphemeralBus {\n const now = options.now ?? Date.now;\n const lease = options.leaseMs ?? INTEREST_LEASE_MS;\n const views = new Map<string, ViewInterest>();\n const interestListeners = new Set<() => void>();\n let lastInterest = \"\";\n\n const viewOf = (artifactId: string, viewId: string): ViewInterest => {\n let view = views.get(viewId);\n if (!view || view.artifactId !== artifactId) {\n view = { artifactId, runs: new Map(), live: new Map(), listeners: new Set() };\n views.set(viewId, view);\n }\n return view;\n };\n\n const interestKey = (): string =>\n [...new Set(currentInterest().map((entry) => `${entry.artifactId}\\u0000${entry.key}`))]\n .sort()\n .join(\"\\u0001\");\n\n const currentInterest = (): LiveInterest[] => {\n const at = now();\n const out: LiveInterest[] = [];\n for (const view of views.values()) {\n for (const [key, lease] of view.live) {\n if (lease.until > at) out.push({ artifactId: view.artifactId, key });\n }\n }\n return out;\n };\n\n const interestChanged = (): void => {\n const next = interestKey();\n if (next === lastInterest) return;\n lastInterest = next;\n for (const listener of interestListeners) listener();\n };\n\n const deliver = (view: ViewInterest, message: EphemeralMessage): void => {\n for (const listener of view.listeners) listener(message);\n if (view.queue && (view.queueUntil ?? 0) > now()) {\n coalesceInto(view, view.queue, message);\n if (view.queue.length > POLL_QUEUE_MAX)\n view.queue.splice(0, view.queue.length - POLL_QUEUE_MAX);\n view.wake?.();\n }\n };\n\n // Expired leases end; views with nothing left are forgotten.\n const sweep = setInterval(\n () => {\n const at = now();\n for (const [viewId, view] of views) {\n for (const [runId, until] of view.runs) if (until <= at) view.runs.delete(runId);\n for (const [key, lease] of view.live) if (lease.until <= at) view.live.delete(key);\n if (view.queue && (view.queueUntil ?? 0) <= at) {\n delete view.queue;\n delete view.queueUntil;\n }\n if (\n view.runs.size === 0 &&\n view.live.size === 0 &&\n view.listeners.size === 0 &&\n !view.queue\n ) {\n views.delete(viewId);\n }\n }\n interestChanged();\n },\n Math.min(5_000, Math.max(100, lease / 4)),\n );\n sweep.unref?.();\n\n return {\n coalesce(artifactId, viewId, queue, message) {\n coalesceInto(viewOf(artifactId, viewId), queue, message);\n },\n attachRuns(artifactId, viewId, runIds) {\n const view = viewOf(artifactId, viewId);\n const until = now() + lease;\n for (const runId of runIds) view.runs.set(runId, until);\n },\n watchLive(artifactId, viewId, keys) {\n const view = viewOf(artifactId, viewId);\n const until = now() + lease;\n for (const entry of keys) {\n view.live.set(entry.key, {\n until,\n ...(entry.window === undefined ? {} : { window: entry.window }),\n });\n }\n interestChanged();\n },\n publishRun(artifactId, message) {\n const at = now();\n for (const view of views.values()) {\n if (view.artifactId !== artifactId) continue;\n if ((view.runs.get(message.run.runId) ?? 0) > at) deliver(view, message);\n }\n },\n publishLive(artifactId, message) {\n const at = now();\n for (const view of views.values()) {\n if (view.artifactId !== artifactId) continue;\n if ((view.live.get(message.live.key)?.until ?? 0) > at) deliver(view, message);\n }\n },\n listen(artifactId, viewId, listener) {\n const view = viewOf(artifactId, viewId);\n view.listeners.add(listener);\n return () => {\n view.listeners.delete(listener);\n };\n },\n drain(artifactId, viewId) {\n const view = viewOf(artifactId, viewId);\n const taken = view.queue ?? [];\n view.queue = [];\n view.queueUntil = now() + lease;\n return taken;\n },\n wait(artifactId, viewId, ms, signal) {\n const view = viewOf(artifactId, viewId);\n if (view.queue && view.queue.length > 0) return Promise.resolve();\n return new Promise((resolve) => {\n const done = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", done);\n if (view.wake === done) delete view.wake;\n resolve();\n };\n const timer = setTimeout(done, ms);\n signal?.addEventListener(\"abort\", done, { once: true });\n view.wake = done;\n });\n },\n liveInterest: currentInterest,\n onLiveInterest(listener) {\n interestListeners.add(listener);\n return () => {\n interestListeners.delete(listener);\n };\n },\n activeViews() {\n const at = now();\n let count = 0;\n for (const view of views.values()) {\n if (view.listeners.size > 0 || (view.queueUntil ?? 0) > at) count += 1;\n }\n return count;\n },\n close() {\n clearInterval(sweep);\n },\n };\n}\n","/**\n * The interaction core (ARCHITECTURE §6; IN-01 to IN-12, LL-01, LL-02): drafts and artifact\n * state, submissions and their delivery, signals, events, `wait` and results. The supervisor's\n * one owner of them: the gateway reaches it for the browser protocol, the protocol server for the\n * host methods, and every change is one ledger transaction that appends its events.\n *\n * ```ts\n * const interaction = createInteraction({ ledger, log, faults, hosts, settings, artifacts });\n * interaction.start();\n * const { submission } = interaction.submit({ artifactId, viewerId, viewId, expectedRevision, channel });\n * ```\n */\nimport {\n type Actor,\n type ArtifactRef,\n type Batches,\n type CapabilityScope,\n type CarryOver,\n type ControlsPolicy,\n createDiagnostic,\n type DeliveryCounts,\n type EventFilter,\n type EventRecord,\n eventsAckMethod,\n eventsReadMethod,\n eventsSubscribeMethod,\n eventsUnsubscribeMethod,\n type FieldOp,\n type FieldScope,\n type FieldState,\n MutationId,\n type MutationResult,\n type Results,\n RpcError,\n type RunState,\n refusal,\n resultsGetMethod,\n type StreamSnapshot,\n type SubmissionSummary,\n type SubmitChannel,\n scopeAllows,\n stateGetMethod,\n statePatchMethod,\n type Viewer,\n type ViewerSpec,\n waitMethod,\n} from \"@mostra/protocol\";\nimport type { Faults } from \"../faults.ts\";\nimport type { Ledger, LedgerDb } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { handler, type MethodHandler, type Session } from \"../protocol-server/index.ts\";\nimport { appendEvent, latestCursor, readEvents } from \"./events.ts\";\nimport {\n applyMutation,\n documentFor,\n type FieldRow,\n liveFields,\n replayedMutation,\n} from \"./fields.ts\";\nimport { type HostConnections, Outbox } from \"./outbox.ts\";\nimport { buildResults, CHOICE, resultsMarkdown, submissionFor } from \"./results.ts\";\nimport {\n appendRunOutput,\n createOrJoinRun,\n finishRun,\n markRunning,\n openRuns,\n type RunEnd,\n type RunFlush,\n type RunOutput,\n type RunRow,\n runById,\n runByKey,\n runState,\n} from \"./runs.ts\";\nimport { raiseSignal } from \"./signals.ts\";\nimport {\n assertChannel,\n assertDraftOpen,\n closingSubmission,\n orphansOf,\n type Snapshot,\n type SubmissionRow,\n submissionSummary,\n submit,\n} from \"./submissions.ts\";\nimport { Subscriptions } from \"./subscriptions.ts\";\nimport {\n localViewerId,\n openView,\n viewControls,\n viewer,\n viewerForHost,\n viewerForLink,\n viewerForSpec,\n viewerForTailnet,\n viewFor,\n} from \"./viewers.ts\";\nimport { waitFor } from \"./wait.ts\";\n\nexport { createEphemeralBus, type EphemeralBus } from \"./ephemeral.ts\";\nexport { appendEvent, compactEvents, redactEvents } from \"./events.ts\";\nexport type { HostConnections } from \"./outbox.ts\";\nexport { policyInForce } from \"./policy.ts\";\nexport type { RunEnd, RunFlush, RunOutput, RunRow } from \"./runs.ts\";\nexport { SubmitConflict } from \"./submissions.ts\";\n\n/** How the interaction core finds an artifact a host names. */\nexport interface InteractionArtifacts {\n /** The artifact's ID; throws `MOSTRA_ARTIFACT_NOT_FOUND` for an unknown one. */\n resolve(ref: ArtifactRef): string;\n}\n\n/** Options for {@link createInteraction}. */\nexport interface InteractionOptions {\n readonly ledger: Ledger;\n readonly log: Log;\n readonly faults: Faults;\n readonly hosts: HostConnections & {\n /** Sends a notification on a connection; `false` when it is gone. */\n notify(session: number, method: string, params: unknown): boolean;\n /** Settles when a full connection drained; `undefined` when it can take more now. */\n drained(session: number): Promise<void> | undefined;\n };\n /** The hosts that always provide the submissions port (`HomeConfig.ports`, D105). */\n readonly expectedHosts: () => readonly string[];\n readonly artifacts: InteractionArtifacts;\n /**\n * Whether a version covers a field ID (D109): from the version's `registry.json`; every ID for\n * a version whose code can use IDs the builder couldn't know.\n */\n readonly coverage: (versionId: string) => (fieldId: string) => boolean;\n /** How long a host has to answer a port call (30 s; tests shorten it). */\n readonly portTimeoutMs?: number;\n}\n\n/** A browser session as the interaction core sees it: who it acts as. */\nexport interface PageIdentity {\n readonly artifactId: string;\n readonly viewerId: string;\n /** The link the page's session came from: a page names only views its own link opened. */\n readonly tokenId?: string;\n /** The link's scopes (D97): a page writes a review set's choice only with `review`. */\n readonly scopes?: readonly CapabilityScope[];\n}\n\n/** The interaction core of one instance. */\nexport interface Interaction {\n /** Starts delivering submissions and events. */\n start(): void;\n /** Stops delivering; pending deliveries stay in the outbox. */\n stop(): void;\n\n /** The viewer a capability token's sessions act as (D104): its own, or the home's local user. */\n viewerOf(tokenViewerId: string | undefined): string;\n /** A viewer by ID (D104). */\n viewer(viewerId: string): Viewer;\n /** The viewer for `view/url`'s `viewer`, inside the caller's transaction. */\n viewerForSpec(db: LedgerDb, spec: ViewerSpec): string;\n /** The viewer a host's identity port named (D143 item 2), in a transaction of its own. */\n viewerForHost(spec: ViewerSpec): string;\n /** A tailnet person by login (D158 item 2), in a transaction of its own. */\n viewerForTailnet(spec: ViewerSpec): string;\n /** A link's own viewer, for a tunnel visitor nobody named (D158 item 2). */\n viewerForLink(tokenId: string, name: string): string;\n /** Records a frame load of a version (D104), with the controls in force (D108); returns its ID. */\n openView(input: {\n readonly artifactId: string;\n readonly versionId: string;\n readonly viewerId: string;\n readonly tokenId?: string;\n readonly controls?: ControlsPolicy;\n }): string;\n /** The channels and controls a page's view was opened with (D108). */\n viewControls(page: PageIdentity, viewId: string): ControlsPolicy;\n\n /** A viewer's mutation of their draft or the artifact's state, from a page (IN-01, LL-01). */\n mutate(\n page: PageIdentity,\n input: {\n readonly viewId: string;\n readonly scope: FieldScope;\n readonly mutationId: string;\n readonly baseRevision: number;\n readonly ops: readonly FieldOp[];\n },\n ): MutationResult;\n /** A viewer's submit (IN-05); `SubmitConflict` under a closed `once`. */\n submit(\n page: PageIdentity,\n input: {\n readonly viewId: string;\n readonly expectedRevision: number;\n readonly channel: SubmitChannel;\n },\n ): SubmissionSummary & { readonly duplicate?: true };\n /**\n * The shell's trusted Choose (D65, D113): writes `review.<set>.choice` in the viewer's draft\n * through the `shell` channel, keeping the candidate's label.\n */\n choose(\n page: PageIdentity,\n input: {\n readonly viewId: string;\n readonly mutationId: string;\n readonly baseRevision: number;\n readonly reviewSetId: string;\n readonly candidateId: string;\n readonly label?: string;\n },\n ): MutationResult;\n /** The viewer's draft fields a version doesn't cover (D42, D109). */\n carryOver(\n page: PageIdentity,\n version: { readonly id: string; readonly number: number },\n ): CarryOver;\n /** Whether the viewer follows the artifact's new versions (D63). */\n following(page: PageIdentity): boolean;\n /** Sets the viewer's \"Always follow this artifact\" (D63, LL-03). */\n setFollowing(page: PageIdentity, follow: boolean): void;\n /** A viewer's signal (IN-09); returns its cursor. */\n signal(\n page: PageIdentity,\n input: { readonly viewId: string; readonly name: string; readonly payload?: unknown },\n ): string;\n /** Checks that a view belongs to this page's artifact and viewer (D104). */\n checkView(page: PageIdentity, viewId: string): void;\n /** Where a page stands: its viewer, draft, the artifact state and the newest cursor. */\n pageSnapshot(page: PageIdentity): StreamSnapshot;\n /** The events a page may see after a cursor (D104): never another viewer's draft or signals. */\n pageEvents(\n page: PageIdentity,\n after: number,\n limit: number,\n ): { readonly events: EventRecord[]; readonly cursor: string };\n /** Calls `listener` after every commit; returns the unsubscribe function. */\n onCommit(listener: () => void): () => void;\n\n /** The host protocol methods: `state/*`, `results/get`, `wait`, `events/*`. */\n methods(): MethodHandler[];\n /** A connection initialized: hosts with ports get their deliveries. */\n connected(session: Session): void;\n /** A connection closed: its subscriptions end. */\n disconnected(session: Session): void;\n /** The outbox per host, for `instance/status`. */\n deliveries(): DeliveryCounts[];\n\n // ── Actions (WP-08) ──────────────────────────────────────────────────────────────────────\n /** The version a page's view shows: plain calls and runs run there (D104). */\n viewVersion(page: PageIdentity, viewId: string): string;\n /**\n * Records an action run before any worker starts it, or joins the one its key or client key\n * names (AC-03); `started` tells the caller to run it.\n */\n startRun(\n page: PageIdentity,\n input: {\n readonly viewId: string;\n readonly fnId: string;\n readonly args: Batches;\n readonly key?: string;\n readonly clientKey: string;\n },\n ): { readonly state: RunState; readonly row: RunRow; readonly started: boolean };\n /** Runs a page asks for by ID, or by function and key (re-attach, AC-02). */\n runsFor(\n page: PageIdentity,\n input: {\n readonly viewId: string;\n readonly runIds?: readonly string[];\n readonly keyed?: readonly { readonly fnId: string; readonly key: string }[];\n readonly held?: readonly {\n readonly runId: string;\n readonly log: number;\n readonly batches: number;\n }[];\n },\n ): RunState[];\n /** One run of the page's artifact, for a cancel; `MOSTRA_ACTION_RUN_NOT_FOUND` otherwise. */\n runFor(page: PageIdentity, viewId: string, runId: string): RunRow;\n /** A run its worker has. */\n runRunning(runId: string): void;\n /** A run's new log lines, batches and progress. */\n runOutput(runId: string, output: RunOutput): RunFlush | undefined;\n /** Ends a run with its event. */\n endRun(runId: string, end: RunEnd): RunState | undefined;\n /** The runs not yet ended, optionally of one version. */\n openRuns(versionId?: string): RunRow[];\n /** A run's state now. */\n runState(runId: string): RunState | undefined;\n /** `signal()` from server code: `signal.raised`, source `action`, the run as cause (AC-05). */\n serverSignal(\n artifactId: string,\n input: {\n readonly name: string;\n readonly payload?: unknown;\n readonly runId?: string;\n readonly viewerId?: string;\n },\n ): string;\n /** `emit()` from server code: a `host.<name>` event (AC-05). */\n serverEmit(\n artifactId: string,\n input: {\n readonly type: string;\n readonly payload?: unknown;\n readonly runId?: string;\n readonly viewerId?: string;\n },\n ): string;\n /** The artifact state, for `state.get` in server code. */\n serverState(\n artifactId: string,\n ids?: readonly string[],\n ): { revision: string; fields: Record<string, FieldState> };\n /** A state write from server code, as the agent (D63). */\n serverPatch(\n artifactId: string,\n input: {\n readonly ops: readonly FieldOp[];\n readonly mutationId?: string;\n readonly baseRevision?: string;\n readonly runId?: string;\n },\n ): MutationResult;\n /** The artifacts a host subscription names, whose live producers it keeps running. */\n subscribedArtifacts(): Set<string>;\n /** Appends `worker.crashed` (DATA_MODEL §4, RT-04): the version, the cause, the backoff. */\n workerCrashed(crash: {\n readonly artifactId: string;\n readonly versionId: string;\n readonly cause: string;\n readonly kind: string;\n readonly backoffMs: number;\n readonly parked: boolean;\n }): string;\n /** Hears every `version.published` once it commits, by artifact; returns the stop. */\n onPublished(listener: (artifactId: string, versionId: string) => void): () => void;\n /**\n * Hears every submission once it commits, with its Results (INTERFACES §8): how a `mostra dev`\n * session reports what its preview's submits would deliver (D140 item 12). Returns the stop.\n */\n onSubmission(listener: (results: Results) => void): () => void;\n /** How many host subscriptions are open. */\n subscriptionCount(): number;\n}\n\nfunction runNotFound(runId: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_ACTION_RUN_NOT_FOUND\", {\n message: `This artifact has no action run ${String(runId).slice(0, 64)}.`,\n }),\n );\n}\n\n/** The number of a version. */\nfunction versionNumber(db: LedgerDb, versionId: string): number {\n const row = db.get<{ number: number }>(\"SELECT number FROM version WHERE id = ?\", versionId);\n if (!row) throw new Error(`No version ${versionId}.`);\n return row.number;\n}\n\n/**\n * Whether a page may see an event (D104, D130): never another viewer's draft, signal or view;\n * server code's signals only by the viewer whose call raised them; `host.*` events never (they\n * are for hosts, AC-05); an action's run events only through a link that may see its run.\n * `run` looks a run up by its ID.\n */\nfunction visibleTo(\n event: EventRecord,\n page: PageIdentity,\n run: (runId: string) => RunRow | undefined,\n): boolean {\n const viewerId = page.viewerId;\n if (event.type.startsWith(\"draft.\")) return event.payload[\"viewerId\"] === viewerId;\n if (event.type.startsWith(\"host.\")) return false;\n if (event.type.startsWith(\"action.\")) {\n const row = run(String(event.payload[\"runId\"] ?? \"\"));\n return row !== undefined && runVisible(row, page);\n }\n if (event.type === \"signal.raised\" && event.payload[\"source\"] === \"action\") {\n return event.payload[\"viewerId\"] === viewerId;\n }\n if (event.type === \"signal.raised\" || event.type.startsWith(\"view.\")) {\n return event.actor.kind !== \"viewer\" || event.actor.id === viewerId;\n }\n return true;\n}\n\n/**\n * Another viewer as a page sees them: kind and display name, never their viewer or view IDs\n * (D104; Claude review finding 12). The name stays, so a conflict can say who changed a field.\n */\nfunction actorForPage(actor: Actor, viewerId: string): Actor {\n if (actor.kind !== \"viewer\" || actor.id === viewerId) return actor;\n return { kind: \"viewer\", ...(actor.name !== undefined ? { name: actor.name } : {}) };\n}\n\n/** An event as a page sees it: other viewers' identities left out. */\nfunction eventForPage(event: EventRecord, viewerId: string): EventRecord {\n // A worker's crash shows a page only what the shell's notice needs: never the server code's\n // own output, which its cause quotes (Opus review 4).\n if (event.type === \"worker.crashed\") {\n const { cause: _cause, ...payload } = event.payload as Record<string, unknown>;\n return { ...event, payload };\n }\n if (event.type.startsWith(\"action.\") || event.type === \"signal.raised\") {\n // A run's or a signal's own viewer: a page sees only its own runs' viewer, so leave it out.\n const { viewerId: _viewer, ...payload } = event.payload as Record<string, unknown>;\n if (event.actor.kind !== \"viewer\") return { ...event, payload };\n }\n const own = event.actor.kind !== \"viewer\" || event.actor.id === viewerId;\n if (own) return event;\n const { viewerId: _viewer, viewId: _view, ...payload } = event.payload as Record<string, unknown>;\n const causation = event.causation\n ? Object.fromEntries(Object.entries(event.causation).filter(([key]) => key !== \"viewId\"))\n : undefined;\n return {\n ...event,\n actor: actorForPage(event.actor, viewerId),\n ...(causation ? { causation } : {}),\n payload,\n };\n}\n\n/** Fields as a page sees them: who last wrote each, without another viewer's ID. */\nfunction fieldsForPage(\n fields: Record<string, FieldState>,\n viewerId: string,\n): Record<string, FieldState> {\n return Object.fromEntries(\n Object.entries(fields).map(([id, field]) => [\n id,\n field.updatedBy ? { ...field, updatedBy: actorForPage(field.updatedBy, viewerId) } : field,\n ]),\n );\n}\n\n/**\n * Whether a page may see a run (D97 item 4, D104, D130): only through a link that may run its\n * function, and then a keyed run belongs to the artifact, since its key makes it one invocation\n * for everyone who may run it, while a run without a key is its viewer's own.\n */\nfunction runVisible(row: RunRow, page: PageIdentity): boolean {\n if (!scopeAllows(page.scopes ?? [], `action:${row.action}` as CapabilityScope)) return false;\n return row.key !== null || row.viewer_id === page.viewerId;\n}\n\n/** Creates the interaction core. */\n\nexport function createInteraction(options: InteractionOptions): Interaction {\n const { ledger, log, hosts } = options;\n const outbox = new Outbox({\n ledger,\n log,\n hosts,\n expected: options.expectedHosts,\n faults: options.faults,\n ...(options.portTimeoutMs !== undefined ? { portTimeoutMs: options.portTimeoutMs } : {}),\n });\n const subscriptions = new Subscriptions({\n ledger,\n log,\n notify: (session, method, params) => hosts.notify(session, method, params),\n drained: (session) => hosts.drained(session),\n });\n\n const pageActor = (page: PageIdentity): Actor => {\n const record = ledger.read((db) => viewer(db, page.viewerId));\n return {\n kind: \"viewer\",\n id: page.viewerId,\n ...(record.name !== undefined ? { name: record.name } : {}),\n };\n };\n\n const documentSnapshot = (db: LedgerDb, artifactId: string, viewerId: string | null) => {\n const document = documentFor(db, artifactId, viewerId);\n return {\n revision: String(document?.revision ?? 0),\n epoch: document?.epoch ?? 1,\n fields: liveFields(db, document?.id),\n };\n };\n\n const clientActor = (session: Session, as: \"agent\" | \"host\" = \"agent\"): Actor => ({\n kind: as,\n ...(session.client ? { id: session.client.name } : {}),\n });\n\n return {\n start() {\n outbox.start();\n subscriptions.start();\n },\n stop() {\n outbox.stop();\n subscriptions.stop();\n },\n\n viewerOf(tokenViewerId) {\n if (tokenViewerId !== undefined) return tokenViewerId;\n const existing = ledger.read((db) =>\n db.get<{ id: string }>(\n \"SELECT id FROM viewer WHERE kind = 'local' AND external_ref = 'local'\",\n ),\n );\n return existing?.id ?? ledger.write((db) => localViewerId(db));\n },\n viewer: (viewerId) => ledger.read((db) => viewer(db, viewerId)),\n viewerForSpec,\n viewerForHost: (spec) => ledger.write((db) => viewerForHost(db, spec)),\n viewerForTailnet: (spec) => ledger.write((db) => viewerForTailnet(db, spec)),\n viewerForLink: (tokenId, name) => ledger.write((db) => viewerForLink(db, tokenId, name)),\n openView(input) {\n return ledger.write((db) => openView(db, input));\n },\n viewControls(page, viewId) {\n return ledger.read((db) =>\n viewControls(viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId)),\n );\n },\n\n mutate(page, input) {\n const actor = pageActor(page);\n const outcome = ledger.write((db) => {\n const view = viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);\n const mutation = {\n artifactId: page.artifactId,\n scope: input.scope,\n ...(input.scope === \"viewer\" ? { viewerId: page.viewerId } : {}),\n mutationId: input.mutationId,\n baseRevision: input.baseRevision,\n ops: input.ops,\n actor,\n viewId: input.viewId,\n versionNumber: versionNumber(db, view.version_id),\n };\n // A committed mutation replays its result even after a submission closed the draft (D106):\n // the retry of a save whose answer was lost must not turn into a failure.\n const replay = replayedMutation(db, mutation);\n if (replay) return { result: replay, changed: false, replayed: true };\n if (input.scope === \"viewer\") {\n assertDraftOpen(db, page.artifactId, page.viewerId);\n if (input.ops.some((op) => CHOICE.test(op.id))) {\n // A choice needs the `review` scope however it is written, as the trusted Choose\n // does (D97; Claude review finding 7)…\n if (page.scopes !== undefined && !scopeAllows(page.scopes, \"review\")) {\n throw new RpcError(\n refusal(\"MOSTRA_HYGIENE_SCOPE_DENIED\", \"This link doesn't carry the review scope.\")\n .diagnostic,\n );\n }\n // …and a page's own choice is the artifact channel, which the host may not allow (D108).\n assertChannel(view, \"artifact\");\n }\n }\n return applyMutation(db, mutation);\n });\n const result = {\n ...outcome.result,\n conflicts: outcome.result.conflicts.map((conflict) =>\n conflict.updatedBy\n ? { ...conflict, updatedBy: actorForPage(conflict.updatedBy, page.viewerId) }\n : conflict,\n ),\n };\n if (outcome.changed && input.scope === \"viewer\")\n outbox.mirror(page.artifactId, page.viewerId);\n return result;\n },\n submit(page, input) {\n const owners = outbox.owners();\n const outcome = ledger.write((db) =>\n submit(db, {\n artifactId: page.artifactId,\n viewerId: page.viewerId,\n ...(page.tokenId !== undefined ? { tokenId: page.tokenId } : {}),\n viewId: input.viewId,\n expectedRevision: input.expectedRevision,\n channel: input.channel,\n owners,\n covers: options.coverage,\n }),\n );\n if (outcome.created) {\n log.info(\"interaction.submitted\", {\n artifactId: page.artifactId,\n submissionId: outcome.submission.id,\n channel: input.channel,\n });\n }\n // Read again after the commit: the outbox's first step runs on commit and may already have\n // marked a delivery waiting, which the answer must not contradict (Claude review finding 8).\n const fresh = ledger.read((db) => {\n const row = db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE id = ?\",\n outcome.submission.id,\n );\n return row ? submissionSummary(db, row) : undefined;\n });\n if (!fresh) return outcome.submission;\n return outcome.submission.duplicate ? { ...fresh, duplicate: true } : fresh;\n },\n choose(page, input) {\n const actor = pageActor(page);\n const outcome = ledger.write((db) => {\n const view = viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);\n assertChannel(view, \"shell\");\n const mutation = {\n artifactId: page.artifactId,\n scope: \"viewer\" as const,\n viewerId: page.viewerId,\n mutationId: input.mutationId,\n baseRevision: input.baseRevision,\n ops: [\n {\n id: `review.${input.reviewSetId}.choice`,\n value: input.candidateId,\n ...(input.label !== undefined ? { label: input.label } : {}),\n },\n ],\n actor,\n viewId: input.viewId,\n versionNumber: versionNumber(db, view.version_id),\n channel: \"shell\" as const,\n };\n const replay = replayedMutation(db, mutation);\n if (replay) return { result: replay, changed: false, replayed: true };\n assertDraftOpen(db, page.artifactId, page.viewerId);\n return applyMutation(db, mutation);\n });\n if (outcome.changed) outbox.mirror(page.artifactId, page.viewerId);\n return outcome.result;\n },\n carryOver(page, version) {\n const covers = options.coverage(version.id);\n return ledger.read((db) => {\n const draft = documentFor(db, page.artifactId, page.viewerId);\n const rows =\n draft === undefined\n ? []\n : db.all<FieldRow>(\n \"SELECT * FROM field WHERE document_id = ? AND deleted = 0 ORDER BY field_id\",\n draft.id,\n );\n return { version, orphans: orphansOf(rows.filter((row) => !covers(row.field_id))) };\n });\n },\n following(page) {\n return ledger.read(\n (db) =>\n db.get(\n \"SELECT 1 FROM follow WHERE viewer_id = ? AND artifact_id = ?\",\n page.viewerId,\n page.artifactId,\n ) !== undefined,\n );\n },\n setFollowing(page, follow) {\n ledger.write((db) => {\n if (follow) {\n db.run(\n \"INSERT OR IGNORE INTO follow (viewer_id, artifact_id, followed_at) VALUES (?, ?, ?)\",\n page.viewerId,\n page.artifactId,\n new Date().toISOString(),\n );\n } else {\n db.run(\n \"DELETE FROM follow WHERE viewer_id = ? AND artifact_id = ?\",\n page.viewerId,\n page.artifactId,\n );\n }\n });\n },\n signal(page, input) {\n const actor = pageActor(page);\n return ledger.write((db) => {\n viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);\n return raiseSignal(db, {\n artifactId: page.artifactId,\n name: input.name,\n ...(input.payload !== undefined ? { payload: input.payload } : {}),\n source: \"artifact\",\n actor,\n viewId: input.viewId,\n });\n });\n },\n checkView(page, viewId) {\n ledger.read((db) => viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId));\n },\n pageSnapshot(page) {\n return ledger.read((db) => {\n const closing = closingSubmission(db, page.artifactId, page.viewerId);\n const latestOwn =\n closing ??\n db.get<SubmissionRow>(\n \"SELECT * FROM submission WHERE artifact_id = ? AND viewer_id = ? ORDER BY position DESC LIMIT 1\",\n page.artifactId,\n page.viewerId,\n );\n return {\n cursor: String(latestCursor(db)),\n viewer: viewer(db, page.viewerId),\n draft: documentSnapshot(db, page.artifactId, page.viewerId),\n state: (() => {\n const state = documentSnapshot(db, page.artifactId, null);\n return { ...state, fields: fieldsForPage(state.fields, page.viewerId) };\n })(),\n ...(latestOwn ? { submission: submissionSummary(db, latestOwn) } : {}),\n ...(() => {\n // The latest version, so a page that missed its `version.published` learns of it.\n const latest = db.get<{ id: string; number: number }>(\n `SELECT version.id, version.number FROM artifact\n JOIN version ON version.id = artifact.latest_version_id WHERE artifact.id = ?`,\n page.artifactId,\n );\n return latest ? { latest: { id: latest.id, number: latest.number } } : {};\n })(),\n };\n });\n },\n pageEvents(page, after, limit) {\n // Read in pages until enough visible events or the end, so other viewers' events never\n // stall a page.\n return ledger.read((db) => {\n const events: EventRecord[] = [];\n let cursor = after;\n const runs = new Map<string, RunRow | undefined>();\n const runOf = (runId: string): RunRow | undefined => {\n if (!runs.has(runId)) runs.set(runId, runById(db, page.artifactId, runId));\n return runs.get(runId);\n };\n for (;;) {\n const read = readEvents(db, {\n filter: { artifacts: [page.artifactId] },\n after: cursor,\n limit,\n });\n for (const event of read.events) {\n if (events.length === limit) return { events, cursor: String(cursor) };\n cursor = Number(event.cursor);\n if (visibleTo(event, page, runOf)) events.push(eventForPage(event, page.viewerId));\n }\n cursor = Math.max(cursor, Number(read.cursor));\n if (read.events.length < limit || events.length === limit) {\n return { events, cursor: String(cursor) };\n }\n }\n });\n },\n onCommit: (listener) => ledger.onCommit(listener),\n\n methods: () => [\n handler(stateGetMethod, (params) => {\n const artifactId = options.artifacts.resolve(params.artifact);\n return ledger.read((db) => {\n const snapshot = documentSnapshot(db, artifactId, null);\n const fields =\n params.ids === undefined\n ? snapshot.fields\n : Object.fromEntries(\n Object.entries(snapshot.fields).filter(([id]) => params.ids?.includes(id)),\n );\n return { revision: snapshot.revision, fields };\n });\n }),\n handler(statePatchMethod, (params, session) => {\n const artifactId = options.artifacts.resolve(params.artifact);\n return ledger.write(\n (db) =>\n applyMutation(db, {\n artifactId,\n scope: \"artifact\",\n mutationId: params.mutationId,\n ...(params.baseRevision !== undefined\n ? { baseRevision: Number(params.baseRevision) }\n : {}),\n ops: params.ops,\n actor: clientActor(session, params.as),\n }).result,\n );\n }),\n handler(resultsGetMethod, (params) => {\n const artifactId = options.artifacts.resolve(params.artifact);\n return ledger.read((db) => {\n const row = submissionFor(db, artifactId, params.submission);\n const results = buildResults(db, row);\n if (params.format !== \"md\") return results;\n return {\n submissionId: row.id,\n markdown: resultsMarkdown(results, JSON.parse(row.snapshot_json) as Snapshot),\n };\n });\n }),\n handler(waitMethod, (params, session) =>\n waitFor({\n ledger,\n artifactId: options.artifacts.resolve(params.artifact),\n until: params.until,\n after: params.after === undefined ? undefined : Number(params.after),\n timeoutMs: params.timeoutMs,\n signal: session.signal,\n }),\n ),\n handler(eventsReadMethod, (params) =>\n ledger.read((db) =>\n readEvents(db, {\n filter: params.filter as EventFilter | undefined,\n after: params.after === undefined ? 0 : Number(params.after),\n limit: params.limit ?? 100,\n ...(params.acceptCompacted ? { acceptCompacted: true } : {}),\n }),\n ),\n ),\n handler(eventsSubscribeMethod, (params, session) => subscriptions.subscribe(session, params)),\n handler(eventsUnsubscribeMethod, (params, session) => {\n subscriptions.unsubscribe(session, params.subscriptionId);\n return {};\n }),\n handler(eventsAckMethod, (params, session) => {\n subscriptions.ack(session, params.subscriptionId, Number(params.cursor));\n return {};\n }),\n ],\n connected(session) {\n if (session.ports.has(\"submissions\") && session.client)\n outbox.registered(session.client.name);\n },\n disconnected(session) {\n subscriptions.closed(session.id);\n },\n deliveries: () => outbox.counts(),\n\n viewVersion(page, viewId) {\n return ledger.read(\n (db) => viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId).version_id,\n );\n },\n startRun(page, input) {\n const actor = pageActor(page);\n return ledger.write((db) => {\n const view = viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);\n const { row, joined } = createOrJoinRun(db, {\n artifactId: page.artifactId,\n versionId: view.version_id,\n viewId: view.id,\n viewerId: page.viewerId,\n fnId: input.fnId,\n args: input.args,\n ...(input.key !== undefined ? { key: input.key } : {}),\n clientKey: input.clientKey,\n actor,\n });\n // A joined run is shown only to a link that may see it (D130): the scope was checked for\n // the function asked, and the run joined is of that function, but say so here too.\n if (joined && !runVisible(row, page)) throw runNotFound(row.id);\n return { row, state: runState(db, row, joined), started: !joined };\n });\n },\n runsFor(page, input) {\n return ledger.read((db) => {\n viewFor(db, input.viewId, page.artifactId, page.viewerId, page.tokenId);\n const rows = new Map<string, RunRow>();\n for (const runId of input.runIds ?? []) {\n const row = runById(db, page.artifactId, runId);\n if (row && runVisible(row, page)) rows.set(row.id, row);\n }\n for (const entry of input.keyed ?? []) {\n const row = runByKey(db, page.artifactId, entry.fnId, entry.key);\n if (row && runVisible(row, page)) rows.set(row.id, row);\n }\n const held = new Map((input.held ?? []).map((entry) => [entry.runId, entry]));\n return [...rows.values()].map((row) => runState(db, row, undefined, held.get(row.id)));\n });\n },\n runFor(page, viewId, runId) {\n return ledger.read((db) => {\n viewFor(db, viewId, page.artifactId, page.viewerId, page.tokenId);\n const row = runById(db, page.artifactId, runId);\n if (!row || !runVisible(row, page)) throw runNotFound(runId);\n return row;\n });\n },\n runRunning(runId) {\n ledger.write((db) => markRunning(db, runId));\n },\n runOutput(runId, output) {\n return ledger.write((db) => appendRunOutput(db, runId, output));\n },\n endRun(runId, end) {\n return ledger.write((db) => {\n const row = finishRun(db, runId, end);\n return row ? runState(db, row) : undefined;\n });\n },\n openRuns(versionId) {\n return ledger.read((db) => openRuns(db, versionId));\n },\n runState(runId) {\n return ledger.read((db) => {\n const row = db.get<RunRow>(\"SELECT * FROM action_run WHERE id = ?\", runId);\n return row ? runState(db, row) : undefined;\n });\n },\n serverSignal(artifactId, input) {\n return ledger.write((db) =>\n raiseSignal(db, {\n artifactId,\n name: input.name,\n ...(input.payload !== undefined ? { payload: input.payload } : {}),\n source: \"action\",\n actor: { kind: \"agent\" },\n // No view: a page never learns another viewer's view from an action's signal (D104).\n // The viewer whose call raised it decides which page may see it.\n ...(input.viewerId !== undefined ? { viewerId: input.viewerId } : {}),\n ...(input.runId !== undefined ? { causation: { runId: input.runId } } : {}),\n }),\n );\n },\n serverEmit(artifactId, input) {\n return ledger.write((db) =>\n appendEvent(db, {\n artifactId,\n type: input.type,\n actor: { kind: \"agent\" },\n ...(input.runId !== undefined ? { causation: { runId: input.runId } } : {}),\n payload: {\n ...(input.payload === undefined ? {} : { data: input.payload }),\n ...(input.viewerId !== undefined ? { viewerId: input.viewerId } : {}),\n },\n }),\n );\n },\n serverState(artifactId, ids) {\n return ledger.read((db) => {\n const snapshot = documentSnapshot(db, artifactId, null);\n const fields =\n ids === undefined\n ? snapshot.fields\n : Object.fromEntries(\n Object.entries(snapshot.fields).filter(([id]) => ids.includes(id)),\n );\n return { revision: snapshot.revision, fields };\n });\n },\n serverPatch(artifactId, input) {\n return ledger.write(\n (db) =>\n applyMutation(db, {\n artifactId,\n scope: \"artifact\",\n mutationId: input.mutationId ?? MutationId.create(),\n ...(input.baseRevision !== undefined\n ? { baseRevision: Number(input.baseRevision) }\n : {}),\n ops: input.ops,\n actor: { kind: \"agent\", ...(input.runId !== undefined ? { id: input.runId } : {}) },\n }).result,\n );\n },\n subscribedArtifacts: () => subscriptions.subscribedArtifacts(),\n workerCrashed(crash) {\n return ledger.write((db) =>\n appendEvent(db, {\n artifactId: crash.artifactId,\n type: \"worker.crashed\",\n actor: { kind: \"mostra\" },\n payload: {\n versionId: crash.versionId,\n cause: crash.cause,\n kind: crash.kind,\n backoffMs: crash.backoffMs,\n parked: crash.parked,\n },\n }),\n );\n },\n onSubmission(listener) {\n let position = ledger.read(\n (db) =>\n db.get<{ last: number | null }>(\"SELECT MAX(position) AS last FROM submission\")?.last ??\n 0,\n );\n return ledger.onCommit(() => {\n const made = ledger.read((db) =>\n db\n .all<SubmissionRow>(\n \"SELECT * FROM submission WHERE position > ? ORDER BY position\",\n position,\n )\n .map((row) => ({ position: row.position, results: buildResults(db, row) })),\n );\n for (const { position: at, results } of made) {\n position = at;\n listener(results);\n }\n });\n },\n onPublished(listener) {\n let cursor = ledger.read((db) => latestCursor(db));\n return ledger.onCommit(() => {\n const published = ledger.read((db) =>\n db.all<{ cursor: number; artifact_id: string; payload_json: string }>(\n \"SELECT cursor, artifact_id, payload_json FROM event WHERE cursor > ? AND type = 'version.published' ORDER BY cursor\",\n cursor,\n ),\n );\n cursor = ledger.read((db) => latestCursor(db));\n for (const row of published) {\n const { versionId } = JSON.parse(row.payload_json) as { versionId: string };\n listener(row.artifact_id, versionId);\n }\n });\n },\n subscriptionCount: () => subscriptions.size,\n };\n}\n","/**\n * The content-addressed version store on disk (DATA_MODEL §1, FAILURE_MODEL §3): `versions/<id>/`\n * and `sources/<artifactId>/<sourceDigest>.tar.zst`. A version directory is assembled in staging,\n * synced and made read-only (`platform`: modes on POSIX, an access list on Windows), then renamed\n * into place; it becomes visible only when its ledger row\n * commits, and anything without a row is removed at the next start.\n */\nimport { mkdir, readdir, rm, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { fsyncPath, removeTree, renamePath, sealPlaced, sealTree } from \"../platform/index.ts\";\n\nexport { fsyncPath, removeTree, sealTree };\n\n/** The version store of one home. */\nexport interface VersionStore {\n readonly versionsDir: string;\n readonly sourcesDir: string;\n /** Where staging directories live (`cache/staging`), on the same file system as `versions/`. */\n readonly stagingDir: string;\n versionDir(versionId: string): string;\n snapshotPath(artifactId: string, sourceDigest: string): string;\n /** Seals `built` and renames it to `versions/<versionId>`, replacing a leftover without a row. */\n promote(built: string, versionId: string): Promise<void>;\n /** Removes staging, and version directories and snapshots no ledger row names. */\n sweep(known: {\n readonly versions: ReadonlySet<string>;\n readonly snapshots: ReadonlySet<string>;\n }): Promise<{ readonly versions: string[]; readonly snapshots: string[] }>;\n}\n\n/** Opens the version store of the home at `home`, creating its directories. */\nexport async function openVersionStore(home: string): Promise<VersionStore> {\n const versionsDir = join(home, \"versions\");\n const sourcesDir = join(home, \"sources\");\n const stagingDir = join(home, \"cache\", \"staging\");\n for (const dir of [versionsDir, sourcesDir, stagingDir])\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const versionDir = (versionId: string): string => join(versionsDir, versionId);\n return {\n versionsDir,\n sourcesDir,\n stagingDir,\n versionDir,\n snapshotPath: (artifactId, sourceDigest) =>\n join(sourcesDir, artifactId, `${sourceDigest}.tar.zst`),\n async promote(built, versionId) {\n await sealTree(built, true);\n const target = versionDir(versionId);\n // A directory without a ledger row is a leftover of an interrupted publish (FAILURE_MODEL §3).\n await removeTree(target);\n await renamePath(built, target);\n await sealPlaced(target);\n fsyncPath(versionsDir, true);\n },\n async sweep(known) {\n const removed = { versions: [] as string[], snapshots: [] as string[] };\n await removeTree(stagingDir);\n await mkdir(stagingDir, { recursive: true, mode: 0o700 });\n for (const name of await readdir(versionsDir)) {\n if (!known.versions.has(name)) {\n await removeTree(join(versionsDir, name));\n removed.versions.push(name);\n }\n }\n for (const artifact of await readdir(sourcesDir)) {\n const dir = join(sourcesDir, artifact);\n if (!(await stat(dir)).isDirectory()) continue;\n for (const name of await readdir(dir)) {\n if (!known.snapshots.has(`${artifact}/${name}`)) {\n await rm(join(dir, name), { force: true });\n removed.snapshots.push(`${artifact}/${name}`);\n }\n }\n }\n return removed;\n },\n };\n}\n","/**\n * The registry (DATA_MODEL §2, §3): which artifacts and versions exist, which source path each\n * artifact is bound to, and the content-addressed version store on disk. The publish module\n * commits a version through {@link Registry.commit}, one ledger transaction that resolves the\n * artifact's identity, inserts the version, binds the source and appends the events\n * (ARCHITECTURE §3 step 6). `artifact/list` and `artifact/get` read through it.\n */\nimport {\n type ArtifactDetail,\n type ArtifactManifest,\n type ArtifactRef,\n type ArtifactSummary,\n createDiagnostic,\n RpcError,\n type SubmissionPolicy,\n type VersionSummary,\n} from \"@mostra/protocol\";\nimport type { Faults } from \"../faults.ts\";\nimport { appendEvent, policyInForce } from \"../interaction/index.ts\";\nimport { type Ledger, type LedgerDb, type RequestKey, recordResult } from \"../ledger/index.ts\";\nimport { openVersionStore, type VersionStore } from \"./store.ts\";\n\nexport { fsyncPath, removeTree, type VersionStore } from \"./store.ts\";\n\ninterface ArtifactRow {\n id: string;\n title: string;\n family: string | null;\n links_json: string;\n policy_json: string | null;\n policy_chosen_json: string | null;\n created_at: string;\n latest_version_id: string | null;\n}\n\ninterface VersionRow {\n id: string;\n artifact_id: string;\n number: number;\n source_digest: string;\n env_digest: string;\n output_digest: string;\n manifest_json: string;\n forced_codes_json: string | null;\n published_at: string;\n verify_json?: string | null;\n /** When gc collected its files (D140), from `version_collected`; absent or null otherwise. */\n collected_at?: string | null;\n}\n\n/** Version rows with their collection, if any (D140 item 14). */\nconst VERSION_ROWS =\n \"SELECT version.*, (SELECT collected_at FROM version_collected WHERE version_id = version.id) AS collected_at FROM version\";\n\n/** A version to commit (ARCHITECTURE §3 step 6). */\nexport interface VersionCommit {\n /** The artifact the publish resolved before building. */\n readonly artifactId: string;\n /** The real path of the source (D51). */\n readonly bindingPath: string;\n /** The manifest's `id`, when it has one. */\n readonly manifestId: string | undefined;\n readonly versionId: string;\n readonly sourceDigest: string;\n readonly envDigest: string;\n /** Absent when the version already exists (a reuse). */\n readonly outputDigest: string | undefined;\n readonly manifest: ArtifactManifest;\n /** The policy this publish names; it sticks for later publishes that name none (D102). */\n readonly policy: SubmissionPolicy | undefined;\n /** The home's policy (`HomeConfig.submission`, D102). */\n readonly homePolicy?: SubmissionPolicy | undefined;\n readonly forcedCodes: readonly string[];\n /**\n * What verify found for this version (D138 item 4): `pass` only when its verdict had no error\n * and nothing was forced. Absent when no verify ran (a reuse, a repair).\n */\n readonly verify?: { readonly status: \"pass\" | \"fail\"; readonly verifyRevision: string };\n /**\n * Whether `path` still claims `artifactId` in its manifest (D51): a moved source no longer does,\n * a copy still does. Runs inside the transaction, so it must be synchronous.\n */\n readonly stillClaims: (path: string, artifactId: string) => boolean;\n /** Test fault points: `publish:in-commit` runs inside the transaction, before it commits. */\n readonly faults?: Faults;\n /**\n * The publish's `requestId` (H-03): its receipt is recorded in the same transaction, so a retry\n * after any crash replays exactly what the first attempt committed.\n */\n readonly request?: RequestKey | undefined;\n /** Runs inside the transaction, after the version and the binding are written. */\n readonly inTransaction?: (db: LedgerDb) => void;\n}\n\n/** What a commit recorded. */\nexport interface CommittedVersion {\n readonly version: number;\n /** The cursor of the version's `version.published` event. */\n readonly cursor: string;\n readonly reused: boolean;\n}\n\n/** The registry of one home. */\nexport interface Registry {\n readonly store: VersionStore;\n /**\n * The artifact a source would publish as, before building (D51): the manifest's `id`, else the\n * artifact its path is bound to, else a new one. {@link Registry.commit} checks it again.\n */\n identityFor(bindingPath: string, manifestId: string | undefined, generate: () => string): string;\n /** The artifact a source path is bound to, if any (D51). */\n artifactAt(bindingPath: string): string | undefined;\n /** The newest version of an artifact whose recorded verdict passed (D138 item 4). */\n passedVersion(artifactId: string): string | undefined;\n /** The version row of `versionId`, if it was committed. */\n hasVersion(versionId: string): boolean;\n /** Commits a version in one ledger transaction. Throws `MOSTRA_PUBLISH_ID_CONFLICT` for a copied ID. */\n commit(input: VersionCommit): CommittedVersion;\n /** The source path an artifact was last published from. */\n sourceOf(artifactId: string): string | undefined;\n /** One committed version: its artifact, number, output digest and manifest (WP-08's workers). */\n version(versionId: string):\n | {\n readonly artifactId: string;\n readonly number: number;\n readonly outputDigest: string;\n readonly manifest: ArtifactManifest;\n /** The error codes `--force` recorded when it was published (D41). */\n readonly forcedCodes: readonly string[];\n /** The verdict it was published on (D138 item 4); absent before verify existed. */\n readonly verify?: { readonly status: \"pass\" | \"fail\"; readonly verifyRevision: string };\n }\n | undefined;\n /** Every artifact's latest version, by artifact ID. */\n latestVersions(): ReadonlyMap<string, string>;\n list(filter?: { readonly family?: string }): ArtifactSummary[];\n /** One artifact in full; `MOSTRA_ARTIFACT_NOT_FOUND` when unknown. */\n get(ref: ArtifactRef): ArtifactDetail;\n /** Removes staging, and version directories and snapshots without a ledger row (FAILURE_MODEL §3). */\n recover(): Promise<{ readonly versions: string[]; readonly snapshots: string[] }>;\n}\n\nfunction conflict(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_PUBLISH_ID_CONFLICT\", { message }));\n}\n\nfunction notFound(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ARTIFACT_NOT_FOUND\", { message }));\n}\n\nconst versionSummary = (row: VersionRow): VersionSummary => {\n const forced = row.forced_codes_json ? (JSON.parse(row.forced_codes_json) as string[]) : [];\n return {\n id: row.id,\n number: row.number,\n publishedAt: row.published_at,\n sourceDigest: row.source_digest,\n envDigest: row.env_digest,\n outputDigest: row.output_digest,\n ...(forced.length > 0 ? { forcedDiagnostics: forced } : {}),\n ...(row.collected_at ? { collected: row.collected_at } : {}),\n };\n};\n\n/** Opens the registry over a home's ledger and version store. */\nexport async function openRegistry(options: {\n readonly home: string;\n readonly ledger: Ledger;\n}): Promise<Registry> {\n const { ledger } = options;\n const store = await openVersionStore(options.home);\n\n const boundArtifact = (db: LedgerDb, path: string): string | undefined =>\n db.get<{ artifact_id: string }>(\"SELECT artifact_id FROM source_binding WHERE path = ?\", path)\n ?.artifact_id;\n\n const summary = (\n db: LedgerDb,\n row: ArtifactRow,\n ): { summary: ArtifactSummary; latest: VersionRow | undefined } => {\n const latest = row.latest_version_id\n ? db.get<VersionRow>(`${VERSION_ROWS} WHERE id = ?`, row.latest_version_id)\n : undefined;\n const manifest = latest ? (JSON.parse(latest.manifest_json) as ArtifactManifest) : undefined;\n const source = db.get<{ path: string }>(\n \"SELECT path FROM source_binding WHERE artifact_id = ? ORDER BY bound_at DESC, path LIMIT 1\",\n row.id,\n )?.path;\n const result: ArtifactSummary = {\n id: row.id,\n title: row.title,\n ...(manifest?.description !== undefined ? { description: manifest.description } : {}),\n ...(row.family !== null ? { family: row.family } : {}),\n links: JSON.parse(row.links_json) as ArtifactSummary[\"links\"],\n mode: manifest?.mode ?? \"spa\",\n ...(row.policy_json ? { policy: JSON.parse(row.policy_json) as SubmissionPolicy } : {}),\n ...(source !== undefined ? { source } : {}),\n createdAt: row.created_at,\n ...(latest ? { latestVersion: versionSummary(latest) } : {}),\n };\n return { summary: result, latest };\n };\n\n return {\n store,\n identityFor(bindingPath, manifestId, generate) {\n if (manifestId !== undefined) return manifestId;\n return ledger.read((db) => boundArtifact(db, bindingPath)) ?? generate();\n },\n artifactAt(bindingPath) {\n return ledger.read((db) => boundArtifact(db, bindingPath));\n },\n passedVersion(artifactId) {\n return ledger.read(\n (db) =>\n db.get<{ id: string }>(\n \"SELECT id FROM version WHERE artifact_id = ? AND json_extract(verify_json, '$.status') = 'pass' ORDER BY number DESC LIMIT 1\",\n artifactId,\n )?.id,\n );\n },\n hasVersion(versionId) {\n return ledger.read(\n (db) => db.get(\"SELECT 1 FROM version WHERE id = ?\", versionId) !== undefined,\n );\n },\n commit(input) {\n return ledger.write((db) => {\n const now = new Date().toISOString();\n // Identity (D51): the manifest's id wins; a path bound elsewhere follows it; a moved source\n // rebinds; a copy that still claims the id is a conflict.\n if (input.manifestId !== undefined) {\n const others = db.all<{ path: string }>(\n \"SELECT path FROM source_binding WHERE artifact_id = ? AND path != ?\",\n input.manifestId,\n input.bindingPath,\n );\n for (const { path } of others) {\n if (input.stillClaims(path, input.manifestId)) {\n throw conflict(\n `${input.bindingPath} and ${path} both claim the artifact ID ${input.manifestId}.`,\n );\n }\n db.run(\"DELETE FROM source_binding WHERE path = ?\", path);\n }\n }\n const resolved =\n input.manifestId ?? boundArtifact(db, input.bindingPath) ?? input.artifactId;\n if (resolved !== input.artifactId) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_PUBLISH_SOURCE_CHANGED\", {\n message: `The artifact ${input.bindingPath} belongs to changed while it was being published.`,\n }),\n );\n }\n\n let artifact = db.get<ArtifactRow>(\"SELECT * FROM artifact WHERE id = ?\", input.artifactId);\n if (!artifact) {\n db.run(\n \"INSERT INTO artifact (id, title, family, links_json, policy_json, created_at, latest_version_id) VALUES (?, ?, ?, ?, ?, ?, NULL)\",\n input.artifactId,\n input.manifest.title,\n input.manifest.family ?? null,\n JSON.stringify(input.manifest.links ?? []),\n null,\n now,\n );\n appendEvent(db, {\n artifactId: input.artifactId,\n type: \"artifact.created\",\n payload: { title: input.manifest.title, family: input.manifest.family ?? null },\n });\n artifact = db.get<ArtifactRow>(\n \"SELECT * FROM artifact WHERE id = ?\",\n input.artifactId,\n ) as ArtifactRow;\n }\n\n const existing = db.get<VersionRow>(\"SELECT * FROM version WHERE id = ?\", input.versionId);\n let number: number;\n let cursor: string | undefined;\n if (existing) {\n number = existing.number;\n // Publishing a collected version's exact source restored its files (D140 item 14).\n db.run(\"DELETE FROM version_collected WHERE version_id = ?\", input.versionId);\n if (artifact.latest_version_id === input.versionId) {\n cursor = db\n .get<{ cursor: number }>(\n \"SELECT MAX(cursor) AS cursor FROM event WHERE artifact_id = ? AND type = 'version.published' AND json_extract(payload_json, '$.versionId') = ?\",\n input.artifactId,\n input.versionId,\n )\n ?.cursor?.toString();\n }\n } else {\n if (input.outputDigest === undefined)\n throw new Error(\"A new version needs its output digest.\");\n number =\n db.get<{ next: number }>(\n \"SELECT COALESCE(MAX(number), 0) + 1 AS next FROM version WHERE artifact_id = ?\",\n input.artifactId,\n )?.next ?? 1;\n db.run(\n \"INSERT INTO version (id, artifact_id, number, source_digest, env_digest, output_digest, manifest_json, forced_codes_json, published_at, verify_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n input.versionId,\n input.artifactId,\n number,\n input.sourceDigest,\n input.envDigest,\n input.outputDigest,\n JSON.stringify(input.manifest),\n input.forcedCodes.length > 0 ? JSON.stringify(input.forcedCodes) : null,\n now,\n input.verify ? JSON.stringify(input.verify) : null,\n );\n }\n if (cursor === undefined) {\n // A new version, or an earlier one published again: it becomes the latest (D09).\n cursor = appendEvent(db, {\n artifactId: input.artifactId,\n type: \"version.published\",\n payload: {\n versionId: input.versionId,\n number,\n forcedCodes: [...input.forcedCodes],\n ...(existing ? { republished: true } : {}),\n },\n });\n }\n const manifest = existing\n ? (JSON.parse(existing.manifest_json) as ArtifactManifest)\n : input.manifest;\n // D102: the policy in force, resolved at each publish and stored: this publish's policy, or\n // the one an earlier publish chose, then the home's, then the manifest's request.\n const chosen =\n input.policy ??\n (artifact.policy_chosen_json === null\n ? undefined\n : (JSON.parse(artifact.policy_chosen_json) as SubmissionPolicy));\n const policy = policyInForce(chosen, input.homePolicy, manifest.submission);\n db.run(\n \"UPDATE artifact SET title = ?, family = ?, links_json = ?, policy_json = ?, policy_chosen_json = ?, latest_version_id = ? WHERE id = ?\",\n manifest.title,\n manifest.family ?? null,\n JSON.stringify(manifest.links ?? []),\n JSON.stringify(policy),\n chosen === undefined ? null : JSON.stringify(chosen),\n input.versionId,\n input.artifactId,\n );\n db.run(\n \"INSERT INTO source_binding (path, artifact_id, bound_at) VALUES (?, ?, ?) ON CONFLICT(path) DO UPDATE SET artifact_id = excluded.artifact_id, bound_at = excluded.bound_at\",\n input.bindingPath,\n input.artifactId,\n now,\n );\n input.inTransaction?.(db);\n const committed = { version: number, cursor, reused: existing !== undefined };\n if (input.request !== undefined) {\n const receipt = {\n artifactId: input.artifactId,\n versionId: input.versionId,\n ...committed,\n ...(input.forcedCodes.length > 0 ? { forcedDiagnostics: [...input.forcedCodes] } : {}),\n };\n recordResult(db, input.request, receipt);\n }\n input.faults?.at(\"publish:in-commit\");\n return committed;\n });\n },\n version(versionId) {\n return ledger.read((db) => {\n const row = db.get<VersionRow>(\"SELECT * FROM version WHERE id = ?\", versionId);\n return row\n ? {\n artifactId: row.artifact_id,\n number: row.number,\n outputDigest: row.output_digest,\n manifest: JSON.parse(row.manifest_json) as ArtifactManifest,\n forcedCodes: row.forced_codes_json\n ? (JSON.parse(row.forced_codes_json) as string[])\n : [],\n ...(row.verify_json\n ? {\n verify: JSON.parse(row.verify_json) as {\n status: \"pass\" | \"fail\";\n verifyRevision: string;\n },\n }\n : {}),\n }\n : undefined;\n });\n },\n latestVersions() {\n return ledger.read(\n (db) =>\n new Map(\n db\n .all<{ id: string; latest_version_id: string }>(\n \"SELECT id, latest_version_id FROM artifact WHERE latest_version_id IS NOT NULL\",\n )\n .map((row) => [row.id, row.latest_version_id]),\n ),\n );\n },\n sourceOf(artifactId) {\n return ledger.read(\n (db) =>\n db.get<{ path: string }>(\n \"SELECT path FROM source_binding WHERE artifact_id = ? ORDER BY bound_at DESC, path LIMIT 1\",\n artifactId,\n )?.path,\n );\n },\n list(filter = {}) {\n return ledger.read((db) => {\n const rows = db.all<ArtifactRow & { published_at: string }>(\n `SELECT artifact.*, version.published_at FROM artifact\n JOIN version ON version.id = artifact.latest_version_id\n ${filter.family !== undefined ? \"WHERE artifact.family = ?\" : \"\"}\n ORDER BY (SELECT MAX(cursor) FROM event\n WHERE event.artifact_id = artifact.id AND event.type = 'version.published') DESC,\n artifact.id`,\n ...(filter.family !== undefined ? [filter.family] : []),\n );\n return rows.map((row) => summary(db, row).summary);\n });\n },\n get(ref) {\n return ledger.read((db) => {\n const id =\n \"artifactId\" in ref ? ref.artifactId : (boundArtifact(db, ref.path) ?? undefined);\n const row =\n id === undefined\n ? undefined\n : db.get<ArtifactRow>(\"SELECT * FROM artifact WHERE id = ?\", id);\n if (!row) {\n throw notFound(\n \"artifactId\" in ref\n ? `No artifact ${ref.artifactId} was published in this home.`\n : `No artifact was published from ${ref.path} in this home.`,\n );\n }\n const { summary: base, latest } = summary(db, row);\n const versions = db\n .all<VersionRow>(`${VERSION_ROWS} WHERE artifact_id = ? ORDER BY number DESC`, row.id)\n .map(versionSummary);\n return {\n ...base,\n manifest: latest\n ? (JSON.parse(latest.manifest_json) as ArtifactManifest)\n : { title: row.title },\n versions,\n };\n });\n },\n async recover() {\n const known = ledger.read((db) => ({\n // A collected version's files are what gc removes; one an interrupted gc left behind goes\n // now (D140 item 14).\n versions: new Set(\n db\n .all<{ id: string }>(\n \"SELECT id FROM version WHERE id NOT IN (SELECT version_id FROM version_collected)\",\n )\n .map((row) => row.id),\n ),\n snapshots: new Set(\n db\n .all<{ artifact_id: string; source_digest: string }>(\n \"SELECT artifact_id, source_digest FROM version WHERE id NOT IN (SELECT version_id FROM version_collected)\",\n )\n .map((row) => `${row.artifact_id}/${row.source_digest}.tar.zst`),\n ),\n }));\n return store.sweep(known);\n },\n };\n}\n","/**\n * Field-ID lint (AU-05, D52, D138 item 3): pure judgements over a version's static field scan\n * (`registry.json`'s `fields`, D109) and what the field probe saw mounted.\n *\n * - **Duplicate IDs**: one ID used with another hook kind, another scope or an initial value of\n * another type is an error, whether the static scan or the page shows it.\n * - **Shared IDs**: the same ID mounted several times the same way is a deliberate shared value,\n * a hint.\n * - **Changing IDs**: two fresh boots with identical inputs and one fixed clock; an ID mounted in\n * one and not the other, that no literal ID of the scan names, is an error.\n */\nimport { createDiagnostic, type Diagnostic, type ProbedField } from \"@mostra/protocol\";\nimport type { FieldCoverage, FieldEntry } from \"../builder/index.ts\";\n\nconst where = (entry: FieldEntry): string =>\n `${entry.location.file}:${entry.location.line}:${entry.location.column}`;\n\n/** The literal IDs the static scan names with two hooks or two scopes, with the two entries. */\nfunction staticConflicts(\n coverage: FieldCoverage | undefined,\n): { readonly id: string; readonly first: FieldEntry; readonly other: FieldEntry }[] {\n if (!coverage) return [];\n const byId = new Map<string, FieldEntry[]>();\n for (const entry of coverage.entries) {\n if (entry.id === undefined) continue;\n byId.set(entry.id, [...(byId.get(entry.id) ?? []), entry]);\n }\n const conflicts: { id: string; first: FieldEntry; other: FieldEntry }[] = [];\n for (const [id, entries] of byId) {\n const first = entries[0] as FieldEntry;\n const other = entries.find(\n (entry) =>\n entry.hook !== first.hook || (entry.scope ?? \"viewer\") !== (first.scope ?? \"viewer\"),\n );\n if (other) conflicts.push({ id, first, other });\n }\n return conflicts;\n}\n\nconst staticConflictIds = (coverage: FieldCoverage | undefined): ReadonlySet<string> =>\n new Set(staticConflicts(coverage).map((conflict) => conflict.id));\n\n/** Static duplicates: one literal ID named by two hooks, or with two literal scopes. */\nexport function staticFieldLint(coverage: FieldCoverage | undefined): Diagnostic[] {\n const findings: Diagnostic[] = [];\n for (const { id, first, other } of staticConflicts(coverage)) {\n const how =\n other.hook !== first.hook\n ? `with ${first.hook} at ${where(first)} and ${other.hook} at ${where(other)}`\n : `with scope ${first.scope ?? \"viewer\"} at ${where(first)} and scope ${other.scope ?? \"viewer\"} at ${where(other)}`;\n findings.push(\n createDiagnostic(\"MOSTRA_FIELD_DUPLICATE_ID\", {\n message: `The field ID \"${id}\" is used for two different fields: ${how}.`,\n location: other.location,\n }),\n );\n }\n return findings;\n}\n\n/**\n * What the probe saw: conflicting mounts (errors) and IDs mounted more than once (hints). An ID\n * the static scan already reported as a duplicate isn't reported again.\n */\nexport function probedFieldLint(\n fields: readonly ProbedField[],\n viewport: string,\n coverage?: FieldCoverage,\n): Diagnostic[] {\n const flagged = staticConflictIds(coverage);\n const findings: Diagnostic[] = [];\n for (const field of fields) {\n if (field.conflicts.length > 0) {\n if (flagged.has(field.id)) continue;\n findings.push(\n createDiagnostic(\"MOSTRA_FIELD_DUPLICATE_ID\", {\n message: `The page mounted the field ID \"${field.id}\" for two different fields: ${field.conflicts.join(\"; \")}.`,\n location: { viewport },\n }),\n );\n } else if (field.mounts > 1) {\n findings.push(\n createDiagnostic(\"MOSTRA_FIELD_SHARED\", {\n message: `${field.mounts} mounted components use the field ID \"${field.id}\" the same way, so they edit one saved value.`,\n location: { viewport },\n }),\n );\n }\n }\n return findings;\n}\n\n/** Whether a literal ID of the static scan names `id`. */\nconst literal = (coverage: FieldCoverage | undefined, id: string): boolean =>\n coverage?.entries.some((entry) => entry.id === id) ?? false;\n\n/**\n * IDs that differ between two boots with identical inputs (D138 item 3): mounted in one and not\n * the other, and named by no literal ID of the scan.\n */\nexport function unstableFieldLint(\n first: readonly ProbedField[],\n second: readonly ProbedField[],\n coverage: FieldCoverage | undefined,\n viewport: string,\n): Diagnostic[] {\n const mounted = (fields: readonly ProbedField[]): Set<string> =>\n new Set(fields.filter((field) => field.mounts > 0).map((field) => field.id));\n const a = mounted(first);\n const b = mounted(second);\n const changed = [...a].filter((id) => !b.has(id) && !literal(coverage, id));\n const appeared = [...b].filter((id) => !a.has(id) && !literal(coverage, id));\n if (changed.length === 0 && appeared.length === 0) return [];\n const sample = (ids: string[]): string =>\n ids\n .slice(0, 3)\n .map((id) => `\"${id}\"`)\n .join(\", \");\n return [\n createDiagnostic(\"MOSTRA_FIELD_ID_UNSTABLE\", {\n message: `Two loads of the page with identical inputs mounted different field IDs: ${sample(changed) || \"none\"} the first time, ${sample(appeared) || \"none\"} the second. A viewer's saved answers under them would be lost on reload.`,\n location: { viewport },\n }),\n ];\n}\n","/**\n * Regressions against the last passing version (AX-04, ROUND-3 §9, D138 item 4): contracts from\n * the two versions' `registry.json`, the controls and landmarks of their ARIA snapshots, and the\n * share of pixels that differ. Every regression is a warning that says what was observed (D72):\n * a redesign may change any of them on purpose.\n */\nimport { createDiagnostic, type Diagnostic } from \"@mostra/protocol\";\nimport { coverageMatcher, type VersionRegistry } from \"../builder/index.ts\";\n\n/** The share of differing pixels above which a viewport counts as changed. */\nexport const PIXEL_THRESHOLD = 0.01;\n\n/** The roles a regression of the ARIA snapshot compares: controls and landmarks. */\nconst COMPARED_ROLES = new Set([\n \"button\",\n \"link\",\n \"textbox\",\n \"searchbox\",\n \"checkbox\",\n \"radio\",\n \"switch\",\n \"combobox\",\n \"listbox\",\n \"slider\",\n \"spinbutton\",\n \"tab\",\n \"menuitem\",\n \"main\",\n \"navigation\",\n \"banner\",\n \"contentinfo\",\n \"form\",\n \"search\",\n \"region\",\n \"dialog\",\n]);\n\n/**\n * The controls and landmarks of an ARIA snapshot, as `role \"name\"` with digits folded, so a\n * counter or a date in a name doesn't read as a removed control.\n */\nexport function ariaControls(snapshot: string): string[] {\n const found: string[] = [];\n for (const match of snapshot.matchAll(/^\\s*- ([a-z]+)(?: \"((?:[^\"\\\\]|\\\\.)*)\")?/gm)) {\n const role = match[1] as string;\n if (!COMPARED_ROLES.has(role)) continue;\n const name = (match[2] ?? \"\").replace(/\\d+/g, \"#\").trim();\n found.push(name ? `${role} \"${name}\"` : role);\n }\n return found;\n}\n\n/** The controls and landmarks the baseline had and the candidate doesn't, counting repeats. */\nexport function removedControls(baseline: string, candidate: string): string[] {\n const left = new Map<string, number>();\n for (const control of ariaControls(candidate)) left.set(control, (left.get(control) ?? 0) + 1);\n const removed: string[] = [];\n for (const control of ariaControls(baseline)) {\n const count = left.get(control) ?? 0;\n if (count > 0) left.set(control, count - 1);\n else removed.push(control);\n }\n return removed;\n}\n\n/** The ARIA regression of one viewport, if the baseline had controls the candidate lacks. */\nexport function ariaRegression(\n baseline: string,\n candidate: string,\n viewport: string,\n): { readonly diagnostic: Diagnostic; readonly summary: string } | undefined {\n const removed = removedControls(baseline, candidate);\n if (removed.length === 0) return undefined;\n const shown = removed.slice(0, 5).join(\", \");\n const more = removed.length > 5 ? ` and ${removed.length - 5} more` : \"\";\n const summary = `${viewport}: ${shown}${more}`;\n return {\n summary,\n diagnostic: createDiagnostic(\"MOSTRA_REGRESSION_ARIA\", {\n message: `Observed at ${viewport}: the last passing version showed ${shown}${more}, which this source doesn't.`,\n location: { viewport },\n }),\n };\n}\n\n/** The pixel regression of one viewport, when its difference passes {@link PIXEL_THRESHOLD}. */\nexport function pixelRegression(\n ratio: number,\n sizeChanged: boolean,\n viewport: string,\n diffPath: string,\n): Diagnostic | undefined {\n if (!sizeChanged && ratio <= PIXEL_THRESHOLD) return undefined;\n return createDiagnostic(\"MOSTRA_REGRESSION_PIXELS\", {\n message: `Observed at ${viewport}: ${(ratio * 100).toFixed(1)} % of the pixels differ from the last passing version, rendered in the same run with the same clock and data. The difference is in ${diffPath}.`,\n location: { viewport },\n });\n}\n\n/**\n * What the candidate's registry drops of the baseline's: literal field IDs it no longer covers,\n * server functions, live sources and page routes. `savedAnswers` counts the answers the home holds\n * under a field ID, which become orphans when viewers switch (D42).\n */\nexport function contractRegressions(\n baseline: VersionRegistry,\n candidate: VersionRegistry,\n savedAnswers: (fieldId: string) => number,\n): { readonly diagnostics: Diagnostic[]; readonly summary: string[] } {\n const diagnostics: Diagnostic[] = [];\n const summary: string[] = [];\n const covers = coverageMatcher(candidate.fields);\n const fields = new Set(\n (baseline.fields?.entries ?? []).flatMap((entry) => (entry.id !== undefined ? [entry.id] : [])),\n );\n for (const id of [...fields].sort()) {\n if (covers(id)) continue;\n const saved = savedAnswers(id);\n summary.push(`field ${id}`);\n diagnostics.push(\n createDiagnostic(\"MOSTRA_REGRESSION_FIELD_REMOVED\", {\n message: `Observed: the last passing version used the field ID \"${id}\" and this source doesn't${saved > 0 ? `; ${saved} saved ${saved === 1 ? \"answer\" : \"answers\"} under it won't carry over` : \"\"}.`,\n }),\n );\n }\n const actions = new Set(candidate.actions.map((entry) => entry.id));\n for (const entry of baseline.actions) {\n if (actions.has(entry.id)) continue;\n summary.push(`action ${entry.id}`);\n diagnostics.push(\n createDiagnostic(\"MOSTRA_REGRESSION_ACTION_REMOVED\", {\n message: `Observed: the last passing version had the server function ${entry.id} and this source doesn't.`,\n }),\n );\n }\n const sources = new Set(candidate.liveSources.map((entry) => entry.key));\n for (const entry of baseline.liveSources) {\n if (sources.has(entry.key)) continue;\n summary.push(`live source ${entry.key}`);\n diagnostics.push(\n createDiagnostic(\"MOSTRA_REGRESSION_LIVE_REMOVED\", {\n message: `Observed: the last passing version had the live source ${entry.key} and this source doesn't.`,\n }),\n );\n }\n const pages = new Set(candidate.pages.map((page) => page.path));\n for (const page of baseline.pages) {\n if (pages.has(page.path)) continue;\n summary.push(`page ${page.path}`);\n diagnostics.push(\n createDiagnostic(\"MOSTRA_REGRESSION_PAGE_REMOVED\", {\n message: `Observed: the last passing version had the page ${page.path} and this source doesn't.`,\n }),\n );\n }\n return { diagnostics, summary };\n}\n","/**\n * HTTP plumbing shared by the gateway's listeners: the headers every response carries (D98 item\n * 6, D98 item 4), refusal responses, cookies and JSON bodies. No policy lives here beyond the\n * response shapes; the checks themselves are `@mostra/protocol`'s `checkRequest` and the route\n * declarations in `routes.ts`.\n */\nimport type { IncomingMessage } from \"node:http\";\nimport type { HttpBindings } from \"@hono/node-server\";\nimport type { Diagnostic, Refusal } from \"@mostra/protocol\";\nimport { refusal } from \"@mostra/protocol\";\n\n/** The Hono environment of a listener: Node's request and response objects. */\nexport type HttpEnv = { Bindings: HttpBindings };\n\n/** The longest JSON body a gateway endpoint reads. */\nexport const MAX_JSON_BODY: number = 64 * 1024;\n\n/** Headers on every gateway response (D98 item 6). */\nexport const BASE_HEADERS: Readonly<Record<string, string>> = {\n \"cross-origin-resource-policy\": \"same-origin\",\n \"referrer-policy\": \"no-referrer\",\n \"x-content-type-options\": \"nosniff\",\n};\n\n/** A listener's identity, which decides its framing headers. */\nexport interface ListenerKind {\n readonly kind: \"shell\" | \"artifact\";\n /** The listener's own origin. */\n readonly origin: string;\n /** The shell's origin: the only page that may frame an artifact (D98 item 4). */\n readonly shellOrigin: string;\n}\n\n/**\n * The framing and content-security headers of a document: the shell is never framed, and its own\n * page loads only from itself; an artifact page may be framed by the shell alone. An artifact's\n * content is otherwise unrestricted (D05): only `frame-ancestors` is set.\n */\nexport function documentHeaders(\n listener: ListenerKind,\n frameOrigins: string,\n): Record<string, string> {\n if (listener.kind === \"shell\") {\n return {\n \"content-security-policy\": [\n \"default-src 'self'\",\n \"script-src 'self'\",\n \"style-src 'self'\",\n \"img-src 'self' data:\",\n \"connect-src 'self'\",\n `frame-src ${frameOrigins}`,\n \"frame-ancestors 'none'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n \"object-src 'none'\",\n ].join(\"; \"),\n \"x-frame-options\": \"DENY\",\n // Popups the artifact frame opens get no opener, so none can navigate this page (D98\n // item 7): Firefox lets even a sandboxed popup navigate `opener.top`.\n \"cross-origin-opener-policy\": \"same-origin\",\n };\n }\n return { \"content-security-policy\": `frame-ancestors ${listener.shellOrigin}` };\n}\n\n/** Every header of a request as `[name, value]` pairs, repeats kept. */\nexport function headerPairs(incoming: IncomingMessage): [string, string][] {\n const pairs: [string, string][] = [];\n const raw = incoming.rawHeaders;\n for (let index = 0; index + 1 < raw.length; index += 2) {\n pairs.push([raw[index] as string, raw[index + 1] as string]);\n }\n return pairs;\n}\n\n/** The header the worker-mode service worker adds to a navigation it sends on (D70). */\nexport const NAVIGATION_HEADER = \"x-mostra-navigation\";\n\n/** Whether a request is a navigation that should get an HTML page rather than JSON. */\nexport function wantsDocument(headers: Headers): boolean {\n // A worker-mode frame's navigation, which its service worker sends again as a plain request\n // (D70): the browser marks that one `Sec-Fetch-Dest: empty`.\n if (headers.get(NAVIGATION_HEADER) === \"1\") return true;\n const dest = headers.get(\"sec-fetch-dest\");\n if (dest !== null) return dest === \"document\" || dest === \"iframe\" || dest === \"frame\";\n return (headers.get(\"accept\") ?? \"\").includes(\"text/html\");\n}\n\n/** Escapes text for HTML. */\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (char) => `&#${char.charCodeAt(0)};`);\n}\n\n/** A plain page for a refused navigation: no scripts, no external resources. */\nfunction refusalPage(diagnostic: Diagnostic): string {\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"referrer\" content=\"no-referrer\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Mostra</title><style>body{font-family:system-ui,sans-serif;margin:0;min-height:100vh;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:.25rem;padding:2rem;text-align:center;color-scheme:light dark}h1{font-size:1.25rem;margin:0}p{margin:0;opacity:.8}code{opacity:.5;font-size:.75rem;margin-top:1rem}</style></head><body><h1>${escapeHtml(diagnostic.message)}</h1>${diagnostic.hint ? `<p>${escapeHtml(diagnostic.hint)}</p>` : \"\"}<code>${escapeHtml(diagnostic.code)}</code></body></html>`;\n}\n\n/** The response for a refusal: the diagnostic as JSON, or a plain page for a navigation. */\nexport function refusalResponse(\n refused: Refusal & { readonly retryAfter?: number },\n options: {\n readonly document: boolean;\n readonly method?: string;\n readonly frameAncestors?: string;\n },\n): Response {\n const headers: Record<string, string> = { ...BASE_HEADERS, \"cache-control\": \"no-store\" };\n if (refused.retryAfter !== undefined) headers[\"retry-after\"] = String(refused.retryAfter);\n if (refused.status === 405) headers[\"allow\"] = \"GET, HEAD, POST\";\n const head = options.method === \"HEAD\";\n if (options.document) {\n headers[\"content-type\"] = \"text/html; charset=utf-8\";\n // The page has an inline style and nothing else; only the shell may frame it (on artifacts).\n headers[\"content-security-policy\"] = [\n \"default-src 'none'\",\n \"style-src 'unsafe-inline'\",\n `frame-ancestors ${options.frameAncestors ?? \"'none'\"}`,\n \"base-uri 'none'\",\n ].join(\"; \");\n return new Response(head ? null : refusalPage(refused.diagnostic), {\n status: refused.status,\n headers,\n });\n }\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n return new Response(head ? null : JSON.stringify(refused.diagnostic), {\n status: refused.status,\n headers,\n });\n}\n\n/** A JSON response with the base headers, never cached. */\nexport function jsonResponse(\n body: unknown,\n init: { readonly status?: number; readonly headers?: Record<string, string> } = {},\n): Response {\n return new Response(JSON.stringify(body), {\n status: init.status ?? 200,\n headers: {\n ...BASE_HEADERS,\n \"cache-control\": \"no-store\",\n \"content-type\": \"application/json; charset=utf-8\",\n ...init.headers,\n },\n });\n}\n\n/** Every value of the cookie `name` in a `Cookie` header, in order (D98: there may be several). */\nexport function cookieValues(header: string | null, name: string): string[] {\n if (header === null) return [];\n const values: string[] = [];\n for (const part of header.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index < 0) continue;\n if (part.slice(0, index).trim() === name) values.push(part.slice(index + 1).trim());\n }\n return values;\n}\n\n/**\n * The `Set-Cookie` value of a session cookie (D98 item 1): never `Secure` over loopback HTTP,\n * always over a tunnel's HTTPS address (D158), where it must never travel in clear.\n */\nexport function sessionCookie(\n name: string,\n value: string,\n path: string,\n maxAgeSeconds: number,\n secure = false,\n): string {\n return `${name}=${value}; Path=${path}; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Strict${secure ? \"; Secure\" : \"\"}`;\n}\n\n/**\n * Reads a JSON object body of at most `maxBytes` (default {@link MAX_JSON_BODY}) bytes; a larger,\n * unreadable or non-object body is `MOSTRA_HYGIENE_REQUEST_MALFORMED`.\n */\nexport async function readJsonObject(\n request: Request,\n maxBytes: number = MAX_JSON_BODY,\n): Promise<Record<string, unknown> | Refusal> {\n const length = Number(request.headers.get(\"content-length\") ?? \"0\");\n if (length > maxBytes) {\n return refusal(\n \"MOSTRA_HYGIENE_REQUEST_MALFORMED\",\n \"The request body is larger than this endpoint reads.\",\n 413,\n );\n }\n let text: string;\n try {\n const chunks: Uint8Array[] = [];\n let size = 0;\n const reader = request.body?.getReader();\n for (;;) {\n if (!reader) break;\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n // A body sent without Content-Length is cut off as soon as it passes the limit.\n if (size > maxBytes) {\n await reader.cancel();\n return refusal(\n \"MOSTRA_HYGIENE_REQUEST_MALFORMED\",\n \"The request body is larger than this endpoint reads.\",\n 413,\n );\n }\n chunks.push(value);\n }\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.concat(chunks));\n } catch {\n return refusal(\n \"MOSTRA_HYGIENE_REQUEST_MALFORMED\",\n \"The request body couldn't be read as UTF-8.\",\n );\n }\n try {\n const value: unknown = text === \"\" ? {} : JSON.parse(text);\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return refusal(\"MOSTRA_HYGIENE_REQUEST_MALFORMED\", \"The request body must be a JSON object.\");\n }\n return value as Record<string, unknown>;\n } catch {\n return refusal(\"MOSTRA_HYGIENE_REQUEST_MALFORMED\", \"The request body isn't valid JSON.\");\n }\n}\n\n/** Whether a value is a {@link Refusal}. */\nexport function isRefusal(value: unknown): value is Refusal {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"status\" in value &&\n \"diagnostic\" in value &&\n typeof (value as { status: unknown }).status === \"number\"\n );\n}\n","/**\n * The browser protocol's action and live routes (INTERFACES §4, WP-08): `call/{fnId}` (a plain\n * server-function call, its result streamed as NDJSON), `runs` (start or join a durable run),\n * `runs/attach` (read runs and follow them), `runs/{id}/cancel`, and `live` (read live sources\n * and keep them produced). They run behind the route table's checks (session, CSRF, Origin, scope;\n * D96, D97 item 4), and each function a request names is checked against the link's\n * `action:<name>` scopes. Mostra's cookies never reach a worker: only the call's arguments and its\n * context (viewer, view, run) do (D38).\n */\nimport {\n CallRequest,\n type CapabilityScope,\n type Diagnostic,\n LiveRequest,\n RpcError,\n RunAttachRequest,\n RunCancelRequest,\n RunRequest,\n refusal,\n scopeAllows,\n} from \"@mostra/protocol\";\nimport type * as z from \"zod\";\nimport type { Actions } from \"../actions/index.ts\";\nimport type { Interaction, PageIdentity } from \"../interaction/index.ts\";\nimport type { Live } from \"../live/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { BASE_HEADERS, isRefusal, jsonResponse, readJsonObject } from \"./http.ts\";\nimport type { RouteContext } from \"./routes.ts\";\n\n/** The largest request body: 16 MiB of arguments and the envelope. */\nconst ACTION_BODY_MAX: number = 17 * 1024 * 1024;\n\n/** The HTTP status of each diagnostic these routes answer. */\nconst STATUS: Readonly<Record<string, number>> = {\n MOSTRA_HOST_INVALID_PARAMS: 400,\n MOSTRA_ACTION_UNKNOWN_FUNCTION: 404,\n MOSTRA_ACTION_RUN_NOT_FOUND: 404,\n MOSTRA_ACTION_TOO_LARGE: 413,\n MOSTRA_ACTION_UNSERIALIZABLE: 400,\n MOSTRA_SUBMIT_VIEW_INVALID: 403,\n MOSTRA_HYGIENE_SCOPE_DENIED: 403,\n MOSTRA_RUNTIME_WORKER_PARKED: 503,\n MOSTRA_RUNTIME_WORKER_CRASHED: 503,\n // A verify run's sandbox refuses an action that didn't opt into `dryRun()` (D55, D138).\n MOSTRA_VERIFY_ACTION_SKIPPED: 409,\n MOSTRA_HOME_DISK_FULL: 507,\n MOSTRA_HOME_GONE: 503,\n};\n\ntype Handler = (context: RouteContext) => Response | Promise<Response>;\n\n/** The handlers. */\nexport interface ActionRoutes {\n readonly call: Handler;\n readonly runs: Handler;\n readonly attach: Handler;\n readonly cancel: Handler;\n readonly live: Handler;\n}\n\n/** Options for {@link actionRoutes}. */\nexport interface ActionRoutesOptions {\n readonly interaction: Interaction;\n readonly actions: Actions;\n readonly live: Live;\n readonly log: Log;\n /** The browser-protocol revisions served. */\n readonly revisions: readonly string[];\n}\n\nfunction answer(diagnostic: Diagnostic, status: number): Response {\n return jsonResponse({ ...diagnostic }, { status });\n}\n\nfunction failure(error: unknown): Response {\n if (error instanceof RpcError)\n return answer(error.diagnostic, STATUS[error.diagnostic.code] ?? 500);\n throw error;\n}\n\nfunction denied(fnId: string): Response {\n return answer(\n refusal(\n \"MOSTRA_HYGIENE_SCOPE_DENIED\",\n `This link may not run the server function ${fnId.slice(0, 200)}.`,\n 403,\n ).diagnostic,\n 403,\n );\n}\n\nasync function body<T>(context: RouteContext, schema: z.ZodType<T>): Promise<T | Response> {\n const raw = await readJsonObject(context.request, ACTION_BODY_MAX);\n if (isRefusal(raw)) return answer(raw.diagnostic, raw.status);\n const parsed = schema.safeParse(raw);\n if (parsed.success) return parsed.data;\n const [issue] = parsed.error.issues;\n return answer(\n refusal(\n \"MOSTRA_HYGIENE_REQUEST_MALFORMED\",\n `The request body doesn't match the browser protocol at ${issue?.path.join(\".\") || \"(root)\"}: ${issue?.message ?? \"invalid\"}.`,\n ).diagnostic,\n 400,\n );\n}\n\n/** The routes' handlers. */\nexport function actionRoutes(options: ActionRoutesOptions): ActionRoutes {\n const { interaction, actions, live, log } = options;\n\n const served = (context: RouteContext): Response | undefined => {\n const rev = context.params[\"rev\"];\n if (rev !== undefined && options.revisions.includes(rev)) return undefined;\n return answer(\n refusal(\n \"MOSTRA_HYGIENE_NOT_SERVED\",\n `This gateway serves browser-protocol revisions ${options.revisions.join(\", \")}, not ${String(rev)}.`,\n 404,\n ).diagnostic,\n 404,\n );\n };\n\n const pageOf = (context: RouteContext): PageIdentity => {\n const session = context.session;\n const artifactId = context.artifactId;\n if (!session || artifactId === undefined) throw new Error(\"session route without a session\");\n return {\n artifactId,\n viewerId: interaction.viewerOf(session.viewerId),\n tokenId: session.grant.tokenId,\n scopes: session.grant.scopes,\n };\n };\n\n const may = (page: PageIdentity, fnId: string): boolean =>\n scopeAllows(page.scopes ?? [], `action:${fnId}` as CapabilityScope);\n\n return {\n async call(context) {\n const refused = served(context);\n if (refused) return refused;\n const fnId = context.params[\"fn\"] ?? \"\";\n const request = await body(context, CallRequest);\n if (request instanceof Response) return request;\n const page = pageOf(context);\n // The route checked `action:<fnId>` already (D97 item 4); this keeps the rule in one place.\n if (!may(page, fnId)) return denied(fnId);\n let lines: AsyncIterable<unknown>;\n const abort = new AbortController();\n context.request.signal.addEventListener(\"abort\", () => abort.abort(), { once: true });\n try {\n lines = await actions.call(\n page,\n { viewId: request.viewId, fnId, args: request.args },\n abort.signal,\n );\n } catch (error) {\n return failure(error);\n }\n const encoder = new TextEncoder();\n const iterator = lines[Symbol.asyncIterator]();\n const stream = new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const next = await iterator.next();\n if (next.done) {\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(`${JSON.stringify(next.value)}\\n`));\n } catch (error) {\n log.error(\"gateway.call_failed\", { error });\n controller.error(error);\n }\n },\n cancel() {\n abort.abort();\n void iterator.return?.();\n },\n },\n new CountQueuingStrategy({ highWaterMark: 1 }),\n );\n return new Response(stream, {\n headers: {\n ...BASE_HEADERS,\n \"content-type\": \"application/x-ndjson; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"x-accel-buffering\": \"no\",\n },\n });\n },\n\n async runs(context) {\n const refused = served(context);\n if (refused) return refused;\n const request = await body(context, RunRequest);\n if (request instanceof Response) return request;\n const page = pageOf(context);\n if (!may(page, request.fnId)) return denied(request.fnId);\n try {\n return jsonResponse(\n actions.startRun(page, {\n viewId: request.viewId,\n fnId: request.fnId,\n args: request.args,\n ...(request.key !== undefined ? { key: request.key } : {}),\n clientKey: request.clientKey,\n }),\n );\n } catch (error) {\n return failure(error);\n }\n },\n\n async attach(context) {\n const refused = served(context);\n if (refused) return refused;\n const request = await body(context, RunAttachRequest);\n if (request instanceof Response) return request;\n const page = pageOf(context);\n for (const entry of request.keyed ?? [])\n if (!may(page, entry.fnId)) return denied(entry.fnId);\n try {\n const runs = actions\n .attach(page, {\n viewId: request.viewId,\n ...(request.runIds ? { runIds: request.runIds } : {}),\n ...(request.keyed ? { keyed: request.keyed } : {}),\n })\n // A link sees only the runs of functions it may run.\n .filter((run) => may(page, run.fnId));\n return jsonResponse({ runs });\n } catch (error) {\n return failure(error);\n }\n },\n\n async cancel(context) {\n const refused = served(context);\n if (refused) return refused;\n const request = await body(context, RunCancelRequest);\n if (request instanceof Response) return request;\n const page = pageOf(context);\n const runId = context.params[\"run\"] ?? \"\";\n try {\n const row = interaction.runFor(page, request.viewId, runId);\n if (!may(page, row.action)) return denied(row.action);\n return jsonResponse(actions.cancel(page, request.viewId, runId));\n } catch (error) {\n return failure(error);\n }\n },\n\n async live(context) {\n const refused = served(context);\n if (refused) return refused;\n const request = await body(context, LiveRequest);\n if (request instanceof Response) return request;\n try {\n return jsonResponse({ sources: live.read(pageOf(context), request) });\n } catch (error) {\n return failure(error);\n }\n },\n };\n}\n","/**\n * The browser protocol's interaction routes (INTERFACES §4, D106): `fields`, `submit`, `signal`,\n * `events` (SSE) and `events/poll` on an artifact's origin. They run behind the route table's\n * checks (session, CSRF, scope; `routes.ts`), act as the session's viewer (D104), and hand every\n * change to the interaction core, so a page and a host go through one path.\n */\nimport {\n BROWSER_PROTOCOL_REVISIONS,\n ChooseRequest,\n type Diagnostic,\n type EphemeralMessage,\n type EventRecord,\n FieldsRequest,\n FollowRequest,\n RpcError,\n refusal,\n ShellSubmitRequest,\n SignalRequest,\n type StreamSnapshot,\n type SubmissionSummary,\n SubmitRequest,\n ViewId,\n} from \"@mostra/protocol\";\nimport type * as z from \"zod\";\nimport {\n type EphemeralBus,\n type Interaction,\n type PageIdentity,\n SubmitConflict,\n} from \"../interaction/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport type { Capabilities } from \"./capabilities.ts\";\nimport { BASE_HEADERS, isRefusal, jsonResponse, readJsonObject } from \"./http.ts\";\nimport type { RouteContext } from \"./routes.ts\";\n\n/** The largest `fields` body: a mutation may carry up to a whole document (DATA_MODEL §5). */\nexport const FIELDS_BODY_MAX: number = 17 * 1024 * 1024;\n\n/** The largest `signal` body: a 64 KiB payload and its envelope. */\nconst SIGNAL_BODY_MAX: number = 80 * 1024;\n\n/** How often an idle event stream sends a comment, so proxies and browsers keep it open. */\nexport const HEARTBEAT_MS = 15_000;\n\n/** The longest a poll waits for an event (D47), in seconds. */\nexport const POLL_MAX_WAIT_S = 25;\n\n/** Events per stream message batch. */\nconst BATCH = 100;\n\n/** The HTTP status of each diagnostic a browser route answers. */\nconst STATUS: Readonly<Record<string, number>> = {\n MOSTRA_HOST_INVALID_PARAMS: 400,\n MOSTRA_FIELD_ID_INVALID: 400,\n MOSTRA_SUBMIT_SIGNAL_INVALID: 400,\n MOSTRA_FIELD_TOO_LARGE: 413,\n MOSTRA_SUBMIT_VIEW_INVALID: 403,\n MOSTRA_SUBMIT_ALREADY: 409,\n MOSTRA_SUBMIT_REVISION_MOVED: 409,\n MOSTRA_SUBMIT_POLICY_NONE: 409,\n MOSTRA_SUBMIT_CHANNEL_DENIED: 403,\n MOSTRA_FIELD_MUTATION_ID_REUSED: 409,\n MOSTRA_HOST_CURSOR_COMPACTED: 410,\n MOSTRA_HOME_DISK_FULL: 507,\n MOSTRA_HOME_GONE: 503,\n MOSTRA_HYGIENE_SCOPE_DENIED: 403,\n};\n\n/** Options for {@link browserRoutes}. */\nexport interface BrowserRoutesOptions {\n readonly interaction: Interaction;\n readonly capabilities: Capabilities;\n readonly log: Log;\n /**\n * The browser-protocol revisions served, oldest first: every revision Mostra ever shipped\n * (`BROWSER_PROTOCOL_REVISIONS`, VR-10), and in tests a newer one the release doesn't have yet.\n */\n readonly revisions?: readonly string[];\n /** A version of an artifact by number, for the carry-over route. */\n readonly versionOf: (\n artifactId: string,\n number: number,\n ) => { readonly id: string; readonly number: number } | undefined;\n /**\n * Run and live updates for pages (WP-08): a stream sends them as `event: run` and `event: live`\n * without an `id`, a poll as its `ephemeral` (LL-04). Absent: neither carries any.\n */\n readonly bus?: EphemeralBus;\n /** Tells a host with a `trustedControls` port that a trusted control was used (D108). */\n readonly activated: (event: {\n readonly artifactId: string;\n readonly control: \"submit\" | \"choose\";\n readonly viewerId: string;\n readonly viewId: string;\n readonly detail: Readonly<Record<string, string>>;\n }) => void;\n}\n\n/** A refusal or a diagnostic as the browser gets it. */\nfunction answer(\n diagnostic: Diagnostic,\n status: number,\n extra: Record<string, unknown> = {},\n): Response {\n return jsonResponse({ ...diagnostic, ...extra }, { status });\n}\n\nfunction malformed(message: string): Response {\n return answer(refusal(\"MOSTRA_HYGIENE_REQUEST_MALFORMED\", message).diagnostic, 400);\n}\n\n/** Turns an interaction refusal into its response; anything else is a defect for `onError`. */\nfunction failure(error: unknown): Response {\n if (error instanceof SubmitConflict) {\n return answer(error.diagnostic, 409, { submission: error.submission });\n }\n if (error instanceof RpcError)\n return answer(error.diagnostic, STATUS[error.diagnostic.code] ?? 500);\n throw error;\n}\n\n/** The revision a route was called at, when this gateway serves it (FAILURE_MODEL §7). */\nfunction revisionServed(context: RouteContext, revisions: readonly string[]): Response | undefined {\n const rev = context.params[\"rev\"];\n if (rev !== undefined && revisions.includes(rev)) return undefined;\n return answer(\n refusal(\n \"MOSTRA_HYGIENE_NOT_SERVED\",\n `This gateway serves browser-protocol revisions ${revisions.join(\", \")}, not ${String(rev)}.`,\n 404,\n ).diagnostic,\n 404,\n );\n}\n\n/** Reads and validates a JSON body against a schema. */\nasync function body<T>(\n context: RouteContext,\n schema: z.ZodType<T>,\n maxBytes?: number,\n): Promise<T | Response> {\n const raw = await readJsonObject(context.request, maxBytes);\n if (isRefusal(raw)) return answer(raw.diagnostic, raw.status);\n const parsed = schema.safeParse(raw);\n if (parsed.success) return parsed.data;\n const [issue] = parsed.error.issues;\n return malformed(\n `The request body doesn't match the browser protocol at ${issue?.path.join(\".\") || \"(root)\"}: ${issue?.message ?? \"invalid\"}.`,\n );\n}\n\n/**\n * The cursor a stream or poll resumes from: the newer of `?cursor=` and `Last-Event-ID`. An\n * `EventSource` reconnects to the URL it opened, query included, and adds `Last-Event-ID` with\n * the last event it received, which is never older; taking the newer never repeats an event\n * (Claude review finding 3).\n */\nfunction cursorOf(request: Request): number | undefined | \"invalid\" {\n const url = new URL(request.url);\n let resume: number | undefined;\n for (const value of [url.searchParams.get(\"cursor\"), request.headers.get(\"last-event-id\")]) {\n if (value === null || value === \"\") continue;\n if (!/^(0|[1-9][0-9]{0,15})$/.test(value)) return \"invalid\";\n resume = Math.max(resume ?? 0, Number(value));\n }\n return resume;\n}\n\n/** A route handler. */\ntype Handler = (context: RouteContext) => Response | Promise<Response>;\n\n/** The handlers of the browser protocol's interaction routes. */\nexport interface BrowserRoutes {\n readonly fields: Handler;\n readonly submit: Handler;\n readonly signal: Handler;\n readonly stream: Handler;\n readonly poll: Handler;\n /** The shell's trusted Submit (the `shell` channel, D40), on the shell origin. */\n readonly shellSubmit: Handler;\n /** The shell's trusted Choose (D65, D113), on the shell origin. */\n readonly choose: Handler;\n /** \"Always follow this artifact\" (D63), on the shell origin. */\n readonly follow: Handler;\n /** The viewer's answers a version doesn't carry over (D42, D109), on the shell origin. */\n readonly carry: Handler;\n}\n\n/** The browser protocol's interaction routes' handlers. */\nexport function browserRoutes(options: BrowserRoutesOptions): BrowserRoutes {\n const { interaction, capabilities, log } = options;\n const served: readonly string[] = options.revisions ?? BROWSER_PROTOCOL_REVISIONS;\n const knownRevision = (context: RouteContext): Response | undefined =>\n revisionServed(context, served);\n\n const pageOf = (context: RouteContext): PageIdentity => {\n const session = context.session;\n const artifactId = context.artifactId;\n if (!session || artifactId === undefined) throw new Error(\"session route without a session\");\n return {\n artifactId,\n viewerId: interaction.viewerOf(session.viewerId),\n // A page names only views its own link opened (Claude review finding 11).\n tokenId: session.grant.tokenId,\n scopes: session.grant.scopes,\n };\n };\n\n /** The view a stream or poll is for, checked against the page (D104). */\n const viewOf = (context: RouteContext, page: PageIdentity): Response | undefined => {\n const view = new URL(context.request.url).searchParams.get(\"view\");\n if (view === null || !ViewId.is(view)) return malformed(\"The stream needs the page's `view`.\");\n try {\n interaction.checkView(page, view);\n } catch (error) {\n return failure(error);\n }\n return undefined;\n };\n\n /** The page's view, from the query (checked by {@link viewOf} first). */\n const viewIdOf = (context: RouteContext): string =>\n new URL(context.request.url).searchParams.get(\"view\") ?? \"\";\n\n /** The most ephemeral messages a stream holds for a slow reader; older ones are dropped. */\n const EPHEMERAL_HELD = 1000;\n\n const fields = async (context: RouteContext): Promise<Response> => {\n const refused = knownRevision(context);\n if (refused) return refused;\n const request = await body(context, FieldsRequest, FIELDS_BODY_MAX);\n if (request instanceof Response) return request;\n try {\n return jsonResponse(\n interaction.mutate(pageOf(context), {\n viewId: request.viewId,\n scope: request.scope,\n mutationId: request.mutationId,\n baseRevision: Number(request.baseRevision),\n ops: request.ops,\n }),\n );\n } catch (error) {\n return failure(error);\n }\n };\n\n const submit = async (context: RouteContext): Promise<Response> => {\n const refused = knownRevision(context);\n if (refused) return refused;\n const request = await body(context, SubmitRequest);\n if (request instanceof Response) return request;\n try {\n return jsonResponse(\n interaction.submit(pageOf(context), {\n viewId: request.viewId,\n expectedRevision: Number(request.expectedRevision),\n channel: \"artifact\",\n }),\n );\n } catch (error) {\n return failure(error);\n }\n };\n\n const signal = async (context: RouteContext): Promise<Response> => {\n const refused = knownRevision(context);\n if (refused) return refused;\n const request = await body(context, SignalRequest, SIGNAL_BODY_MAX);\n if (request instanceof Response) return request;\n try {\n const cursor = interaction.signal(pageOf(context), {\n viewId: request.viewId,\n name: request.name,\n ...(request.payload !== undefined ? { payload: request.payload } : {}),\n });\n return jsonResponse({ cursor });\n } catch (error) {\n return failure(error);\n }\n };\n\n /** Whether the session's link still works; a revoked link ends its streams. */\n const live = (context: RouteContext): boolean => {\n const tokenId = context.session?.grant.tokenId;\n return tokenId !== undefined && capabilities.grant(tokenId)?.live === true;\n };\n\n /** The page's events after a cursor; a compacted cursor gets a fresh snapshot instead. */\n const next = (\n page: PageIdentity,\n after: number,\n ): { events: EventRecord[]; cursor: number } | { snapshot: StreamSnapshot } => {\n try {\n const read = interaction.pageEvents(page, after, BATCH);\n return { events: read.events, cursor: Number(read.cursor) };\n } catch (error) {\n if (error instanceof RpcError && error.diagnostic.code === \"MOSTRA_HOST_CURSOR_COMPACTED\") {\n return { snapshot: interaction.pageSnapshot(page) };\n }\n throw error;\n }\n };\n\n const stream = (context: RouteContext): Response => {\n const refused = knownRevision(context);\n if (refused) return refused;\n const page = pageOf(context);\n const badView = viewOf(context, page);\n if (badView) return badView;\n const resume = cursorOf(context.request);\n if (resume === \"invalid\") return malformed(\"`cursor` must be an event cursor.\");\n const encoder = new TextEncoder();\n // Pull-based: a page of events is read only when the client took the last one, so a slow\n // reader or a long backlog never makes the gateway buffer more than a page, and every page\n // yields to the event loop (Claude review finding 6).\n let cursor = resume ?? -1;\n let open = true;\n let dirty = false;\n let wake: (() => void) | undefined;\n const unsubscribe = interaction.onCommit(() => {\n dirty = true;\n wake?.();\n });\n // Run and live updates for this view: lossy by design (a page reads what it missed), so a\n // slow reader drops the oldest rather than making the gateway hold more.\n // Held as messages and coalesced while the reader is behind (Opus review 12): a newer live\n // value replaces an older one of its source, and a run's deltas merge.\n const held: EphemeralMessage[] = [];\n const heldText = (): string =>\n held\n .splice(0)\n .map(\n (message) =>\n `event: ${message.kind}\\ndata: ${JSON.stringify(message.kind === \"run\" ? message.run : message.live)}\\n\\n`,\n )\n .join(\"\");\n const unlisten =\n options.bus?.listen(page.artifactId, viewIdOf(context), (message) => {\n options.bus?.coalesce(page.artifactId, viewIdOf(context), held, message);\n if (held.length > EPHEMERAL_HELD) held.splice(0, held.length - EPHEMERAL_HELD);\n wake?.();\n }) ?? (() => {});\n const close = (controller?: ReadableStreamDefaultController<Uint8Array>): void => {\n if (!open) return;\n open = false;\n unsubscribe();\n unlisten();\n wake?.();\n context.request.signal.removeEventListener(\"abort\", aborted);\n try {\n controller?.close();\n } catch {\n // Already closed by the client.\n }\n };\n const aborted = (): void => close();\n context.request.signal.addEventListener(\"abort\", aborted, { once: true });\n const snapshotText = (value: StreamSnapshot): string => {\n cursor = Number(value.cursor);\n return `id: ${value.cursor}\\nevent: snapshot\\ndata: ${JSON.stringify(value)}\\n\\n`;\n };\n const body = new ReadableStream<Uint8Array>(\n {\n start(controller) {\n // `ready` first, whatever follows: a page that hears nothing has a stream something holds\n // back (a buffering proxy or tunnel, a stalled browser) and long-polls instead (WP-13).\n let text = \"retry: 2000\\n\\nevent: ready\\ndata: {}\\n\\n\";\n if (resume === undefined) text += snapshotText(interaction.pageSnapshot(page));\n controller.enqueue(encoder.encode(text));\n },\n async pull(controller) {\n await new Promise((resolve) => setImmediate(resolve));\n for (;;) {\n if (!open) return;\n if (!live(context)) {\n close(controller);\n return;\n }\n dirty = false;\n let read: ReturnType<typeof next>;\n try {\n read = next(page, cursor);\n } catch (error) {\n log.error(\"gateway.stream_failed\", { error });\n close(controller);\n return;\n }\n if (\"snapshot\" in read) {\n controller.enqueue(encoder.encode(snapshotText(read.snapshot)));\n return;\n }\n cursor = read.cursor;\n const ephemeral = heldText();\n if (read.events.length > 0 || ephemeral !== \"\") {\n controller.enqueue(\n encoder.encode(\n read.events\n .map(\n (event) =>\n `id: ${event.cursor}\\nevent: mostra\\ndata: ${JSON.stringify(event)}\\n\\n`,\n )\n .join(\"\") + ephemeral,\n ),\n );\n return;\n }\n // Nothing new: wait for a commit or an update, or send a heartbeat after a while.\n if (dirty || held.length > 0) continue;\n const woke = await new Promise<\"commit\" | \"heartbeat\">((resolve) => {\n const timer = setTimeout(() => resolve(\"heartbeat\"), HEARTBEAT_MS);\n timer.unref?.();\n wake = () => {\n clearTimeout(timer);\n resolve(\"commit\");\n };\n if (held.length > 0) wake();\n });\n wake = undefined;\n if (woke === \"heartbeat\" && open) {\n controller.enqueue(encoder.encode(\": keepalive\\n\\n\"));\n return;\n }\n }\n },\n cancel() {\n close();\n },\n },\n new CountQueuingStrategy({ highWaterMark: 1 }),\n );\n return new Response(body, {\n headers: {\n ...BASE_HEADERS,\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"x-accel-buffering\": \"no\",\n },\n });\n };\n\n const poll = async (context: RouteContext): Promise<Response> => {\n const refused = knownRevision(context);\n if (refused) return refused;\n const page = pageOf(context);\n const badView = viewOf(context, page);\n if (badView) return badView;\n const resume = cursorOf(context.request);\n if (resume === \"invalid\") return malformed(\"`cursor` must be an event cursor.\");\n const waitParam = new URL(context.request.url).searchParams.get(\"wait\");\n const waitS = waitParam === null ? POLL_MAX_WAIT_S : Number(waitParam);\n if (!Number.isInteger(waitS) || waitS < 0 || waitS > POLL_MAX_WAIT_S) {\n return malformed(`\\`wait\\` must be a whole number of seconds from 0 to ${POLL_MAX_WAIT_S}.`);\n }\n const viewId = viewIdOf(context);\n const bus = options.bus;\n // Polling views collect their run and live updates between polls (LL-04).\n // Taking what is queued also starts the queue, so updates during the wait are kept.\n let early = bus?.drain(page.artifactId, viewId) ?? [];\n const withEphemeral = <T extends object>(value: T): T & { ephemeral?: unknown[] } => {\n const ephemeral = [...early, ...(bus?.drain(page.artifactId, viewId) ?? [])];\n early = [];\n return ephemeral.length > 0 ? { ...value, ephemeral } : value;\n };\n if (resume === undefined) {\n const snapshot = interaction.pageSnapshot(page);\n return jsonResponse(withEphemeral({ cursor: snapshot.cursor, events: [], snapshot }));\n }\n const revoked = (): Response =>\n answer(\n refusal(\n \"MOSTRA_HYGIENE_TOKEN_REVOKED\",\n \"The link this page came from was revoked or has expired.\",\n 410,\n ).diagnostic,\n 410,\n );\n const once = () => {\n const read = next(page, resume);\n return \"snapshot\" in read\n ? { cursor: read.snapshot.cursor, events: [], snapshot: read.snapshot }\n : { cursor: String(read.cursor), events: read.events };\n };\n try {\n const first = once();\n if (first.events.length > 0 || \"snapshot\" in first || waitS === 0 || early.length > 0) {\n return jsonResponse(withEphemeral(first));\n }\n let ended = false;\n const stopWaiting = new AbortController();\n const result = await new Promise<ReturnType<typeof once>>((resolve, reject) => {\n let done = false;\n const finish = (value?: ReturnType<typeof once>): void => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n unsubscribe();\n context.request.signal.removeEventListener(\"abort\", aborted);\n // A failing read here (the ledger closing at shutdown, say) answers this request; it\n // never escapes the timer as an uncaught exception (Claude review finding 8).\n try {\n resolve(value ?? once());\n } catch (error) {\n reject(error);\n }\n };\n const aborted = (): void => finish(first);\n const unsubscribe = interaction.onCommit(() =>\n setImmediate(() => {\n if (done) return;\n // A revoked or expired link ends the poll before it reads anything more.\n if (!live(context)) {\n ended = true;\n finish(first);\n return;\n }\n try {\n const value = once();\n if (value.events.length > 0 || \"snapshot\" in value) finish(value);\n } catch (error) {\n done = true;\n clearTimeout(timer);\n unsubscribe();\n reject(error);\n }\n }),\n );\n const timer = setTimeout(() => finish(), waitS * 1000);\n context.request.signal.addEventListener(\"abort\", aborted, { once: true });\n // A run or live update for this view answers the poll too.\n void bus?.wait(page.artifactId, viewId, waitS * 1000, stopWaiting.signal).then(() => {\n if (!done) finish(first);\n });\n });\n stopWaiting.abort();\n // The link is checked again at the end: nothing read after it died leaves (HY-03).\n if (ended || !live(context)) return revoked();\n return jsonResponse(withEphemeral(result));\n } catch (error) {\n return failure(error);\n }\n };\n\n // ── The shell's own routes (WP-07) ─────────────────────────────────────────────────────\n // They run on the shell origin behind the shell's session, its exact Origin and its CSRF\n // token, none of which an artifact's page holds: only the trusted page can call them (SH-02).\n\n const shellSubmit = async (context: RouteContext): Promise<Response> => {\n const refused = knownRevision(context);\n if (refused) return refused;\n const request = await body(context, ShellSubmitRequest);\n if (request instanceof Response) return request;\n const page = pageOf(context);\n let submission: SubmissionSummary & { readonly duplicate?: true };\n try {\n submission = interaction.submit(page, {\n viewId: request.viewId,\n expectedRevision: Number(request.expectedRevision),\n channel: \"shell\",\n });\n } catch (error) {\n return failure(error);\n }\n if (submission.duplicate !== true) {\n options.activated({\n artifactId: page.artifactId,\n control: \"submit\",\n viewerId: page.viewerId,\n viewId: request.viewId,\n detail: { submissionId: submission.id },\n });\n }\n return jsonResponse(submission);\n };\n\n const choose = async (context: RouteContext): Promise<Response> => {\n const refused = knownRevision(context);\n if (refused) return refused;\n const request = await body(context, ChooseRequest);\n if (request instanceof Response) return request;\n const page = pageOf(context);\n try {\n const result = interaction.choose(page, {\n viewId: request.viewId,\n mutationId: request.mutationId,\n baseRevision: Number(request.baseRevision),\n reviewSetId: request.reviewSetId,\n candidateId: request.candidateId,\n ...(request.label !== undefined ? { label: request.label } : {}),\n });\n if (result.applied.length > 0) {\n options.activated({\n artifactId: page.artifactId,\n control: \"choose\",\n viewerId: page.viewerId,\n viewId: request.viewId,\n detail: { reviewSetId: request.reviewSetId, candidateId: request.candidateId },\n });\n }\n return jsonResponse(result);\n } catch (error) {\n return failure(error);\n }\n };\n\n const follow = async (context: RouteContext): Promise<Response> => {\n const refused = knownRevision(context);\n if (refused) return refused;\n const request = await body(context, FollowRequest);\n if (request instanceof Response) return request;\n try {\n interaction.setFollowing(pageOf(context), request.follow);\n return jsonResponse({ follow: request.follow });\n } catch (error) {\n return failure(error);\n }\n };\n\n const carry = (context: RouteContext): Response => {\n const refused = knownRevision(context);\n if (refused) return refused;\n const page = pageOf(context);\n const wanted = Number(new URL(context.request.url).searchParams.get(\"version\"));\n if (!Number.isSafeInteger(wanted) || wanted < 1) {\n return malformed(\"`version` must be a version number.\");\n }\n // A link that names a version learns nothing of another (D97 item 9).\n const pinned = context.session?.grant.pinnedVersion;\n if (pinned !== undefined && wanted !== pinned) {\n return answer(\n refusal(\"MOSTRA_HYGIENE_SCOPE_DENIED\", `This link opens version ${pinned} only.`)\n .diagnostic,\n 403,\n );\n }\n const version = options.versionOf(page.artifactId, wanted);\n if (!version) {\n return answer(\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", `This artifact has no version ${wanted}.`, 404)\n .diagnostic,\n 404,\n );\n }\n try {\n return jsonResponse(interaction.carryOver(page, version));\n } catch (error) {\n return failure(error);\n }\n };\n\n return { fields, submit, signal, stream, poll, shellSubmit, choose, follow, carry };\n}\n","/**\n * Capability tokens, sessions and frame tickets (D97, D98, HY-03): the gateway's authority over\n * who may use an artifact. Tokens are minted with secrets derived from the home's capability key\n * and stored only as hashes; sessions are stored as hashes of their cookies and bound to the one\n * origin they were issued for; tickets live in memory for 60 seconds, work once and only while the\n * shell session that asked for them lives. A link works only at the shell address it was minted\n * for. Every check reads the ledger, so a revocation applies to the very next request.\n */\nimport { createHash, createHmac, randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n writeSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n ALL_SCOPES,\n type CapabilityScope,\n normalizeScopes,\n type Refusal,\n refusal,\n safeEqual,\n TokenId,\n} from \"@mostra/protocol\";\nimport { appendEvent } from \"../interaction/index.ts\";\nimport type { Ledger, LedgerDb } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { renamePathSync } from \"../platform/index.ts\";\n\n/** Crockford base32, the alphabet of every Mostra ID body (D77). */\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/** The length of every secret: 26 Crockford characters, 130 bits. */\nexport const SECRET_LENGTH = 26;\n\n/** How long a frame ticket works (D98). */\nexport const TICKET_TTL_MS = 60_000;\n\n/** How many frame tickets, and how many stream tickets, a session holds at once (D158 item 5). */\nexport const TICKETS_PER_SESSION = 8;\n\n/** How often expired tickets are swept at most. */\nconst SWEEP_INTERVAL_MS = 1_000;\n\n/**\n * Failed capability tokens tolerated per artifact and minute (D97 item 8). Tickets don't count:\n * they are single-use 130-bit secrets that live for a minute, and any page on the host could spend\n * a count by loading an entry URL.\n */\nexport const FAILURE_LIMIT = 30;\nconst FAILURE_WINDOW_MS = 60_000;\n\n/** How long a session the browser no longer presents is kept: the cookie's own lifetime. */\nexport const SESSION_MAX_AGE_S: number = 400 * 24 * 60 * 60;\n\n/** How often a session's `last_seen_at` is written at most. */\nconst TOUCH_INTERVAL_MS = 60 * 60 * 1000;\n\n/** Whether two origins are on the same scheme and host, whatever their ports. */\nfunction sameHost(a: string, b: string): boolean {\n try {\n const one = new URL(a);\n const two = new URL(b);\n return one.protocol === two.protocol && one.hostname === two.hostname;\n } catch {\n return false;\n }\n}\n\n/** Encodes the first 130 bits of `bytes` as 26 Crockford base32 characters. */\nfunction crockford(bytes: Uint8Array): string {\n let bits = 0;\n let value = 0;\n let out = \"\";\n for (const byte of bytes) {\n value = ((value << 8) | byte) & 0xffff;\n bits += 8;\n while (bits >= 5 && out.length < SECRET_LENGTH) {\n out += CROCKFORD[(value >>> (bits - 5)) & 31];\n bits -= 5;\n }\n if (out.length === SECRET_LENGTH) break;\n }\n return out;\n}\n\n/** A fresh random secret: a session cookie, a CSRF token or a ticket (130 bits). */\nexport function randomSecret(): string {\n return crockford(randomBytes(17));\n}\n\n/** The SHA-256 of a secret, as stored (lowercase hex). */\nexport function hashSecret(secret: string): string {\n return createHash(\"sha256\").update(secret, \"utf8\").digest(\"hex\");\n}\n\n/**\n * A session's CSRF token, derived from its cookie (D98 item 2). The ledger holds neither: only\n * the SHA-256 of the cookie (the session's ID) and of the CSRF token, and neither hash leads to\n * the other. Whoever holds the cookie already holds the session, so deriving costs nothing.\n */\nexport function csrfOf(cookie: string): string {\n return crockford(createHash(\"sha256\").update(`mostra csrf ${cookie}`, \"utf8\").digest());\n}\n\n/** Whether a value has the shape of a secret, checked before any lookup. */\nexport function looksLikeSecret(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length === SECRET_LENGTH &&\n /^[0-9A-HJKMNP-TV-Z]+$/.test(value)\n );\n}\n\n/**\n * Reads the home's capability key (`<home>/keys/capability`, 32 random bytes, mode 0600),\n * creating it when it doesn't exist. A key that can't be read is replaced: links minted under it\n * still verify by their hashes; only showing them again needs the key (D97 item 2).\n */\nexport function capabilityKey(home: string, log: Log): Buffer {\n const dir = join(home, \"keys\");\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n const file = join(dir, \"capability\");\n try {\n const key = readFileSync(file);\n if (key.length === 32) return key;\n log.warn(\"gateway.key_replaced\", { reason: `the key file has ${key.length} bytes` });\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\") log.warn(\"gateway.key_replaced\", { reason: code ?? \"unreadable\" });\n }\n const key = randomBytes(32);\n // Written aside, synced and renamed, so a crash never leaves a short key behind.\n const aside = `${file}.${process.pid}.tmp`;\n const fd = openSync(aside, \"w\", 0o600);\n try {\n writeSync(fd, key);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n renamePathSync(aside, file);\n chmodSync(file, 0o600);\n return key;\n}\n\n/** What a token grants (DATA_MODEL §3 `token`). */\nexport interface Grant {\n readonly tokenId: string;\n readonly artifactId: string;\n readonly scopes: readonly CapabilityScope[];\n /** When it stops working, if it does. */\n readonly expiresAt?: string;\n /** The version number its link names, if it pins one. */\n readonly pinnedVersion?: number;\n /** Whether it is the artifact's default link. */\n readonly isDefault: boolean;\n /** The shell origin the link was minted for; it works only there. */\n readonly shellOrigin: string;\n /** The viewer the link acts for (D104); absent: the home's local user. */\n readonly viewerId?: string;\n}\n\n/** A token with its secret, just minted or derived again. */\nexport interface MintedToken extends Grant {\n readonly secret: string;\n}\n\n/** A session as a request presents it, resolved. */\nexport interface ResolvedSession {\n /** The session's ID (the SHA-256 of its cookie). */\n readonly id: string;\n readonly csrf: string;\n /** The version a frame session entered (D98 item 5). */\n readonly versionId?: string;\n /** How the session authenticates: a cookie, or the frame header of worker mode (D70). */\n readonly mode: \"cookie\" | \"worker\";\n readonly grant: Grant;\n /**\n * The viewer the session acts as: its link's viewer (D104), else the one the host's identity\n * port named when the link was exchanged (D143 item 2); absent: the home's local user.\n */\n readonly viewerId?: string;\n}\n\n/** What a redeemed frame ticket carries. */\nexport interface TicketGrant {\n readonly tokenId: string;\n readonly artifactId: string;\n readonly versionId: string;\n /** The artifact origin the ticket is good for. */\n readonly origin: string;\n /** The shell origin that minted it, which the frame's bridge talks to. */\n readonly shellOrigin: string;\n /** The shell session that asked for it: the ticket works only while that session lives. */\n readonly shellSessionId: string;\n /** The viewer that shell session acts as, which the frame's session acts as too (D143). */\n readonly viewerId?: string | undefined;\n}\n\ninterface TokenRow {\n id: string;\n secret_hash: string;\n artifact_id: string;\n scopes_json: string;\n expires_at: string | null;\n revoked_at: string | null;\n is_default: number;\n pinned_version: number | null;\n shell_origin: string;\n viewer_id: string | null;\n}\n\ninterface SessionRow {\n id: string;\n token_id: string;\n origin: string;\n mode: \"cookie\" | \"worker\";\n csrf: string;\n version_id: string | null;\n viewer_id: string | null;\n}\n\nconst grantOf = (row: TokenRow): Grant => ({\n tokenId: row.id,\n artifactId: row.artifact_id,\n scopes: JSON.parse(row.scopes_json) as CapabilityScope[],\n ...(row.expires_at !== null ? { expiresAt: row.expires_at } : {}),\n ...(row.pinned_version !== null ? { pinnedVersion: row.pinned_version } : {}),\n isDefault: row.is_default === 1,\n shellOrigin: row.shell_origin,\n ...(row.viewer_id !== null ? { viewerId: row.viewer_id } : {}),\n});\n\n/** Options for {@link Capabilities}. */\nexport interface CapabilitiesOptions {\n readonly ledger: Ledger;\n readonly log: Log;\n /** The home's capability key. */\n readonly key: Buffer;\n /** The clock, in milliseconds since the epoch. */\n readonly now: () => number;\n /**\n * The loopback shell's origin, once the gateway listens: links are minted for it unless the\n * caller names another shell address (a share's, a host's, D158), and work only there.\n */\n readonly shellOrigin: () => string;\n /**\n * Whether the gateway serves a shell at this origin now (the loopback shell, a share's shell\n * face, a host's): a launch ticket is only minted for a link whose address is served.\n */\n readonly servesShell?: (origin: string) => boolean;\n}\n\n/** What a stream ticket opens (D158 item 5). */\nexport type StreamTicketPurpose = \"stream\" | \"socket\";\n\n/** The capability authority of one instance. */\nexport class Capabilities {\n readonly #ledger: Ledger;\n readonly #log: Log;\n readonly #key: Buffer;\n readonly #now: () => number;\n readonly #shellOrigin: () => string;\n readonly #servesShell: (origin: string) => boolean;\n /** Single-use stream and socket tickets (D158 item 5), by the SHA-256 of their secret. */\n readonly #streamTickets = new Map<\n string,\n {\n readonly sessionId: string;\n readonly origin: string;\n readonly artifactId: string;\n readonly purpose: StreamTicketPurpose;\n readonly expires: number;\n }\n >();\n readonly #tickets = new Map<string, TicketGrant & { readonly expires: number }>();\n /** One-time launch tickets (D140 item 15), by the SHA-256 of their secret. */\n readonly #launches = new Map<string, { readonly tokenId: string; readonly expires: number }>();\n /** The frame tickets and the stream tickets each session holds, oldest first. */\n readonly #ticketsBySession = new Map<string, string[]>();\n readonly #streamTicketsBySession = new Map<string, string[]>();\n /** When the tickets were last swept. */\n #swept = Number.NEGATIVE_INFINITY;\n /** Failure times per artifact (`\"\"` for tokens of no artifact in this home). */\n readonly #failures = new Map<string, number[]>();\n readonly #touched = new Map<string, number>();\n\n constructor(options: CapabilitiesOptions) {\n this.#ledger = options.ledger;\n this.#log = options.log;\n this.#key = options.key;\n this.#now = options.now;\n this.#shellOrigin = options.shellOrigin;\n this.#servesShell = options.servesShell ?? ((origin) => origin === this.#shellOrigin());\n }\n\n /** Runs `fn` in the caller's transaction, or in a new one. */\n #tx<T>(db: LedgerDb | undefined, fn: (db: LedgerDb) => T): T {\n return db ? fn(db) : this.#ledger.write(fn);\n }\n\n /** The secret of a token, derived from its ID under the home's key (D97 item 2). */\n secretOf(tokenId: string): string {\n return crockford(\n createHmac(\"sha256\", this.#key).update(`mostra capability ${tokenId}`).digest(),\n );\n }\n\n #iso(ms: number): string {\n return new Date(ms).toISOString();\n }\n\n #live(row: TokenRow): boolean {\n return (\n row.revoked_at === null &&\n (row.expires_at === null || Date.parse(row.expires_at) > this.#now())\n );\n }\n\n #insert(\n db: LedgerDb,\n input: {\n readonly artifactId: string;\n readonly scopes: readonly CapabilityScope[];\n readonly expiresAt?: string | undefined;\n readonly pinnedVersion?: number | undefined;\n readonly isDefault: boolean;\n readonly tokenId?: string;\n readonly viewerId?: string | undefined;\n readonly shellOrigin?: string | undefined;\n },\n ): MintedToken {\n const tokenId = input.tokenId ?? TokenId.create();\n const secret = this.secretOf(tokenId);\n const scopes = normalizeScopes(input.scopes);\n const shellOrigin = input.shellOrigin ?? this.#shellOrigin();\n db.run(\n \"INSERT INTO token (id, secret_hash, artifact_id, scopes_json, viewer_id, expires_at, revoked_at, created_at, is_default, pinned_version, shell_origin) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?)\",\n tokenId,\n hashSecret(secret),\n input.artifactId,\n JSON.stringify(scopes),\n input.viewerId ?? null,\n input.expiresAt ?? null,\n this.#iso(this.#now()),\n input.isDefault ? 1 : 0,\n input.pinnedVersion ?? null,\n shellOrigin,\n );\n return {\n tokenId,\n secret,\n artifactId: input.artifactId,\n scopes,\n ...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),\n ...(input.pinnedVersion !== undefined ? { pinnedVersion: input.pinnedVersion } : {}),\n isDefault: input.isDefault,\n shellOrigin,\n ...(input.viewerId !== undefined ? { viewerId: input.viewerId } : {}),\n };\n }\n\n /** Mints a new token (`view/url`), in the caller's transaction when it passes one. */\n mint(\n input: {\n readonly artifactId: string;\n readonly scopes?: readonly CapabilityScope[] | undefined;\n readonly ttlMs?: number | undefined;\n readonly pinnedVersion?: number | undefined;\n /** The viewer the link acts for (D104). */\n readonly viewerId?: string | undefined;\n /** The shell address the link works at (D97 item 10); default: the loopback shell. */\n readonly shellOrigin?: string | undefined;\n },\n within?: LedgerDb,\n ): MintedToken {\n return this.#tx(within, (db) =>\n this.#insert(db, {\n artifactId: input.artifactId,\n scopes: input.scopes ?? ALL_SCOPES,\n expiresAt: input.ttlMs === undefined ? undefined : this.#iso(this.#now() + input.ttlMs),\n pinnedVersion: input.pinnedVersion,\n isDefault: false,\n viewerId: input.viewerId,\n shellOrigin: input.shellOrigin,\n }),\n );\n }\n\n /**\n * The artifact's default link (D97 item 3): the live default token, shown again from its\n * derived secret, or a new one. A default whose secret the current key no longer derives (the\n * key was replaced) stays valid for whoever holds it, and a new default takes its place; so does\n * one minted for another shell address, which works again if the gateway returns there.\n */\n defaultLink(artifactId: string, shellOrigin?: string): MintedToken {\n const origin = shellOrigin ?? this.#shellOrigin();\n return this.#ledger.write((db) => {\n const row = db.get<TokenRow>(\n \"SELECT * FROM token WHERE artifact_id = ? AND is_default = 1\",\n artifactId,\n );\n if (row) {\n const secret = this.secretOf(row.id);\n const here = row.shell_origin === origin;\n if (here && safeEqual(hashSecret(secret), row.secret_hash)) {\n return { ...grantOf(row), secret };\n }\n db.run(\"UPDATE token SET is_default = 0 WHERE id = ?\", row.id);\n this.#log.warn(\"gateway.default_link_replaced\", {\n artifactId,\n tokenId: row.id,\n reason: here ? \"the capability key changed\" : \"the shell's address changed\",\n });\n }\n return this.#insert(db, {\n artifactId,\n scopes: ALL_SCOPES,\n isDefault: true,\n shellOrigin: origin,\n });\n });\n }\n\n /** A token's grant, live or not; `undefined` when no such token exists. */\n grant(tokenId: string): (Grant & { readonly live: boolean }) | undefined {\n const row = this.#ledger.read((db) =>\n db.get<TokenRow>(\"SELECT * FROM token WHERE id = ?\", tokenId),\n );\n return row ? { ...grantOf(row), live: this.#live(row) } : undefined;\n }\n\n /**\n * The token that stands for `tokenId` now: itself, or the token its rotations led to (D97 item\n * 6), so what holds a token ID (a share) follows its link through `view/rotate`.\n */\n current(tokenId: string): string {\n let id = tokenId;\n for (let hop = 0; hop < 1000; hop++) {\n const next = this.#ledger.read(\n (db) =>\n db.get<{ replaced_by: string | null }>(\"SELECT replaced_by FROM token WHERE id = ?\", id)\n ?.replaced_by ?? null,\n );\n if (next === null) return id;\n id = next;\n }\n return id;\n }\n\n /** The token's link again, from its derived secret, when the current key still derives it. */\n reveal(tokenId: string): MintedToken | undefined {\n const row = this.#ledger.read((db) =>\n db.get<TokenRow>(\"SELECT * FROM token WHERE id = ?\", tokenId),\n );\n if (!row) return undefined;\n const secret = this.secretOf(row.id);\n return safeEqual(hashSecret(secret), row.secret_hash) ? { ...grantOf(row), secret } : undefined;\n }\n\n /** Revokes a token and its sessions (`view/revoke`); revoking a revoked token is a no-op. */\n revoke(tokenId: string, within?: LedgerDb): \"revoked\" | \"already\" | \"unknown\" {\n return this.#tx(within, (db) => {\n const row = db.get<TokenRow>(\"SELECT * FROM token WHERE id = ?\", tokenId);\n if (!row) return \"unknown\";\n if (row.revoked_at !== null) return \"already\";\n // Its sessions stay, so they keep answering 410 rather than 401 (FAILURE_MODEL §8).\n db.run(\n \"UPDATE token SET revoked_at = ?, is_default = 0 WHERE id = ?\",\n this.#iso(this.#now()),\n tokenId,\n );\n appendEvent(db, {\n artifactId: row.artifact_id,\n type: \"token.revoked\",\n payload: { tokenId, reason: \"revoked\" },\n });\n return \"revoked\";\n });\n }\n\n /**\n * Replaces a live token with a new one of the same artifact, scopes, expiry, pinned version and viewer,\n * in one transaction (`view/rotate`, D97 item 6). Returns `undefined` for an unknown token and\n * `\"dead\"` for a revoked or expired one.\n */\n rotate(tokenId: string, within?: LedgerDb): MintedToken | \"dead\" | undefined {\n return this.#tx(within, (db) => {\n const row = db.get<TokenRow>(\"SELECT * FROM token WHERE id = ?\", tokenId);\n if (!row) return undefined;\n if (!this.#live(row)) return \"dead\";\n const grant = grantOf(row);\n const replacement = TokenId.create();\n // The old token stops being the default first (one default per artifact), in the only update\n // a revocation makes: a revoked token never changes again (the ledger's trigger).\n db.run(\n \"UPDATE token SET revoked_at = ?, is_default = 0, replaced_by = ? WHERE id = ?\",\n this.#iso(this.#now()),\n replacement,\n tokenId,\n );\n const minted = this.#insert(db, {\n tokenId: replacement,\n artifactId: grant.artifactId,\n scopes: grant.scopes,\n expiresAt: grant.expiresAt,\n pinnedVersion: grant.pinnedVersion,\n isDefault: grant.isDefault,\n viewerId: grant.viewerId,\n // A link stays at the address its holder uses: a share's, a host's external base, served\n // now or not (a share's faces are down while it is set up again after a restart, Opus\n // review of WP-13). Only a loopback link whose shell moved to another port moves to the\n // shell's address now (D97 item 10, GPT review of WP-13).\n shellOrigin:\n sameHost(grant.shellOrigin, this.#shellOrigin()) && !this.#servesShell(grant.shellOrigin)\n ? undefined\n : grant.shellOrigin,\n });\n appendEvent(db, {\n artifactId: grant.artifactId,\n type: \"token.revoked\",\n payload: { tokenId, reason: \"rotated\", replacedBy: minted.tokenId },\n });\n return minted;\n });\n }\n\n /**\n * A refusal, with its `Retry-After` seconds, while too many tokens for `artifactId` failed in the\n * last minute (D97 item 8). One artifact's limit never holds another's links back.\n */\n limited(artifactId: string): (Refusal & { readonly retryAfter: number }) | undefined {\n const now = this.#now();\n const failures = this.#failures.get(artifactId);\n if (!failures) return undefined;\n while (failures.length > 0 && (failures[0] ?? 0) <= now - FAILURE_WINDOW_MS) failures.shift();\n if (failures.length === 0) {\n this.#failures.delete(artifactId);\n return undefined;\n }\n if (failures.length < FAILURE_LIMIT) return undefined;\n const retry = Math.max(1, Math.ceil(((failures[0] ?? now) + FAILURE_WINDOW_MS - now) / 1000));\n return {\n ...refusal(\"MOSTRA_HYGIENE_RATE_LIMITED\", `Too many failed attempts; retry in ${retry} s.`),\n retryAfter: retry,\n };\n }\n\n /** Counts a failed token for `artifactId`; a token for no artifact of this home counts once, under `\"\"`. */\n #fail(artifactId: string): void {\n const known =\n artifactId !== \"\" &&\n this.#ledger.read((db) => db.get(\"SELECT 1 FROM artifact WHERE id = ?\", artifactId)) !==\n undefined;\n const key = known ? artifactId : \"\";\n const now = this.#now();\n const failures = (this.#failures.get(key) ?? []).filter((at) => at > now - FAILURE_WINDOW_MS);\n failures.push(now);\n this.#failures.set(key, failures);\n }\n\n /**\n * Checks a capability token presented for `artifactId`. While the artifact's guessing limit\n * holds, every token is refused, a right one too, and the limit is checked here, at the moment\n * of the check, so concurrent guesses can't slip past it. An unknown secret, or one for another\n * artifact, is `MOSTRA_HYGIENE_TOKEN_INVALID`; a revoked or expired one, or one minted for\n * another shell address, `_TOKEN_REVOKED`. Unknown secrets count towards the limit.\n */\n presentToken(\n secret: unknown,\n artifactId: string,\n shellOrigin?: string,\n ): Grant | (Refusal & { readonly retryAfter?: number }) {\n const limited = this.limited(artifactId);\n if (limited) return limited;\n if (!looksLikeSecret(secret)) {\n this.#fail(artifactId);\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n \"The capability token isn't one Mostra minted.\",\n );\n }\n const row = this.#ledger.read((db) =>\n db.get<TokenRow>(\"SELECT * FROM token WHERE secret_hash = ?\", hashSecret(secret)),\n );\n if (!row || row.artifact_id !== artifactId) {\n this.#fail(artifactId);\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n \"No capability token in this home matches this link.\",\n );\n }\n if (!this.#live(row)) {\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_REVOKED\",\n row.revoked_at !== null ? \"This link was revoked.\" : \"This link has expired.\",\n );\n }\n if (row.shell_origin !== (shellOrigin ?? this.#shellOrigin())) {\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_REVOKED\",\n `This link was made for ${row.shell_origin}, not this address.`,\n );\n }\n return grantOf(row);\n }\n\n /** Starts a session for a grant on one origin; returns the cookie secret and CSRF token. */\n createSession(input: {\n readonly tokenId: string;\n readonly origin: string;\n readonly versionId?: string;\n /** The person the host's identity port named, for a link without a viewer (D143 item 2). */\n readonly viewerId?: string | undefined;\n /** `worker` for a worker-mode frame (D70), whose secret travels in a header; default `cookie`. */\n readonly mode?: \"cookie\" | \"worker\";\n }): {\n readonly cookie: string;\n readonly csrf: string;\n readonly id: string;\n } {\n const cookie = randomSecret();\n const csrf = csrfOf(cookie);\n const id = hashSecret(cookie);\n const now = this.#iso(this.#now());\n this.#ledger.write((db) =>\n db.run(\n \"INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at, viewer_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n id,\n input.tokenId,\n input.origin,\n input.mode ?? \"cookie\",\n hashSecret(csrf),\n input.versionId ?? null,\n now,\n now,\n input.viewerId ?? null,\n ),\n );\n return { cookie, csrf, id };\n }\n\n /**\n * Resolves the session a request presents on `origin` for `artifactId`. Every candidate cookie\n * value is tried, since another page of the host may have set a cookie of the same name (D98):\n * only a session issued for this origin, whose token is live and grants this artifact, counts.\n */\n session(\n cookies: readonly string[],\n origin: string,\n artifactId: string,\n mode: \"cookie\" | \"worker\" = \"cookie\",\n ): ResolvedSession | Refusal {\n let revoked = false;\n for (const value of cookies) {\n if (!looksLikeSecret(value)) continue;\n const found = this.#ledger.read((db) => {\n const session = db.get<SessionRow>(\"SELECT * FROM session WHERE id = ?\", hashSecret(value));\n // A session works only the way it was made: a cookie never stands for a frame header.\n if (!session || session.origin !== origin || session.mode !== mode) return undefined;\n const token = db.get<TokenRow>(\"SELECT * FROM token WHERE id = ?\", session.token_id);\n return token && token.artifact_id === artifactId ? { session, token } : undefined;\n });\n if (!found) continue;\n if (!this.#live(found.token)) {\n revoked = true;\n continue;\n }\n const csrf = csrfOf(value);\n // A row whose CSRF hash doesn't match was not made by this code: it doesn't count.\n if (!safeEqual(hashSecret(csrf), found.session.csrf)) continue;\n this.#touch(found.session.id);\n const grant = grantOf(found.token);\n // A link's own viewer always wins: a token's viewer never changes (D104).\n const viewerId = grant.viewerId ?? found.session.viewer_id ?? undefined;\n return {\n id: found.session.id,\n csrf,\n mode,\n ...(found.session.version_id !== null ? { versionId: found.session.version_id } : {}),\n grant,\n ...(viewerId !== undefined ? { viewerId } : {}),\n };\n }\n return revoked\n ? refusal(\n \"MOSTRA_HYGIENE_TOKEN_REVOKED\",\n \"The link this session came from was revoked or has expired.\",\n )\n : refusal(\n \"MOSTRA_HYGIENE_SESSION_MISSING\",\n \"The request carries no session for this origin.\",\n );\n }\n\n /** Records the version a frame session entered (D98 item 5). */\n enterVersion(sessionId: string, versionId: string): void {\n this.#ledger.write((db) =>\n db.run(\n \"UPDATE session SET version_id = ?, last_seen_at = ? WHERE id = ?\",\n versionId,\n this.#iso(this.#now()),\n sessionId,\n ),\n );\n }\n\n /** Writes `last_seen_at` at most hourly, so serving files doesn't write the ledger per request. */\n #touch(sessionId: string): void {\n const now = this.#now();\n if (now - (this.#touched.get(sessionId) ?? 0) < TOUCH_INTERVAL_MS) return;\n this.#touched.set(sessionId, now);\n this.#ledger.write((db) =>\n db.run(\"UPDATE session SET last_seen_at = ? WHERE id = ?\", this.#iso(now), sessionId),\n );\n }\n\n /** Mints a single-use frame ticket (D98 item 3); a shell session holds at most a few at once. */\n mintTicket(grant: Omit<TicketGrant, never>): string {\n const ticket = randomSecret();\n this.#sweepTickets();\n const key = hashSecret(ticket);\n this.#tickets.set(key, { ...grant, expires: this.#now() + TICKET_TTL_MS });\n this.#hold(this.#ticketsBySession, this.#tickets, grant.shellSessionId, key);\n return ticket;\n }\n\n /**\n * Records a session's new ticket and drops its oldest beyond {@link TICKETS_PER_SESSION}, so no\n * link holder can make the maps grow without bound by asking for tickets in a loop (Opus review\n * of WP-13). A page uses one or two at a time.\n */\n #hold(\n bySession: Map<string, string[]>,\n tickets: Map<string, unknown>,\n sessionId: string,\n key: string,\n ): void {\n const held = (bySession.get(sessionId) ?? []).filter((one) => tickets.has(one));\n held.push(key);\n while (held.length > TICKETS_PER_SESSION) tickets.delete(held.shift() as string);\n bySession.set(sessionId, held);\n }\n\n /**\n * Redeems a ticket on `origin`, once, while the shell session that asked for it lives and its\n * link is live (D98 item 3).\n */\n redeemTicket(ticket: unknown, origin: string): TicketGrant | Refusal {\n this.#sweepTickets();\n const key = looksLikeSecret(ticket) ? hashSecret(ticket) : undefined;\n const entry = key === undefined ? undefined : this.#tickets.get(key);\n if (key !== undefined) this.#tickets.delete(key);\n if (!entry || entry.expires <= this.#now() || entry.origin !== origin) {\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n \"The frame ticket is unknown, used or expired.\",\n );\n }\n const shellSession = this.#ledger.read((db) =>\n db.get<{ token_id: string }>(\n \"SELECT token_id FROM session WHERE id = ?\",\n entry.shellSessionId,\n ),\n );\n if (shellSession?.token_id !== entry.tokenId) {\n return refusal(\n \"MOSTRA_HYGIENE_SESSION_MISSING\",\n \"The shell session that asked for this frame ticket has ended.\",\n );\n }\n const grant = this.grant(entry.tokenId);\n if (!grant?.live) {\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_REVOKED\",\n \"The link behind this frame was revoked or has expired.\",\n );\n }\n const { expires: _expires, ...rest } = entry;\n return rest;\n }\n\n /**\n * Mints a single-use ticket that opens one event stream, long poll or WebSocket of a session\n * without the session's credential (D158 item 5): a worker-mode page's streams bypass its\n * service worker, which can't carry them. It lives 60 s in memory and is never recorded.\n */\n mintStreamTicket(input: {\n readonly sessionId: string;\n readonly origin: string;\n readonly artifactId: string;\n readonly purpose: StreamTicketPurpose;\n }): { readonly ticket: string; readonly expiresAt: string } {\n this.#sweepTickets();\n const ticket = randomSecret();\n const expires = this.#now() + TICKET_TTL_MS;\n const key = hashSecret(ticket);\n this.#streamTickets.set(key, { ...input, expires });\n this.#hold(this.#streamTicketsBySession, this.#streamTickets, input.sessionId, key);\n return { ticket, expiresAt: this.#iso(expires) };\n }\n\n /**\n * Spends a stream ticket on `origin` for `artifactId` and `purpose`, and resolves its session\n * as a request carrying the session's credential would, its link's liveness included. The\n * session's CSRF token isn't known here: a ticket opens reads only (streams, polls, sockets).\n */\n redeemStreamTicket(\n ticket: unknown,\n origin: string,\n artifactId: string,\n purpose: StreamTicketPurpose,\n ): ResolvedSession | Refusal {\n this.#sweepTickets();\n const key = looksLikeSecret(ticket) ? hashSecret(ticket) : undefined;\n const entry = key === undefined ? undefined : this.#streamTickets.get(key);\n if (key !== undefined) this.#streamTickets.delete(key);\n if (\n !entry ||\n entry.expires <= this.#now() ||\n entry.origin !== origin ||\n entry.artifactId !== artifactId ||\n entry.purpose !== purpose\n ) {\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n \"The stream ticket is unknown, used or expired.\",\n );\n }\n const found = this.#ledger.read((db) => {\n const session = db.get<SessionRow>(\"SELECT * FROM session WHERE id = ?\", entry.sessionId);\n if (!session || session.origin !== origin) return undefined;\n const token = db.get<TokenRow>(\"SELECT * FROM token WHERE id = ?\", session.token_id);\n return token && token.artifact_id === artifactId ? { session, token } : undefined;\n });\n if (!found) {\n return refusal(\"MOSTRA_HYGIENE_SESSION_MISSING\", \"The session behind this ticket has ended.\");\n }\n if (!this.#live(found.token)) {\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_REVOKED\",\n \"The link this session came from was revoked or has expired.\",\n );\n }\n const grant = grantOf(found.token);\n const viewerId = grant.viewerId ?? found.session.viewer_id ?? undefined;\n return {\n id: found.session.id,\n csrf: \"\",\n mode: found.session.mode,\n ...(found.session.version_id !== null ? { versionId: found.session.version_id } : {}),\n grant,\n ...(viewerId !== undefined ? { viewerId } : {}),\n };\n }\n\n /**\n * Drops expired tickets, at most once a second: every use checks a ticket's expiry itself, so a\n * sweep only frees memory, and a burst of requests never makes each one walk every ticket (Opus\n * review of WP-13).\n */\n #sweepTickets(): void {\n const now = this.#now();\n if (now - this.#swept < SWEEP_INTERVAL_MS && now >= this.#swept) return;\n this.#swept = now;\n for (const [sessionId, held] of this.#ticketsBySession) {\n if (!held.some((key) => this.#tickets.has(key))) this.#ticketsBySession.delete(sessionId);\n }\n for (const [sessionId, held] of this.#streamTicketsBySession) {\n if (!held.some((key) => this.#streamTickets.has(key))) {\n this.#streamTicketsBySession.delete(sessionId);\n }\n }\n for (const [key, entry] of this.#tickets) if (entry.expires <= now) this.#tickets.delete(key);\n for (const [key, entry] of this.#streamTickets) {\n if (entry.expires <= now) this.#streamTickets.delete(key);\n }\n for (const [key, entry] of this.#launches) if (entry.expires <= now) this.#launches.delete(key);\n }\n\n /**\n * Mints a one-time launch ticket for a live link (D140 item 15): a browser opened from a command\n * line gets it instead of the link's secret, which other local users could read there. It lives\n * 60 s in memory and is never recorded. `undefined` for an unknown token, `\"dead\"` for a\n * revoked or expired one, or one minted for another shell address.\n */\n mintLaunch(\n tokenId: string,\n ):\n | { readonly ticket: string; readonly grant: Grant; readonly expiresAt: string }\n | \"dead\"\n | undefined {\n const grant = this.grant(tokenId);\n if (!grant) return undefined;\n if (!grant.live || !this.#servesShell(grant.shellOrigin)) return \"dead\";\n this.#sweepTickets();\n const ticket = randomSecret();\n const expires = this.#now() + TICKET_TTL_MS;\n this.#launches.set(hashSecret(ticket), { tokenId, expires });\n const { live: _live, ...rest } = grant;\n return { ticket, grant: rest, expiresAt: this.#iso(expires) };\n }\n\n /**\n * Checks a launch ticket presented for `artifactId` like a token (the guessing limit applies,\n * and unknown tickets count), and spends it when `spend` is set. The exchange spends it only\n * once a session exists, so a viewer who chooses between two links (D98 item 8) can still use it\n * within its minute.\n */\n presentLaunch(\n ticket: unknown,\n artifactId: string,\n spend: boolean,\n shellOrigin?: string,\n ): Grant | (Refusal & { readonly retryAfter?: number }) {\n const limited = this.limited(artifactId);\n if (limited) return limited;\n this.#sweepTickets();\n const key = looksLikeSecret(ticket) ? hashSecret(ticket) : undefined;\n const found = key === undefined ? undefined : this.#launches.get(key);\n const entry = found && found.expires > this.#now() ? found : undefined;\n const grant = entry ? this.grant(entry.tokenId) : undefined;\n if (!entry || !grant || grant.artifactId !== artifactId) {\n this.#fail(artifactId);\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n \"The launch ticket is unknown, used or expired.\",\n );\n }\n if (!grant.live || grant.shellOrigin !== (shellOrigin ?? this.#shellOrigin())) {\n return refusal(\n \"MOSTRA_HYGIENE_TOKEN_REVOKED\",\n \"The link behind this launch ticket was revoked, has expired, or is for another address.\",\n );\n }\n if (spend && key !== undefined) this.#launches.delete(key);\n const { live: _live, ...rest } = grant;\n return rest;\n }\n\n /**\n * Spends a launch ticket that started a session: `true` only for the caller that spent it, so\n * two exchanges that both presented it while a host's identity port was answering get one\n * session between them (GPT review of WP-12, finding 1).\n */\n spendLaunch(ticket: unknown): boolean {\n // An expired ticket can't be spent (Opus review of WP-12, finding 3).\n this.#sweepTickets();\n if (!looksLikeSecret(ticket)) return false;\n const key = hashSecret(ticket);\n const entry = this.#launches.get(key);\n if (!entry || entry.expires <= this.#now()) return false;\n return this.#launches.delete(key);\n }\n\n /** Removes sessions unseen for longer than their cookie lives; no browser holds them any more. */\n prune(): number {\n const cutoff = this.#iso(this.#now() - SESSION_MAX_AGE_S * 1000);\n return this.#ledger.write(\n (db) => db.run(\"DELETE FROM session WHERE last_seen_at < ?\", cutoff).changes,\n );\n }\n}\n","/**\n * The dev sandbox's artifact origin in front of `mostra dev`'s Vite server (D140 item 12): every\n * file request and the HMR WebSocket pass the gateway's checks first (exact Host and Origin, the\n * origin-bound frame session), then reach the dev server on loopback with the session's secret,\n * which nothing else holds. Mostra's cookies never go upstream (D38).\n */\nimport { request as httpRequest, type IncomingMessage } from \"node:http\";\nimport { connect } from \"node:net\";\nimport type { Duplex } from \"node:stream\";\nimport { DEV_SECRET_HEADER } from \"../builder/index.ts\";\n\n/** Where a dev session's server listens, and the secret it wants. */\nexport interface DevUpstream {\n readonly port: number;\n readonly secret: string;\n}\n\n/** Request headers the gateway passes to the dev server; everything else stays (cookies above all). */\nconst FORWARDED = [\n \"accept\",\n \"accept-language\",\n \"if-none-match\",\n \"if-modified-since\",\n \"user-agent\",\n \"sec-fetch-dest\",\n \"sec-fetch-mode\",\n \"sec-fetch-site\",\n] as const;\n\n/** Response headers the gateway passes back; its own security headers are added by the caller. */\nconst RETURNED = [\n \"content-type\",\n \"etag\",\n \"last-modified\",\n \"cache-control\",\n \"content-length\",\n] as const;\n\n/** Fetches `path` from the dev server; resolves with its status, headers and body. */\nexport function devFetch(\n upstream: DevUpstream,\n request: Request,\n path: string,\n): Promise<{ status: number; headers: Record<string, string>; body: Buffer }> {\n const headers: Record<string, string> = {\n host: `127.0.0.1:${upstream.port}`,\n [DEV_SECRET_HEADER]: upstream.secret,\n };\n for (const name of FORWARDED) {\n const value = request.headers.get(name);\n if (value !== null) headers[name] = value;\n }\n return new Promise((resolve, reject) => {\n const outgoing = httpRequest(\n {\n host: \"127.0.0.1\",\n port: upstream.port,\n method: request.method,\n path,\n headers,\n agent: false,\n },\n (response) => {\n const chunks: Buffer[] = [];\n response.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n response.on(\"end\", () => {\n const back: Record<string, string> = {};\n for (const name of RETURNED) {\n const value = response.headers[name];\n if (typeof value === \"string\") back[name] = value;\n }\n resolve({\n status: response.statusCode ?? 502,\n headers: back,\n body: Buffer.concat(chunks),\n });\n });\n response.on(\"error\", reject);\n },\n );\n outgoing.on(\"error\", reject);\n outgoing.end();\n });\n}\n\n/**\n * Hands an upgrade the gateway accepted to the dev server: the request line and its headers, with\n * the secret added, the Host rewritten and Mostra's cookies removed, then both directions piped.\n */\nexport function devUpgrade(\n upstream: DevUpstream,\n incoming: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n): void {\n const target = connect({ host: \"127.0.0.1\", port: upstream.port });\n const lines = [`${incoming.method ?? \"GET\"} ${incoming.url ?? \"/\"} HTTP/1.1`];\n for (let index = 0; index + 1 < incoming.rawHeaders.length; index += 2) {\n const name = incoming.rawHeaders[index] as string;\n const lower = name.toLowerCase();\n if (lower === \"cookie\" || lower === \"host\" || lower === DEV_SECRET_HEADER) continue;\n lines.push(`${name}: ${incoming.rawHeaders[index + 1] as string}`);\n }\n lines.push(`Host: 127.0.0.1:${upstream.port}`, `${DEV_SECRET_HEADER}: ${upstream.secret}`);\n const close = (): void => {\n target.destroy();\n socket.destroy();\n };\n target.on(\"error\", close);\n socket.on(\"error\", close);\n target.on(\"close\", () => socket.destroy());\n socket.on(\"close\", () => target.destroy());\n target.on(\"connect\", () => {\n target.write(`${lines.join(\"\\r\\n\")}\\r\\n\\r\\n`);\n if (head.length > 0) target.write(head);\n target.pipe(socket);\n socket.pipe(target);\n });\n}\n","/**\n * Who a browser is (D143 item 2). A link minted with a viewer acts for that viewer (D104) and asks\n * nothing. For a link without one, a host that registered the `identity` port names the person\n * from the request's headers; without such a host, the session acts as the home's local user.\n */\nimport {\n createDiagnostic,\n type Diagnostic,\n type IdentityVia,\n portIdentityResolveMethod,\n type ViewerSpec,\n} from \"@mostra/protocol\";\nimport type { Log } from \"../log.ts\";\n\n/** How long a host has to answer `port/identity.resolve`: a page waits for it, as for D108. */\nexport const IDENTITY_TIMEOUT_MS = 5_000;\n\n/** What {@link resolveIdentity} reads. */\nexport interface IdentityInput {\n /** The artifact whose link is being exchanged. */\n readonly artifactId: string;\n /** How the request reached the gateway. */\n readonly via: IdentityVia;\n /** The request's headers. */\n readonly headers: Headers;\n readonly log: Log;\n /** Hosts that always provide `identity` (`HomeConfig.ports`), by client name. */\n readonly expected: () => readonly string[];\n /** The newest connection that registered `identity`, if any. */\n readonly registrant: () => { readonly session: number; readonly owner: string } | undefined;\n /** Calls the port on that connection; rejects on a transport failure or the timeout. */\n readonly call: (session: number, params: unknown) => Promise<unknown>;\n}\n\n/** The person a host named, the standalone default, or why nobody can be named. */\nexport type IdentityOutcome =\n | { readonly kind: \"person\"; readonly viewer: ViewerSpec }\n | { readonly kind: \"default\" }\n | { readonly kind: \"unavailable\"; readonly diagnostic: Diagnostic };\n\n/**\n * The headers a host sees: names in lower case, without `cookie` (Mostra's sessions and every\n * other page's of this host) and without Mostra's own `x-mostra-*` headers.\n */\nexport function identityHeaders(headers: Headers): Record<string, string> {\n const seen: Record<string, string> = {};\n headers.forEach((value, name) => {\n const key = name.toLowerCase();\n if (key === \"cookie\" || key.startsWith(\"x-mostra-\")) return;\n seen[key] = value;\n });\n return seen;\n}\n\n/**\n * Asks the host that took identity over. Its outage never makes the session someone else: a\n * failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is\n * `unavailable`, and the exchange is refused.\n */\nexport async function resolveIdentity(input: IdentityInput): Promise<IdentityOutcome> {\n const registrant = input.registrant();\n const unavailable = (message: string): IdentityOutcome => ({\n kind: \"unavailable\",\n diagnostic: createDiagnostic(\"MOSTRA_HOST_IDENTITY_UNAVAILABLE\", { message }),\n });\n if (registrant) {\n try {\n const answer = await input.call(registrant.session, {\n artifactId: input.artifactId,\n via: input.via,\n headers: identityHeaders(input.headers),\n });\n const parsed = portIdentityResolveMethod.result.safeParse(answer);\n if (parsed.success) {\n return parsed.data === null ? { kind: \"default\" } : { kind: \"person\", viewer: parsed.data };\n }\n input.log.warn(\"gateway.identity_invalid\", {\n owner: registrant.owner,\n artifactId: input.artifactId,\n });\n return unavailable(\n `The host ${registrant.owner} answered who this is in a form Mostra refuses.`,\n );\n } catch (error) {\n input.log.warn(\"gateway.identity_failed\", {\n owner: registrant.owner,\n artifactId: input.artifactId,\n error: (error as Error).message,\n });\n return unavailable(`The host ${registrant.owner} didn't say who this is.`);\n }\n }\n const away = input.expected();\n if (away.length > 0) {\n input.log.warn(\"gateway.identity_host_away\", { owners: away, artifactId: input.artifactId });\n return unavailable(\n `The host that identifies this home's viewers (${away.join(\", \")}) isn't running.`,\n );\n }\n return { kind: \"default\" };\n}\n\n/**\n * Decodes RFC 2047 encoded words (`=?utf-8?q?Ferris_B=C3=BCller?=`, and `b` for base64), as\n * Tailscale Serve writes a non-ASCII name; text outside encoded words is kept, and whitespace\n * between two encoded words is dropped (RFC 2047 §6.2). Anything malformed is kept as written.\n */\nexport function decodeEncodedWords(value: string): string {\n const word = /=\\?([^?\\s]+)\\?([qQbB])\\?([^?\\s]*)\\?=/g;\n const decodeOne = (charset: string, encoding: string, text: string): string | undefined => {\n let bytes: Uint8Array;\n if (encoding.toLowerCase() === \"b\") {\n bytes = Buffer.from(text, \"base64\");\n } else {\n const out: number[] = [];\n for (let index = 0; index < text.length; index++) {\n const char = text[index] as string;\n if (char === \"_\") out.push(0x20);\n else if (char === \"=\" && /^[0-9A-Fa-f]{2}$/.test(text.slice(index + 1, index + 3))) {\n out.push(Number.parseInt(text.slice(index + 1, index + 3), 16));\n index += 2;\n } else out.push(char.charCodeAt(0) & 0xff);\n }\n bytes = Uint8Array.from(out);\n }\n try {\n return new TextDecoder(charset, { fatal: true }).decode(bytes);\n } catch {\n return undefined;\n }\n };\n let result = \"\";\n let last = 0;\n let previousWasWord = false;\n for (const match of value.matchAll(word)) {\n const between = value.slice(last, match.index);\n const decoded = decodeOne(match[1] as string, match[2] as string, match[3] as string);\n if (decoded === undefined) {\n result += between + match[0];\n previousWasWord = false;\n } else {\n result += previousWasWord && /^\\s*$/.test(between) ? \"\" : between;\n result += decoded;\n previousWasWord = true;\n }\n last = match.index + match[0].length;\n }\n return result + value.slice(last);\n}\n\n/** Whether a connection's peer is this machine: the only way a tunnel tool reaches a face. */\nexport function isLoopbackPeer(remote: string | undefined): boolean {\n if (remote === undefined) return false;\n const address = remote.startsWith(\"::ffff:\") ? remote.slice(7) : remote;\n return address === \"::1\" || /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(address);\n}\n\n/**\n * The tailnet person Tailscale Serve names in a request (D158 item 2): `Tailscale-User-Login` and\n * `Tailscale-User-Name`, which Serve sets on every tailnet request after removing any a client\n * sent. They are believed only from a loopback peer (faces bind loopback, so only `tailscaled` and\n * this machine's own programs reach them) and never beside `Tailscale-Funnel-Request`, which\n * marks a public request. A tagged device sends no login, so nobody is named.\n */\nexport function tailnetPerson(\n headers: Headers,\n remote: string | undefined,\n): ViewerSpec | undefined {\n if (!isLoopbackPeer(remote) || headers.has(\"tailscale-funnel-request\")) return undefined;\n const login = headers.get(\"tailscale-user-login\");\n if (login === null) return undefined;\n const ref = decodeEncodedWords(login).trim();\n if (ref === \"\" || ref.length > 512) return undefined;\n const name = decodeEncodedWords(headers.get(\"tailscale-user-name\") ?? \"\").trim();\n return { ref, ...(name !== \"\" && name.length <= 256 ? { name } : {}) };\n}\n","/**\n * Integrity of served versions (FAILURE_MODEL §3: reads verify content). Before a version's\n * files are served, its stored tree is checked once against the output digest its manifest\n * records, and the change time of every file is remembered. A file served later whose change time\n * differs (any write or `chmod` changes it) makes the whole version checked again, so a version\n * altered while the gateway runs is refused from the next request on, not after a restart.\n */\nimport { readdir, realpath, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { Log } from \"../log.ts\";\nimport type { FoundFile } from \"./serve.ts\";\n\n/**\n * How long a damaged version's verdict is kept before its files are hashed again, unless its\n * directory was replaced (a republish rebuilds it in place, D98 and WP-03).\n */\nconst DAMAGE_TTL_MS = 10_000;\n\n/** What the integrity checks need to know about versions. */\nexport interface VersionStore {\n /** The directory of a published version (`versions/<id>`). */\n versionDir(versionId: string): string;\n /** What is wrong with a version's stored files, or `undefined` when they match their digest. */\n damage(versionId: string): Promise<string | undefined>;\n}\n\n/** The checks of one gateway. */\nexport interface VersionIntegrity {\n /** The version's damage, or `undefined` when its stored files match their digest. */\n check(versionId: string): Promise<string | undefined>;\n /**\n * Whether `file`, found in the version's `client/` tree, may be served: `undefined` when it may,\n * else what is wrong. A file whose change time differs from the last check checks the version\n * again.\n */\n serve(versionId: string, file: FoundFile): Promise<string | undefined>;\n}\n\n/** The change time of every file under `root`, by real path. */\nasync function changeTimes(root: string): Promise<Map<string, number>> {\n const times = new Map<string, number>();\n const real = await realpath(root);\n for (const entry of await readdir(real, { recursive: true, withFileTypes: true })) {\n if (entry.isDirectory()) continue;\n const path = await realpath(join(entry.parentPath, entry.name));\n const info = await stat(path);\n if (info.isFile()) times.set(path, info.ctimeMs);\n }\n return times;\n}\n\n/** Creates the integrity checks of one gateway. */\nexport function versionIntegrity(store: VersionStore, log: Log): VersionIntegrity {\n const verified = new Map<string, Map<string, number>>();\n const damaged = new Map<\n string,\n { readonly damage: string; readonly until: number; readonly dir: string }\n >();\n /** The identity of a version's directory: a rebuild puts a new one in place. */\n const dirIdentity = async (versionId: string): Promise<string> => {\n try {\n const info = await stat(store.versionDir(versionId));\n return `${info.ino}:${info.ctimeMs}`;\n } catch {\n return \"missing\";\n }\n };\n const running = new Map<string, Promise<string | undefined>>();\n\n const check = (versionId: string): Promise<string | undefined> => {\n if (verified.has(versionId)) return Promise.resolve(undefined);\n const pending = running.get(versionId);\n if (pending) return pending;\n const started = (async () => {\n const dir = await dirIdentity(versionId);\n const known = damaged.get(versionId);\n if (known && known.until > Date.now() && known.dir === dir) return known.damage;\n // Change times first: a write between them and the hashing is caught by the hashing, and\n // a write after it by the change time.\n let times: Map<string, number>;\n try {\n times = await changeTimes(join(store.versionDir(versionId), \"client\"));\n } catch (error) {\n times = new Map();\n log.warn(\"gateway.version_unreadable\", {\n versionId,\n code: (error as NodeJS.ErrnoException).code,\n });\n }\n const damage = await store.damage(versionId);\n if (damage !== undefined) {\n log.error(\"gateway.version_damaged\", { versionId, damage });\n damaged.set(versionId, { damage, until: Date.now() + DAMAGE_TTL_MS, dir });\n return damage;\n }\n damaged.delete(versionId);\n verified.set(versionId, times);\n return undefined;\n })().finally(() => running.delete(versionId));\n running.set(versionId, started);\n return started;\n };\n\n return {\n check,\n async serve(versionId, file) {\n if (verified.get(versionId)?.get(file.path) === file.ctimeMs) return undefined;\n // First sight of this file, or it changed since the check: check the version again.\n verified.delete(versionId);\n const damage = await check(versionId);\n if (damage !== undefined) return damage;\n return verified.get(versionId)?.get(file.path) === file.ctimeMs\n ? undefined\n : \"a file changed while the version was checked\";\n },\n };\n}\n","/**\n * Route declarations (D96): every gateway endpoint declares what it is for (its intent), whether\n * it needs a session, whether it takes a capability token or ticket, and the scope it needs. One\n * runner applies the checks in one order for all of them, so an endpoint a later package adds is\n * behind the same checks by construction:\n *\n * 1. the `Origin` and content type its intent needs (`checkRequest`; the envelope was checked\n * before routing);\n * 2. the rate limit, on token paths;\n * 3. the session, bound to this origin, with a live token (401, 410): its cookie in cookie mode,\n * its frame header in worker mode (D70), or a single-use stream ticket on stream routes\n * (D158 item 5);\n * 4. the session's CSRF token, on mutations;\n * 5. the scope.\n *\n * A route declared without a handler is a browser-protocol path a later package serves\n * (INTERFACES §4): it answers 501 once every check has passed.\n */\nimport {\n type CapabilityScope,\n checkRequest,\n FRAME_SESSION_HEADER,\n type Refusal,\n type RequestIntent,\n type RequestPolicy,\n refusal,\n scopeAllows,\n} from \"@mostra/protocol\";\nimport type { Context, Hono } from \"hono\";\nimport type { Log } from \"../log.ts\";\nimport type { Capabilities, ResolvedSession } from \"./capabilities.ts\";\nimport {\n cookieValues,\n type HttpEnv,\n headerPairs,\n isRefusal,\n refusalResponse,\n wantsDocument,\n} from \"./http.ts\";\n\n/** What a route needs before its handler runs. */\nexport interface RouteSpec {\n readonly method: \"GET\" | \"POST\";\n /** A Hono path pattern. */\n readonly path: string;\n readonly intent: RequestIntent;\n /** `session`: a session of this origin, for the listener's artifact, is required. */\n readonly auth: \"none\" | \"session\";\n /** The route takes a capability token or a frame ticket: failures are rate-limited (D97 item 8). */\n readonly tokenPath?: boolean;\n /**\n * The scope the request needs beyond `view`, from its path parameters. `any-action` means some\n * action scope; the handler checks the exact function (D96).\n */\n readonly scope?: (params: Readonly<Record<string, string>>) => CapabilityScope | \"any-action\";\n /**\n * An event stream (SSE): refused on a face streams don't pass, and in worker mode without a\n * ticket, so the page long-polls instead (D158 item 5).\n */\n readonly sse?: true;\n /** Serves the request. Absent: declared for a later package, answered with 501. */\n readonly handler?: (context: RouteContext) => Response | Promise<Response>;\n}\n\n/** What a handler receives. */\nexport interface RouteContext {\n readonly request: Request;\n readonly params: Readonly<Record<string, string>>;\n /** The artifact this request is for; always set on `auth: \"session\"` routes. */\n readonly artifactId: string | undefined;\n /** The session, for `auth: \"session\"` routes. */\n readonly session?: ResolvedSession;\n /** Whether the client is navigating (answer with HTML rather than JSON). */\n readonly document: boolean;\n /** The address of the connection's peer: on a face, the tunnel's own process (D158 item 2). */\n readonly remote: string | undefined;\n}\n\n/** What a listener contributes to every route's checks. */\nexport interface ListenerChecks {\n /** The listener's origin and Host allowlist, known once it is bound. */\n readonly policy: () => RequestPolicy;\n readonly capabilities: Capabilities;\n readonly log: Log;\n /** The session cookie's name on this listener: `mostra-<port>` (D98 item 1). */\n readonly cookieName: () => string;\n /** Who may frame this listener's refusal pages: `'none'` on the shell, the shell's origin on artifacts. */\n readonly frameAncestors: () => string;\n /** The artifact a request is for: fixed on an artifact's listener, from the path on the shell. */\n readonly artifactOf: (params: Readonly<Record<string, string>>) => string | undefined;\n /**\n * How this listener's sessions authenticate (D70): `cookie` (the default), or `worker`, where a\n * frame's service worker sends the session's secret as `X-Mostra-Frame`.\n */\n readonly mode?: () => \"cookie\" | \"worker\";\n /** Whether event streams pass to this listener's browsers; `false` behind a quick tunnel. */\n readonly streams?: () => boolean;\n}\n\n/** Logs a refusal without any of the request's capability material, and answers it. */\nexport function refuse(\n checks: Pick<ListenerChecks, \"log\" | \"policy\" | \"frameAncestors\">,\n refused: Refusal & { readonly retryAfter?: number },\n request: { readonly method: string; readonly path: string; readonly document: boolean },\n): Response {\n checks.log.warn(\"gateway.refused\", {\n code: refused.diagnostic.code,\n status: refused.status,\n method: request.method,\n // The path never carries a token (links keep it in the fragment); a ticket query is redacted\n // by the log's redactor all the same.\n path: request.path,\n origin: checks.policy().origin,\n });\n return refusalResponse(refused, {\n document: request.document,\n method: request.method,\n frameAncestors: checks.frameAncestors(),\n });\n}\n\nconst NOT_SERVED_YET = (method: string, path: string): Refusal =>\n refusal(\n \"MOSTRA_HYGIENE_NOT_SERVED\",\n `This Mostra release doesn't serve ${method} ${path} yet.`,\n 501,\n );\n\n/** Mounts routes on a listener's Hono app behind the common checks. */\nexport function mount(\n app: Hono<HttpEnv>,\n checks: ListenerChecks,\n routes: readonly RouteSpec[],\n): void {\n for (const route of routes) {\n const handle = async (c: Context<HttpEnv>): Promise<Response> => {\n const request = c.req.raw;\n const url = new URL(request.url);\n const document = wantsDocument(request.headers);\n const meta = { method: request.method, path: url.pathname, document };\n const params = c.req.param() as Record<string, string>;\n const incoming = c.env.incoming;\n const facts = {\n method: request.method,\n target: incoming.url ?? url.pathname,\n headers: headerPairs(incoming),\n };\n // 1. Origin and content type; CSRF comes once the session is known.\n const policy = checks.policy();\n const early = checkRequest(policy, {\n ...facts,\n intent: route.intent === \"mutation\" ? \"exchange\" : route.intent,\n });\n if (early) return refuse(checks, early, meta);\n const artifactId = checks.artifactOf(params);\n if (route.auth === \"session\" && artifactId === undefined) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"No artifact is served at this path.\"),\n meta,\n );\n }\n // 2. The rate limit holds every attempt while too many failed.\n if (route.tokenPath && artifactId !== undefined) {\n const limited = checks.capabilities.limited(artifactId);\n if (limited) return refuse(checks, limited, meta);\n }\n // 3. The session: a stream ticket on a stream route, else the cookie, or the frame header\n // in worker mode. An event stream only passes where streams do, and in worker mode only\n // with a ticket: a stream through the service worker stalls in Firefox (VERIFIED_FACTS).\n const mode = checks.mode?.() ?? \"cookie\";\n const ticket = route.intent === \"stream\" ? url.searchParams.get(\"ticket\") : null;\n if (route.sse && (checks.streams?.() === false || (mode === \"worker\" && ticket === null))) {\n return refuse(\n checks,\n refusal(\n \"MOSTRA_HYGIENE_NOT_SERVED\",\n checks.streams?.() === false\n ? \"Event streams don't pass this address; long-poll instead (events/poll).\"\n : \"A worker-mode frame opens its event stream with a ticket; long-poll instead.\",\n 503,\n ),\n meta,\n );\n }\n let session: ResolvedSession | undefined;\n if (route.auth === \"session\" && artifactId !== undefined) {\n const resolved =\n ticket !== null\n ? checks.capabilities.redeemStreamTicket(ticket, policy.origin, artifactId, \"stream\")\n : mode === \"worker\"\n ? checks.capabilities.session(\n [request.headers.get(FRAME_SESSION_HEADER) ?? \"\"],\n policy.origin,\n artifactId,\n \"worker\",\n )\n : checks.capabilities.session(\n cookieValues(request.headers.get(\"cookie\"), checks.cookieName()),\n policy.origin,\n artifactId,\n );\n if (isRefusal(resolved)) return refuse(checks, resolved, meta);\n session = resolved;\n // 4. The CSRF token of this session.\n if (route.intent === \"mutation\") {\n const csrf = checkRequest(policy, { ...facts, intent: \"mutation\", csrf: session.csrf });\n if (csrf) return refuse(checks, csrf, meta);\n }\n // 5. The scope.\n const needed = route.scope?.(params);\n const allowed =\n needed === undefined\n ? true\n : needed === \"any-action\"\n ? session.grant.scopes.some((scope) => scope.startsWith(\"action:\"))\n : scopeAllows(session.grant.scopes, needed);\n if (!allowed) {\n return refuse(\n checks,\n refusal(\n \"MOSTRA_HYGIENE_SCOPE_DENIED\",\n `This link doesn't carry the ${needed === \"any-action\" ? \"action\" : needed} scope.`,\n ),\n meta,\n );\n }\n }\n if (!route.handler) return refuse(checks, NOT_SERVED_YET(request.method, url.pathname), meta);\n return route.handler({\n request,\n params,\n artifactId,\n ...(session ? { session } : {}),\n document,\n remote: incoming.socket.remoteAddress,\n });\n };\n if (route.method === \"GET\") app.get(route.path, handle);\n else app.post(route.path, handle);\n }\n}\n","/**\n * One gateway listener: a Node HTTP server on a leased port with a Hono app behind it. Every\n * request's envelope (exact `Host`, plain path, single headers) is checked before routing,\n * methods other than GET, HEAD and POST are refused, upgrades are refused after their `Origin`\n * check unless the listener takes them (a dev sandbox's HMR WebSocket, D140 item 12; terminals add\n * theirs, WP-22), and every response leaves with the base headers.\n */\nimport { createServer, type IncomingMessage, type Server } from \"node:http\";\nimport type { Socket } from \"node:net\";\nimport type { Duplex } from \"node:stream\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport {\n checkRequest,\n createDiagnostic,\n type Refusal,\n type RequestPolicy,\n refusal,\n} from \"@mostra/protocol\";\nimport { Hono } from \"hono\";\nimport type { Log } from \"../log.ts\";\nimport { BASE_HEADERS, type HttpEnv, headerPairs, refusalResponse } from \"./http.ts\";\nimport { refuse } from \"./routes.ts\";\n\n/**\n * Node's limit on request headers for gateway listeners. Every port of the loopback host shares one\n * cookie jar, and any artifact's page can fill it; Chromium, Firefox and WebKit keep about 410 KB\n * per host (100 cookies of 4 KiB), so a jar filled to the brim fits with room to spare\n * (VERIFIED_FACTS, WP-05). A request past this limit is answered with a page that clears the\n * host's cookies (D98 item 9).\n */\nexport const MAX_HEADER_SIZE: number = 1024 * 1024;\n\n/**\n * How long a listener keeps an idle connection open: longer than browsers keep theirs (Chromium\n * 300 s, Firefox 115 s), so the browser reuses its connections and closes them itself (D157 item\n * 2). Node's default, 5 s, made the gateway close first, and each connection it closed stayed in\n * TIME_WAIT on its side, where Chromium's random local ports on Windows collided with it and\n * failed the connect at once with `ERR_NO_BUFFER_SPACE` (#66).\n */\nexport const KEEP_ALIVE_MS: number = 305_000;\n\n/** A listener: its server and its Hono app. */\nexport interface Listener {\n readonly server: Server;\n readonly app: Hono<HttpEnv>;\n /** Stops accepting connections and closes the open ones. */\n close(): Promise<void>;\n}\n\n/** Writes a refusal straight to a socket, for upgrades and envelope failures before Hono. */\nfunction writeRaw(\n socket: Duplex,\n refused: Refusal,\n extra: { readonly html?: string; readonly headers?: readonly string[] } = {},\n): void {\n const body = extra.html ?? JSON.stringify(refused.diagnostic);\n const headers = [\n `HTTP/1.1 ${refused.status} Refused`,\n \"connection: close\",\n extra.html !== undefined\n ? \"content-type: text/html; charset=utf-8\"\n : \"content-type: application/json; charset=utf-8\",\n `content-length: ${Buffer.byteLength(body)}`,\n \"cache-control: no-store\",\n ...Object.entries(BASE_HEADERS).map(([name, value]) => `${name}: ${value}`),\n ...(extra.headers ?? []),\n ];\n socket.end(`${headers.join(\"\\r\\n\")}\\r\\n\\r\\n${body}`);\n lingerAfterRefusal(socket);\n}\n\n/** Connections already answered with a refusal: a later parse error on them changes nothing. */\nconst refusedSockets = new WeakSet<Duplex>();\n\n/** How long a refused connection is read before it is closed regardless. */\nconst LINGER_MS = 5000;\n/** How much of a refused request is read and dropped before the connection is closed. */\nconst LINGER_BYTES = 16 * 1024 * 1024;\n\n/**\n * Reads and drops what the client is still sending after its refusal, until it closes the\n * connection, for at most {@link LINGER_MS} and {@link LINGER_BYTES}. A socket closed with unread\n * bytes is reset, and a reset can reach the client before it read the answer, which it then never\n * sees: on Windows a browser sending a megabyte of cookies got a reset instead of the page that\n * clears them (WP-W2). The answer is already written; this only keeps the connection open long\n * enough for it to be read, as HTTP servers do for a \"lingering close\".\n */\nfunction lingerAfterRefusal(socket: Duplex): void {\n refusedSockets.add(socket);\n // Node's HTTP server keeps feeding what arrives to the request parser that just failed, which\n // fails again (a second `clientError`) and ends the connection: from here on this reads alone.\n socket.removeAllListeners(\"data\");\n socket.once(\"end\", () => socket.destroy());\n let read = 0;\n const timer = setTimeout(() => socket.destroy(), LINGER_MS);\n timer.unref();\n socket.once(\"close\", () => clearTimeout(timer));\n socket.on(\"error\", () => socket.destroy());\n socket.on(\"data\", (chunk: Buffer) => {\n read += chunk.length;\n if (read > LINGER_BYTES) socket.destroy();\n });\n socket.resume();\n}\n\n/**\n * The answer to headers past {@link MAX_HEADER_SIZE}: a page that says what happened and clears\n * the host's cookies, which is what made them that large (D98 item 9). `Clear-Site-Data` acts on\n * the host, so it empties the jar every port shares; Mostra's sessions return when a link is\n * opened again. The page runs nothing and can't be framed.\n */\nfunction headersTooLarge(socket: Duplex): void {\n const refused = refusal(\n \"MOSTRA_HYGIENE_HEADERS_TOO_LARGE\",\n \"This browser sent more cookies than any page here sets.\",\n );\n const html = `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"referrer\" content=\"no-referrer\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Mostra</title><style>body{font-family:system-ui,sans-serif;margin:0;min-height:100vh;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:.25rem;padding:2rem;text-align:center;color-scheme:light dark}h1{font-size:1.25rem;margin:0}p{margin:0;opacity:.8}code{opacity:.5;font-size:.75rem;margin-top:1rem}</style></head><body><h1>This browser sent more cookies than Mostra accepts</h1><p>A page on this machine filled them. They have been cleared: open your link again.</p><code>MOSTRA_HYGIENE_HEADERS_TOO_LARGE</code></body></html>`;\n writeRaw(socket, refused, {\n html,\n headers: [\n 'clear-site-data: \"cookies\"',\n \"content-security-policy: default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'\",\n ],\n });\n}\n\n/**\n * Records every connection and request of a listener in the supervisor's log: its arrival and its\n * end, whether it was answered, with the time between them and the client's port, so a request a\n * browser saw go unanswered shows whether it ever reached the gateway (#66). Only a request's\n * method and path are kept, never its query (a frame ticket travels there) or its headers; a test\n * switch (`MOSTRA_TEST_REQUEST_LOG`), since a long-lived daemon would log every asset it serves.\n */\nfunction traceRequests(server: Server, log: Log, origin: () => string): void {\n server.on(\"connection\", (socket: Socket) => {\n const opened = Date.now();\n const client = socket.remotePort;\n log.info(\"gateway.connection\", { origin: origin(), client });\n socket.once(\"close\", (hadError: boolean) =>\n log.info(\"gateway.connection_closed\", {\n origin: origin(),\n client,\n ms: Date.now() - opened,\n read: socket.bytesRead,\n written: socket.bytesWritten,\n ...(hadError ? { hadError } : {}),\n }),\n );\n });\n server.prependListener(\"request\", (incoming: IncomingMessage, outgoing) => {\n const started = Date.now();\n const fields = {\n origin: origin(),\n client: incoming.socket.remotePort,\n method: incoming.method,\n path: (incoming.url ?? \"\").replace(/[?#].*$/s, \"\"),\n };\n log.info(\"gateway.request\", fields);\n // `finished`: the whole answer was handed to the connection. A stream (events, a long poll)\n // the browser leaves ends unfinished with its headers sent; a request that got nothing ends\n // with neither.\n outgoing.once(\"close\", () =>\n log.info(\"gateway.request_closed\", {\n ...fields,\n status: outgoing.statusCode,\n headersSent: outgoing.headersSent,\n finished: outgoing.writableFinished,\n ms: Date.now() - started,\n }),\n );\n });\n}\n\n/** Creates a listener whose routes `configure` mounts; the server isn't bound yet. */\nexport function createListener(options: {\n readonly policy: () => RequestPolicy;\n readonly log: Log;\n readonly frameAncestors: () => string;\n readonly configure: (app: Hono<HttpEnv>) => void;\n /**\n * Takes an upgrade whose Host, target and Origin passed the checks (a dev sandbox's HMR\n * WebSocket, D140 item 12), or answers why it is refused. Without it every upgrade is refused.\n */\n readonly upgrade?: (\n incoming: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n ) => Refusal | undefined;\n /** Logs every connection and request ({@link traceRequests}): tests only. */\n readonly traceRequests?: boolean;\n}): Listener {\n const app = new Hono<HttpEnv>();\n options.configure(app);\n app.notFound((c) =>\n refuse(options, refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"Nothing is served at this path.\"), {\n method: c.req.method,\n path: new URL(c.req.url).pathname,\n document: false,\n }),\n );\n app.onError((error, c) => {\n options.log.error(\"gateway.handler_failed\", { error, path: new URL(c.req.url).pathname });\n return refusalResponse(\n {\n status: 500,\n diagnostic: createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: \"The gateway failed to answer this request.\",\n }),\n },\n { document: false, method: c.req.method },\n );\n });\n const listener = getRequestListener(app.fetch, { overrideGlobalObjects: false });\n\n const server = createServer({ maxHeaderSize: MAX_HEADER_SIZE }, (incoming, outgoing) => {\n const policy = options.policy();\n const method = incoming.method ?? \"\";\n const envelope =\n checkRequest(policy, {\n method,\n target: incoming.url ?? \"\",\n headers: headerPairs(incoming),\n }) ??\n (method === \"GET\" || method === \"HEAD\" || method === \"POST\"\n ? undefined\n : method === \"OPTIONS\"\n ? // A preflight never gets an Access-Control-* answer: no other origin may call in.\n refusal(\n \"MOSTRA_HYGIENE_ORIGIN_REFUSED\",\n \"This gateway answers no cross-origin requests.\",\n )\n : refusal(\n \"MOSTRA_HYGIENE_NOT_SERVED\",\n `This gateway doesn't serve ${method} requests.`,\n 405,\n ));\n if (envelope) {\n options.log.warn(\"gateway.refused\", {\n code: envelope.diagnostic.code,\n status: envelope.status,\n method,\n origin: policy.origin,\n });\n const response = refusalResponse(envelope, { document: false, method });\n // A request refused before routing ends its connection: nothing else is read from it.\n outgoing.shouldKeepAlive = false;\n outgoing.writeHead(response.status, {\n ...Object.fromEntries(response.headers),\n connection: \"close\",\n });\n void response.text().then((text) => outgoing.end(text));\n return;\n }\n void listener(incoming, outgoing);\n });\n if (options.traceRequests) traceRequests(server, options.log, () => options.policy().origin);\n // A client that sends something Node can't parse gets a 400 and its connection closed.\n server.on(\"clientError\", (error: NodeJS.ErrnoException, socket) => {\n if (refusedSockets.has(socket)) return;\n if (!socket.writable) {\n socket.destroy();\n return;\n }\n if (error.code === \"HPE_HEADER_OVERFLOW\") {\n options.log.warn(\"gateway.refused\", {\n code: \"MOSTRA_HYGIENE_HEADERS_TOO_LARGE\",\n status: 431,\n origin: options.policy().origin,\n });\n headersTooLarge(socket);\n return;\n }\n writeRaw(\n socket,\n refusal(\"MOSTRA_HYGIENE_REQUEST_MALFORMED\", \"The request couldn't be parsed.\"),\n );\n });\n server.on(\"upgrade\", (incoming: IncomingMessage, socket: Duplex, head: Buffer) => {\n const policy = options.policy();\n const checked = checkRequest(policy, {\n method: incoming.method ?? \"\",\n target: incoming.url ?? \"\",\n headers: headerPairs(incoming),\n intent: \"upgrade\",\n });\n const refused =\n checked ??\n (options.upgrade\n ? options.upgrade(incoming, socket, head)\n : refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"This gateway serves no WebSocket here.\"));\n if (refused === undefined) return;\n options.log.warn(\"gateway.refused\", {\n code: refused.diagnostic.code,\n status: refused.status,\n method: \"UPGRADE\",\n origin: policy.origin,\n });\n writeRaw(socket, refused);\n });\n server.headersTimeout = 30_000;\n server.requestTimeout = 120_000;\n // An idle connection waits for its next request without these two limits, which count from a\n // request's first byte.\n server.keepAliveTimeout = KEEP_ALIVE_MS;\n\n return {\n server,\n app,\n close: () =>\n new Promise((resolve) => {\n if (!server.listening) return resolve();\n server.close(() => resolve());\n server.closeAllConnections();\n }),\n };\n}\n","/**\n * Static files (RT-05, VR-03): the gateway serves a published version's client build and the\n * shell's built page straight from disk, with no process. A file is found only under its root,\n * through a path the hygiene checks already proved plain, and only when its real path stays inside\n * the root. Responses support `HEAD`, a single byte range (media seeking needs it) and conditional\n * requests.\n */\nimport { createReadStream } from \"node:fs\";\nimport { realpath, stat } from \"node:fs/promises\";\nimport { extname, join, sep } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { BASE_HEADERS } from \"./http.ts\";\n\nconst TYPES: Readonly<Record<string, string>> = {\n \".html\": \"text/html; charset=utf-8\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".map\": \"application/json; charset=utf-8\",\n \".txt\": \"text/plain; charset=utf-8\",\n \".md\": \"text/markdown; charset=utf-8\",\n \".csv\": \"text/csv; charset=utf-8\",\n \".xml\": \"application/xml; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".ico\": \"image/x-icon\",\n \".bmp\": \"image/bmp\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".otf\": \"font/otf\",\n \".wasm\": \"application/wasm\",\n \".mp4\": \"video/mp4\",\n \".webm\": \"video/webm\",\n \".ogg\": \"audio/ogg\",\n \".mp3\": \"audio/mpeg\",\n \".wav\": \"audio/wav\",\n \".m4a\": \"audio/mp4\",\n \".pdf\": \"application/pdf\",\n \".zip\": \"application/zip\",\n \".cast\": \"application/x-asciicast\",\n \".glb\": \"model/gltf-binary\",\n \".gltf\": \"model/gltf+json\",\n};\n\n/** The `Content-Type` of a file, by extension. */\nexport function contentType(path: string): string {\n return TYPES[extname(path).toLowerCase()] ?? \"application/octet-stream\";\n}\n\n/** A file found under a root. */\nexport interface FoundFile {\n readonly path: string;\n readonly size: number;\n readonly mtimeMs: number;\n /** When its contents or mode last changed; integrity checks compare it (FAILURE_MODEL §3). */\n readonly ctimeMs: number;\n}\n\n/**\n * Finds the regular file `path` (a decoded, plain path starting with `/`) names under `root`, or\n * `undefined`. Its real path must stay under the root's real path, so a link can't lead out.\n */\nexport async function findFile(root: string, path: string): Promise<FoundFile | undefined> {\n if (path.includes(\"\\0\")) return undefined;\n try {\n const realRoot = await realpath(root);\n const real = await realpath(join(realRoot, path));\n if (real !== realRoot && !real.startsWith(`${realRoot}${sep}`)) return undefined;\n const info = await stat(real);\n return info.isFile()\n ? { path: real, size: info.size, mtimeMs: info.mtimeMs, ctimeMs: info.ctimeMs }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Answers a request for a found file, with the given extra headers. */\nexport function fileResponse(\n file: FoundFile,\n request: Request,\n headers: Readonly<Record<string, string>>,\n): Response {\n const etag = `W/\"${file.size.toString(36)}-${Math.trunc(file.mtimeMs).toString(36)}\"`;\n const base: Record<string, string> = {\n ...BASE_HEADERS,\n \"content-type\": contentType(file.path),\n \"accept-ranges\": \"bytes\",\n etag,\n ...headers,\n };\n if (request.headers.get(\"if-none-match\") === etag) {\n return new Response(null, { status: 304, headers: base });\n }\n const head = request.method === \"HEAD\";\n const range = /^bytes=(\\d*)-(\\d*)$/.exec(request.headers.get(\"range\") ?? \"\");\n if (range && (range[1] !== \"\" || range[2] !== \"\")) {\n let start: number;\n let end: number;\n if (range[1] === \"\") {\n // A suffix range: the last N bytes.\n start = Math.max(0, file.size - Number(range[2]));\n end = file.size - 1;\n } else {\n start = Number(range[1]);\n end = range[2] === \"\" ? file.size - 1 : Math.min(Number(range[2]), file.size - 1);\n }\n if (start > end || start >= file.size) {\n return new Response(null, {\n status: 416,\n headers: { ...base, \"content-range\": `bytes */${file.size}` },\n });\n }\n const body = head\n ? null\n : (Readable.toWeb(createReadStream(file.path, { start, end })) as ReadableStream);\n return new Response(body, {\n status: 206,\n headers: {\n ...base,\n \"content-range\": `bytes ${start}-${end}/${file.size}`,\n \"content-length\": String(end - start + 1),\n },\n });\n }\n const body = head ? null : (Readable.toWeb(createReadStream(file.path)) as ReadableStream);\n return new Response(body, {\n status: 200,\n headers: { ...base, \"content-length\": String(file.size) },\n });\n}\n","/**\n * Worker-mode frame sessions (D70, D158 item 5): where the shell and the artifact are two sites,\n * no cookie reaches the artifact's frame (VERIFIED_FACTS, cross-site frames). The frame enters\n * through a bootstrap page instead: it exchanges the shell's single-use ticket for a frame\n * session, installs Mostra's service worker at `/`, and enters the version, whose every\n * same-origin request then carries the session in a header. Event streams, polls and WebSockets\n * bypass the worker with single-use tickets, since Firefox stalls on endless responses a worker\n * passes on.\n *\n * This module holds the two documents the browser runs: the bootstrap page and the worker. Both\n * are plain scripts with no imports, served by the gateway from the artifact's origin.\n */\nimport { FRAME_SESSION_HEADER } from \"@mostra/protocol\";\n\n/** Where the service worker is served; its registration's scope is `/`. */\nexport const SERVICE_WORKER_PATH = \"/_mostra/sw.js\";\n\n/** The IndexedDB the frame session's secret is kept in, per artifact origin and top-level site. */\nconst DB = \"mostra-frame\";\n\n/**\n * The service worker (D70): it adds the frame session's header to every same-origin request but\n * its own script, the bootstrap's, and ticketed ones (`?ticket=`: streams, polls and sockets),\n * and keeps the secret in IndexedDB, since a browser stops idle workers and their memory goes.\n * A request a header can't be added to as made (a `no-cors` script or image, a navigation) is\n * sent again as a same-origin request, which carries it.\n */\nexport const SERVICE_WORKER_SOURCE: string = `// Mostra's frame-session worker (D70). It signs this origin's requests for the artifact's frame.\n\"use strict\";\nconst HEADER = ${JSON.stringify(FRAME_SESSION_HEADER)};\nconst DB = ${JSON.stringify(DB)};\nconst STORE = \"session\";\nlet secret;\nfunction store(mode, act) {\n return new Promise((resolve, reject) => {\n const open = indexedDB.open(DB, 1);\n open.onupgradeneeded = () => open.result.createObjectStore(STORE);\n open.onerror = () => reject(open.error);\n open.onsuccess = () => {\n const db = open.result;\n const tx = db.transaction(STORE, mode);\n const request = act(tx.objectStore(STORE));\n tx.oncomplete = () => { db.close(); resolve(request.result); };\n tx.onerror = tx.onabort = () => { db.close(); reject(tx.error); };\n };\n });\n}\nasync function current() {\n if (secret === undefined) {\n try { secret = await store(\"readonly\", (s) => s.get(\"secret\")); } catch { secret = undefined; }\n }\n return secret;\n}\nself.addEventListener(\"install\", () => { self.skipWaiting(); });\nself.addEventListener(\"activate\", (event) => { event.waitUntil(self.clients.claim()); });\nself.addEventListener(\"message\", (event) => {\n const data = event.data;\n if (!data || data.type !== \"mostra/frame-session\" || typeof data.secret !== \"string\") return;\n secret = data.secret;\n const port = event.ports[0];\n event.waitUntil(\n store(\"readwrite\", (s) => s.put(data.secret, \"secret\")).then(\n () => port && port.postMessage({ ok: true }),\n (error) => port && port.postMessage({ ok: false, message: String(error) }),\n ),\n );\n});\nself.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n const url = new URL(request.url);\n if (url.origin !== self.location.origin) return;\n if (url.pathname === ${JSON.stringify(SERVICE_WORKER_PATH)} || url.pathname === \"/_mostra/enter\") return;\n if (url.searchParams.has(\"ticket\")) return;\n event.respondWith(signed(request));\n});\nasync function signed(request) {\n const value = await current();\n if (!value) return fetch(request);\n const headers = new Headers(request.headers);\n headers.set(HEADER, value);\n const navigate = request.mode === \"navigate\";\n // Sent on, a navigation is an ordinary request: the gateway learns it was one from this header.\n if (navigate) headers.set(\"x-mostra-navigation\", \"1\");\n const init = {\n method: request.method,\n headers,\n mode: navigate || request.mode === \"no-cors\" ? \"same-origin\" : request.mode,\n credentials: request.credentials,\n cache: request.cache === \"only-if-cached\" ? \"default\" : request.cache,\n redirect: navigate ? \"manual\" : request.redirect,\n referrerPolicy: request.referrerPolicy,\n integrity: request.integrity,\n keepalive: request.keepalive,\n signal: request.signal,\n };\n if (request.method !== \"GET\" && request.method !== \"HEAD\") init.body = await request.arrayBuffer();\n return fetch(new Request(request.url, init));\n}\n`;\n\n/**\n * The bootstrap page at `/_mostra/enter#t=<ticket>` (D70): it takes the ticket from the fragment\n * (so no server, log or `Referer` sees it), exchanges it at `POST /_mostra/enter` (sending the\n * session it kept, so a frame that re-enters keeps its session and switches version), installs\n * the worker at `/`, hands it the secret, tells the shell (`mostra/frameSession.entered`) and\n * enters the version at `/`. Whatever stops it is reported to the shell as\n * `mostra/frameSession.failed` with `MOSTRA_HYGIENE_FRAME_SESSION`.\n */\nexport const BOOTSTRAP_PAGE: string = `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"referrer\" content=\"no-referrer\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Mostra</title>\n<style>body{font-family:system-ui,sans-serif;margin:0;min-height:100vh;display:flex;justify-content:center;align-items:center;padding:2rem;text-align:center;color-scheme:light dark;opacity:.8}</style>\n</head>\n<body>\n<script>\n(async () => {\n \"use strict\";\n const HEADER = ${JSON.stringify(FRAME_SESSION_HEADER)};\n let shell = \"*\";\n const fail = (reason, message) => {\n document.body.textContent = message;\n parent.postMessage(\n { jsonrpc: \"2.0\", method: \"mostra/frameSession.failed\",\n params: { code: \"MOSTRA_HYGIENE_FRAME_SESSION\", reason, message } },\n shell,\n );\n };\n const kept = () => new Promise((resolve) => {\n try {\n const open = indexedDB.open(${JSON.stringify(DB)}, 1);\n open.onupgradeneeded = () => open.result.createObjectStore(\"session\");\n open.onerror = () => resolve(undefined);\n open.onsuccess = () => {\n const db = open.result;\n try {\n const read = db.transaction(\"session\", \"readonly\").objectStore(\"session\").get(\"secret\");\n read.onsuccess = () => { db.close(); resolve(typeof read.result === \"string\" ? read.result : undefined); };\n read.onerror = () => { db.close(); resolve(undefined); };\n } catch { db.close(); resolve(undefined); }\n };\n } catch { resolve(undefined); }\n });\n const ticket = new URLSearchParams(location.hash.slice(1)).get(\"t\");\n history.replaceState(null, \"\", location.pathname);\n if (!ticket) return fail(\"refused\", \"This frame was opened without a ticket.\");\n if (!(\"serviceWorker\" in navigator) || typeof indexedDB === \"undefined\") {\n return fail(\"unsupported\", \"This browser offers the artifact's frame no service worker here, which this link needs.\");\n }\n let answer;\n try {\n const previous = await kept();\n const response = await fetch(\"/_mostra/enter\", {\n method: \"POST\",\n credentials: \"omit\",\n cache: \"no-store\",\n headers: { \"content-type\": \"application/json\", ...(previous ? { [HEADER]: previous } : {}) },\n body: JSON.stringify({ ticket }),\n });\n answer = await response.json().catch(() => ({}));\n if (!response.ok) return fail(\"refused\", answer.message || \"The frame's entry was refused.\");\n } catch (error) {\n return fail(\"refused\", \"The frame couldn't reach Mostra: \" + error);\n }\n shell = answer.shellOrigin;\n try {\n const found = await navigator.serviceWorker.getRegistration(\"/\");\n const script = found && (found.active || found.waiting || found.installing);\n if (script && new URL(script.scriptURL).pathname !== ${JSON.stringify(SERVICE_WORKER_PATH)}) {\n console.warn(\"Mostra replaced another service worker at / on this origin: a worker-mode frame needs its own there (MOSTRA_HYGIENE_FRAME_SESSION).\");\n }\n const registration = await navigator.serviceWorker.register(${JSON.stringify(SERVICE_WORKER_PATH)}, { scope: \"/\", updateViaCache: \"none\" });\n const worker = registration.installing || registration.waiting || registration.active;\n if (!worker) throw new Error(\"no worker\");\n if (worker.state !== \"activated\") {\n await new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(\"the worker didn't activate in 20 s\")), 20000);\n worker.addEventListener(\"statechange\", () => {\n if (worker.state === \"activated\") { clearTimeout(timer); resolve(); }\n if (worker.state === \"redundant\") { clearTimeout(timer); reject(new Error(\"the worker was replaced\")); }\n });\n });\n }\n const stored = await new Promise((resolve) => {\n const channel = new MessageChannel();\n const timer = setTimeout(() => resolve({ ok: false, message: \"no answer\" }), 10000);\n channel.port1.onmessage = (event) => { clearTimeout(timer); resolve(event.data); };\n worker.postMessage({ type: \"mostra/frame-session\", secret: answer.session }, [channel.port2]);\n });\n if (!stored || !stored.ok) throw new Error(stored && stored.message);\n } catch (error) {\n return fail(\"blocked\", \"This browser didn't let the artifact's frame install the service worker this link needs (\" + error + \").\");\n }\n // The shell waits for the page from here: this page's own load wasn't the page's.\n parent.postMessage({ jsonrpc: \"2.0\", method: \"mostra/frameSession.entered\", params: {} }, shell);\n location.replace(\"/\");\n})();\n</script>\n</body>\n</html>\n`;\n","/**\n * The submit channels and trusted controls in force for a view (D40, D108). A host that\n * registered the `trustedControls` port answers per artifact; otherwise the home's\n * `HomeConfig.submitChannels` holds; otherwise both channels, as D40's standalone default.\n */\nimport {\n type ArtifactDetail,\n type ControlsPolicy,\n portTrustedControlsPolicyMethod,\n type SubmitChannel,\n} from \"@mostra/protocol\";\nimport type { Log } from \"../log.ts\";\n\n/** How long a host has to answer `port/trustedControls.policy`: a page waits for it (D108). */\nexport const CONTROLS_POLICY_TIMEOUT_MS = 5_000;\n\n/** Both channels, every control. */\nconst STANDALONE: ControlsPolicy = { submitChannels: [\"shell\", \"artifact\"] };\n\n/** The shell channel only: what a host's failed answer narrows a view to. */\nconst SHELL_ONLY: ControlsPolicy = { submitChannels: [\"shell\"] };\n\n/** What {@link controlsPolicy} reads. */\nexport interface ControlsPolicyInput {\n /** The artifact a frame is about to show. */\n readonly artifact: ArtifactDetail;\n readonly log: Log;\n /** The home's `submitChannels`, if a host set them. */\n readonly home: () => readonly SubmitChannel[] | undefined;\n /**\n * Hosts that always provide `trustedControls` (`HomeConfig.ports`, D105), by client name: one\n * that is away decides nothing, so its views get the shell channel only.\n */\n readonly expected: () => readonly string[];\n /** The newest connection that registered `trustedControls`, if any. */\n readonly registrant: () => { readonly session: number; readonly owner: string } | undefined;\n /** Calls the port on that connection; rejects on a transport failure or the timeout. */\n readonly call: (session: number, params: unknown) => Promise<unknown>;\n}\n\n/**\n * The policy for a new view (D108). A host's answer wins; a host that registered the port but\n * fails to answer, or that always provides it (`HomeConfig.ports`) and isn't connected, narrows\n * the view to the shell channel, so its outage never widens what it allows.\n */\nexport async function controlsPolicy(input: ControlsPolicyInput): Promise<ControlsPolicy> {\n const registrant = input.registrant();\n if (registrant) {\n const { versions: _versions, manifest: _manifest, ...summary } = input.artifact;\n try {\n const answer = await input.call(registrant.session, { artifact: summary });\n const parsed = portTrustedControlsPolicyMethod.result.safeParse(answer);\n if (parsed.success) return normalize(parsed.data);\n input.log.warn(\"gateway.controls_policy_invalid\", {\n owner: registrant.owner,\n artifactId: input.artifact.id,\n });\n } catch (error) {\n input.log.warn(\"gateway.controls_policy_failed\", {\n owner: registrant.owner,\n artifactId: input.artifact.id,\n error: (error as Error).message,\n });\n }\n return SHELL_ONLY;\n }\n // A host that takes the policy over but is away right now (restarting, or the link opened\n // first) never has it widened by its absence: the view lives on after it returns (Claude\n // review finding 10).\n const away = input.expected();\n if (away.length > 0) {\n input.log.warn(\"gateway.controls_policy_host_away\", {\n owners: away,\n artifactId: input.artifact.id,\n });\n return SHELL_ONLY;\n }\n const channels = input.home();\n return channels === undefined ? STANDALONE : normalize({ submitChannels: channels });\n}\n\n/** Channels deduplicated and in a stable order. */\nfunction normalize(policy: ControlsPolicy): ControlsPolicy {\n const submitChannels = ([\"shell\", \"artifact\"] as const).filter((channel) =>\n policy.submitChannels.includes(channel),\n );\n return {\n submitChannels: submitChannels.length > 0 ? submitChannels : [\"shell\"],\n ...(policy.controls !== undefined ? { controls: [...new Set(policy.controls)] } : {}),\n };\n}\n","/**\n * The gateway (ARCHITECTURE §5, §10; D38, D96 to D99, D158): the HTTP side of an instance. It\n * serves the shell on the shell's leased port and each opened artifact on its own leased port, all\n * on one host, so the shell and every artifact are same-site but different origins. Only\n * capability holders get in: a link's token becomes a shell session, the shell hands the\n * artifact's frame a single-use ticket, and the frame's session lets it load its version's files.\n * Every request goes through the same checks (`routes.ts`), and published versions are served\n * straight from disk, with no process (RT-05). It also serves `view/url`, `view/rotate` and\n * `view/revoke`.\n *\n * Beside those loopback listeners, the gateway has **faces** (D158 item 1): external addresses of\n * the shell or one artifact (a tailnet, Funnel or Cloudflare address a share set up, or a host's\n * external base), each its own listener on loopback with one origin and one exact `Host`. Which\n * face a request came through is the socket it arrived on, so a tunnel's visitor can't claim\n * another address. A face pairs with the faces of its group (a share's, a host's): its shell opens\n * frames on the group's artifact face, in cookie mode when both are one site and in worker mode\n * (D70) when they are two.\n *\n * ```ts\n * const gateway = createGateway({ ledger, log, addressing, capabilities, artifacts, shellDir });\n * await gateway.start();\n * const { url } = await gateway.defaultLink(artifactId); // the publish receipt's URL\n * const face = await gateway.openFace({ by: \"cloudflare\", group, listener: \"shell\", … });\n * ```\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport type { IncomingMessage } from \"node:http\";\nimport { join, resolve } from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport {\n type ArtifactDetail,\n ArtifactId,\n type ArtifactRef,\n BROWSER_PROTOCOL_REVISIONS,\n type CapabilityLink,\n type CapabilityScope,\n type ControlsPolicy,\n createDiagnostic,\n type Diagnostic,\n durationMs,\n EnterRequest,\n type FaceStatus,\n FRAME_SESSION_HEADER,\n type FrameSessionFacts,\n type FrameTicket,\n type IdentityVia,\n type PortAddressingExternalBaseResult,\n type Refusal,\n RpcError,\n refusal,\n StreamTicketRequest,\n safePath,\n scopeAllows,\n viewDefaultMethod,\n viewLaunchMethod,\n viewRevokeMethod,\n viewRotateMethod,\n viewUrlMethod,\n} from \"@mostra/protocol\";\nimport type { Actions } from \"../actions/index.ts\";\nimport { type Addressing, type FrameMode, hostOf } from \"../addressing/index.ts\";\nimport { runtimeRoot } from \"../deps/index.ts\";\nimport type { EphemeralBus, Interaction } from \"../interaction/index.ts\";\nimport {\n type Ledger,\n type LedgerDb,\n type RequestKey,\n recordedResult,\n recordResult,\n requestKey,\n} from \"../ledger/index.ts\";\nimport type { Live } from \"../live/index.ts\";\nimport type { Environment, Log } from \"../log.ts\";\nimport { handler, type MethodHandler } from \"../protocol-server/index.ts\";\nimport { type ActionRoutes, actionRoutes } from \"./actions.ts\";\nimport { type BrowserRoutes, type BrowserRoutesOptions, browserRoutes } from \"./browser.ts\";\nimport {\n type Capabilities,\n type Grant,\n type MintedToken,\n SESSION_MAX_AGE_S,\n} from \"./capabilities.ts\";\nimport { type DevUpstream, devFetch, devUpgrade } from \"./dev.ts\";\nimport {\n BASE_HEADERS,\n cookieValues,\n documentHeaders,\n isRefusal,\n jsonResponse,\n type ListenerKind,\n readJsonObject,\n refusalResponse,\n sessionCookie,\n} from \"./http.ts\";\nimport { type IdentityOutcome, tailnetPerson } from \"./identity.ts\";\nimport { versionIntegrity } from \"./integrity.ts\";\nimport { createListener, type Listener } from \"./listener.ts\";\nimport { type ListenerChecks, mount, type RouteContext, type RouteSpec, refuse } from \"./routes.ts\";\nimport { fileResponse, findFile } from \"./serve.ts\";\nimport { BOOTSTRAP_PAGE, SERVICE_WORKER_PATH, SERVICE_WORKER_SOURCE } from \"./worker.ts\";\n\nexport { Capabilities, capabilityKey } from \"./capabilities.ts\";\nexport { CONTROLS_POLICY_TIMEOUT_MS, controlsPolicy } from \"./controls.ts\";\nexport type { DevUpstream } from \"./dev.ts\";\nexport { IDENTITY_TIMEOUT_MS, resolveIdentity } from \"./identity.ts\";\n\n/** What the gateway reads about artifacts and versions. */\nexport interface GatewayArtifacts {\n /** An artifact in full; throws `MOSTRA_ARTIFACT_NOT_FOUND` for an unknown one. */\n get(ref: ArtifactRef): ArtifactDetail;\n /** The directory of a published version (`versions/<id>`). */\n versionDir(versionId: string): string;\n /** What is wrong with a version's stored files, or `undefined` when they match their digest. */\n damage(versionId: string): Promise<string | undefined>;\n}\n\n/** Who keeps a face (D158 item 1): a share's tunnel, or a host's addressing port. */\nexport type FaceBy = \"tailnet\" | \"funnel\" | \"cloudflare\" | \"host\";\n\n/** What a share asks the gateway to open: one external address of the shell or an artifact. */\nexport interface FaceSpec {\n readonly by: FaceBy;\n /**\n * The faces that pair: a shell face opens frames on the artifact faces of its group (`tailnet`,\n * `funnel`, a Cloudflare share's own, a host's per artifact).\n */\n readonly group: string;\n readonly listener: \"shell\" | \"artifact\";\n /** The artifact, for an artifact's face. */\n readonly artifactId?: string;\n /** How requests through it reach the gateway, as the identity port hears it (D143 item 2). */\n readonly via: IdentityVia;\n /** Keep a leased loopback port, so the face's address survives restarts. */\n readonly lease: boolean;\n /** Whether event streams pass; `false` behind a Cloudflare quick tunnel. Default `true`. */\n readonly streams?: boolean;\n /** An artifact face's frame mode, when its keeper knows it; else decided by the pair (D70). */\n readonly mode?: FrameMode;\n}\n\n/** An open face. */\nexport interface FaceHandle {\n /** Its key: `<group>:shell` or `<group>:<artifactId>`. */\n readonly key: string;\n /** The loopback port the tunnel forwards to. */\n readonly port: number;\n /** `http://127.0.0.1:<port>`. */\n readonly local: string;\n /** The origin browsers use; until it is set, the face refuses every request (421). */\n origin(): string | undefined;\n /** Sets the origin once the tunnel knows its address; `undefined` closes the address again. */\n setOrigin(origin: string | undefined): void;\n}\n\n/** The answer a host's addressing port gave, or why there is none. */\nexport type ExternalBaseAnswer =\n | {\n readonly kind: \"base\";\n readonly base: NonNullable<PortAddressingExternalBaseResult>;\n /** The host that gave it, by its client name. */\n readonly owner: string;\n }\n | { readonly kind: \"none\" }\n | { readonly kind: \"failed\" }\n | { readonly kind: \"away\" };\n\n/** Options for {@link createGateway}. */\nexport interface GatewayOptions {\n readonly ledger: Ledger;\n readonly log: Log;\n readonly addressing: Addressing;\n readonly capabilities: Capabilities;\n readonly artifacts: GatewayArtifacts;\n /** The shell's built files, or `undefined` when the runtime lacks them (`MOSTRA_ENV_SHELL_MISSING`). */\n readonly shellDir: string | undefined;\n /** The interaction core the browser protocol's routes hand their work to (WP-06). */\n readonly interaction: Interaction;\n /**\n * The submit channels and trusted controls in force for a new view of an artifact (D108): the\n * `trustedControls` port's answer, the home's `submitChannels`, or both channels.\n */\n readonly controls: (artifact: ArtifactDetail) => Promise<ControlsPolicy>;\n /** Tells hosts with a `trustedControls` port that a trusted control was used (D108). */\n readonly activated: BrowserRoutesOptions[\"activated\"];\n /**\n * Who a browser is that exchanges a link minted without a viewer (D143 item 2): the person a\n * host's identity port names, the standalone default, or a refusal. Absent: the default.\n */\n readonly identity?: (input: {\n readonly artifactId: string;\n readonly via: IdentityVia;\n readonly headers: Headers;\n }) => Promise<IdentityOutcome>;\n /**\n * Asks the host that registered the `addressing` port for a listener's external origin (HO-10,\n * D158 item 6). Absent: no host addresses, links stay on loopback.\n */\n readonly externalBase?: {\n /** Whether a connected host registered the port now: none asks nothing and opens no face. */\n readonly registered: () => boolean;\n readonly ask: (input: {\n readonly artifactId: string;\n readonly listener: \"shell\" | \"artifact\";\n readonly local: string;\n }) => Promise<ExternalBaseAnswer>;\n };\n /**\n * Logs every connection and request of every listener (`MOSTRA_TEST_REQUEST_LOG`, #66): tests\n * only, so a request a browser saw go unanswered shows whether it reached the gateway.\n */\n readonly traceRequests?: boolean;\n /** The browser-protocol revisions served; `BROWSER_PROTOCOL_REVISIONS` unless a test adds one. */\n readonly revisions?: readonly string[];\n /**\n * Server functions and live data (WP-08): plain calls, action runs and live sources. Absent,\n * their routes answer 501 behind their checks, as before WP-08.\n */\n readonly actions?: Actions;\n readonly live?: Live;\n /** Run and live updates for page streams and polls (WP-08). */\n readonly bus?: EphemeralBus;\n /** Whether a version's worker is parked (WP-08): its frame ticket tells the shell. */\n readonly parked?: (versionId: string) => boolean;\n /**\n * The delivery target the gateway serves pages for (D111): `live` for viewers, `verify` for a\n * verify run's sandbox (D138), whose tickets name it and whose documents get\n * `<meta name=\"mostra-target\" content=\"verify\">` as they are served. The stored build never\n * holds the tag, so what publish promotes is byte-identical to what verify built.\n */\n readonly target?: \"live\" | \"verify\";\n /**\n * `mostra dev`'s sandbox (D140 item 12): the artifact origin's files and its HMR WebSocket come\n * from the session's Vite server, behind the same checks, and frame tickets say the page is a\n * development preview. `upstream` is where that server listens now.\n */\n readonly dev?: { readonly upstream: () => DevUpstream | undefined };\n}\n\n/** The gateway of one instance. */\nexport interface Gateway {\n /** Binds the shell's port, recently viewed artifacts' ports and the hosts' kept faces (D99). */\n start(): Promise<void>;\n /** The loopback shell's origin. */\n readonly shellOrigin: () => string;\n /**\n * The artifact's default link (D97 item 3), shown again or minted: the publish receipt's URL. A\n * host's external base (D158 item 6), when it gives one, is the link's address.\n */\n defaultLink(artifactId: string): Promise<{ readonly url: string; readonly tokenId: string }>;\n /**\n * Mints a link with every scope, for a version only when `version` names its number (D97\n * item 9): what `view/url` mints, for callers inside the instance (a verify run's sandbox).\n */\n link(input: { readonly artifactId: string; readonly version?: number }): string;\n /**\n * Mints a link at a face's shell address (a share's, D158 item 3), in the caller's transaction\n * when it passes one.\n */\n mintAt(\n input: {\n readonly artifactId: string;\n readonly shellOrigin: string;\n readonly scopes?: readonly CapabilityScope[] | undefined;\n readonly ttlMs?: number | undefined;\n readonly viewerId?: string | undefined;\n },\n within?: LedgerDb,\n ): CapabilityLink;\n /** A link minted before, shown again from its derived secret; `undefined` once it can't be. */\n reveal(tokenId: string): string | undefined;\n /** Opens a face (D158 item 1): its listener on loopback, refusing everything until its origin is set. */\n openFace(spec: FaceSpec): Promise<FaceHandle>;\n /** The face with this key, if it is open. */\n face(key: string): FaceHandle | undefined;\n /** Closes a face's listener; its leased port is released when `release` is set. */\n closeFace(key: string, release?: boolean): Promise<void>;\n /** The open faces, for `instance/status`. */\n faces(): readonly FaceStatus[];\n /** Whether a shell is served at this origin now: launch tickets are minted only for those. */\n servesShell(origin: string): boolean;\n /** The handlers of `view/url`, `view/rotate` and `view/revoke`. */\n methods(): MethodHandler[];\n /** The origins of the artifact listeners that are bound, by artifact ID. */\n artifactOrigins(): ReadonlyMap<string, string>;\n /** Stops every listener. */\n close(): Promise<void>;\n}\n\n/** A frame ticket's answer to the shell: the view it opens and its controls (D104, D108). */\ntype TicketAnswer = FrameTicket;\n\nconst NO_STORE = { \"cache-control\": \"no-store\" };\n\n/** How recently an artifact must have been viewed for its port to be bound at start (D129). */\nconst RECENT_VIEW_MS = 7 * 24 * 60 * 60 * 1000;\n\n/** How long a host's answer for an artifact's frame address is reused (D158 item 6). */\nconst EXTERNAL_BASE_REUSE_MS = 30_000;\n\n/**\n * How long a withdrawn face's listener stays open, refusing everything, so the request that\n * learned of the withdrawal still gets its answer (D158 item 6).\n */\nconst FACE_LINGER_MS = 2_000;\n\n/** The key of a face: `<group>:shell`, or `<group>:<artifactId>` for an artifact's. */\nexport function faceKey(\n group: string,\n listener: \"shell\" | \"artifact\",\n artifactId?: string,\n): string {\n return `${group}:${listener === \"shell\" ? \"shell\" : (artifactId ?? \"\")}`;\n}\n\n/**\n * One way into the gateway, for the routes it serves: the loopback shell or an artifact's\n * listener, or a face. Everything a route needs to know about where a request came in.\n */\ninterface Way {\n readonly listener: \"shell\" | \"artifact\";\n /** `loopback` for the gateway's own listeners. */\n readonly by: FaceBy | \"loopback\";\n readonly via: IdentityVia;\n readonly artifactId: string | undefined;\n port(): number;\n /** The origin browsers use; `undefined` while a face waits for its tunnel. */\n origin(): string | undefined;\n /** The exact `Host` values accepted. */\n hosts(): readonly string[];\n streams(): boolean;\n}\n\n/**\n * The browser-protocol routes of INTERFACES §4 (D96): WP-06 serves `fields`, `submit`, `signal`,\n * `events` and `events/poll`; WP-08 the calls, runs and live sources; WP-13 the stream tickets.\n */\nfunction laterArtifactRoutes(\n served: BrowserRoutes,\n acting: ActionRoutes | undefined,\n ticket: (context: RouteContext) => Promise<Response>,\n): RouteSpec[] {\n const action = (params: Readonly<Record<string, string>>): CapabilityScope | \"any-action\" => {\n const id = params[\"fn\"];\n return id ? (`action:${id}` as CapabilityScope) : \"any-action\";\n };\n return [\n {\n method: \"POST\",\n path: \"/_mostra/v/:rev/fields\",\n intent: \"mutation\",\n auth: \"session\",\n scope: () => \"draft\",\n handler: served.fields,\n },\n {\n method: \"POST\",\n path: \"/_mostra/v/:rev/submit\",\n intent: \"mutation\",\n auth: \"session\",\n scope: () => \"submit\",\n handler: served.submit,\n },\n {\n method: \"POST\",\n path: \"/_mostra/v/:rev/signal\",\n intent: \"mutation\",\n auth: \"session\",\n scope: () => \"signal\",\n handler: served.signal,\n },\n // A function ID may hold `/` (`lib/mail.ts#send`), so the call path takes the rest of the path.\n {\n method: \"POST\",\n path: \"/_mostra/v/:rev/call/:fn{.+}\",\n intent: \"mutation\",\n auth: \"session\",\n scope: action,\n ...(acting ? { handler: acting.call } : {}),\n },\n {\n method: \"POST\",\n path: \"/_mostra/v/:rev/runs\",\n intent: \"mutation\",\n auth: \"session\",\n scope: () => \"any-action\",\n ...(acting ? { handler: acting.runs } : {}),\n },\n // WP-08: read runs and follow them (re-attach), by ID or by function and key.\n {\n method: \"POST\",\n path: \"/_mostra/v/:rev/runs/attach\",\n intent: \"mutation\",\n auth: \"session\",\n scope: () => \"any-action\",\n ...(acting ? { handler: acting.attach } : {}),\n },\n {\n method: \"POST\",\n path: \"/_mostra/v/:rev/runs/:run/cancel\",\n intent: \"mutation\",\n auth: \"session\",\n scope: () => \"any-action\",\n ...(acting ? { handler: acting.cancel } : {}),\n },\n // WP-08: live sources a page reads and keeps produced; every link may (`view`).\n {\n method: \"POST\",\n path: \"/_mostra/v/:rev/live\",\n intent: \"mutation\",\n auth: \"session\",\n ...(acting ? { handler: acting.live } : {}),\n },\n // WP-13: single-use tickets for streams, polls and WebSockets that bypass the worker (D70).\n {\n method: \"POST\",\n path: \"/_mostra/v/:rev/ticket\",\n intent: \"mutation\",\n auth: \"session\",\n handler: ticket,\n },\n {\n method: \"GET\",\n path: \"/_mostra/v/:rev/events\",\n intent: \"stream\",\n auth: \"session\",\n sse: true,\n handler: served.stream,\n },\n {\n method: \"GET\",\n path: \"/_mostra/v/:rev/events/poll\",\n intent: \"stream\",\n auth: \"session\",\n handler: served.poll,\n },\n ];\n}\n\n/** A face as the gateway keeps it. */\ninterface FaceEntry {\n readonly key: string;\n readonly spec: FaceSpec;\n readonly listener: Listener;\n readonly port: number;\n origin: string | undefined;\n}\n\n/** Creates the gateway; nothing is bound until {@link Gateway.start}. */\nexport function createGateway(options: GatewayOptions): Gateway {\n const { addressing, capabilities, artifacts, log, interaction } = options;\n const served = browserRoutes({\n interaction,\n capabilities,\n log,\n versionOf: (artifactId, number) => {\n const found = artifacts.get({ artifactId }).versions.find((v) => v.number === number);\n return found\n ? {\n id: found.id,\n number: found.number,\n ...(found.collected !== undefined ? { collected: found.collected } : {}),\n }\n : undefined;\n },\n activated: options.activated,\n ...(options.revisions ? { revisions: options.revisions } : {}),\n ...(options.bus ? { bus: options.bus } : {}),\n });\n const acting: ActionRoutes | undefined =\n options.actions && options.live\n ? actionRoutes({\n interaction,\n actions: options.actions,\n live: options.live,\n log,\n revisions: options.revisions ?? BROWSER_PROTOCOL_REVISIONS,\n })\n : undefined;\n let shellPort: number | undefined;\n const shellOrigin = (): string => {\n if (shellPort === undefined) throw new Error(\"The gateway hasn't started.\");\n return addressing.origin(shellPort);\n };\n const artifactListeners = new Map<\n string,\n { readonly listener: Listener; readonly port: number }\n >();\n const opening = new Map<string, Promise<number>>();\n const faces = new Map<string, FaceEntry>();\n const openingFaces = new Map<string, Promise<FaceEntry>>();\n /** A host's recent answers for artifacts' frame addresses, by face key (D158 item 6). */\n const askedRecently = new Map<string, number>();\n const integrity = versionIntegrity(artifacts, log);\n\n // ── Ways in: the loopback listeners and the faces ───────────────────────────────────────\n\n const loopbackShell: Way = {\n listener: \"shell\",\n by: \"loopback\",\n via: \"local\",\n artifactId: undefined,\n port: () => shellPort ?? 0,\n origin: () => shellOrigin(),\n hosts: () => addressing.hosts(shellPort ?? 0),\n streams: () => true,\n };\n\n const loopbackArtifact = (artifactId: string, port: () => number): Way => ({\n listener: \"artifact\",\n by: \"loopback\",\n via: \"local\",\n artifactId,\n port,\n origin: () => addressing.origin(port()),\n hosts: () => addressing.hosts(port()),\n streams: () => true,\n });\n\n const faceWay = (entry: FaceEntry): Way => ({\n listener: entry.spec.listener,\n by: entry.spec.by,\n via: entry.spec.via,\n artifactId: entry.spec.artifactId,\n port: () => entry.port,\n origin: () => entry.origin,\n hosts: () => (entry.origin === undefined ? [] : [hostOf(entry.origin)]),\n streams: () => entry.spec.streams !== false,\n });\n\n /** The shell of a way's group: the loopback shell, or the group's shell face. */\n const shellOf = (way: Way, group: string | undefined): Way | undefined => {\n if (way.by === \"loopback\" || group === undefined) return loopbackShell;\n const entry = faces.get(faceKey(group, \"shell\"));\n return entry ? faceWay(entry) : undefined;\n };\n\n /** How an artifact way's frames authenticate: by the pair, unless its keeper said (D70). */\n const modeOf = (artifact: Way, group: string | undefined): FrameMode => {\n if (artifact.by === \"loopback\" || group === undefined) return \"cookie\";\n const entry = faces.get(faceKey(group, \"artifact\", artifact.artifactId));\n if (entry?.spec.mode) return entry.spec.mode;\n const shell = shellOf(artifact, group)?.origin();\n const own = artifact.origin();\n return shell !== undefined && own !== undefined ? addressing.frameMode(shell, own) : \"worker\";\n };\n\n /** Whether an origin is `https:`, where every cookie is `Secure`. */\n const secure = (origin: string | undefined): boolean => origin?.startsWith(\"https:\") === true;\n\n /** Whether the gateway serves a shell at this origin now: launch tickets go only there. */\n const servesShell = (origin: string): boolean =>\n origin === shellOrigin() ||\n [...faces.values()].some((entry) => entry.spec.listener === \"shell\" && entry.origin === origin);\n\n /** The answer for a damaged version: a plain page for a navigation, else the diagnostic. */\n const damaged = (\n number: number | undefined,\n damage: string,\n document: boolean,\n frameAncestors: string,\n ): Response =>\n refusalResponse(\n {\n status: 500,\n diagnostic: createDiagnostic(\"MOSTRA_HOME_INTEGRITY\", {\n message: `${number === undefined ? \"A version\" : `Version ${number}`} of this artifact is damaged: ${damage}.`,\n }),\n },\n { document, frameAncestors },\n );\n\n const link = (token: MintedToken): CapabilityLink => ({\n url: `${token.shellOrigin}/a/${token.artifactId}${token.pinnedVersion !== undefined ? `/v/${token.pinnedVersion}` : \"\"}#t=${token.secret}`,\n tokenId: token.tokenId,\n scopes: token.scopes,\n ...(token.expiresAt !== undefined ? { expiresAt: token.expiresAt } : {}),\n ...(token.viewerId !== undefined ? { viewer: interaction.viewer(token.viewerId) } : {}),\n });\n\n /** The version a request names (number or ID), or the latest; `undefined` when there is none. */\n const versionOf = (\n detail: ArtifactDetail,\n wanted: number | string | undefined,\n ): { readonly id: string; readonly number: number; readonly collected?: string } | undefined => {\n const found =\n wanted === undefined\n ? (detail.latestVersion ?? detail.versions[0])\n : detail.versions.find((version) =>\n typeof wanted === \"number\" ? version.number === wanted : version.id === wanted,\n );\n return found\n ? {\n id: found.id,\n number: found.number,\n ...(found.collected !== undefined ? { collected: found.collected } : {}),\n }\n : undefined;\n };\n\n // ── Faces (D158 item 1) ─────────────────────────────────────────────────────────────────\n\n const openFace = (spec: FaceSpec, origin?: string): Promise<FaceEntry> => {\n const key = faceKey(spec.group, spec.listener, spec.artifactId);\n const open = faces.get(key);\n if (open) return Promise.resolve(open);\n const pending = openingFaces.get(key);\n if (pending) return pending;\n const started = (async () => {\n let entry: FaceEntry | undefined;\n const way = (): Way =>\n entry\n ? faceWay(entry)\n : {\n ...loopbackShell,\n origin: () => undefined,\n hosts: () => [],\n };\n const listener = createListener({\n policy: () => ({ origin: entry?.origin ?? \"\", hosts: way().hosts() }),\n log,\n frameAncestors: () =>\n spec.listener === \"shell\" ? \"'none'\" : (shellOf(way(), spec.group)?.origin() ?? \"'none'\"),\n configure: (app) => {\n if (spec.listener === \"shell\") mount(app, shellChecks(way), shellRoutes(way, spec.group));\n else {\n const artifactId = spec.artifactId as string;\n mount(\n app,\n artifactChecks(artifactId, way, spec.group),\n artifactRoutes(artifactId, way, spec.group),\n );\n }\n },\n ...(spec.listener === \"artifact\"\n ? { upgrade: socketUpgrade(spec.artifactId as string, way, spec.group) }\n : {}),\n ...(options.traceRequests ? { traceRequests: true } : {}),\n });\n // A withdrawn face of this key may still hold its leased port for a moment.\n await endLingering(key);\n const port = await addressing.listenFace(listener.server, { key, lease: spec.lease });\n entry = { key, spec, listener, port, origin };\n faces.set(key, entry);\n log.info(\"gateway.face_open\", {\n key,\n by: spec.by,\n local: addressing.faceLocal(port),\n ...(origin !== undefined ? { origin } : {}),\n });\n return entry;\n })().finally(() => openingFaces.delete(key));\n openingFaces.set(key, started);\n return started;\n };\n\n const handleOf = (entry: FaceEntry): FaceHandle => ({\n key: entry.key,\n port: entry.port,\n local: addressing.faceLocal(entry.port),\n origin: () => entry.origin,\n setOrigin: (origin) => {\n if (entry.origin !== origin) {\n log.info(\"gateway.face_address\", {\n key: entry.key,\n ...(origin !== undefined ? { origin } : {}),\n });\n }\n entry.origin = origin;\n },\n });\n\n const closeFace = async (key: string, release = false): Promise<void> => {\n const pending = openingFaces.get(key);\n if (pending) await pending.catch(() => undefined);\n const entry = faces.get(key);\n if (entry) {\n faces.delete(key);\n await entry.listener.close();\n log.info(\"gateway.face_closed\", { key });\n }\n if (release) addressing.releaseFace(key);\n };\n\n /**\n * Withdrawn faces' listeners, by face key, closing after {@link FACE_LINGER_MS}; a face of the\n * same key opened meanwhile, or the gateway's close, closes one at once.\n */\n const lingering = new Map<string, Listener>();\n\n /** Closes a withdrawn face's listener now, if one still lingers, freeing its port. */\n const endLingering = async (key: string): Promise<void> => {\n const listener = lingering.get(key);\n if (!listener) return;\n lingering.delete(key);\n await listener.close();\n };\n\n /**\n * Withdraws a face at once and closes its listener a moment later: from now on its `Host` is\n * served nowhere (every request is refused, 421), while the request that learned of the\n * withdrawal (an exchange that asked the host) still gets its own answer, 410, rather than a\n * connection closed under it.\n */\n const withdrawFace = (key: string): void => {\n const entry = faces.get(key);\n if (!entry) {\n addressing.releaseFace(key);\n return;\n }\n faces.delete(key);\n entry.origin = undefined;\n lingering.set(key, entry.listener);\n log.info(\"gateway.face_withdrawn\", { key });\n const timer = setTimeout(() => {\n if (lingering.get(key) !== entry.listener) return;\n void endLingering(key).then(() => {\n // Its lease goes once its port is free, unless a new face of the key holds it.\n if (!faces.has(key)) addressing.releaseFace(key);\n });\n }, FACE_LINGER_MS);\n timer.unref?.();\n };\n\n // ── A host's external bases (HO-10, D158 item 6) ────────────────────────────────────────\n\n /** The kept external bases, so a restart serves their links before the host answers again. */\n const keptBases = (): {\n key: string;\n listener: \"shell\" | \"artifact\";\n artifact_id: string | null;\n origin: string;\n mode: FrameMode | null;\n }[] =>\n options.ledger.read((db) =>\n db.all<{\n key: string;\n listener: \"shell\" | \"artifact\";\n artifact_id: string | null;\n origin: string;\n mode: FrameMode | null;\n }>(\"SELECT key, listener, artifact_id, origin, mode FROM external_base\"),\n );\n\n const hostSpec = (\n artifactId: string,\n listener: \"shell\" | \"artifact\",\n mode?: FrameMode,\n ): FaceSpec => ({\n by: \"host\",\n group: `host:${artifactId}`,\n listener,\n artifactId,\n via: \"token\",\n lease: true,\n ...(mode ? { mode } : {}),\n });\n\n /**\n * The host's face of one of an artifact's listeners, asked again now: the address it gives\n * (kept, so its links work after a restart), or none. `null`, or another origin, withdraws the\n * face given before, whose links stop working; a host that fails or is away keeps what it gave.\n */\n const hostFaceTurns = new Map<string, Promise<unknown>>();\n /**\n * One question to the host per face at a time (Opus review of WP-13): a question that fails\n * never closes a face another question just set up, and every question reads what the one\n * before it left.\n */\n const hostFace = (\n artifactId: string,\n listener: \"shell\" | \"artifact\",\n ): Promise<FaceEntry | undefined> => {\n const key = faceKey(`host:${artifactId}`, listener, artifactId);\n const before = hostFaceTurns.get(key) ?? Promise.resolve();\n const turn = before.then(\n () => askHostFace(artifactId, listener),\n () => askHostFace(artifactId, listener),\n );\n const settled = turn.catch(() => undefined);\n hostFaceTurns.set(key, settled);\n void settled.then(() => {\n if (hostFaceTurns.get(key) === settled) hostFaceTurns.delete(key);\n });\n return turn;\n };\n\n const askHostFace = async (\n artifactId: string,\n listener: \"shell\" | \"artifact\",\n ): Promise<FaceEntry | undefined> => {\n // Only an artifact of this home has a host's address: nothing is opened or asked for others.\n try {\n artifacts.get({ artifactId });\n } catch {\n return undefined;\n }\n const port = options.externalBase;\n const group = `host:${artifactId}`;\n const key = faceKey(group, listener, artifactId);\n const kept = faces.get(key);\n // Without a host to ask, a face a host gave before (kept across a restart) still serves.\n if (!port?.registered()) return kept?.origin !== undefined ? kept : undefined;\n if (\n listener === \"artifact\" &&\n kept &&\n Date.now() - (askedRecently.get(key) ?? 0) < EXTERNAL_BASE_REUSE_MS\n ) {\n return kept;\n }\n // The face listens first, on its leased port, so the host is told where to forward.\n const entry = kept ?? (await openFace(hostSpec(artifactId, listener)));\n const answer = await port.ask({\n artifactId,\n listener,\n local: addressing.faceLocal(entry.port),\n });\n if (answer.kind === \"failed\" || answer.kind === \"away\") {\n if (kept?.origin !== undefined) return kept;\n if (!kept) await closeFace(key, true);\n return undefined;\n }\n if (answer.kind === \"none\") {\n options.ledger.write((db) => db.run(\"DELETE FROM external_base WHERE key = ?\", key));\n if (kept?.origin !== undefined) withdrawFace(key);\n else await closeFace(key, true);\n return undefined;\n }\n const origin = answer.base.origin;\n const mode = answer.base.mode;\n if (entry.origin !== origin || (entry.spec.mode ?? null) !== (mode ?? null)) {\n // Another origin withdraws the one before: its Host is no longer served. The same mode\n // keeps the listener, whose Host and origin follow the entry at once; another mode needs a\n // listener of its own, on the same leased port.\n if ((entry.spec.mode ?? null) !== (mode ?? null)) await closeFace(key);\n const fresh =\n faces.get(key) ?? (await openFace(hostSpec(artifactId, listener, mode), origin));\n fresh.origin = origin;\n options.ledger.write((db) =>\n db.run(\n \"INSERT INTO external_base (key, listener, artifact_id, origin, mode, client, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET origin = excluded.origin, mode = excluded.mode, updated_at = excluded.updated_at\",\n key,\n listener,\n artifactId,\n origin,\n mode ?? null,\n answer.owner,\n new Date().toISOString(),\n ),\n );\n askedRecently.set(key, Date.now());\n return fresh;\n }\n askedRecently.set(key, Date.now());\n return entry;\n };\n\n /** Where an artifact's links point: a host's external base when it gives one, else loopback. */\n const linkBase = async (artifactId: string): Promise<string> => {\n const face = await hostFace(artifactId, \"shell\");\n return face?.origin ?? shellOrigin();\n };\n\n /** The artifact way a shell way opens frames on, or why there is none. */\n const artifactWayFor = async (\n shell: Way,\n group: string | undefined,\n artifactId: string,\n ): Promise<{ readonly way: Way; readonly group: string | undefined } | Refusal> => {\n if (shell.by === \"loopback\" || group === undefined) {\n const port = await openArtifact(artifactId);\n return { way: loopbackArtifact(artifactId, () => port), group: undefined };\n }\n if (shell.by === \"host\") {\n const entry = await hostFace(artifactId, \"artifact\");\n if (entry?.origin === undefined) {\n return refusal(\n \"MOSTRA_HYGIENE_NOT_SERVED\",\n \"The host gives this artifact's frame no address here.\",\n 503,\n );\n }\n return { way: faceWay(entry), group };\n }\n const entry = faces.get(faceKey(group, \"artifact\", artifactId));\n if (entry?.origin === undefined) {\n return refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"This artifact isn't shared at this address.\");\n }\n return { way: faceWay(entry), group };\n };\n\n // ── The shell ────────────────────────────────────────────────────────────────────────────\n\n const shellKind = (way: Way): ListenerKind => ({\n kind: \"shell\",\n origin: way.origin() ?? \"\",\n shellOrigin: way.origin() ?? \"\",\n });\n const shellChecks = (way: () => Way): ListenerChecks => ({\n policy: () => ({ origin: way().origin() ?? \"\", hosts: way().hosts() }),\n capabilities,\n log,\n cookieName: () => `mostra-${way().port()}`,\n frameAncestors: () => \"'none'\",\n artifactOf: (params) => {\n const id = params[\"artifactId\"];\n // A face kept for one artifact (a host's external base) serves that artifact only: any\n // other path is refused before anything is opened or asked (Opus review of WP-13).\n const own = way().artifactId;\n return id !== undefined && ArtifactId.is(id) && (own === undefined || own === id)\n ? id\n : undefined;\n },\n // The shell's own stream is refused where streams don't pass, as the frame's is (D158 item 5).\n streams: () => way().streams(),\n });\n\n const shellMissing = (): Response =>\n jsonResponse(\n createDiagnostic(\"MOSTRA_ENV_SHELL_MISSING\", {\n message: \"This Mostra runtime has no built shell.\",\n }),\n { status: 503 },\n );\n\n /** The exchanges each browser made, by artifact (WP-12; see `exchange`). */\n const madeSessions = new Map<string, { readonly order: number; readonly grant: Grant }>();\n let exchangeOrder = 0;\n const browserKey = (artifactId: string, browser: unknown): string | undefined =>\n typeof browser === \"string\" && /^[A-Za-z0-9_-]{16,64}$/.test(browser)\n ? `${artifactId}\\u0000${browser}`\n : undefined;\n\n /** What a link allows, as the shell shows it when two links meet. */\n const access = (grant: Grant) => ({\n scopes: grant.scopes,\n ...(grant.expiresAt !== undefined ? { expiresAt: grant.expiresAt } : {}),\n ...(grant.pinnedVersion !== undefined ? { version: grant.pinnedVersion } : {}),\n });\n\n /** The session's facts, for the shell and the frame alike. */\n const sessionFacts = (artifactId: string, grant: Grant) => {\n const detail = artifacts.get({ artifactId });\n return { artifact: { id: detail.id, title: detail.title }, ...access(grant) };\n };\n\n const shellRoutes = (wayOf: () => Way, group: string | undefined): RouteSpec[] => {\n const checks = shellChecks(wayOf);\n\n /** The shell's page: the same for every artifact; it learns everything from its session. */\n const shellPage = async (context: RouteContext): Promise<Response> => {\n if (options.shellDir === undefined) return shellMissing();\n const way = wayOf();\n if (context.artifactId === undefined) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"No artifact is named at this path.\"),\n {\n method: context.request.method,\n path: new URL(context.request.url).pathname,\n document: true,\n },\n );\n }\n // The page may frame only its artifact's origin: on loopback any port of the host, at an\n // external address exactly the artifact's face there.\n let frames = `http://${addressing.urlHost}:*`;\n if (way.by !== \"loopback\") {\n const found = await artifactWayFor(way, group, context.artifactId).catch(() => undefined);\n frames = found && !isRefusal(found) ? (found.way.origin() ?? \"'none'\") : \"'none'\";\n }\n const html = readFileSync(join(options.shellDir, \"index.html\"));\n return new Response(context.request.method === \"HEAD\" ? null : html, {\n headers: {\n ...BASE_HEADERS,\n ...documentHeaders(shellKind(way), frames),\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-cache\",\n },\n });\n };\n\n const shellAsset = async (context: RouteContext): Promise<Response> => {\n if (options.shellDir === undefined) return shellMissing();\n const url = new URL(context.request.url);\n const path = safePath(url.pathname)?.slice(\"/_mostra/shell\".length) ?? \"\";\n const file = path.startsWith(\"/assets/\") ? await findFile(options.shellDir, path) : undefined;\n if (!file) {\n return refuse(checks, refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"No shell file at this path.\"), {\n method: context.request.method,\n path: url.pathname,\n document: false,\n });\n }\n return fileResponse(file, context.request, {\n ...documentHeaders(shellKind(wayOf()), `http://${addressing.urlHost}:*`),\n \"cache-control\": \"public, max-age=31536000, immutable\",\n });\n };\n\n /**\n * Who the session acts as when the link names nobody and no host did (D143 item 2, D158 item\n * 2): the home's local user on loopback; over a tunnel the tailnet person Tailscale Serve\n * named, else the link's own viewer, never the home's local user.\n */\n const defaultViewer = (way: Way, context: RouteContext, grant: Grant): string | undefined => {\n if (way.via === \"local\") return undefined;\n if (way.via === \"tailnet\") {\n const person = tailnetPerson(context.request.headers, context.remote);\n if (person) return interaction.viewerForTailnet(person);\n }\n return interaction.viewerForLink(grant.tokenId, \"Shared link\");\n };\n\n const exchange = async (context: RouteContext): Promise<Response> => {\n const way = wayOf();\n const origin = way.origin() ?? \"\";\n const startedAt = exchangeOrder;\n const meta = { method: \"POST\", path: new URL(context.request.url).pathname, document: false };\n // No artifact this address serves (another's, at a host's address): nothing is read,\n // opened or asked (Opus review of WP-13).\n if (context.artifactId === undefined) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"No artifact is served at this path.\"),\n meta,\n );\n }\n const artifactId = context.artifactId;\n const body = await readJsonObject(context.request);\n if (isRefusal(body)) return refuse(checks, body, meta);\n // A host's address is asked again at every exchange: one it withdrew stops working (D158).\n if (way.by === \"host\") {\n const still = await hostFace(artifactId, \"shell\");\n if (still?.origin !== origin) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_TOKEN_REVOKED\", \"The host no longer serves this address.\", 410),\n meta,\n );\n }\n }\n // A link's token, or a one-time launch ticket from `mostra open` (D140 item 15), which is\n // spent only once it started (or reused) a session.\n const launch = body[\"token\"] === undefined && body[\"launch\"] !== undefined;\n const browser = browserKey(artifactId, body[\"browser\"]);\n let grant = launch\n ? capabilities.presentLaunch(body[\"launch\"], artifactId, false, origin)\n : capabilities.presentToken(body[\"token\"], artifactId, origin);\n if (isRefusal(grant)) return refuse(checks, grant, meta);\n // A live session from another link is never replaced silently (D98 item 8): a page elsewhere\n // could send the viewer to its own, narrower link and take over their tabs.\n const existing = capabilities.session(\n cookieValues(context.request.headers.get(\"cookie\"), checks.cookieName()),\n origin,\n artifactId,\n );\n if (!isRefusal(existing)) {\n if (existing.grant.tokenId === grant.tokenId) {\n if (launch) capabilities.spendLaunch(body[\"launch\"]);\n return jsonResponse({ csrf: existing.csrf, ...sessionFacts(artifactId, existing.grant) });\n }\n if (body[\"replace\"] !== true) {\n log.info(\"gateway.session_conflict\", { artifactId, origin });\n return jsonResponse(\n {\n ...refusal(\n \"MOSTRA_HYGIENE_SESSION_CONFLICT\",\n \"This browser already has this artifact open from another link.\",\n ).diagnostic,\n current: access(existing.grant),\n offered: access(grant),\n },\n { status: 409 },\n );\n }\n }\n // A link without a viewer acts for whoever the host's identity port names (D143 item 2);\n // a host that took identity over and can't answer refuses the link, never a guess.\n let viewerId: string | undefined;\n if (grant.viewerId === undefined) {\n const outcome: IdentityOutcome = options.identity\n ? await options.identity({ artifactId, via: way.via, headers: context.request.headers })\n : { kind: \"default\" };\n if (outcome.kind === \"unavailable\") {\n log.warn(\"gateway.session_refused\", { artifactId, code: outcome.diagnostic.code });\n return jsonResponse(outcome.diagnostic, { status: 503 });\n }\n viewerId =\n outcome.kind === \"person\"\n ? interaction.viewerForHost(outcome.viewer)\n : defaultViewer(way, context, grant);\n }\n // Everything is judged again after the await, in one synchronous step with the session's\n // creation: a link revoked or expired meanwhile gets no session (Opus review of WP-12,\n // finding 3), and a launch ticket is spent here, so it opens one session however many\n // exchanges presented it while the identity port answered (GPT review finding 1).\n const now = launch\n ? capabilities.presentLaunch(body[\"launch\"], artifactId, true, origin)\n : capabilities.presentToken(body[\"token\"], artifactId, origin);\n if (isRefusal(now)) return refuse(checks, now, meta);\n grant = now;\n const made = browser === undefined ? undefined : madeSessions.get(browser);\n if (\n made !== undefined &&\n made.order > startedAt &&\n made.grant.tokenId !== grant.tokenId &&\n body[\"replace\"] !== true\n ) {\n log.info(\"gateway.session_conflict\", { artifactId, origin });\n return jsonResponse(\n {\n ...refusal(\n \"MOSTRA_HYGIENE_SESSION_CONFLICT\",\n \"This browser already has this artifact open from another link.\",\n ).diagnostic,\n current: access(made.grant),\n offered: access(grant),\n },\n { status: 409 },\n );\n }\n const session = capabilities.createSession({ tokenId: grant.tokenId, origin, viewerId });\n if (browser !== undefined) {\n exchangeOrder += 1;\n madeSessions.delete(browser);\n madeSessions.set(browser, { order: exchangeOrder, grant });\n if (madeSessions.size > 4096)\n madeSessions.delete(madeSessions.keys().next().value as string);\n }\n log.info(\"gateway.session_started\", { origin, artifactId, tokenId: grant.tokenId });\n return jsonResponse(\n { csrf: session.csrf, ...sessionFacts(artifactId, grant) },\n {\n headers: {\n \"set-cookie\": sessionCookie(\n checks.cookieName(),\n session.cookie,\n `/a/${artifactId}`,\n SESSION_MAX_AGE_S,\n secure(origin),\n ),\n },\n },\n );\n };\n\n const readShellSession = (context: RouteContext): Response => {\n const session = context.session;\n if (!session || context.artifactId === undefined)\n throw new Error(\"session route without a session\");\n return jsonResponse({\n csrf: session.csrf,\n ...sessionFacts(context.artifactId, session.grant),\n });\n };\n\n const ticket = async (context: RouteContext): Promise<Response> => {\n const way = wayOf();\n const session = context.session;\n const artifactId = context.artifactId;\n if (!session || artifactId === undefined) throw new Error(\"session route without a session\");\n const meta = { method: \"POST\", path: new URL(context.request.url).pathname, document: false };\n const body = await readJsonObject(context.request);\n if (isRefusal(body)) return refuse(checks, body, meta);\n const asked = body[\"version\"];\n if (asked !== undefined && !(Number.isSafeInteger(asked) && (asked as number) >= 1)) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_REQUEST_MALFORMED\", \"`version` must be a version number.\"),\n meta,\n );\n }\n const pinned = session.grant.pinnedVersion;\n // A link that names a version opens that version only (D97 item 9).\n if (pinned !== undefined && asked !== undefined && asked !== pinned) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_SCOPE_DENIED\", `This link opens version ${pinned} only.`),\n meta,\n );\n }\n const detail = artifacts.get({ artifactId });\n const version = versionOf(detail, (asked as number | undefined) ?? pinned);\n const latest = versionOf(detail, undefined);\n if (!version || !latest) {\n return jsonResponse(\n createDiagnostic(\"MOSTRA_ARTIFACT_VERSION_NOT_FOUND\", {\n message:\n `This artifact has no version ${asked ?? session.grant.pinnedVersion ?? \"\"}.`.replace(\n \" .\",\n \".\",\n ),\n }),\n { status: 404 },\n );\n }\n // A collected version's files are gone until its source is published again (D140 item 14).\n if (version.collected !== undefined) {\n return jsonResponse(collectedDiagnostic(version.number), { status: 410 });\n }\n // A damaged version is never shown (FAILURE_MODEL §3).\n // A dev preview has no stored build to check: Vite serves the source (D140 item 12).\n const damage = options.dev ? undefined : await integrity.check(version.id);\n if (damage !== undefined) return damaged(version.number, damage, false, \"'none'\");\n // The frame opens on the artifact's way in this shell's group: its loopback listener, or\n // the artifact's face at this address (D158 item 1), in the mode the pair needs (D70).\n const found = await artifactWayFor(way, group, artifactId);\n if (isRefusal(found)) return refuse(checks, found, meta);\n const artifactOrigin = found.way.origin() as string;\n const mode = modeOf(found.way, found.group);\n const value = capabilities.mintTicket({\n tokenId: session.grant.tokenId,\n artifactId,\n versionId: version.id,\n origin: artifactOrigin,\n shellOrigin: way.origin() ?? \"\",\n shellSessionId: session.id,\n viewerId: session.viewerId,\n });\n // One frame load is one view, of exactly this version, by this link's viewer (D104), with\n // the channels and controls in force for it (D108).\n const controls = await options.controls(detail);\n const viewerId = interaction.viewerOf(session.viewerId);\n const viewId = interaction.openView({\n artifactId,\n versionId: version.id,\n viewerId,\n tokenId: session.grant.tokenId,\n controls,\n });\n const answer: TicketAnswer = {\n artifactId,\n viewId,\n // Worker mode takes its ticket in the fragment, which only the bootstrap page reads.\n src:\n mode === \"worker\"\n ? `${artifactOrigin}/_mostra/enter#t=${value}`\n : `${artifactOrigin}/_mostra/enter?ticket=${value}`,\n artifactOrigin,\n version,\n latest,\n policy: detail.policy ?? { policy: \"once\", scope: \"per-artifact\" },\n submitChannels: controls.submitChannels,\n // What the shell offers this link: a control its scopes can't use isn't shown (D97).\n controls: (controls.controls ?? [\"submit\", \"choose\", \"approve\"]).filter((control) =>\n control === \"submit\"\n ? scopeAllows(session.grant.scopes, \"submit\")\n : control === \"choose\"\n ? scopeAllows(session.grant.scopes, \"review\")\n : true,\n ),\n target: options.target ?? \"live\",\n follow: interaction.following({ artifactId, viewerId }),\n pinned: pinned !== undefined,\n ...(options.parked?.(version.id) ? { serverParked: true as const } : {}),\n ...(options.dev ? { devPreview: true as const } : {}),\n ...(mode === \"worker\" ? { mode: \"worker\" as const } : {}),\n };\n return jsonResponse(answer);\n };\n\n return [\n { method: \"GET\", path: \"/a/:artifactId\", intent: \"read\", auth: \"none\", handler: shellPage },\n { method: \"GET\", path: \"/a/:artifactId/\", intent: \"read\", auth: \"none\", handler: shellPage },\n {\n method: \"GET\",\n path: \"/a/:artifactId/v/:number{[1-9][0-9]{0,8}}\",\n intent: \"read\",\n auth: \"none\",\n handler: shellPage,\n },\n {\n method: \"GET\",\n path: \"/_mostra/shell/*\",\n intent: \"read\",\n auth: \"none\",\n handler: shellAsset,\n },\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/session\",\n intent: \"exchange\",\n auth: \"none\",\n tokenPath: true,\n handler: exchange,\n },\n {\n method: \"GET\",\n path: \"/a/:artifactId/_mostra/session\",\n intent: \"read\",\n auth: \"session\",\n handler: readShellSession,\n },\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/ticket\",\n intent: \"mutation\",\n auth: \"session\",\n handler: ticket,\n },\n // The trusted controls, the version banner's sources and follow (WP-07), and review\n // (WP-20), behind the shell's session (D96). The specific routes come before the wildcard.\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/v/:rev/submit\",\n intent: \"mutation\",\n auth: \"session\",\n scope: () => \"submit\",\n handler: served.shellSubmit,\n },\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/v/:rev/review/choose\",\n intent: \"mutation\",\n auth: \"session\",\n scope: () => \"review\",\n handler: served.choose,\n },\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/v/:rev/follow\",\n intent: \"mutation\",\n auth: \"session\",\n handler: served.follow,\n },\n {\n method: \"GET\",\n path: \"/a/:artifactId/_mostra/v/:rev/carry\",\n intent: \"read\",\n auth: \"session\",\n handler: served.carry,\n },\n {\n method: \"GET\",\n path: \"/a/:artifactId/_mostra/v/:rev/events\",\n intent: \"stream\",\n auth: \"session\",\n sse: true,\n handler: served.stream,\n },\n {\n method: \"GET\",\n path: \"/a/:artifactId/_mostra/v/:rev/events/poll\",\n intent: \"stream\",\n auth: \"session\",\n handler: served.poll,\n },\n {\n method: \"POST\",\n path: \"/a/:artifactId/_mostra/v/:rev/review/*\",\n intent: \"mutation\",\n auth: \"session\",\n scope: () => \"review\",\n },\n ];\n };\n\n // ── Artifacts ────────────────────────────────────────────────────────────────────────────\n\n const artifactChecks = (\n artifactId: string,\n wayOf: () => Way,\n group: string | undefined,\n ): ListenerChecks => ({\n policy: () => ({ origin: wayOf().origin() ?? \"\", hosts: wayOf().hosts() }),\n capabilities,\n log,\n cookieName: () => `mostra-${wayOf().port()}`,\n frameAncestors: () => shellOf(wayOf(), group)?.origin() ?? \"'none'\",\n artifactOf: () => artifactId,\n mode: () => modeOf(wayOf(), group),\n streams: () => wayOf().streams(),\n });\n\n const artifactRoutes = (\n artifactId: string,\n wayOf: () => Way,\n group: string | undefined,\n ): RouteSpec[] => {\n const origin = (): string => wayOf().origin() ?? \"\";\n const shell = (): string => shellOf(wayOf(), group)?.origin() ?? \"\";\n const kind = (): ListenerKind => ({\n kind: \"artifact\",\n origin: origin(),\n shellOrigin: shell(),\n });\n const checks = artifactChecks(artifactId, wayOf, group);\n const mode = (): FrameMode => modeOf(wayOf(), group);\n const notServed = (context: RouteContext, message: string): Response =>\n refuse(checks, refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", message), {\n method: context.request.method,\n path: new URL(context.request.url).pathname,\n document: context.document,\n });\n\n /**\n * `GET /_mostra/enter`: in cookie mode the frame's entry with its ticket (D98 item 3); in\n * worker mode the bootstrap page, whose ticket is in the fragment (D70).\n */\n const enter = (context: RouteContext): Response => {\n const url = new URL(context.request.url);\n const meta = { method: \"GET\", path: url.pathname, document: true };\n if (mode() === \"worker\") {\n if (url.searchParams.has(\"ticket\")) {\n return notServed(context, \"A worker-mode frame enters through its bootstrap page.\");\n }\n return new Response(context.request.method === \"HEAD\" ? null : BOOTSTRAP_PAGE, {\n headers: {\n ...BASE_HEADERS,\n ...documentHeaders(kind(), \"\"),\n ...NO_STORE,\n \"content-type\": \"text/html; charset=utf-8\",\n },\n });\n }\n // A frame enters from its shell, which is same-site. A page elsewhere can navigate a hidden\n // frame here with junk tickets; its entries are refused before redeeming, so they never\n // count towards the guessing limit and can't lock real viewers out (D97 item 8).\n if (context.request.headers.get(\"sec-fetch-site\") === \"cross-site\") {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_ORIGIN_REFUSED\", \"A frame enters only from its shell.\"),\n meta,\n );\n }\n const redeemed = capabilities.redeemTicket(url.searchParams.get(\"ticket\"), origin());\n if (isRefusal(redeemed)) return refuse(checks, redeemed, meta);\n if (redeemed.artifactId !== artifactId) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_TOKEN_INVALID\", \"The ticket is for another artifact.\"),\n meta,\n );\n }\n const headers: Record<string, string> = { ...BASE_HEADERS, ...NO_STORE, location: \"/\" };\n // A frame that has a session from the same link keeps it and switches version (D98 item 5).\n const existing = capabilities.session(\n cookieValues(context.request.headers.get(\"cookie\"), checks.cookieName()),\n origin(),\n artifactId,\n );\n // The frame acts as its shell session's viewer (D143 item 2): a session of the same link\n // for someone else (the identity port named another person) is never reused.\n if (\n !isRefusal(existing) &&\n existing.grant.tokenId === redeemed.tokenId &&\n existing.viewerId === redeemed.viewerId\n ) {\n capabilities.enterVersion(existing.id, redeemed.versionId);\n } else {\n const session = capabilities.createSession({\n tokenId: redeemed.tokenId,\n origin: origin(),\n versionId: redeemed.versionId,\n viewerId: redeemed.viewerId,\n });\n headers[\"set-cookie\"] = sessionCookie(\n checks.cookieName(),\n session.cookie,\n \"/\",\n SESSION_MAX_AGE_S,\n secure(origin()),\n );\n log.info(\"gateway.session_started\", {\n origin: origin(),\n artifactId,\n tokenId: redeemed.tokenId,\n });\n }\n return new Response(null, { status: 303, headers });\n };\n\n /**\n * `POST /_mostra/enter` (worker mode, D70): the bootstrap page exchanges the shell's ticket\n * for a frame session whose secret it hands the service worker. A frame that presents the\n * session it kept, from the same link and viewer, keeps it and switches version.\n */\n const enterWorker = async (context: RouteContext): Promise<Response> => {\n const url = new URL(context.request.url);\n const meta = { method: \"POST\", path: url.pathname, document: false };\n if (mode() !== \"worker\") {\n return notServed(context, \"This frame enters in cookie mode, with `GET /_mostra/enter`.\");\n }\n const body = await readJsonObject(context.request);\n if (isRefusal(body)) return refuse(checks, body, meta);\n const parsed = EnterRequest.safeParse(body);\n if (!parsed.success) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_REQUEST_MALFORMED\", \"The entry needs the frame's `ticket`.\"),\n meta,\n );\n }\n const redeemed = capabilities.redeemTicket(parsed.data.ticket, origin());\n if (isRefusal(redeemed)) return refuse(checks, redeemed, meta);\n if (redeemed.artifactId !== artifactId) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_TOKEN_INVALID\", \"The ticket is for another artifact.\"),\n meta,\n );\n }\n const kept = context.request.headers.get(FRAME_SESSION_HEADER);\n const existing =\n kept === null ? undefined : capabilities.session([kept], origin(), artifactId, \"worker\");\n let secret: string;\n if (\n kept !== null &&\n existing !== undefined &&\n !isRefusal(existing) &&\n existing.grant.tokenId === redeemed.tokenId &&\n existing.viewerId === redeemed.viewerId\n ) {\n capabilities.enterVersion(existing.id, redeemed.versionId);\n secret = kept;\n } else {\n const session = capabilities.createSession({\n tokenId: redeemed.tokenId,\n origin: origin(),\n versionId: redeemed.versionId,\n viewerId: redeemed.viewerId,\n mode: \"worker\",\n });\n secret = session.cookie;\n log.info(\"gateway.session_started\", {\n origin: origin(),\n artifactId,\n tokenId: redeemed.tokenId,\n mode: \"worker\",\n });\n }\n return jsonResponse({ session: secret, shellOrigin: redeemed.shellOrigin });\n };\n\n /** `GET /_mostra/sw.js`: the worker-mode service worker, allowed to control `/` (D70). */\n const serviceWorker = (context: RouteContext): Response => {\n if (mode() !== \"worker\") {\n return notServed(context, \"This frame enters in cookie mode and has no service worker.\");\n }\n return new Response(context.request.method === \"HEAD\" ? null : SERVICE_WORKER_SOURCE, {\n headers: {\n ...BASE_HEADERS,\n \"content-type\": \"text/javascript; charset=utf-8\",\n \"service-worker-allowed\": \"/\",\n \"cache-control\": \"no-cache\",\n },\n });\n };\n\n /** `POST /_mostra/v/{rev}/ticket`: a single-use ticket for one stream, poll or socket. */\n const streamTicket = async (context: RouteContext): Promise<Response> => {\n const session = context.session;\n if (!session) throw new Error(\"session route without a session\");\n const meta = { method: \"POST\", path: new URL(context.request.url).pathname, document: false };\n const body = await readJsonObject(context.request);\n if (isRefusal(body)) return refuse(checks, body, meta);\n const parsed = StreamTicketRequest.safeParse(body);\n if (!parsed.success) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_REQUEST_MALFORMED\", \"`purpose` is `stream` or `socket`.\"),\n meta,\n );\n }\n return jsonResponse(\n capabilities.mintStreamTicket({\n sessionId: session.id,\n origin: origin(),\n artifactId,\n purpose: parsed.data.purpose ?? \"stream\",\n }),\n );\n };\n\n const frameSession = (context: RouteContext): Response => {\n const session = context.session;\n if (!session) throw new Error(\"session route without a session\");\n const detail = artifacts.get({ artifactId });\n const version = detail.versions.find((entry) => entry.id === session.versionId);\n const facts: FrameSessionFacts = {\n csrf: session.csrf,\n artifactId,\n shellOrigin: shell(),\n scopes: session.grant.scopes,\n // The viewer the page acts as, so edits made before its first snapshot are journaled\n // under it (WP-07; Claude review finding 4).\n viewer: interaction.viewer(interaction.viewerOf(session.viewerId)),\n ...(version ? { version: { id: version.id, number: version.number } } : {}),\n ...(mode() === \"worker\" ? { mode: \"worker\" as const } : {}),\n ...(wayOf().streams() ? {} : { streams: false }),\n };\n return jsonResponse(facts);\n };\n\n const files = async (context: RouteContext): Promise<Response> => {\n const session = context.session;\n const url = new URL(context.request.url);\n const meta = {\n method: context.request.method,\n path: url.pathname,\n document: context.document,\n };\n // `checkRequest` refused unsafe targets already; an unsafe one here is still never served.\n const path = safePath(url.pathname);\n if (\n path === undefined ||\n !session?.versionId ||\n path === \"/_mostra\" ||\n path.startsWith(\"/_mostra/\")\n ) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"Nothing is served at this path.\"),\n meta,\n );\n }\n const headers = { ...documentHeaders(kind(), \"\") };\n if (options.dev) {\n // A development preview: the session's Vite server answers, never a stored version.\n const upstream = options.dev.upstream();\n if (!upstream) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"The dev server isn't running.\", 503),\n meta,\n );\n }\n const answered = await devFetch(upstream, context.request, url.pathname + url.search).catch(\n () => undefined,\n );\n if (!answered) {\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"The dev server didn't answer.\", 502),\n meta,\n );\n }\n // Statuses that carry no body (a 304 to a revalidation above all, RFC 9110 §15.4.5).\n const bodiless =\n context.request.method === \"HEAD\" || [204, 205, 304].includes(answered.status);\n return new Response(bodiless ? null : new Uint8Array(answered.body), {\n status: answered.status,\n headers: { ...answered.headers, ...headers, \"cache-control\": \"no-cache\" },\n });\n }\n const root = (versionId: string): string => join(artifacts.versionDir(versionId), \"client\");\n const versionId = session.versionId;\n let file = await findFile(root(versionId), path);\n let from = versionId;\n // Content-hashed chunks stay reachable after another tab moved the session on (D98 item 5),\n // from the versions the link may open: a pinned link's own only (D97 item 9).\n if (!file && path.startsWith(\"/assets/\") && session.grant.pinnedVersion === undefined) {\n for (const version of artifacts.get({ artifactId }).versions) {\n if (version.id === versionId) continue;\n file = await findFile(root(version.id), path);\n if (file) {\n from = version.id;\n break;\n }\n }\n }\n // Every file served comes from a version whose stored files match their digest, checked\n // again whenever a file changed since (FAILURE_MODEL §3).\n const checked =\n file ?? (context.document ? await findFile(root(versionId), \"/index.html\") : undefined);\n if (checked) {\n const damage = await integrity.serve(from, checked);\n if (damage !== undefined) {\n const number = artifacts.get({ artifactId }).versions.find((v) => v.id === from)?.number;\n return damaged(number, damage, context.document, shell() || \"'none'\");\n }\n }\n if (file && options.target === \"verify\" && file.path.endsWith(\".html\")) {\n return verifyDocument(file.path, context.request, {\n ...headers,\n \"cache-control\": \"no-cache\",\n });\n }\n if (file) {\n return fileResponse(file, context.request, {\n ...headers,\n \"cache-control\": path.startsWith(\"/assets/\")\n ? \"private, max-age=31536000, immutable\"\n : \"no-cache\",\n });\n }\n // A deep link inside the artifact's routes (D57) gets its page.\n const page = context.document\n ? await findFile(root(session.versionId), \"/index.html\")\n : undefined;\n if (page && options.target === \"verify\") {\n return verifyDocument(page.path, context.request, {\n ...headers,\n \"cache-control\": \"no-cache\",\n });\n }\n if (page)\n return fileResponse(page, context.request, { ...headers, \"cache-control\": \"no-cache\" });\n return refuse(\n checks,\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"This version has no file at this path.\"),\n meta,\n );\n };\n\n return [\n { method: \"GET\", path: \"/_mostra/enter\", intent: \"read\", auth: \"none\", handler: enter },\n {\n method: \"POST\",\n path: \"/_mostra/enter\",\n intent: \"exchange\",\n auth: \"none\",\n handler: enterWorker,\n },\n {\n method: \"GET\",\n path: SERVICE_WORKER_PATH,\n intent: \"read\",\n auth: \"none\",\n handler: serviceWorker,\n },\n {\n method: \"GET\",\n path: \"/_mostra/session\",\n intent: \"read\",\n auth: \"session\",\n handler: frameSession,\n },\n ...laterArtifactRoutes(served, acting, streamTicket),\n { method: \"GET\", path: \"/*\", intent: \"read\", auth: \"session\", handler: files },\n ];\n };\n\n /**\n * WebSocket upgrades on an artifact's listener, after the listener checked Host, target and\n * Origin: a dev sandbox's HMR socket (D140 item 12), and the browser protocol's sockets\n * (`/_mostra/v/{rev}/term/{session}`), which open with a single-use socket ticket (D158 item 5)\n * and arrive with the terminals (WP-22, WP-23).\n */\n const socketUpgrade =\n (artifactId: string, wayOf: () => Way, group: string | undefined) =>\n (incoming: IncomingMessage, socket: Duplex, head: Buffer): Refusal | undefined => {\n const way = wayOf();\n const url = new URL(incoming.url ?? \"/\", \"http://gateway.invalid\");\n if (/^\\/_mostra\\/v\\/[^/]+\\/term\\/[^/]+$/.test(url.pathname)) {\n const redeemed = capabilities.redeemStreamTicket(\n url.searchParams.get(\"ticket\"),\n way.origin() ?? \"\",\n artifactId,\n \"socket\",\n );\n if (isRefusal(redeemed)) return redeemed;\n return refusal(\n \"MOSTRA_HYGIENE_NOT_SERVED\",\n \"Live terminals arrive with a later Mostra release.\",\n 501,\n );\n }\n if (options.dev && way.by === \"loopback\" && group === undefined) {\n const upstream = options.dev.upstream();\n if (!upstream)\n return refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"The dev server isn't running.\", 503);\n const cookie = incoming.headers.cookie;\n const session = capabilities.session(\n cookieValues(typeof cookie === \"string\" ? cookie : null, `mostra-${way.port()}`),\n way.origin() ?? \"\",\n artifactId,\n );\n if (isRefusal(session)) return session;\n devUpgrade(upstream, incoming, socket, head);\n return undefined;\n }\n return refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"This gateway serves no WebSocket here.\");\n };\n\n /** Binds the artifact's listener on its leased port, once; resolves with the port. */\n const openArtifact = (artifactId: string): Promise<number> => {\n const bound = artifactListeners.get(artifactId);\n if (bound) return Promise.resolve(bound.port);\n const pending = opening.get(artifactId);\n if (pending) return pending;\n const started = (async () => {\n let port = 0;\n const way = loopbackArtifact(artifactId, () => port);\n const listener = createListener({\n policy: () => ({ origin: addressing.origin(port), hosts: addressing.hosts(port) }),\n log,\n frameAncestors: () => shellOrigin(),\n configure: (app) =>\n mount(\n app,\n artifactChecks(artifactId, () => way, undefined),\n artifactRoutes(artifactId, () => way, undefined),\n ),\n upgrade: socketUpgrade(artifactId, () => way, undefined),\n ...(options.traceRequests ? { traceRequests: true } : {}),\n });\n port = await addressing.listen(listener.server, { purpose: \"artifact\", owner: artifactId });\n artifactListeners.set(artifactId, { listener, port });\n log.info(\"gateway.artifact_listening\", { artifactId, origin: addressing.origin(port) });\n return port;\n })().finally(() => opening.delete(artifactId));\n opening.set(artifactId, started);\n return started;\n };\n\n let shellListener: Listener | undefined;\n\n // ── View methods ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Replays a request recorded with the same parameters (H-03), or runs `fn` and records\n * `{ tokenId }` in the same transaction. The same `requestId` with other parameters is\n * `MOSTRA_HOST_REQUEST_ID_REUSED`, never another link.\n */\n const recorded = (\n key: RequestKey | undefined,\n fn: (db: LedgerDb) => MintedToken,\n ): CapabilityLink => {\n const token = options.ledger.write((db) => {\n if (key !== undefined) {\n const row = recordedResult<{ tokenId: string }>(db, key);\n if (row) return { replay: row.tokenId };\n }\n const minted = fn(db);\n // Only the token ID is recorded: the ledger never holds a link's secret (D97 item 2).\n if (key !== undefined) recordResult(db, key, { tokenId: minted.tokenId });\n return { minted };\n });\n if (\"minted\" in token) return link(token.minted);\n const shown = capabilities.reveal(token.replay);\n if (!shown) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HYGIENE_TOKEN_REVOKED\", {\n message:\n \"The link this request created can't be shown again: the home's capability key changed.\",\n }),\n );\n }\n return link(shown);\n };\n\n const fail = (refused: Refusal): never => {\n throw new RpcError(refused.diagnostic);\n };\n\n /** Opens the faces a host gave before a restart, so their links work before it answers again. */\n const restoreBases = async (): Promise<void> => {\n for (const row of keptBases()) {\n if (row.artifact_id === null) continue;\n try {\n artifacts.get({ artifactId: row.artifact_id });\n } catch {\n continue;\n }\n try {\n const entry = await openFace(\n hostSpec(row.artifact_id, row.listener, row.mode ?? undefined),\n row.origin,\n );\n entry.origin = row.origin;\n } catch (error) {\n log.warn(\"gateway.face_restore_failed\", { key: row.key, error: (error as Error).message });\n }\n }\n };\n\n return {\n shellOrigin,\n async start() {\n const pruned = capabilities.prune();\n if (pruned > 0) log.info(\"gateway.sessions_pruned\", { count: pruned });\n shellListener = createListener({\n policy: () => ({ origin: shellOrigin(), hosts: addressing.hosts(shellPort ?? 0) }),\n log,\n frameAncestors: () => \"'none'\",\n configure: (app) =>\n mount(\n app,\n shellChecks(() => loopbackShell),\n shellRoutes(() => loopbackShell, undefined),\n ),\n ...(options.traceRequests ? { traceRequests: true } : {}),\n });\n shellPort = await addressing.listen(shellListener.server, {\n purpose: \"shell\",\n owner: \"shell\",\n });\n log.info(\"gateway.listening\", { origin: shellOrigin(), bind: addressing.bindAddress });\n // The ports of artifacts viewed lately are bound now, so their open frames reload after a\n // restart (D62, FAILURE_MODEL §8). Every other lease stays leased and is bound when its next\n // frame ticket is issued, so a home with thousands of artifacts holds no thousand listeners\n // (D129, amending D99); a lease never moves, so links keep their origins.\n const since = new Date(Date.now() - RECENT_VIEW_MS).toISOString();\n const recent = new Set(\n options.ledger.read((db) =>\n db\n .all<{ artifact_id: string }>(\n \"SELECT DISTINCT artifact_id FROM view WHERE opened_at >= ?\",\n since,\n )\n .map((row) => row.artifact_id),\n ),\n );\n for (const lease of addressing.leases()) {\n if (lease.purpose !== \"artifact\" || !recent.has(lease.owner)) continue;\n try {\n artifacts.get({ artifactId: lease.owner });\n } catch {\n continue;\n }\n await openArtifact(lease.owner);\n }\n await restoreBases();\n },\n async defaultLink(artifactId) {\n const base = await linkBase(artifactId);\n const { url, tokenId } = link(capabilities.defaultLink(artifactId, base));\n return { url, tokenId };\n },\n link(input) {\n return link(\n capabilities.mint({\n artifactId: input.artifactId,\n ...(input.version !== undefined ? { pinnedVersion: input.version } : {}),\n }),\n ).url;\n },\n mintAt(input, within) {\n return link(\n capabilities.mint(\n {\n artifactId: input.artifactId,\n scopes: input.scopes,\n ttlMs: input.ttlMs,\n viewerId: input.viewerId,\n shellOrigin: input.shellOrigin,\n },\n within,\n ),\n );\n },\n reveal(tokenId) {\n const shown = capabilities.reveal(tokenId);\n return shown ? link(shown).url : undefined;\n },\n async openFace(spec) {\n return handleOf(await openFace(spec));\n },\n face(key) {\n const entry = faces.get(key);\n return entry ? handleOf(entry) : undefined;\n },\n closeFace,\n faces: () =>\n [...faces.values()]\n .filter((entry) => entry.origin !== undefined)\n .map((entry) => ({\n origin: entry.origin as string,\n local: addressing.faceLocal(entry.port),\n listener: entry.spec.listener,\n ...(entry.spec.artifactId !== undefined ? { artifactId: entry.spec.artifactId } : {}),\n by: entry.spec.by,\n })),\n methods: () => [\n handler(viewUrlMethod, async (params) => {\n const detail = artifacts.get(params.artifact);\n const version = versionOf(detail, params.version);\n if (!version) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ARTIFACT_VERSION_NOT_FOUND\", {\n message:\n params.version === undefined\n ? `The artifact ${detail.id} has no published version.`\n : `The artifact ${detail.id} has no version ${params.version}.`,\n }),\n );\n }\n if (version.collected !== undefined)\n throw new RpcError(collectedDiagnostic(version.number));\n const base = await linkBase(detail.id);\n return recorded(requestKey(\"view/url\", params), (db) =>\n capabilities.mint(\n {\n artifactId: detail.id,\n scopes: params.scopes,\n ttlMs: params.ttl === undefined ? undefined : durationMs(params.ttl),\n pinnedVersion: params.version === undefined ? undefined : version.number,\n viewerId:\n params.viewer === undefined\n ? undefined\n : interaction.viewerForSpec(db, params.viewer),\n shellOrigin: base,\n },\n db,\n ),\n );\n }),\n handler(viewDefaultMethod, async (params) => {\n const detail = artifacts.get(params.artifact);\n return link(capabilities.defaultLink(detail.id, await linkBase(detail.id)));\n }),\n handler(viewLaunchMethod, (params) => {\n const minted = capabilities.mintLaunch(params.tokenId);\n if (minted === undefined) {\n return fail(\n refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n `No capability token ${params.tokenId} exists in this home.`,\n ),\n );\n }\n if (minted === \"dead\") {\n return fail(\n refusal(\n \"MOSTRA_HYGIENE_TOKEN_REVOKED\",\n `The token ${params.tokenId} was revoked, has expired, or was made for another address.`,\n ),\n );\n }\n const { grant } = minted;\n return {\n url: `${grant.shellOrigin}/a/${grant.artifactId}${grant.pinnedVersion !== undefined ? `/v/${grant.pinnedVersion}` : \"\"}#l=${minted.ticket}`,\n expiresAt: minted.expiresAt,\n };\n }),\n handler(viewRotateMethod, (params) =>\n recorded(requestKey(\"view/rotate\", params), (db) => {\n const rotated = capabilities.rotate(params.tokenId, db);\n if (rotated === undefined) {\n return fail(\n refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n `No capability token ${params.tokenId} exists in this home.`,\n ),\n );\n }\n if (rotated === \"dead\") {\n return fail(\n refusal(\n \"MOSTRA_HYGIENE_TOKEN_REVOKED\",\n `The token ${params.tokenId} was revoked or has expired.`,\n ),\n );\n }\n return rotated;\n }),\n ),\n handler(viewRevokeMethod, (params) => {\n // Revoking is idempotent by itself, so a retried request needs no record.\n const outcome = capabilities.revoke(params.tokenId);\n if (outcome === \"unknown\") {\n fail(\n refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n `No capability token ${params.tokenId} exists in this home.`,\n ),\n );\n }\n if (outcome === \"revoked\") log.info(\"gateway.token_revoked\", { tokenId: params.tokenId });\n return {};\n }),\n ],\n artifactOrigins: () =>\n new Map(\n [...artifactListeners].map(([artifactId, entry]) => [\n artifactId,\n addressing.origin(entry.port),\n ]),\n ),\n async close() {\n await Promise.allSettled([...opening.values(), ...openingFaces.values()]);\n await Promise.all([\n shellListener?.close(),\n ...[...artifactListeners.values()].map((entry) => entry.listener.close()),\n ...[...faces.values()].map((entry) => entry.listener.close()),\n ...[...lingering.keys()].map((key) => endLingering(key)),\n ]);\n faces.clear();\n },\n servesShell,\n };\n}\n\n/** The answer for a version `mostra gc` collected (D140 item 14). */\nfunction collectedDiagnostic(number: number): Diagnostic {\n return createDiagnostic(\"MOSTRA_ARTIFACT_VERSION_COLLECTED\", {\n message: `Version ${number} of this artifact was collected by gc; its files are gone until its source is published again.`,\n });\n}\n\n/** The tag that tells the client runtime it runs for `verify` (D111, D138). */\nconst VERIFY_TARGET_TAG = '<meta name=\"mostra-target\" content=\"verify\" />';\n\n/**\n * A version's HTML document as a verify run's sandbox serves it: the stored file with the verify\n * target's tag added at the start of its head, so the build itself never carries it (D138).\n */\nasync function verifyDocument(\n path: string,\n request: Request,\n headers: Record<string, string>,\n): Promise<Response> {\n const text = await readFile(path, \"utf8\");\n const head = /<head[^>]*>/i.exec(text);\n const at = head ? head.index + head[0].length : 0;\n const body = `${text.slice(0, at)}\\n ${VERIFY_TARGET_TAG}\\n${text.slice(at)}`;\n return new Response(request.method === \"HEAD\" ? null : body, {\n headers: { ...BASE_HEADERS, ...headers, \"content-type\": \"text/html; charset=utf-8\" },\n });\n}\n\n/**\n * Finds the shell's built files: `MOSTRA_SHELL_DIR`, else `shell/dist` beside the runtime package,\n * as the runtime bundle and this repository lay them out. `undefined` when they're missing: the\n * instance still starts, artifact frames are still served, and the shell's pages answer\n * `MOSTRA_ENV_SHELL_MISSING`.\n */\nexport function locateShell(env: Environment): string | undefined {\n const dir = env[\"MOSTRA_SHELL_DIR\"] ?? resolve(runtimeRoot(), \"..\", \"shell\", \"dist\");\n return existsSync(join(dir, \"index.html\")) ? dir : undefined;\n}\n","/**\n * Live sources (D56, D63, LL-04, AC-07): values a page reads with `useLive(key)`, produced by the\n * `live.ts` of the artifact's latest version in its worker, or pushed by an agent or host\n * (`live/push`). The latest value persists with a revision that only grows, and in append mode a\n * ring keeps the recent values; updates reach the views reading them as ephemeral messages, never\n * as events, so a dashboard open all week never fills the event log.\n *\n * A producer runs while some view reads its source (a one-minute lease the page renews), while a\n * host subscribes to the artifact's events, or always when its source says `always: true`.\n */\nimport {\n type ArtifactRef,\n type Batches,\n createDiagnostic,\n type Frame,\n LIVE_RING_DEFAULT,\n LIVE_RING_MAX,\n LIVE_VALUE_MAX,\n type LiveSourceInfo,\n type LiveState,\n livePushMethod,\n RpcError,\n ServerLiveValueParams,\n serializeAll,\n type WireError,\n} from \"@mostra/protocol\";\nimport type { EphemeralBus, Interaction, PageIdentity } from \"../interaction/index.ts\";\nimport type { Ledger, LedgerDb, RequestKey } from \"../ledger/index.ts\";\nimport { recordedResult, recordResult, requestKey } from \"../ledger/index.ts\";\nimport { type Log, redactFrames, redactValue } from \"../log.ts\";\nimport { handler, type MethodHandler } from \"../protocol-server/index.ts\";\nimport type { WorkerCrash, WorkerHandle, WorkerPool, WorkerVersion } from \"../workers/index.ts\";\n\n/** What the live module knows of an artifact's latest version. */\nexport interface LatestLive {\n readonly versionId: string;\n /**\n * The sources its `live.ts` defines, from its registry: `always` is `true` or `false` when the\n * builder read it as a literal, `undefined` when it couldn't (the worker then tells).\n */\n readonly sources: readonly { readonly key: string; readonly always?: boolean }[];\n}\n\n/** Options for {@link createLive}. */\nexport interface LiveOptions {\n readonly ledger: Ledger;\n readonly log: Log;\n readonly bus: EphemeralBus;\n readonly pool: WorkerPool;\n readonly interaction: Pick<Interaction, \"subscribedArtifacts\" | \"checkView\">;\n /** The latest version of an artifact with live sources, or `undefined`. */\n readonly latest: (artifactId: string) => LatestLive | undefined;\n /** Every artifact whose latest version defines live sources. */\n readonly artifactsWithLive: () => readonly string[];\n /** What the pool needs to start a version's worker. */\n readonly version: (versionId: string) => WorkerVersion | undefined;\n /** How often the producers are checked against who wants them; default 5 s. */\n readonly reconcileMs?: number;\n /** Removes secrets from every value stored (AC-06). */\n readonly redactor?: { redact(text: string): string };\n}\n\n/** The live module. */\nexport interface Live {\n /** Reads sources for a page and keeps them produced for its view for a minute (LL-04). */\n read(\n page: PageIdentity,\n input: {\n readonly viewId: string;\n readonly keys: readonly {\n readonly key: string;\n readonly window?: number;\n readonly refresh?: boolean;\n }[];\n },\n ): LiveState[];\n /** `live/push` (D56): a value from an agent or a host. */\n push(\n artifactId: string,\n input: { readonly key: string; readonly value: unknown; readonly mode?: \"replace\" | \"append\" },\n requestKey?: RequestKey,\n ): Promise<{ revision: string }>;\n /** A worker's `server/live.value`. */\n produced(\n worker: { readonly artifactId: string; readonly versionId: string },\n params: unknown,\n ): void;\n /** A worker crashed: its producers start again when its backoff ends. */\n crashed(crash: WorkerCrash): void;\n /** Checks the producers against who wants them now. */\n reconcile(): void;\n /**\n * A publish cleared the artifact's park (FAILURE_MODEL §2): its producers may start again,\n * also when the publish reused the parked version.\n */\n unpark(artifactId: string): void;\n /**\n * A version's worker was replaced on purpose (a dev session's server code built again, D140\n * item 12): its producers ran in the old worker, so they start again in the new one, from the\n * sources it describes.\n */\n replaced(versionId: string): void;\n /** How many producers run: the daemon stays while any do (D62). */\n activity(): number;\n /** Starts checking producers. */\n start(): void;\n /** Stops checking; the pool stops the producers with their workers. */\n stop(): void;\n /** The artifact's sources whose producers failed last, with the error each reported (verify, D138). */\n failures(artifactId: string): { readonly key: string; readonly error: WireError }[];\n}\n\ninterface LiveRow {\n readonly revision: number;\n readonly value_json: string;\n readonly at: string;\n}\n\nconst keyOf = (artifactId: string, key: string): string => `${artifactId}\\u0000${key}`;\n\n/** After a worker couldn't start to describe its sources, how long before it is tried again. */\nconst DISCOVERY_RETRY_MS = 60_000;\n\nfunction tooLarge(key: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_LIVE_TOO_LARGE\", {\n message: `The value for the live source ${key} is larger than 4 MiB once serialized; it was not stored.`,\n }),\n );\n}\n\n/** Creates the live module. */\nexport function createLive(options: LiveOptions): Live {\n const { ledger, log, bus, pool } = options;\n /** Producers running now, by artifact and key, with the version producing. */\n const running = new Map<\n string,\n { artifactId: string; key: string; versionId: string; handle: WorkerHandle }\n >();\n /** Producers being started. */\n const starting = new Set<string>();\n /** Each version's sources as its worker described them (`ring`, `always`). */\n const described = new Map<string, readonly LiveSourceInfo[]>();\n /** The last failure of each source, shown until its next good value. */\n const failures = new Map<string, WireError>();\n /** Versions whose producers wait for their worker's backoff. */\n const retryAt = new Map<string, number>();\n /** Versions whose producers stopped because their worker is parked, by version, to their artifact. */\n const parkedVersions = new Map<string, string>();\n /** Why each parked version parked: its sources' error names the last cause. */\n const parkCauses = new Map<string, string>();\n const parkError = (cause: string): WireError => ({\n code: \"MOSTRA_RUNTIME_WORKER_PARKED\",\n message: `The artifact's server code keeps crashing, so its live sources stopped (${cause}).`,\n });\n let timer: ReturnType<typeof setInterval> | undefined;\n let scheduled = false;\n let stopped = false;\n /** A worker is starting only to say which of its version's sources are `always`. */\n let discovering = false;\n\n const ringOf = (key: string, versionId: string | undefined): number | undefined => {\n if (!versionId) return undefined;\n return described.get(versionId)?.find((source) => source.key === key)?.ring;\n };\n\n /** Stores a value under the next revision, and in the ring when the source keeps one. */\n const store = (\n db: LedgerDb,\n artifactId: string,\n key: string,\n value: Batches,\n producerVersionId: string | null,\n ring: number | undefined,\n ): { revision: number; at: string } => {\n const current = db.get<{ revision: number }>(\n \"SELECT revision FROM live_value WHERE artifact_id = ? AND key = ?\",\n artifactId,\n key,\n );\n const revision = (current?.revision ?? 0) + 1;\n const at = new Date().toISOString();\n const json = JSON.stringify(redactBatches(value));\n db.run(\n `INSERT INTO live_value (artifact_id, key, revision, value_json, producer_version_id, at)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (artifact_id, key) DO UPDATE SET revision = excluded.revision,\n value_json = excluded.value_json, producer_version_id = excluded.producer_version_id,\n at = excluded.at`,\n artifactId,\n key,\n revision,\n json,\n producerVersionId,\n at,\n );\n if (ring !== undefined && ring > 0) {\n db.run(\n \"INSERT INTO live_ring (artifact_id, key, revision, value_json, at) VALUES (?, ?, ?, ?, ?)\",\n artifactId,\n key,\n revision,\n json,\n at,\n );\n db.run(\n \"DELETE FROM live_ring WHERE artifact_id = ? AND key = ? AND revision <= ?\",\n artifactId,\n key,\n revision - Math.min(ring, LIVE_RING_MAX),\n );\n }\n return { revision, at };\n };\n\n const publishValue = (\n artifactId: string,\n key: string,\n revision: number,\n at: string,\n value: Batches,\n ): void => {\n bus.publishLive(artifactId, {\n kind: \"live\",\n live: {\n key,\n revision: String(revision),\n at,\n value: redactBatches(value),\n },\n });\n };\n\n /** A live value's batches as frames, redacted as values (D131; Opus review 7). */\n const redactBatches = (value: Batches): Batches => {\n const redactor = options.redactor;\n return redactor ? value.map((batch) => redactFrames([...batch], redactor)) : value;\n };\n\n const fail = (artifactId: string, key: string, raw: WireError): void => {\n // An error is output too: a producer's message may carry a secret it read (AC-06).\n const error = options.redactor ? redactValue(raw, options.redactor) : raw;\n failures.set(keyOf(artifactId, key), error);\n bus.publishLive(artifactId, { kind: \"live\", live: { key, error } });\n };\n\n const wanted = (): Map<string, { artifactId: string; key: string }> => {\n const out = new Map<string, { artifactId: string; key: string }>();\n const add = (artifactId: string, key: string): void => {\n out.set(keyOf(artifactId, key), { artifactId, key });\n };\n for (const entry of bus.liveInterest()) add(entry.artifactId, entry.key);\n const subscribed = options.interaction.subscribedArtifacts();\n for (const artifactId of options.artifactsWithLive()) {\n const latest = options.latest(artifactId);\n if (!latest) continue;\n const known = described.get(latest.versionId);\n for (const source of latest.sources) {\n const always = known?.find((info) => info.key === source.key)?.always ?? source.always;\n if (subscribed.has(artifactId) || always === true) add(artifactId, source.key);\n }\n }\n return out;\n };\n\n const startProducer = async (\n artifactId: string,\n key: string,\n versionId: string,\n ): Promise<void> => {\n const id = keyOf(artifactId, key);\n const version = options.version(versionId);\n if (!version) return;\n starting.add(id);\n try {\n const handle = await pool.acquire(version);\n described.set(versionId, handle.started.live);\n const source = handle.started.live.find((info) => info.key === key);\n if (!source) return;\n // A page that read it before its worker said may be waiting for a first load that won't\n // come: a source that only streams. (A worker that doesn't say counts as loading, as\n // `stateOf` reads it.)\n if (source.load === false)\n bus.publishLive(artifactId, { kind: \"live\", live: { key, awaiting: false } });\n // Known before it starts: its first value can arrive before the start's answer.\n running.set(id, { artifactId, key, versionId, handle });\n try {\n await handle.liveStart(key);\n } catch (error) {\n running.delete(id);\n throw error;\n }\n } catch (error) {\n // A start the park cut short says the park, never its own failure (#42). The park may not\n // have named this source: a worker that never answered its start told nobody its sources\n // (GPT review of MT-01).\n if (parkedVersions.has(versionId)) {\n if (failures.get(id)?.code !== \"MOSTRA_RUNTIME_WORKER_PARKED\") {\n fail(artifactId, key, parkError(parkCauses.get(versionId) ?? \"its last start failed\"));\n }\n return;\n }\n const diagnostic = error instanceof RpcError ? error.diagnostic : undefined;\n fail(artifactId, key, {\n message: diagnostic?.message ?? String(error),\n code: diagnostic?.code ?? \"MOSTRA_LIVE_SOURCE_FAILED\",\n });\n } finally {\n starting.delete(id);\n }\n };\n\n const reconcileNow = (): void => {\n if (stopped) return;\n const want = wanted();\n const now = Date.now();\n // Versions whose `always` the registry couldn't read: their worker says. One at a time, and\n // a worker started only to say stops at once unless it has a producer to run, so a home of\n // many such artifacts never starts many workers together (Opus review 2).\n if (!discovering) {\n for (const artifactId of options.artifactsWithLive()) {\n const latest = options.latest(artifactId);\n if (!latest || described.has(latest.versionId)) continue;\n if (!latest.sources.some((source) => source.always === undefined)) continue;\n if ((retryAt.get(latest.versionId) ?? 0) > now) continue;\n const version = options.version(latest.versionId);\n if (!version) continue;\n discovering = true;\n void pool\n .acquire(version)\n .then(\n (handle) => {\n described.set(latest.versionId, handle.started.live);\n const needed =\n handle.started.live.some((source) => source.always === true) ||\n [...want.values()].some((entry) => entry.artifactId === artifactId);\n if (!needed) pool.release(latest.versionId);\n },\n () => {\n // Never sooner than a crash's backoff or park asked for.\n const later = Date.now() + DISCOVERY_RETRY_MS;\n retryAt.set(latest.versionId, Math.max(retryAt.get(latest.versionId) ?? 0, later));\n },\n )\n .finally(() => {\n discovering = false;\n schedule();\n });\n break;\n }\n }\n for (const [id, producer] of running) {\n const latest = options.latest(producer.artifactId);\n if (!want.has(id) || latest?.versionId !== producer.versionId) {\n running.delete(id);\n void producer.handle.liveStop(producer.key);\n }\n }\n for (const [id, entry] of want) {\n if (running.has(id) || starting.has(id)) continue;\n const latest = options.latest(entry.artifactId);\n if (!latest?.sources.some((source) => source.key === entry.key)) continue;\n if ((retryAt.get(latest.versionId) ?? 0) > now) continue;\n void startProducer(entry.artifactId, entry.key, latest.versionId);\n }\n };\n\n const schedule = (): void => {\n if (scheduled || stopped) return;\n scheduled = true;\n setImmediate(() => {\n scheduled = false;\n try {\n reconcileNow();\n } catch (error) {\n log.error(\"live.reconcile_failed\", { error });\n }\n });\n };\n\n const stateOf = (db: LedgerDb, artifactId: string, key: string, window?: number): LiveState => {\n const row = db.get<LiveRow>(\n \"SELECT revision, value_json, at FROM live_value WHERE artifact_id = ? AND key = ?\",\n artifactId,\n key,\n );\n const failure = failures.get(keyOf(artifactId, key));\n // Its first load is on its way when the latest version defines it and, once its worker said,\n // has a `load` (a stream's first value may never come). A key only pushes write isn't.\n const latest = options.latest(artifactId);\n const producing =\n latest?.sources.some((source) => source.key === key) === true &&\n (described.get(latest.versionId)?.find((source) => source.key === key)?.load ?? true);\n const ring =\n window === undefined\n ? undefined\n : db\n .all<LiveRow>(\n \"SELECT revision, value_json, at FROM live_ring WHERE artifact_id = ? AND key = ? ORDER BY revision DESC LIMIT ?\",\n artifactId,\n key,\n window,\n )\n .reverse()\n .map((entry) => ({\n revision: String(entry.revision),\n at: entry.at,\n value: JSON.parse(entry.value_json) as Batches,\n }));\n return {\n key,\n ...(row\n ? {\n revision: String(row.revision),\n at: row.at,\n value: JSON.parse(row.value_json) as Batches,\n }\n : {}),\n ...(ring ? { ring } : {}),\n ...(failure ? { error: failure } : {}),\n ...(!row && !failure && producing ? { awaiting: true } : {}),\n };\n };\n\n return {\n failures(artifactId) {\n const prefix = keyOf(artifactId, \"\");\n return [...failures]\n .filter(([id]) => id.startsWith(prefix))\n .map(([id, error]) => ({ key: id.slice(prefix.length), error }));\n },\n read(page, input) {\n options.interaction.checkView(page, input.viewId);\n bus.watchLive(page.artifactId, input.viewId, input.keys);\n for (const entry of input.keys) {\n if (entry.refresh)\n running.get(keyOf(page.artifactId, entry.key))?.handle.liveRefresh(entry.key);\n }\n schedule();\n return ledger.read((db) =>\n input.keys.map((entry) => stateOf(db, page.artifactId, entry.key, entry.window)),\n );\n },\n\n async push(artifactId, input, requestKey) {\n let batches: Batches;\n try {\n batches = await serializeAll(input.value, { mode: \"argument\" });\n } catch {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", {\n message: `The value pushed to ${input.key} isn't JSON.`,\n }),\n );\n }\n if (JSON.stringify(batches).length > LIVE_VALUE_MAX) throw tooLarge(input.key);\n const latest = options.latest(artifactId);\n const ring =\n input.mode === \"append\"\n ? (ringOf(input.key, latest?.versionId) ?? LIVE_RING_DEFAULT)\n : ringOf(input.key, latest?.versionId);\n const result = ledger.write((db) => {\n if (requestKey) {\n const replay = recordedResult<{ revision: string }>(db, requestKey);\n if (replay) return { replay };\n }\n const stored = store(db, artifactId, input.key, batches, null, ring);\n const answer = { revision: String(stored.revision) };\n if (requestKey) recordResult(db, requestKey, answer);\n return { stored, answer };\n });\n if (\"replay\" in result && result.replay) return result.replay;\n const { stored, answer } = result as {\n stored: { revision: number; at: string };\n answer: { revision: string };\n };\n failures.delete(keyOf(artifactId, input.key));\n publishValue(artifactId, input.key, stored.revision, stored.at, batches);\n return answer;\n },\n\n produced(worker, params) {\n const parsed = ServerLiveValueParams.safeParse(params);\n if (!parsed.success) return;\n const { key } = parsed.data;\n const producer = running.get(keyOf(worker.artifactId, key));\n // Only the producer of the latest version writes the source; a stale one is ignored.\n if (!producer || producer.versionId !== worker.versionId) return;\n if (parsed.data.error) {\n fail(worker.artifactId, key, parsed.data.error);\n return;\n }\n const value = parsed.data.value as Batches | undefined;\n if (!value) return;\n if (JSON.stringify(value).length > LIVE_VALUE_MAX) {\n fail(worker.artifactId, key, {\n code: \"MOSTRA_LIVE_TOO_LARGE\",\n message: tooLarge(key).diagnostic.message,\n });\n return;\n }\n const ring = ringOf(key, worker.versionId);\n try {\n const stored = ledger.write((db) =>\n store(db, worker.artifactId, key, value as Frame[][], worker.versionId, ring),\n );\n failures.delete(keyOf(worker.artifactId, key));\n publishValue(worker.artifactId, key, stored.revision, stored.at, value);\n } catch (error) {\n log.error(\"live.store_failed\", { key, error });\n }\n },\n\n crashed(crash) {\n const ended = new Set(crash.liveKeys);\n for (const [id, producer] of running) {\n if (producer.versionId !== crash.versionId) continue;\n running.delete(id);\n ended.add(producer.key);\n }\n if (crash.parked) {\n // Every source of the parked version says so, not only the producers the worker had\n // started when it crashed: one being started then, or due after the backoff, never runs\n // again either, and its page would otherwise wait on it without a word (#42).\n for (const source of described.get(crash.versionId) ?? []) ended.add(source.key);\n for (const key of ended) fail(crash.artifactId, key, parkError(crash.cause));\n retryAt.set(crash.versionId, Number.POSITIVE_INFINITY);\n parkedVersions.set(crash.versionId, crash.artifactId);\n parkCauses.set(crash.versionId, crash.cause);\n return;\n }\n retryAt.set(crash.versionId, Date.now() + crash.backoffMs);\n setTimeout(() => {\n retryAt.delete(crash.versionId);\n schedule();\n }, crash.backoffMs + 10).unref?.();\n },\n\n reconcile: schedule,\n\n replaced(versionId) {\n for (const [id, producer] of running) {\n if (producer.versionId === versionId) running.delete(id);\n }\n described.delete(versionId);\n retryAt.delete(versionId);\n schedule();\n },\n\n unpark(artifactId) {\n let cleared = false;\n for (const [versionId, owner] of parkedVersions) {\n if (owner !== artifactId) continue;\n parkedVersions.delete(versionId);\n parkCauses.delete(versionId);\n retryAt.delete(versionId);\n cleared = true;\n }\n if (!cleared) return;\n for (const [id, error] of failures) {\n if (id.startsWith(keyOf(artifactId, \"\")) && error.code === \"MOSTRA_RUNTIME_WORKER_PARKED\") {\n failures.delete(id);\n }\n }\n schedule();\n },\n\n activity() {\n return running.size + starting.size;\n },\n\n start() {\n stopped = false;\n bus.onLiveInterest(schedule);\n timer = setInterval(schedule, options.reconcileMs ?? 5_000);\n timer.unref?.();\n schedule();\n },\n\n stop() {\n stopped = true;\n if (timer !== undefined) clearInterval(timer);\n },\n };\n}\n\n/** `live/push` (D56): a value from an agent or host into an artifact's live source. */\nexport function liveMethods(\n live: Live,\n resolveArtifact: (ref: ArtifactRef) => string,\n): MethodHandler[] {\n return [\n handler(livePushMethod, (params) =>\n live.push(\n resolveArtifact(params.artifact),\n {\n key: params.key,\n value: params.value,\n ...(params.mode !== undefined ? { mode: params.mode } : {}),\n },\n requestKey(livePushMethod.method, params),\n ),\n ),\n ];\n}\n","/**\n * Launching artifact workers (D124): the `WorkerLauncher` seam that becomes the remote server's\n * `SandboxPort`. A launch names the version by reference (its ID, output digest and a locator),\n * never by a directory path, and the channel it returns carries only serializable messages, so a\n * launcher whose worker runs as a separate process over a socket, or on another machine, fits\n * without a change. Secrets never travel in `env`: a worker asks for them by name (D44).\n */\nimport { connect } from \"node:net\";\nimport { resolve } from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport {\n encodeLine,\n type JsonRpcMessage,\n LineSplitter,\n type WorkerLimits,\n type WorkerVersionRef,\n} from \"@mostra/protocol\";\nimport type { Environment } from \"../log.ts\";\nimport { pathKey } from \"../platform/index.ts\";\nimport type { ProcessManager } from \"../processes/index.ts\";\n\n/** How a worker ended. */\nexport interface WorkerExit {\n readonly code: number | null;\n readonly signal: string | null;\n /** Its last stderr lines, redacted. */\n readonly stderrTail: readonly string[];\n}\n\n/** What a launcher starts. */\nexport interface WorkerLaunchSpec {\n readonly artifactId: string;\n readonly version: WorkerVersionRef;\n /** The worker's environment: never a secret (D124). */\n readonly env: Environment;\n readonly limits: WorkerLimits;\n /**\n * The artifact's source directory on the owner's machine, when it still exists: the working\n * directory of server code and the root of `watch` globs. A launcher elsewhere ignores it.\n */\n readonly sourceDir?: string;\n}\n\n/** A started worker's connection: JSON-RPC messages both ways, and how it ends. */\nexport interface WorkerChannel {\n /** Sends one message to the worker. Does nothing once it has ended. */\n send(message: JsonRpcMessage): void;\n /** Receives every message from the worker; set once, before the first message is read. */\n onMessage(listener: (message: unknown) => void): void;\n /** Resolves once the worker has ended, for whatever reason. */\n readonly ended: Promise<WorkerExit>;\n /** Ends the worker now (SIGKILL locally). */\n kill(): void;\n /** The worker's process, when it runs on this machine. */\n readonly pid?: number;\n}\n\n/** Starts workers (D124). */\nexport interface WorkerLauncher {\n launch(spec: WorkerLaunchSpec): Promise<WorkerChannel>;\n}\n\n/** Reads newline-delimited JSON from `stream` into `deliver`. */\nfunction readLines(stream: Duplex, deliver: (message: unknown) => void): void {\n const splitter = new LineSplitter();\n stream.setEncoding(\"utf8\");\n stream.on(\"data\", (chunk: string) => {\n let lines: string[];\n try {\n lines = splitter.push(chunk);\n } catch {\n stream.destroy();\n return;\n }\n for (const line of lines) {\n if (line.trim() === \"\") continue;\n try {\n deliver(JSON.parse(line));\n } catch {\n // A worker that writes garbage is answered by nothing; its calls time out or it is killed.\n }\n }\n });\n}\n\n/** Options for {@link localLauncher}. */\nexport interface LocalLauncherOptions {\n readonly processes: ProcessManager;\n /** The home's real path, which `home:` locators resolve inside. */\n readonly home: string;\n /** The worker's process entry (`@mostra/worker`'s `dist/main.js`). */\n readonly workerEntry: string;\n /** Extra Node flags, such as `--conditions` in tests. */\n readonly nodeArgs?: readonly string[];\n /**\n * The `node_modules` the version's packages resolve from (D135), made ready before the worker\n * starts; without it, the server bundle's package imports have nothing to resolve from.\n */\n readonly modules?: (target: {\n readonly artifactId: string;\n readonly versionDir: string;\n readonly sourceDir?: string;\n }) => Promise<string>;\n}\n\n/**\n * The local launcher: resolves a `home:` locator to the version's directory in this home and\n * forks the worker as a child of the process manager, in its own process group, with its channel\n * as fd 4 and the heap limit as a V8 flag.\n */\nexport function localLauncher(options: LocalLauncherOptions): WorkerLauncher {\n return {\n async launch(spec) {\n if (!spec.version.locator.startsWith(\"home:\")) {\n throw new Error(`The local launcher can't reach ${spec.version.locator}.`);\n }\n const versionDir = resolve(options.home, spec.version.locator.slice(\"home:\".length));\n // A published version, a build a verify run made and serves from its sandbox (D138), or a\n // `mostra dev` session's server bundle (D140 item 12).\n const roots = [\n resolve(options.home, \"versions\"),\n resolve(options.home, \"cache\", \"builds\"),\n resolve(options.home, \"cache\", \"dev\"),\n ];\n // Strictly inside one of them, compared as the platform compares paths (WP-W1).\n if (!roots.some((root) => pathKey(versionDir).startsWith(`${pathKey(root)}/`))) {\n throw new Error(\n \"A home: locator names a version directory, a verify build or a dev session of the home.\",\n );\n }\n const modules = await options.modules?.({\n artifactId: spec.artifactId,\n versionDir,\n ...(spec.sourceDir ? { sourceDir: spec.sourceDir } : {}),\n });\n const child = await options.processes.spawn({\n kind: \"worker\",\n ownerRef: spec.version.versionId,\n command: process.execPath,\n args: [\n `--max-old-space-size=${spec.limits.heapMb}`,\n ...(options.nodeArgs ?? []),\n options.workerEntry,\n \"--channel\",\n \"fd:4\",\n \"--version-dir\",\n versionDir,\n ...(spec.sourceDir ? [\"--source-dir\", spec.sourceDir] : []),\n ...(modules ? [\"--modules\", modules] : []),\n ],\n cwd: spec.sourceDir ?? versionDir,\n env: spec.env,\n channel: true,\n });\n const stream = child.channel;\n if (!stream) throw new Error(\"The worker started without its channel.\");\n let ended = false;\n void child.exited.then(() => {\n ended = true;\n });\n return {\n pid: child.pid,\n send(message) {\n if (ended || stream.destroyed) return;\n stream.write(encodeLine(message));\n },\n onMessage(listener) {\n readLines(stream, listener);\n },\n ended: child.exited.then((exit) => ({\n code: exit.code,\n signal: exit.signal,\n stderrTail: exit.stderrTail,\n })),\n kill() {\n void child.stop(0);\n },\n };\n },\n };\n}\n\n/** The line a worker host sends after its worker ended, before it closes the connection. */\nexport interface WorkerHostExitLine {\n readonly mostraWorkerExit: WorkerExit;\n}\n\n/**\n * A launcher whose workers run in a separately started worker host, reached over a Unix socket\n * (D124's proof that the seam fits a worker elsewhere). Each launch opens one connection and sends\n * the launch spec as its first line, without the source directory (the host has its own files);\n * the host starts the worker, passes messages through, and ends the connection with a\n * {@link WorkerHostExitLine} once the worker ended. Closing the connection ends the worker.\n */\nexport function socketLauncher(socketPath: string): WorkerLauncher {\n return {\n launch(spec) {\n return new Promise<WorkerChannel>((resolveLaunch, rejectLaunch) => {\n const socket = connect(socketPath);\n let exit: WorkerExit | undefined;\n let listener: ((message: unknown) => void) | undefined;\n let resolveEnded!: (exit: WorkerExit) => void;\n const ended = new Promise<WorkerExit>((done) => {\n resolveEnded = done;\n });\n socket.once(\"error\", rejectLaunch);\n socket.once(\"connect\", () => {\n socket.off(\"error\", rejectLaunch);\n socket.on(\"error\", () => socket.destroy());\n const { sourceDir: _local, ...remote } = spec;\n socket.write(`${JSON.stringify({ launch: remote })}\\n`);\n readLines(socket, (message) => {\n const line = message as Partial<WorkerHostExitLine>;\n if (line.mostraWorkerExit) exit = line.mostraWorkerExit;\n else listener?.(message);\n });\n socket.once(\"close\", () =>\n resolveEnded(\n exit ?? {\n code: null,\n signal: \"SIGKILL\",\n stderrTail: [\"The worker host closed the connection.\"],\n },\n ),\n );\n resolveLaunch({\n send(message) {\n if (!socket.destroyed) socket.write(encodeLine(message));\n },\n onMessage(next) {\n listener = next;\n },\n ended,\n kill() {\n socket.destroy();\n },\n });\n });\n });\n },\n };\n}\n\n/**\n * Where the worker's process entry is: `MOSTRA_WORKER_ENTRY` when set, else `@mostra/worker`\n * beside this runtime (`worker/dist/main.js`; its source, run with the source condition, when\n * this runtime runs from source too).\n */\nexport function locateWorker(\n env: Environment,\n runtimeRoot: string,\n): { readonly entry: string; readonly nodeArgs: readonly string[] } {\n const override = env[\"MOSTRA_WORKER_ENTRY\"];\n if (override) return { entry: override, nodeArgs: [] };\n const fromSource = import.meta.url.endsWith(\".ts\");\n return fromSource\n ? {\n entry: resolve(runtimeRoot, \"..\", \"worker\", \"src\", \"main.ts\"),\n nodeArgs: [\"--conditions=@mostra/source\"],\n }\n : { entry: resolve(runtimeRoot, \"..\", \"worker\", \"dist\", \"main.js\"), nodeArgs: [] };\n}\n","/**\n * The worker pool (RT-03, RT-04, D62, FAILURE_MODEL §2): one worker per active artifact version\n * with server code, started on first need through the `WorkerLauncher`, stopped after its idle\n * minutes, watched by a 10 s event-loop watchdog, restarted after a crash with exponential backoff\n * (1 s to 60 s) and parked after more than 5 crashes in 10 minutes. A crash, an out-of-memory abort\n * or a hang ends only that worker: the supervisor and every other worker keep serving.\n */\nimport {\n type CallContext,\n createDiagnostic,\n DEFAULT_WORKER_LIMITS,\n type Frame,\n RpcError,\n RpcPeer,\n type RunProgress,\n WORKER_METHODS,\n WorkerBatchParams,\n type WorkerCallOutcome,\n WorkerCallOutcome as WorkerCallOutcomeSchema,\n type WorkerLimits,\n WorkerPingResult,\n type WorkerStartResult,\n WorkerStartResult as WorkerStartResultSchema,\n type WorkerStatus,\n type WorkerVersionRef,\n} from \"@mostra/protocol\";\nimport type { Environment, Log } from \"../log.ts\";\nimport type { WorkerChannel, WorkerExit, WorkerLauncher } from \"./launcher.ts\";\n\n/** What the pool needs to know about a version to start its worker. */\nexport interface WorkerVersion {\n readonly artifactId: string;\n readonly ref: WorkerVersionRef;\n /** The server bundle, relative to the version (the render mode's `serverEntry`). */\n readonly entry: string;\n readonly limits: WorkerLimits;\n readonly sourceDir?: string;\n /** The IDs of the version's server functions, from its `registry.json` (the builder's scan). */\n readonly functions: ReadonlySet<string>;\n}\n\n/** A call's link back to the caller: its batches, progress and log lines as they come. */\nexport interface CallListener {\n onBatch?(batch: readonly Frame[]): void;\n onProgress?(progress: RunProgress): void;\n onLog?(line: string): void;\n}\n\n/** Who a call is for, as the bridge sees a worker's requests during it. */\nexport interface CallInfo {\n readonly callId: string;\n readonly context: CallContext;\n readonly viewerId?: string;\n}\n\n/** What a worker asks of the supervisor, and the live values it produces. */\nexport interface WorkerBridge {\n /**\n * Answers a worker's request (`server/secret`, `server/signal`, `server/emit`,\n * `server/state.*`); `call` is the call it came from, when it names one.\n */\n request(\n worker: { readonly artifactId: string; readonly versionId: string },\n method: string,\n params: unknown,\n call: CallInfo | undefined,\n ): Promise<unknown>;\n /** A line a worker logged outside any call. */\n log(worker: { readonly artifactId: string; readonly versionId: string }, line: string): void;\n /** A live value or failure (`server/live.value`). */\n liveValue(\n worker: { readonly artifactId: string; readonly versionId: string },\n params: unknown,\n ): void;\n}\n\n/** A running worker, as the pool hands it out. */\nexport interface WorkerHandle {\n readonly versionId: string;\n readonly artifactId: string;\n readonly started: WorkerStartResult;\n /** Runs a server function; the outcome arrives after every batch was given to `listener`. */\n call(\n info: {\n readonly fnId: string;\n readonly args: unknown;\n readonly context: CallContext;\n readonly viewerId?: string;\n },\n listener: CallListener,\n ): { readonly callId: string; readonly outcome: Promise<WorkerCallOutcome> };\n /** Aborts a call's `abortSignal`. */\n cancel(callId: string, reason?: string): void;\n /** Starts a live producer; it keeps the worker from idling until stopped. */\n liveStart(key: string): Promise<void>;\n liveStop(key: string): Promise<void>;\n liveRefresh(key: string): void;\n}\n\n/** Why a worker ended unexpectedly, and what happens next. */\nexport interface WorkerCrash {\n readonly artifactId: string;\n readonly versionId: string;\n /** For people: \"it ran out of memory (heap limit 1024 MiB)\". */\n readonly cause: string;\n readonly kind: \"crash\" | \"oom\" | \"hang\";\n readonly backoffMs: number;\n readonly parked: boolean;\n /** The calls that were running in it. */\n readonly callIds: readonly string[];\n /** The live producers that were running in it. */\n readonly liveKeys: readonly string[];\n}\n\n/** Options for {@link createWorkerPool}. */\nexport interface WorkerPoolOptions {\n readonly launcher: WorkerLauncher;\n readonly log: Log;\n readonly bridge: WorkerBridge;\n /** The environment every worker gets: the artifact allowlist, never secrets. */\n readonly env: Environment;\n /** Reports a crash, after the pool recorded it: append `worker.crashed`, end runs. */\n readonly onCrash: (crash: WorkerCrash) => void;\n /** How often the watchdog asks; default 1000 ms. */\n readonly watchdogIntervalMs?: number;\n /** Idle time in ms, overriding the versions' `idleMinutes` (tests). */\n readonly idleMsOverride?: number;\n /** The crash window and its limit (FAILURE_MODEL §2: 5 in 10 minutes). */\n readonly parkAfter?: { readonly crashes: number; readonly windowMs: number };\n /** The first backoff after a crash, doubling to 60 s (FAILURE_MODEL §2: 1 s; tests shorten it). */\n readonly backoffMinMs?: number;\n readonly now?: () => number;\n}\n\n/** The pool. */\nexport interface WorkerPool {\n /**\n * The version's worker, started if it isn't; waits out a backoff. Throws\n * `MOSTRA_RUNTIME_WORKER_PARKED` for a parked version and `MOSTRA_RUNTIME_WORKER_CRASHED` when\n * the worker couldn't start.\n */\n acquire(version: WorkerVersion): Promise<WorkerHandle>;\n /** The worker if it runs now, without starting one. */\n running(versionId: string): WorkerHandle | undefined;\n /**\n * Stops a version's worker now if it runs nothing (no call, no producer), rather than after its\n * idle time: for a worker started only to say what its live sources are.\n */\n release(versionId: string): void;\n /** Clears the park and crash history of every version of an artifact (a publish, `verify`). */\n clear(artifactId: string): void;\n /**\n * Replaces a version's server bundle (`mostra dev` only, D140 item 12): stops its worker, busy\n * or not, so the next call starts `version`, the same version ID with a new output digest, and\n * clears its crash history.\n */\n replace(version: WorkerVersion): Promise<void>;\n /** Every version's worker state, for `instance/status`. */\n status(): WorkerStatus[];\n /** How many calls and producers run in all workers: the daemon stays while any do (D62). */\n activity(): number;\n /** Stops every worker. */\n stopAll(): Promise<void>;\n}\n\nconst CRASH_LIMIT = { crashes: 5, windowMs: 10 * 60_000 } as const;\nconst BACKOFF_MIN_MS = 1000;\nconst BACKOFF_MAX_MS = 60_000;\nconst START_TIMEOUT_MS = 60_000;\n\ninterface Slot {\n version: WorkerVersion;\n state: WorkerStatus[\"state\"];\n crashes: number[];\n lastCause?: string;\n retryAt?: number;\n starting?: Promise<Running>;\n current?: Running;\n}\n\ninterface Running {\n readonly handle: WorkerHandle;\n readonly channel: WorkerChannel;\n readonly peer: RpcPeer;\n readonly calls: Map<string, { info: CallInfo; listener: CallListener }>;\n readonly live: Set<string>;\n stopping: boolean;\n /**\n * Set until `worker/start` answers: a worker that ends before then failed to start, which\n * `acquire` records once, with the start's message (Opus review 5).\n */\n starting: boolean;\n hung?: number;\n /** The watchdog stopped it for not answering at all, rather than for a blocked event loop. */\n silent?: boolean;\n /** The heap in use at the last answered ping, in bytes: near the limit, a stall is memory. */\n heapUsed?: number;\n idleTimer?: ReturnType<typeof setTimeout>;\n watchdog?: ReturnType<typeof setInterval>;\n}\n\nlet nextCall = 0;\n\n/** Unanswered pings in a row, each as long as the watchdog's limit, before a worker is stopped. */\nconst PINGS_MISSED_BEFORE_STOP = 3;\n\n/**\n * The share of its heap limit a worker had in use at its last answered ping for a watchdog stop\n * to count as running out of memory rather than hanging.\n */\nconst OOM_STALL_FRACTION = 0.8;\n\n/**\n * An exit code as people look it up: a Windows status (`0xC0000005`, an access violation) in\n * hexadecimal, any other code as a number. Node.js reports a Windows status as an unsigned\n * 32-bit number; on POSIX codes are below 256.\n */\nexport function exitCodeText(code: number | null): string {\n if (code === null) return \"?\";\n if (code >= 0x80000000 || code < 0) {\n return `0x${(code >>> 0).toString(16).toUpperCase().padStart(8, \"0\")}`;\n }\n return String(code);\n}\n\nfunction crashed(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_RUNTIME_WORKER_CRASHED\", { message }));\n}\n\n/** A worker that couldn't start, and how it ended. */\nclass StartFailure extends RpcError {\n readonly kind: WorkerCrash[\"kind\"];\n constructor(message: string, kind: WorkerCrash[\"kind\"]) {\n super(createDiagnostic(\"MOSTRA_RUNTIME_WORKER_CRASHED\", { message }));\n this.kind = kind;\n }\n}\n\n/** Creates the pool. */\nexport function createWorkerPool(options: WorkerPoolOptions): WorkerPool {\n const slots = new Map<string, Slot>();\n const now = options.now ?? Date.now;\n const park = options.parkAfter ?? CRASH_LIMIT;\n const watchdogEvery = options.watchdogIntervalMs ?? 1000;\n const backoffMin = options.backoffMinMs ?? BACKOFF_MIN_MS;\n let stopped = false;\n\n const idleMs = (version: WorkerVersion): number =>\n options.idleMsOverride ?? version.limits.idleMinutes * 60_000;\n\n const scheduleIdle = (slot: Slot, running: Running): void => {\n if (running.idleTimer !== undefined) clearTimeout(running.idleTimer);\n delete running.idleTimer;\n if (running.calls.size > 0 || running.live.size > 0 || running.stopping) return;\n running.idleTimer = setTimeout(() => {\n if (running.calls.size > 0 || running.live.size > 0) return;\n options.log.info(\"worker.idle_stop\", { versionId: slot.version.ref.versionId });\n void stopRunning(running);\n }, idleMs(slot.version));\n running.idleTimer.unref?.();\n };\n\n const stopRunning = async (running: Running): Promise<void> => {\n running.stopping = true;\n if (running.watchdog !== undefined) clearInterval(running.watchdog);\n if (running.idleTimer !== undefined) clearTimeout(running.idleTimer);\n await running.peer.request(WORKER_METHODS.stop, {}, { timeoutMs: 2000 }).catch(() => {});\n const timer = setTimeout(() => running.channel.kill(), 3000);\n await running.channel.ended;\n clearTimeout(timer);\n };\n\n const classify = (\n exit: WorkerExit,\n running: Running,\n limits: WorkerLimits,\n ): { kind: WorkerCrash[\"kind\"]; cause: string } => {\n const tail = exit.stderrTail.join(\"\\n\");\n if (\n /heap out of memory|Allocation failed|Reached heap limit/i.test(tail) ||\n exit.signal === \"SIGABRT\" ||\n exit.code === 134\n ) {\n return { kind: \"oom\", cause: `it ran out of memory (heap limit ${limits.heapMb} MiB)` };\n }\n if (running.hung !== undefined) {\n // Near its heap limit, V8 collects garbage over and over and the event loop stalls before\n // the heap gives out: the watchdog stops it first, and the cause is memory (seen on Linux).\n if ((running.heapUsed ?? 0) >= OOM_STALL_FRACTION * limits.heapMb * 1024 * 1024) {\n return {\n kind: \"oom\",\n cause: `it ran out of memory (heap limit ${limits.heapMb} MiB): collecting garbage blocked its event loop for ${Math.round(running.hung / 1000)} s`,\n };\n }\n return {\n kind: \"hang\",\n cause: running.silent\n ? `it answered nothing for ${Math.round(running.hung / 1000)} s (watchdog limit ${limits.watchdogMs / 1000} s)`\n : `its event loop was blocked for ${Math.round(running.hung / 1000)} s (watchdog limit ${limits.watchdogMs / 1000} s)`,\n };\n }\n // Node ends an uncaught exception's report with its version; the error line says what\n // happened (`Error: …`, `TypeError: …`), so it is the cause, else the last line written.\n const lines = exit.stderrTail.filter(\n (line) => line.trim() !== \"\" && !/^Node\\.js v\\d/.test(line.trim()),\n );\n const last =\n lines.findLast((line) => /^[A-Za-z_$][\\w$.]*(?:Error|Exception)\\b.*:/.test(line.trim())) ??\n lines.findLast((line) => !/^\\s+at\\s/.test(line)) ??\n lines.at(-1);\n const how =\n exit.signal !== null\n ? `it was ended by ${exit.signal}`\n : `it exited with code ${exitCodeText(exit.code)}`;\n return { kind: \"crash\", cause: last ? `${how}: ${last.slice(0, 300)}` : how };\n };\n\n /** Records a crash: the backoff or the park it leads to, the log and the caller's report. */\n const recordCrash = (\n slot: Slot,\n kind: WorkerCrash[\"kind\"],\n cause: string,\n callIds: readonly string[],\n liveKeys: readonly string[],\n ): void => {\n const at = now();\n slot.crashes = [...slot.crashes.filter((when) => at - when < park.windowMs), at];\n slot.lastCause = cause;\n const parked = slot.crashes.length > park.crashes;\n const backoffMs = parked\n ? 0\n : Math.min(BACKOFF_MAX_MS, backoffMin * 2 ** (slot.crashes.length - 1));\n slot.state = parked ? \"parked\" : \"backoff\";\n if (parked) delete slot.retryAt;\n else slot.retryAt = at + backoffMs;\n options.log.warn(\"worker.crashed\", {\n versionId: slot.version.ref.versionId,\n kind,\n cause,\n backoffMs,\n parked,\n });\n options.onCrash({\n artifactId: slot.version.artifactId,\n versionId: slot.version.ref.versionId,\n cause,\n kind,\n backoffMs,\n parked,\n callIds,\n liveKeys,\n });\n };\n\n const onEnded = (slot: Slot, running: Running, exit: WorkerExit): void => {\n if (running.watchdog !== undefined) clearInterval(running.watchdog);\n if (running.idleTimer !== undefined) clearTimeout(running.idleTimer);\n running.peer.close();\n if (slot.current === running) delete slot.current;\n if (running.stopping || stopped) {\n if (slot.state === \"ready\") slot.state = \"stopped\";\n return;\n }\n // A worker that ends during its start failed to start: `acquire` records that, once.\n if (running.starting) return;\n const { kind, cause } = classify(exit, running, slot.version.limits);\n recordCrash(slot, kind, cause, [...running.calls.keys()], [...running.live]);\n };\n\n const start = async (slot: Slot): Promise<Running> => {\n const { version } = slot;\n const who = { artifactId: version.artifactId, versionId: version.ref.versionId };\n const channel = await options.launcher.launch({\n artifactId: version.artifactId,\n version: version.ref,\n env: options.env,\n limits: version.limits,\n ...(version.sourceDir ? { sourceDir: version.sourceDir } : {}),\n });\n const calls: Running[\"calls\"] = new Map();\n const live = new Set<string>();\n const peer = new RpcPeer({\n send: (message) => channel.send(message),\n onRequest: (method, params) => {\n const callId = (params as { callId?: unknown } | undefined)?.callId;\n const call = typeof callId === \"string\" ? calls.get(callId)?.info : undefined;\n return options.bridge.request(who, method, params, call);\n },\n onNotification: (method, params) => {\n const callId = (params as { callId?: unknown } | undefined)?.callId;\n const entry = typeof callId === \"string\" ? calls.get(callId) : undefined;\n switch (method) {\n case WORKER_METHODS.batch: {\n const parsed = WorkerBatchParams.safeParse(params);\n if (parsed.success) entry?.listener.onBatch?.(parsed.data.batch);\n return;\n }\n case WORKER_METHODS.progress: {\n const { callId: _call, ...progress } = params as RunProgress & { callId: string };\n entry?.listener.onProgress?.(progress);\n return;\n }\n case WORKER_METHODS.log: {\n const line = String((params as { line?: unknown }).line ?? \"\");\n if (entry) entry.listener.onLog?.(line);\n else options.bridge.log(who, line);\n return;\n }\n case WORKER_METHODS.liveValue:\n options.bridge.liveValue(who, params);\n return;\n }\n },\n onInternalError: (error, method) =>\n options.log.error(\"worker.channel_error\", { versionId: who.versionId, method, error }),\n });\n channel.onMessage((message) => peer.receive(message));\n\n const running: Running = {\n channel,\n peer,\n calls,\n live,\n stopping: false,\n starting: true,\n handle: undefined as unknown as WorkerHandle,\n };\n void channel.ended.then((exit) => onEnded(slot, running, exit));\n\n let started: WorkerStartResult;\n try {\n const raw = await peer.request(\n WORKER_METHODS.start,\n {\n artifactId: version.artifactId,\n version: version.ref,\n entry: version.entry,\n limits: version.limits,\n },\n { timeoutMs: START_TIMEOUT_MS },\n );\n started = WorkerStartResultSchema.parse(raw);\n running.starting = false;\n } catch (error) {\n running.stopping = true;\n channel.kill();\n const exit = await channel.ended;\n const tail = exit.stderrTail\n .filter((line) => line.trim() !== \"\")\n .slice(-3)\n .join(\" / \");\n // How it ended: a worker that ran out of memory while loading is an OOM, not a crash.\n const { kind } = classify(exit, running, version.limits);\n throw new StartFailure(\n `The server code of ${version.ref.versionId} couldn't start: ${error instanceof RpcError ? error.diagnostic.message : String(error)}${tail ? ` (${tail})` : \"\"}`,\n kind,\n );\n }\n\n const handle: WorkerHandle = {\n versionId: version.ref.versionId,\n artifactId: version.artifactId,\n started,\n call(info, listener) {\n nextCall += 1;\n const callId = `call_${nextCall}`;\n const callInfo: CallInfo = {\n callId,\n context: info.context,\n ...(info.viewerId === undefined ? {} : { viewerId: info.viewerId }),\n };\n calls.set(callId, { info: callInfo, listener });\n scheduleIdle(slot, running);\n const outcome = (async (): Promise<WorkerCallOutcome> => {\n try {\n const raw = await peer.request(WORKER_METHODS.call, {\n callId,\n fnId: info.fnId,\n args: info.args as never,\n context: info.context as never,\n });\n return WorkerCallOutcomeSchema.parse(raw);\n } catch (error) {\n if (\n error instanceof RpcError &&\n error.diagnostic.code === \"MOSTRA_HOST_CONNECTION_CLOSED\"\n ) {\n throw crashed(\n `The server code of ${version.ref.versionId} stopped during the call: ${slot.lastCause ?? \"its worker ended\"}.`,\n );\n }\n throw error;\n } finally {\n calls.delete(callId);\n scheduleIdle(slot, running);\n }\n })();\n return { callId, outcome };\n },\n cancel(callId, reason) {\n peer.notify(WORKER_METHODS.cancel, { callId, ...(reason ? { reason } : {}) });\n },\n async liveStart(key) {\n live.add(key);\n scheduleIdle(slot, running);\n try {\n await peer.request(WORKER_METHODS.liveStart, { key }, { timeoutMs: 30_000 });\n } catch (error) {\n live.delete(key);\n scheduleIdle(slot, running);\n throw error;\n }\n },\n async liveStop(key) {\n if (!live.delete(key)) return;\n scheduleIdle(slot, running);\n await peer.request(WORKER_METHODS.liveStop, { key }, { timeoutMs: 10_000 }).catch(() => {});\n },\n liveRefresh(key) {\n peer.notify(WORKER_METHODS.liveRefresh, { key });\n },\n };\n (running as { handle: WorkerHandle }).handle = handle;\n\n // The watchdog (D62): a worker whose event loop stays blocked past its limit, or that stops\n // answering, is stopped and reported as hung.\n let asking = false;\n // Pings missed in a row. The channel thread answers even while artifact code blocks the\n // event loop, so silence means the channel is congested (a large result ahead of the answer,\n // a slow link to a launcher elsewhere) or the process is gone; only a long silence stops it.\n let missed = 0;\n running.watchdog = setInterval(() => {\n if (asking || running.stopping) return;\n asking = true;\n const limit = version.limits.watchdogMs;\n peer\n .request(WORKER_METHODS.ping, {}, { timeoutMs: limit })\n .then((raw) => {\n const ping = WorkerPingResult.parse(raw);\n missed = 0;\n running.heapUsed = ping.heapUsed;\n if (!ping.waitingForSecret && ping.blockedMs > limit) {\n running.hung = ping.blockedMs;\n channel.kill();\n }\n })\n .catch(() => {\n if (running.stopping || peer.closed) return;\n missed += 1;\n if (missed < PINGS_MISSED_BEFORE_STOP) return;\n running.hung = limit * missed;\n running.silent = true;\n channel.kill();\n })\n .finally(() => {\n asking = false;\n });\n }, watchdogEvery);\n running.watchdog.unref?.();\n scheduleIdle(slot, running);\n return running;\n };\n\n const slotOf = (version: WorkerVersion): Slot => {\n let slot = slots.get(version.ref.versionId);\n if (!slot) {\n slot = { version, state: \"stopped\", crashes: [] };\n slots.set(version.ref.versionId, slot);\n }\n return slot;\n };\n\n return {\n async acquire(version) {\n if (stopped) throw crashed(\"The instance is stopping.\");\n const slot = slotOf(version);\n for (;;) {\n if (stopped) throw crashed(\"The instance is stopping.\");\n if (slot.current && !slot.current.stopping) return slot.current.handle;\n if (slot.current?.stopping) {\n // An idle stop in progress: the version keeps one worker, so its replacement starts\n // only once this one has gone (RT-03).\n await slot.current.channel.ended;\n await Promise.resolve();\n if (slot.current?.stopping) delete slot.current;\n continue;\n }\n if (slot.state === \"parked\") {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_RUNTIME_WORKER_PARKED\", {\n message: `The server code of this artifact crashed ${slot.crashes.length} times in 10 minutes, so it is parked; the last cause: ${slot.lastCause ?? \"unknown\"}.`,\n }),\n );\n }\n if (slot.starting) {\n await slot.starting.catch(() => {});\n if (slot.current) continue;\n throw crashed(\n `The server code of ${version.ref.versionId} couldn't start: ${slot.lastCause ?? \"it failed\"}.`,\n );\n }\n if (slot.retryAt !== undefined && slot.retryAt > now()) {\n await new Promise((resolve) => setTimeout(resolve, (slot.retryAt ?? now()) - now()));\n continue;\n }\n slot.state = \"starting\";\n slot.starting = start(slot);\n try {\n const running = await slot.starting;\n if (slot.current === undefined && !running.stopping) {\n slot.current = running;\n slot.state = \"ready\";\n } else if (!running.stopping) {\n // Never left running untracked: a worker the slot can't hold is stopped at once.\n void stopRunning(running);\n }\n delete slot.retryAt;\n } catch (error) {\n // A worker that can't start crashed as surely as one that died later: it backs off,\n // and a version that never starts is parked like one that keeps crashing.\n recordCrash(\n slot,\n error instanceof StartFailure ? error.kind : \"crash\",\n error instanceof RpcError ? error.diagnostic.message : String(error),\n [],\n [],\n );\n throw error;\n } finally {\n delete slot.starting;\n }\n }\n },\n running(versionId) {\n const current = slots.get(versionId)?.current;\n return current && !current.stopping ? current.handle : undefined;\n },\n release(versionId) {\n const current = slots.get(versionId)?.current;\n if (!current || current.stopping || current.calls.size > 0 || current.live.size > 0) return;\n options.log.info(\"worker.idle_stop\", { versionId, reason: \"released\" });\n void stopRunning(current);\n },\n async replace(version) {\n const slot = slots.get(version.ref.versionId);\n if (!slot) return;\n slot.version = version;\n slot.crashes = [];\n delete slot.retryAt;\n if (slot.state === \"parked\" || slot.state === \"backoff\") slot.state = \"stopped\";\n await slot.starting?.catch(() => {});\n const current = slot.current;\n if (current && !current.stopping) {\n options.log.info(\"worker.replaced\", { versionId: version.ref.versionId });\n await stopRunning(current);\n }\n },\n clear(artifactId) {\n for (const slot of slots.values()) {\n if (slot.version.artifactId !== artifactId) continue;\n slot.crashes = [];\n delete slot.retryAt;\n if (slot.state === \"parked\" || slot.state === \"backoff\") slot.state = \"stopped\";\n }\n },\n status() {\n const at = now();\n return [...slots.values()].map((slot) => {\n const running = slot.current;\n const recent = slot.crashes.filter((when) => at - when < park.windowMs).length;\n return {\n artifactId: slot.version.artifactId,\n versionId: slot.version.ref.versionId,\n state: slot.state,\n ...(running?.channel.pid !== undefined ? { pid: running.channel.pid } : {}),\n crashes: recent,\n ...(slot.lastCause ? { lastCause: slot.lastCause } : {}),\n ...(slot.retryAt !== undefined && slot.state === \"backoff\"\n ? { retryAt: new Date(slot.retryAt).toISOString() }\n : {}),\n active: running ? running.calls.size + running.live.size : 0,\n };\n });\n },\n activity() {\n let count = 0;\n for (const slot of slots.values()) {\n if (slot.current) count += slot.current.calls.size + slot.current.live.size;\n }\n return count;\n },\n async stopAll() {\n stopped = true;\n await Promise.all(\n [...slots.values()].flatMap((slot) => (slot.current ? [stopRunning(slot.current)] : [])),\n );\n },\n };\n}\n\n/** The limits of a version from its manifest's `limits` (D62), within sane bounds. */\nexport function workerLimits(manifest: {\n readonly limits?: {\n readonly heapMb?: number;\n readonly watchdogMs?: number;\n readonly idleMinutes?: number;\n };\n}): WorkerLimits {\n const limits = manifest.limits ?? {};\n const clamp = (value: number | undefined, fallback: number, min: number, max: number): number =>\n typeof value === \"number\" && Number.isFinite(value)\n ? Math.min(max, Math.max(min, value))\n : fallback;\n return {\n heapMb: Math.round(clamp(limits.heapMb, DEFAULT_WORKER_LIMITS.heapMb, 64, 65_536)),\n watchdogMs: Math.round(\n clamp(limits.watchdogMs, DEFAULT_WORKER_LIMITS.watchdogMs, 1000, 3_600_000),\n ),\n idleMinutes: clamp(limits.idleMinutes, DEFAULT_WORKER_LIMITS.idleMinutes, 0.05, 7 * 24 * 60),\n };\n}\n","/**\n * A verify run's sandbox (D138 item 1): the real interaction, actions, live and gateway code over\n * a scratch ledger in `cache/verify/runs/<run>/`, with its own worker pool and two short-lived\n * loopback listeners on ports the operating system assigns, so a run never touches the home's\n * drafts, state, events, hosts or deliveries, and the human-facing gateway never serves an\n * unpublished build.\n *\n * - Pages are reached only with capability links minted in the scratch ledger, through the same\n * session exchange and frame tickets as a viewer's (D97, D98). Documents get the verify target\n * when served (`target: \"verify\"`), never in the build.\n * - Server code runs in workers the gated process manager starts. A function that opted into\n * `dryRun()` runs with it true; any other is refused before anything is recorded (D55).\n * - `secret()` reads the real secrets, as the instance resolves them; nothing else of the home is\n * reached. State starts empty, like a first view.\n * - Closing stops everything and deletes the run's directory; {@link recoverSandboxes} removes\n * what a stopped instance left.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { mkdir, readdir, rm } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport { type ArtifactManifest, type Results, RunId } from \"@mostra/protocol\";\nimport { createActions } from \"../actions/index.ts\";\nimport { createAddressing } from \"../addressing/index.ts\";\nimport {\n coverageMatcher,\n readFieldCoverage,\n readLiveSources,\n readServerFunctions,\n} from \"../builder/index.ts\";\nimport { noFaults } from \"../faults.ts\";\nimport { Capabilities, createGateway, type DevUpstream } from \"../gateway/index.ts\";\nimport { createEphemeralBus, createInteraction } from \"../interaction/index.ts\";\nimport { openLedger } from \"../ledger/index.ts\";\nimport { createLive } from \"../live/index.ts\";\nimport type { Environment, Log, Redactor } from \"../log.ts\";\nimport type { ProcessManager } from \"../processes/index.ts\";\nimport { openRegistry } from \"../registry/index.ts\";\nimport type { Secrets } from \"../secrets/index.ts\";\nimport {\n createWorkerPool,\n localLauncher,\n type WorkerVersion,\n workerLimits,\n} from \"../workers/index.ts\";\n\n/** One version the sandbox serves. */\nexport interface SandboxVersion {\n readonly versionId: string;\n /** Its directory: a verify build in `cache/builds/` or a published version in `versions/`. */\n readonly dir: string;\n readonly manifest: ArtifactManifest;\n readonly sourceDigest: string;\n readonly envDigest: string;\n readonly outputDigest: string;\n}\n\n/** What the sandbox needs of its instance. */\nexport interface SandboxOptions {\n /** The home's real path. */\n readonly home: string;\n readonly log: Log;\n readonly redactor: Redactor;\n readonly processes: ProcessManager;\n readonly runtimeVersion: string;\n /** The worker's entry and Node arguments (`locateWorker`). */\n readonly worker: { readonly entry: string; readonly nodeArgs: readonly string[] };\n /** A version's packages for its server code (`Dependencies.runtimeModules`, D135). */\n readonly modules: (target: {\n readonly artifactId: string;\n readonly versionDir: string;\n readonly sourceDir?: string;\n }) => Promise<string>;\n /** The real secrets, read-only from server code (D138 item 1). */\n readonly secrets: Secrets;\n /** The artifact allowlist environment every worker gets (D95). */\n readonly env: Environment;\n /** The shell's built files. */\n readonly shellDir: string | undefined;\n readonly revisions: readonly string[];\n /** The render mode's server bundle of a version directory (D19 seam 5). */\n readonly serverEntry: (dir: string) => string | undefined;\n /** What is wrong with a version directory's files, or `undefined`. */\n readonly damage: (dir: string) => Promise<string | undefined>;\n}\n\n/** A running sandbox. */\nexport interface Sandbox {\n /** A fresh capability link to a version the sandbox serves: one per render, like a viewer's. */\n link(versionId: string): string;\n /** The shell's origin, for the health check. */\n readonly shellOrigin: string;\n /** The server functions it refused, in order (D55). */\n readonly skipped: ReadonlySet<string>;\n /** The live sources whose producers failed, with their messages. */\n liveFailures(): { readonly key: string; readonly message: string; readonly code?: string }[];\n /**\n * The workers that crashed, couldn't start, ran out of memory or hung, by version: a definite\n * failure of server code even when the page handled the failed call (Opus review finding 4).\n */\n crashes(): readonly {\n readonly versionId: string;\n readonly kind: string;\n readonly cause: string;\n }[];\n /**\n * `mostra dev` only (D140 item 12): the candidate's server bundle changed in place; its worker\n * stops so the next call loads the new bundle.\n */\n replaceServer(): Promise<void>;\n /** Hears every submission made in the sandbox, with its Results (D140 item 12). */\n onSubmission(listener: (results: Results) => void): () => void;\n /** Stops everything and deletes the run's directory. */\n close(): Promise<void>;\n}\n\n/** The directory every run's sandbox lives in. */\nexport const sandboxRoot = (home: string): string => join(home, \"cache\", \"verify\", \"runs\");\n\n/** Removes the sandboxes a stopped instance left (D138 item 1); call it before any run starts. */\nexport async function recoverSandboxes(home: string, log: Log): Promise<void> {\n const root = sandboxRoot(home);\n let left: string[];\n try {\n left = await readdir(root);\n } catch {\n return;\n }\n for (const name of left) await rm(join(root, name), { recursive: true, force: true });\n if (left.length > 0) log.info(\"verify.sandboxes_removed\", { count: left.length });\n}\n\n/** The server functions of a version that check `dryRun()` (`registry.json`, D55). */\nexport function dryRunFunctions(dir: string): ReadonlySet<string> {\n try {\n const registry = JSON.parse(readFileSync(join(dir, \"registry.json\"), \"utf8\")) as {\n readonly actions?: readonly { readonly id?: unknown; readonly dryRun?: unknown }[];\n };\n return new Set(\n (registry.actions ?? [])\n .filter((entry) => entry.dryRun === true && typeof entry.id === \"string\")\n .map((entry) => entry.id as string),\n );\n } catch {\n return new Set();\n }\n}\n\n/**\n * Starts a sandbox serving `versions` of `artifactId` (the baseline first, if any, then the\n * candidate), whose server code runs from `sourceDir` when it exists.\n */\nexport async function startSandbox(\n options: SandboxOptions,\n input: {\n readonly artifactId: string;\n readonly versions: readonly SandboxVersion[];\n readonly sourceDir?: string;\n /** The run's directory; default a new one in {@link sandboxRoot}. */\n readonly runDir?: string;\n /**\n * A `mostra dev` session's sandbox (D140 item 12) instead of a verify run's: the artifact\n * origin serves the session's Vite server (`upstream`), pages run as live pages, and actions\n * run for real with the real secrets. Nothing is delivered to hosts or ports either way.\n */\n readonly dev?: { readonly upstream: () => DevUpstream | undefined };\n /** The shell's port, instead of one the operating system assigns (`mostra dev --port`). */\n readonly shellPort?: number;\n },\n): Promise<Sandbox> {\n const { log } = options;\n const runDir = input.runDir ?? join(sandboxRoot(options.home), RunId.create());\n await mkdir(runDir, { recursive: true, mode: 0o700 });\n const opening = openLedger({\n storeDir: join(runDir, \"store\"),\n runtimeVersion: options.runtimeVersion,\n owner: { pid: process.pid, startTime: `verify-${Date.now()}` },\n log,\n });\n if (!opening.ok) throw new Error(\"A verify sandbox's scratch ledger was locked.\");\n const ledger = opening.ledger;\n // Stops run last-pushed first: everything else, then the ledger, then the directory, so the\n // scratch ledger closes (and checkpoints) before its files are removed.\n const stops: (() => Promise<void> | void)[] = [\n () => rm(runDir, { recursive: true, force: true }),\n () => ledger.close(),\n ];\n const close = async (): Promise<void> => {\n for (const stop of stops.splice(0).reverse()) {\n try {\n await stop();\n } catch (error) {\n log.warn(\"verify.sandbox_stop_failed\", { error });\n }\n }\n };\n try {\n const registry = await openRegistry({ home: runDir, ledger });\n const dirs = new Map<string, string>();\n const numbers = new Map<string, number>();\n for (const version of input.versions) {\n dirs.set(version.versionId, version.dir);\n const committed = registry.commit({\n artifactId: input.artifactId,\n bindingPath: `verify:${input.artifactId}`,\n manifestId: undefined,\n versionId: version.versionId,\n sourceDigest: version.sourceDigest,\n envDigest: version.envDigest,\n outputDigest: version.outputDigest,\n manifest: version.manifest,\n policy: undefined,\n forcedCodes: [],\n stillClaims: () => false,\n });\n numbers.set(version.versionId, committed.version);\n }\n const dirOf = (versionId: string): string => {\n const dir = dirs.get(versionId);\n if (!dir) throw new Error(`The verify sandbox serves no version ${versionId}.`);\n return dir;\n };\n const candidate = input.versions.at(-1);\n if (!candidate) throw new Error(\"A verify sandbox needs a version.\");\n\n const addressing = createAddressing({\n ledger,\n log,\n bind: { address: \"127.0.0.1\" },\n ephemeral: true,\n ...(input.shellPort !== undefined ? { shellPort: input.shellPort } : {}),\n });\n const capabilities = new Capabilities({\n ledger,\n log,\n key: randomBytes(32),\n now: () => Date.now(),\n shellOrigin: () => gateway.shellOrigin(),\n });\n const interaction = createInteraction({\n ledger,\n log,\n faults: noFaults,\n // No host is reached from a sandbox: nothing is delivered, mirrored or asked (D138 item 1).\n hosts: {\n registrants: () => [],\n call: () => Promise.reject(new Error(\"A verify sandbox calls no host.\")),\n notify: () => false,\n drained: () => undefined,\n },\n expectedHosts: () => [],\n artifacts: { resolve: (ref) => registry.get(ref).id },\n coverage: (versionId) => coverageMatcher(readFieldCoverage(dirOf(versionId))),\n });\n stops.push(() => interaction.stop());\n const bus = createEphemeralBus();\n stops.push(() => bus.close());\n\n const optIns = new Map<string, ReadonlySet<string>>();\n const skipped = new Set<string>();\n const crashes: { versionId: string; kind: string; cause: string }[] = [];\n const workerVersion = (versionId: string): WorkerVersion | undefined => {\n const dir = dirs.get(versionId);\n const version = input.versions.find((entry) => entry.versionId === versionId);\n const served = dir ? options.serverEntry(dir) : undefined;\n if (!dir || !version || served === undefined) return undefined;\n return {\n artifactId: input.artifactId,\n ref: {\n versionId,\n outputDigest: version.outputDigest,\n locator: `home:${relative(options.home, dir)}`,\n },\n entry: relative(dir, served),\n limits: workerLimits(version.manifest),\n functions: readServerFunctions(dir),\n ...(input.sourceDir ? { sourceDir: input.sourceDir } : {}),\n };\n };\n const pool = createWorkerPool({\n launcher: localLauncher({\n processes: options.processes,\n home: options.home,\n workerEntry: options.worker.entry,\n nodeArgs: options.worker.nodeArgs,\n modules: options.modules,\n }),\n log,\n env: options.env,\n bridge: {\n request: (worker, method, params, call) =>\n actions.bridge.request(worker, method, params, call),\n log: (worker, line) => actions.bridge.log(worker, line),\n liveValue: (worker, params) => live.produced(worker, params),\n },\n onCrash: (crash) => {\n if (crashes.length < 20)\n crashes.push({ versionId: crash.versionId, kind: crash.kind, cause: crash.cause });\n actions.crashed(crash);\n live.crashed(crash);\n interaction.workerCrashed(crash);\n },\n });\n stops.push(() => pool.stopAll());\n const actions = createActions({\n interaction,\n pool,\n bus,\n secrets: options.secrets,\n redactor: options.redactor,\n log,\n version: workerVersion,\n // In dev, the developer's own code runs for real on their own machine, as any dev server's\n // does (D140 item 12); in verify, only what opted into dryRun() runs (D55).\n ...(input.dev\n ? {}\n : {\n dryRun: {\n optedIn: (versionId: string, fnId: string) => {\n let opted = optIns.get(versionId);\n if (!opted) {\n opted = dryRunFunctions(dirOf(versionId));\n optIns.set(versionId, opted);\n }\n return opted.has(fnId);\n },\n skipped: (fnId: string) => {\n skipped.add(fnId);\n },\n },\n }),\n });\n // A dev session's server code builds again, and its sources with it (D140 item 12).\n let sources = readLiveSources(candidate.dir);\n const live = createLive({\n ledger,\n log,\n bus,\n pool,\n interaction,\n // Every render of the run reads the candidate's producers, so the baseline and the\n // candidate show the same data (D138 item 4).\n latest: (artifactId) =>\n artifactId === input.artifactId && sources.length > 0\n ? { versionId: candidate.versionId, sources }\n : undefined,\n artifactsWithLive: () => (sources.length > 0 ? [input.artifactId] : []),\n version: workerVersion,\n redactor: options.redactor,\n });\n stops.push(() => live.stop());\n\n const gateway = createGateway({\n ledger,\n log,\n addressing,\n capabilities,\n artifacts: {\n get: (ref) => registry.get(ref),\n versionDir: dirOf,\n damage: (versionId) => options.damage(dirOf(versionId)),\n },\n shellDir: options.shellDir,\n interaction,\n // Both channels, every control: the page behaves as it would for a viewer of the standalone\n // host, and the artifact's own Submit is exercised in the sandbox.\n controls: async () => ({ submitChannels: [\"shell\", \"artifact\"] }),\n activated: () => undefined,\n revisions: options.revisions,\n actions,\n live,\n bus,\n parked: () => false,\n ...(input.dev ? { target: \"live\" as const, dev: input.dev } : { target: \"verify\" as const }),\n });\n await gateway.start();\n stops.push(() => gateway.close());\n\n return {\n shellOrigin: gateway.shellOrigin(),\n link: (versionId) =>\n gateway.link({\n artifactId: input.artifactId,\n version: numbers.get(versionId) as number,\n }),\n skipped,\n crashes: () => [...crashes],\n replaceServer: async () => {\n const version = workerVersion(candidate.versionId);\n if (version) await pool.replace(version);\n sources = readLiveSources(candidate.dir);\n live.replaced(candidate.versionId);\n },\n onSubmission: (listener) => interaction.onSubmission(listener),\n liveFailures: () =>\n live.failures(input.artifactId).map(({ key, error }) => ({\n key,\n message: error.message,\n ...(error.code !== undefined ? { code: error.code } : {}),\n })),\n close,\n };\n } catch (error) {\n await close();\n throw error;\n }\n}\n","/**\n * The type check (D138 item 8, as D139 amends it): TypeScript 7 `tsc --noEmit` over an artifact's snapshot, in a\n * child the process manager starts and records, beside the build and inside its 180 s. Imports\n * resolve as the build resolves them: the same `node_modules` layout (the warm set or the lock\n * layout), `@/*` at the snapshot's root, `@mostra/react`'s and `@mostra/server`'s types and the\n * generated live-source declaration. It judges what the build compiles: the build's compile\n * settings first, the artifact's own `tsconfig.json` over them, then the options Mostra forces;\n * imports are declared by Vite's own client types. MDX isn't checked.\n *\n * The check runs in a directory of its own (a copy of the snapshot with the layout linked beside\n * it), so it never races the builder, which links its own `node_modules` into the staging root.\n */\nimport { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { cp, mkdir, rm, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { createDiagnostic, type Diagnostic } from \"@mostra/protocol\";\nimport { LIVE_DECLARATION } from \"../builder/index.ts\";\nimport { runtimeRoot } from \"../deps/index.ts\";\nimport type { Environment, Log } from \"../log.ts\";\nimport { linkDirectory } from \"../platform/index.ts\";\nimport type { ProcessManager } from \"../processes/index.ts\";\n\n/** How long the check may take: the build's own limit, which it runs beside (FAILURE_MODEL §9). */\nexport const TYPECHECK_TIMEOUT_MS = 180_000;\n\n/**\n * How the build compiles, which every check starts from, under an artifact's own `tsconfig.json`\n * too: its options override these (Opus review finding 2: without them a `tsconfig.json` that\n * sets only `strict` failed every JSX file the build compiles).\n */\nconst BUILD_OPTIONS = {\n target: \"ES2022\",\n lib: [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n jsx: \"react-jsx\",\n module: \"ESNext\",\n isolatedModules: true,\n allowImportingTsExtensions: true,\n resolveJsonModule: true,\n allowJs: true,\n checkJs: false,\n // Server code runs in Node (D18): its modules see Node's types.\n types: [\"node\"],\n};\n\n/** What an artifact without a `tsconfig.json` is checked with besides (D138 item 8). */\nconst DEFAULT_OPTIONS = {\n strict: true,\n noUnusedLocals: false,\n noUnusedParameters: false,\n};\n\n/**\n * The options Mostra's check always sets, over an artifact's own `tsconfig.json` too. `baseUrl`\n * is cleared: the build doesn't use it and TypeScript 7 refuses it (TS5102), so a configuration\n * copied from a TypeScript 5 project (shadcn's Vite setup has one) checks like the build builds.\n */\nconst FORCED_OPTIONS = {\n noEmit: true,\n skipLibCheck: true,\n // The build is a bundler: it resolves and emits modules as one, whatever `module` says.\n module: \"ESNext\",\n moduleResolution: \"bundler\",\n baseUrl: null,\n paths: { \"@/*\": [\"./source/*\"] },\n};\n\n/** Vite's own declarations of what imports are (assets, CSS modules, `?raw`, `import.meta`). */\nfunction viteClientTypes(): { readonly path: string; readonly version: string } | undefined {\n try {\n const require = createRequire(import.meta.url);\n const manifest = require.resolve(\"vite/package.json\");\n const version = (JSON.parse(readFileSync(manifest, \"utf8\")) as { version: string }).version;\n const path = join(dirname(manifest), \"client.d.ts\");\n return existsSync(path) ? { path, version } : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * What the files a build bundles are, for the checker: Vite's own client declarations for the\n * pinned release (every asset type, CSS modules as class maps, `?raw`, `?url`, `?inline`,\n * `?worker`, `import.meta.env`, `.glob` and `.hot`; Opus review finding 2), and MDX, which\n * Mostra's build adds.\n */\nconst VITE_CLIENT = viteClientTypes();\nconst AMBIENT = `// Written by Mostra for verify's type check (D138): what the build's imports are.\n${VITE_CLIENT ? `/// <reference path=${JSON.stringify(VITE_CLIENT.path)} />\\n` : \"\"}declare module \"*.mdx\" {\n const Content: (props: Record<string, unknown>) => unknown;\n export default Content;\n export const frontmatter: Record<string, unknown>;\n}\n`;\n\n/**\n * The check configuration's revision: its text, so a change to what verify checks never reuses a\n * verdict made under the old rules (D138 items 5 and 8).\n */\nexport const TYPECHECK_REVISION: string = createHash(\"sha256\")\n .update(\n JSON.stringify({\n BUILD_OPTIONS,\n DEFAULT_OPTIONS,\n FORCED_OPTIONS,\n // The declarations' text without this machine's path to them.\n AMBIENT: AMBIENT.replace(VITE_CLIENT?.path ?? \"\\u0000\", \"vite/client.d.ts\"),\n vite: VITE_CLIENT?.version ?? null,\n revision: 2,\n }),\n )\n .digest(\"hex\");\n\n/** Where TypeScript 7's `tsc` is. */\nfunction tscPath(): string {\n const require = createRequire(import.meta.url);\n return join(dirname(require.resolve(\"typescript/package.json\")), \"bin\", \"tsc\");\n}\n\n/** One line of `tsc --pretty false`: `file(line,col): error TS1234: message`. */\nconst LINE = /^(.+?)\\((\\d+),(\\d+)\\): error (TS\\d+): (.*)$/;\n/** A diagnostic without a file: `error TS5023: Unknown compiler option …`. */\nconst GLOBAL = /^error (TS\\d+): (.*)$/;\n/** The configuration files of a check: Mostra's, which extends the artifact's own. */\nconst CONFIG_FILES = new Set([\n \"tsconfig.verify.json\",\n \".mostra-check/build.json\",\n \"source/tsconfig.json\",\n]);\n\n/** What the check found. */\nexport interface TypecheckOutcome {\n readonly diagnostics: readonly Diagnostic[];\n}\n\n/**\n * Turns `tsc`'s output into diagnostics: errors in the artifact's own files only, TS7016 as an\n * untyped package (a warning), and a TS2307 for an import `alreadyReported` names dropped.\n */\nexport function parseTscOutput(\n lines: readonly string[],\n alreadyReported: (specifier: string) => boolean,\n /** Whether the artifact has its own `tsconfig.json`, which Mostra's configuration extends. */\n ownConfig = false,\n): Diagnostic[] {\n const found: { file: string; line: number; column: number; code: string; text: string }[] = [];\n for (const line of lines) {\n const match = LINE.exec(line);\n const global = match ? undefined : GLOBAL.exec(line);\n if (global) {\n found.push({\n file: \"\",\n line: 1,\n column: 1,\n code: global[1] as string,\n text: global[2] as string,\n });\n } else if (match) {\n found.push({\n file: match[1] as string,\n line: Number(match[2]),\n column: Number(match[3]),\n code: match[4] as string,\n text: match[5] as string,\n });\n } else if (/^\\s+\\S/.test(line) && found.length > 0) {\n const last = found[found.length - 1] as (typeof found)[number];\n if (last.text.length < 1500) last.text = `${last.text}\\n${line.trim()}`;\n }\n }\n const diagnostics: Diagnostic[] = [];\n for (const entry of found) {\n const file = entry.file.replace(/\\\\/g, \"/\");\n // A configuration the compiler refuses means the source was never checked: an error, never\n // a pass (it is the artifact's `tsconfig.json` against how Mostra builds, D138 item 8).\n if (file === \"\" || CONFIG_FILES.has(file)) {\n diagnostics.push(\n createDiagnostic(\"MOSTRA_TYPE_ERROR\", {\n message: `The type check couldn't run with the artifact's tsconfig.json and Mostra's build settings (noEmit, skipLibCheck, moduleResolution \"bundler\", the @/* path): ${entry.code}: ${entry.text}`,\n // The compiler reports options it inherits against the file that extends them, so an\n // artifact with its own configuration is pointed at it.\n ...(file === \"source/tsconfig.json\"\n ? { location: { file: \"tsconfig.json\", line: entry.line, column: entry.column } }\n : ownConfig\n ? { location: { file: \"tsconfig.json\", line: 1, column: 1 } }\n : {}),\n }),\n );\n continue;\n }\n if (!file.startsWith(\"source/\") || file.includes(\"/node_modules/\")) continue;\n const location = { file: file.slice(\"source/\".length), line: entry.line, column: entry.column };\n if (entry.code === \"TS7016\") {\n diagnostics.push(\n createDiagnostic(\"MOSTRA_TYPE_UNTYPED_PACKAGE\", {\n message: `${entry.text} (${entry.code})`,\n location,\n }),\n );\n continue;\n }\n if (entry.code === \"TS2307\") {\n const specifier = /'([^']+)'/.exec(entry.text)?.[1];\n if (specifier !== undefined && alreadyReported(specifier)) continue;\n }\n diagnostics.push(\n createDiagnostic(\"MOSTRA_TYPE_ERROR\", {\n message: `${entry.code}: ${entry.text}`,\n location,\n }),\n );\n }\n return diagnostics;\n}\n\n/** Where `@mostra/server`'s declarations are: the worker provides the package, so no layout has it (D129). */\nfunction serverTypes(): string | undefined {\n const root = runtimeRoot();\n for (const candidate of [\n join(root, \"..\", \"server\", \"dist\", \"index.d.ts\"),\n join(root, \"..\", \"server\", \"src\", \"index.ts\"),\n ]) {\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\n/** Runs the type check of the snapshot in `sourceDir` against `nodeModules`. */\nexport async function typecheck(options: {\n readonly processes: ProcessManager;\n readonly log: Log;\n readonly env: Environment;\n /** The snapshot (staging's `source/`). */\n readonly sourceDir: string;\n /** A fresh directory the check may use, removed afterwards. */\n readonly workDir: string;\n /** The layout the build links: the warm set or the artifact's lock layout. */\n readonly nodeModules: string;\n /** Whether the artifact has `live.ts` (D56). */\n readonly hasLive: boolean;\n /** Whether a TS2307 for this import repeats what the build or dependency stage said. */\n readonly alreadyReported: (specifier: string) => boolean;\n readonly timeoutMs?: number;\n}): Promise<TypecheckOutcome> {\n const { workDir } = options;\n await rm(workDir, { recursive: true, force: true });\n await mkdir(join(workDir, \".mostra-check\"), { recursive: true });\n try {\n await cp(options.sourceDir, join(workDir, \"source\"), { recursive: true });\n await linkDirectory(options.nodeModules, join(workDir, \"node_modules\"));\n await writeFile(join(workDir, \".mostra-check\", \"assets.d.ts\"), AMBIENT);\n if (options.hasLive)\n await writeFile(join(workDir, \".mostra-check\", \"mostra-env.d.ts\"), LIVE_DECLARATION);\n const own = existsSync(join(workDir, \"source\", \"tsconfig.json\"));\n const server = serverTypes();\n const forced = {\n ...FORCED_OPTIONS,\n paths: { ...FORCED_OPTIONS.paths, ...(server ? { \"@mostra/server\": [server] } : {}) },\n };\n // The build's options first, the artifact's own configuration over them, Mostra's forced\n // ones last (an `extends` array applies in order).\n await writeFile(\n join(workDir, \".mostra-check\", \"build.json\"),\n `${JSON.stringify({ compilerOptions: own ? BUILD_OPTIONS : { ...BUILD_OPTIONS, ...DEFAULT_OPTIONS } }, null, 2)}\\n`,\n );\n const config = {\n extends: own\n ? [\"./.mostra-check/build.json\", \"./source/tsconfig.json\"]\n : \"./.mostra-check/build.json\",\n compilerOptions: forced,\n include: [\"source/**/*.ts\", \"source/**/*.tsx\", \".mostra-check/*.d.ts\"],\n exclude: [\"source/**/node_modules\"],\n };\n await writeFile(join(workDir, \"tsconfig.verify.json\"), `${JSON.stringify(config, null, 2)}\\n`);\n const lines: string[] = [];\n const child = await options.processes.spawn({\n kind: \"typecheck\",\n ownerRef: workDir,\n command: process.execPath,\n args: [tscPath(), \"-p\", \"tsconfig.verify.json\", \"--noEmit\", \"--pretty\", \"false\"],\n cwd: workDir,\n env: {\n PATH: options.env[\"PATH\"] ?? \"/usr/bin:/bin\",\n HOME: options.env[\"HOME\"] ?? \"/\",\n ...(options.env[\"TMPDIR\"] ? { TMPDIR: options.env[\"TMPDIR\"] } : {}),\n },\n onStdout: (line) => {\n if (lines.length < 5000) lines.push(line);\n },\n });\n const timeoutMs = options.timeoutMs ?? TYPECHECK_TIMEOUT_MS;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const exit = await Promise.race([\n child.exited,\n new Promise<\"timeout\">((done) => {\n timer = setTimeout(() => done(\"timeout\"), timeoutMs);\n }),\n ]);\n if (timer) clearTimeout(timer);\n if (exit === \"timeout\") {\n await child.stop(2000);\n options.log.warn(\"verify.typecheck_timeout\", { timeoutMs });\n return {\n diagnostics: [\n createDiagnostic(\"MOSTRA_VERIFY_TIMEOUT\", {\n message: `The type check took longer than ${Math.round(timeoutMs / 1000)} s and was stopped.`,\n }),\n ],\n };\n }\n const diagnostics = parseTscOutput(lines, options.alreadyReported, own);\n return { diagnostics: [...diagnostics, ...unexplainedExit(exit, lines, diagnostics)] };\n } finally {\n await rm(workDir, { recursive: true, force: true });\n }\n}\n\n/** Whether the build's diagnostics already name a module the type check couldn't find. */\nexport function reportedByBuild(diagnostics: readonly Diagnostic[], specifier: string): boolean {\n return diagnostics.some(\n (diagnostic) =>\n diagnostic.message.includes(`\"${specifier}\"`) ||\n diagnostic.message.includes(`'${specifier}'`) ||\n diagnostic.message.includes(`\\`${specifier}\\``),\n );\n}\n\n/**\n * What a `tsc` exit says beyond the diagnostics it printed: a signal is a crash of the checker\n * (never cached), and a failing exit with no error found means the source wasn't checked, which\n * fails closed (an error) instead of passing.\n */\nexport function unexplainedExit(\n exit: {\n readonly code: number | null;\n readonly signal: string | null;\n readonly stderrTail: readonly string[];\n },\n lines: readonly string[],\n found: readonly Diagnostic[],\n): Diagnostic[] {\n const tail = [...lines, ...exit.stderrTail]\n .filter((line) => line.trim() !== \"\")\n .slice(-6)\n .join(\"\\n\");\n if (exit.signal !== null) {\n return [\n createDiagnostic(\"MOSTRA_VERIFY_CRASHED\", {\n message: `The type checker stopped (${exit.signal}) before it finished.${tail ? `\\n${tail}` : \"\"}`,\n }),\n ];\n }\n // An exit is explained by any error `tsc` printed in its own format, whatever the check made of\n // it: TS7016 becomes the warning MOSTRA_TYPE_UNTYPED_PACKAGE, a TS2307 the build already\n // reported is dropped, and errors outside the artifact's own files are dropped (D138 item 8).\n // Requiring an error-severity diagnostic instead failed every artifact that imports an untyped\n // package (found by WP-11's bundle smoke test, an on-demand `ms`).\n const printedErrors = lines.some((line) => LINE.test(line) || GLOBAL.test(line));\n if (\n exit.code !== 0 &&\n !printedErrors &&\n !found.some((diagnostic) => diagnostic.severity === \"error\")\n ) {\n return [\n createDiagnostic(\"MOSTRA_TYPE_ERROR\", {\n message: `The type check exited with code ${exit.code} without checking the source${tail ? `:\\n${tail}` : \".\"}`,\n }),\n ];\n }\n return [];\n}\n","/**\n * The supervisor's side of the verify runner (ARCHITECTURE §1, FAILURE_MODEL §2): one runner child\n * at a time, started through the process manager on the first render and kept while it lives (it\n * exits by itself after 10 idle minutes, closing its warm Chromium). A runner that dies during a\n * request fails it with `MOSTRA_VERIFY_CRASHED` and its last lines; the next request starts a\n * fresh one. The supervisor never loads Playwright (RT-02).\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport {\n BUNDLE_NAME,\n type CompareRequest,\n type CompareResult,\n createDiagnostic,\n type RenderRequest,\n type RenderResult,\n RpcError,\n VERIFY_RUNNER_METHODS,\n} from \"@mostra/protocol\";\nimport type { Environment, Log } from \"../log.ts\";\nimport type { ChildHandle, ProcessManager } from \"../processes/index.ts\";\n\n/** Where the runner child is and where its browser lives. */\nexport interface RunnerLocation {\n readonly entry: string;\n readonly nodeArgs: readonly string[];\n /**\n * The runtime bundle's own browsers (`<bundle>/browsers`, D142), when this runtime runs from a\n * bundle: the runner uses exactly the browser the bundle's setup fetched and checked, whatever\n * `PLAYWRIGHT_BROWSERS_PATH` the environment names.\n */\n readonly browsers?: string;\n}\n\n/** The runtime bundle this runtime sits in (four levels above its package), if any. */\nexport function enclosingBundle(runtimeRoot: string): string | undefined {\n const root = resolve(runtimeRoot, \"..\", \"..\", \"..\", \"..\");\n try {\n const info = JSON.parse(readFileSync(join(root, \"bundle.json\"), \"utf8\")) as { name?: unknown };\n return info.name === BUNDLE_NAME ? root : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The runner child's entry and Node arguments: `MOSTRA_VERIFY_ENTRY`, else beside the runtime. */\nexport function locateRunner(env: Environment, runtimeRoot: string): RunnerLocation {\n const bundle = enclosingBundle(runtimeRoot);\n const browsers = bundle !== undefined ? { browsers: join(bundle, \"browsers\") } : {};\n const override = env[\"MOSTRA_VERIFY_ENTRY\"];\n if (override) return { entry: override, nodeArgs: [], ...browsers };\n const fromSource = import.meta.url.endsWith(\".ts\");\n const built = resolve(runtimeRoot, \"..\", \"verify\", \"dist\", \"main.js\");\n if (!fromSource || existsSync(built)) return { entry: built, nodeArgs: [], ...browsers };\n return {\n entry: resolve(runtimeRoot, \"..\", \"verify\", \"src\", \"main.ts\"),\n nodeArgs: [\"--conditions=@mostra/source\"],\n ...browsers,\n };\n}\n\n/**\n * How long past its deadline a runner may take to answer: the runner abandons a render 1 s past\n * its deadline itself (closing that render's context, which ends a page that blocks its main\n * thread), so only a runner this late is stuck as a whole and is stopped.\n */\nconst OVERDUE_GRACE_MS = 8_000;\n\n/** The runner as the verify pipeline uses it. */\nexport interface RunnerClient {\n /**\n * Renders one link. A runner that hasn't answered shortly after `request.deadline` (a page whose\n * code blocks the browser, say) is stopped, browser and all, and the call fails with\n * `MOSTRA_VERIFY_TIMEOUT` (FAILURE_MODEL §9).\n */\n render(request: RenderRequest): Promise<RenderResult>;\n /** Compares two screenshots, bounded by `deadline` like a render. */\n compare(request: CompareRequest, deadline: number): Promise<CompareResult>;\n /** Stops the runner child, if one runs. */\n close(): Promise<void>;\n}\n\n/** The variables the runner child gets: where Playwright's browsers are, and nothing secret. */\nexport function runnerEnvironment(env: Environment, browsers?: string): Environment {\n const keep = [\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"LANG\",\n \"LC_ALL\",\n \"TZ\",\n \"PLAYWRIGHT_BROWSERS_PATH\",\n \"XDG_CACHE_HOME\",\n ];\n const out: Record<string, string> = {};\n for (const name of keep) {\n const value = env[name];\n if (value !== undefined) out[name] = value;\n }\n if (browsers !== undefined) out[\"PLAYWRIGHT_BROWSERS_PATH\"] = browsers;\n const idle = env[\"MOSTRA_TEST_VERIFY_IDLE_MS\"];\n if (idle) out[\"MOSTRA_TEST_VERIFY_IDLE_MS\"] = idle;\n return out;\n}\n\n/** Creates the client; nothing starts until the first request. */\nexport function createRunnerClient(options: {\n readonly processes: ProcessManager;\n readonly log: Log;\n readonly env: Environment;\n readonly entry: string;\n readonly nodeArgs: readonly string[];\n /** The bundle's browsers directory, when the runtime runs from a bundle. */\n readonly browsers?: string | undefined;\n}): RunnerClient {\n let child: Promise<ChildHandle> | undefined;\n\n const start = (): Promise<ChildHandle> => {\n child ??= options.processes\n .spawn({\n kind: \"verify\",\n ownerRef: \"verify-runner\",\n command: process.execPath,\n args: [...options.nodeArgs, options.entry],\n env: runnerEnvironment(options.env, options.browsers),\n ipc: {},\n })\n .then((handle) => {\n void handle.exited.then((exit) => {\n options.log.info(\"verify.runner_exited\", { code: exit.code, signal: exit.signal });\n if (child) {\n void child.then((current) => {\n if (current === handle) child = undefined;\n });\n }\n });\n return handle;\n })\n .catch((error: unknown) => {\n child = undefined;\n throw error;\n });\n return child;\n };\n\n /** Runners this client stopped because a run was overdue: the others' renders are retried. */\n const recycled = new WeakSet<object>();\n\n const ask = async (\n method: string,\n params: object,\n deadline: number,\n retried = false,\n ): Promise<unknown> => {\n const handle = await start();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const overdue = new Promise<{ kind: \"overdue\" }>((done) => {\n timer = setTimeout(\n () => done({ kind: \"overdue\" }),\n Math.max(0, deadline - Date.now()) + OVERDUE_GRACE_MS,\n );\n });\n const outcome = await Promise.race([\n handle.request(method, params as Record<string, unknown>).then(\n (result) => ({ kind: \"result\" as const, result }),\n (error: unknown) => ({ kind: \"error\" as const, error }),\n ),\n handle.exited.then((exit) => ({ kind: \"exit\" as const, exit })),\n overdue,\n ]).finally(() => clearTimeout(timer));\n if (outcome.kind === \"result\") return outcome.result;\n if (outcome.kind === \"overdue\") {\n // The runner is stuck (artifact code blocking the page's main thread keeps every browser\n // call waiting): stop it and its browser; the next run starts a fresh one.\n options.log.warn(\"verify.runner_overdue\", { method });\n if (child) {\n const stuck = child;\n child = undefined;\n const stopped = await stuck.catch(() => undefined);\n if (stopped) recycled.add(stopped);\n await stopped?.stop(2000);\n }\n throw new RpcError(\n createDiagnostic(\"MOSTRA_VERIFY_TIMEOUT\", {\n message:\n \"Verify ran out of time: the browser stopped answering while it checked the page.\",\n }),\n );\n }\n if (outcome.kind === \"error\" && outcome.error instanceof RpcError) {\n // The runner answered with a diagnostic of its own (no browser, say): it stands. A closed\n // channel or an internal error means the runner itself failed, reported as a crash.\n const code = outcome.error.diagnostic.code;\n if (code !== \"MOSTRA_HOST_INTERNAL_ERROR\" && !code.startsWith(\"MOSTRA_HOST_CONNECTION\"))\n throw outcome.error;\n }\n // Another run's recovery stopped the runner under this request: it isn't this page's fault,\n // so the request runs once more on a fresh runner (Opus review finding 5). The retry keeps the\n // request's deadline, so one cut off with no time left ends as a timeout, never as a crash.\n if (recycled.has(handle) && !retried) {\n options.log.info(\"verify.runner_retry\", { method });\n return ask(method, params, deadline, true);\n }\n const exit =\n outcome.kind === \"exit\"\n ? outcome.exit\n : await Promise.race([\n handle.exited,\n new Promise<undefined>((done) => setTimeout(() => done(undefined), 1000)),\n ]);\n const tail = exit?.stderrTail.slice(-10).join(\"\\n\") ?? \"\";\n throw new RpcError(\n createDiagnostic(\"MOSTRA_VERIFY_CRASHED\", {\n message: `The verify runner stopped before it answered${exit ? ` (${exit.signal ?? `code ${exit.code}`})` : \"\"}.${tail ? `\\n${tail}` : \"\"}`,\n }),\n );\n };\n\n return {\n render: (request) =>\n ask(VERIFY_RUNNER_METHODS.render, request, request.deadline) as Promise<RenderResult>,\n compare: (request, deadline) =>\n ask(VERIFY_RUNNER_METHODS.compare, request, deadline) as Promise<CompareResult>,\n async close() {\n const running = child;\n child = undefined;\n if (running) await (await running.catch(() => undefined))?.stop(2000);\n },\n };\n}\n","/**\n * `verify` (D29, D41, D55, D72, D138; ARCHITECTURE §12, INTERFACES §13): one run over a prepared\n * source, giving one verdict. The stages, in order:\n *\n * 1. **compile**: the build (into `cache/builds/<versionId>/`, which publish promotes) and the type\n * check beside it, inside the build's 180 s. A source that didn't build stops here.\n * 2. **lint**: the static field-ID scan.\n * 3. **boot**: a sandbox (`sandbox.ts`) serving the build and the last passing version.\n * 4. **render**: each viewport of the baseline, then of the source, in the warm browser; a second\n * boot for changing field IDs; the smoke test. 120 s cover stages 3 to 5 (FAILURE_MODEL §9).\n * 5. **regression**: contracts, ARIA and pixels against the baseline.\n *\n * The verdict is cached by source digest, environment digest and {@link VERIFY_REVISION}, unless an\n * error says the run couldn't vouch for the page (the environment, a timeout, a crash): publish\n * reuses it for the same digests (D41).\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { mkdir, readdir, rm, stat, utimes, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n type ArtifactManifest,\n ariaSummary,\n createDiagnostic,\n type Diagnostic,\n estimateImageTokens,\n type ProbedField,\n type RenderRequest,\n type RenderResult,\n RpcError,\n type ScreenshotPolicy,\n type VerdictAria,\n type VerdictScreenshot,\n VerifyVerdict,\n type VerifyViewport,\n viewportsFor,\n} from \"@mostra/protocol\";\nimport type { VersionRegistry } from \"../builder/index.ts\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Log, Redactor } from \"../log.ts\";\nimport type { Registry } from \"../registry/index.ts\";\nimport { probedFieldLint, staticFieldLint, unstableFieldLint } from \"./fields.ts\";\nimport { ariaRegression, contractRegressions, pixelRegression } from \"./regression.ts\";\nimport type { RunnerClient } from \"./runner.ts\";\nimport {\n recoverSandboxes,\n type Sandbox,\n type SandboxOptions,\n type SandboxVersion,\n sandboxRoot,\n startSandbox,\n} from \"./sandbox.ts\";\nimport { reportedByBuild, TYPECHECK_REVISION, typecheck } from \"./typecheck.ts\";\n\nexport { createRunnerClient, locateRunner, type RunnerClient } from \"./runner.ts\";\nexport {\n type Sandbox,\n type SandboxOptions,\n startSandbox,\n} from \"./sandbox.ts\";\n\nimport { renamePath } from \"../platform/index.ts\";\n\n/** The revision of verify's rules: a cached verdict made under other rules is never reused. */\nexport const VERIFY_REVISION: string = createHash(\"sha256\")\n .update(`verify 2 ${TYPECHECK_REVISION}`)\n .digest(\"hex\")\n .slice(0, 16);\n\n/** How long the stages after compile may take (FAILURE_MODEL §9, D138 item 6). */\nexport const VERIFY_TIMEOUT_MS = 120_000;\n/** The smoke test's budget (ROUND-3 §9). */\nexport const SMOKE_BUDGET = { maxInteractions: 200, maxMs: 60_000 } as const;\n/** The build cache's cap (D47): least recently used builds go first. */\nconst BUILD_CACHE_BYTES = 5 * 1024 ** 3;\n/** How many verdicts the cache keeps. */\nconst VERDICT_CACHE_ENTRIES = 200;\n\n/** Codes that say a run couldn't vouch for the page: its verdict is never cached (D138 item 5). */\nconst UNCACHEABLE =\n /^MOSTRA_(ENV|VERIFY_TIMEOUT|VERIFY_CRASHED|BUILD_TIMEOUT|BUILD_CRASHED|DEP_OFFLINE|DEP_TIMEOUT)/;\n\n/** A source prepared for verify or publish: snapshot, manifest, dependencies and digests. */\nexport interface PreparedSource {\n /** The source path as the caller named it. */\n readonly path: string;\n /** The staging directory; the snapshot is in its `source/`. */\n readonly stagingDir: string;\n /** The artifact's source directory, where server code runs. */\n readonly sourceDir: string;\n readonly manifest: ArtifactManifest;\n /** The manifest's warnings (unknown keys). */\n readonly warnings: readonly Diagnostic[];\n /** The artifact: known (a manifest `id` or a binding) or provisional. */\n readonly artifactId: string;\n readonly identityKnown: boolean;\n readonly sourceDigest: string;\n readonly envDigest: string;\n readonly versionId: string;\n /** The `node_modules` the build links (D95). */\n readonly nodeModules: string;\n}\n\n/** A finished build in a directory, as publish lays out a version. */\nexport type BuildOutcome =\n | { readonly ok: true; readonly outputDigest: string; readonly registry: VersionRegistry }\n | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] };\n\n/** Options for {@link createVerifier}. */\nexport interface VerifierOptions {\n readonly home: string;\n readonly ledger: Ledger;\n readonly registry: Registry;\n readonly log: Log;\n readonly redactor: Redactor;\n readonly runner: RunnerClient;\n readonly sandbox: SandboxOptions;\n /** Clears the artifact's parked worker in the instance's pool (D133). */\n readonly clearPark: (artifactId: string) => void;\n /** Tests shorten the 120 s and the smoke test's 200 interactions. */\n readonly limits?: { readonly timeoutMs?: number; readonly smokeInteractions?: number };\n}\n\n/** One run's options. */\nexport interface VerifyRun {\n /** Builds the prepared source into `outDir`, laid out as a version (manifest, registry, lock). */\n readonly build: (outDir: string) => Promise<BuildOutcome>;\n readonly screenshots?: ScreenshotPolicy;\n /** Told as each stage starts. */\n readonly progress?: (stage: string) => void;\n}\n\n/** What a run found: its verdict, and whether compile produced a build (D138 item 7). */\nexport interface VerifyOutcome {\n readonly verdict: VerifyVerdict;\n /**\n * Whether the source built. `--force` never publishes a source that didn't, whatever codes its\n * verdict carries (Opus review finding 7).\n */\n readonly built: boolean;\n}\n\n/** The verifier of one instance. */\nexport interface Verifier {\n /** Runs verify; replaces the cached verdict for the same digests. */\n run(prepared: PreparedSource, run: VerifyRun): Promise<VerifyOutcome>;\n /** The cached verdict for these digests, if one was made for this artifact (or none named). */\n cached(prepared: PreparedSource): VerifyOutcome | undefined;\n /** Verify's build of a version, when the cache still holds it complete. */\n builtVersion(versionId: string): string | undefined;\n /** `cache/verify/`: the verdicts, and each verdict's screenshots, ARIA snapshots and diffs. */\n readonly cacheDir: string;\n /**\n * gc's part (D140 item 14): verify's builds past the 5 GB cap, oldest first, and screenshot\n * directories no cached verdict names. A dry run lists them; a real run removes them. The\n * caller holds the instance's gate alone, so no verify run serves a build meanwhile.\n */\n collect(dryRun: boolean): Promise<{ readonly count: number; readonly bytes: number }>;\n}\n\n/** The source's page never got ready: the browser stages after its first render can't run. */\nclass NotReady extends Error {}\n\n/** The verdict cache's key for two digests. */\nexport function verdictKey(sourceDigest: string, envDigest: string): string {\n return createHash(\"sha256\")\n .update(`${sourceDigest}\\u0000${envDigest}\\u0000${VERIFY_REVISION}`)\n .digest(\"hex\");\n}\n\nconst hasError = (diagnostics: readonly Diagnostic[]): boolean =>\n diagnostics.some((diagnostic) => diagnostic.severity === \"error\");\n\n/** The directory size, for the build cache's cap. */\nasync function sizeOf(dir: string): Promise<number> {\n let total = 0;\n for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) total += await sizeOf(path);\n else total += (await stat(path).catch(() => ({ size: 0 }))).size;\n }\n return total;\n}\n\n/**\n * Removes what a stopped instance left of verify (D138 item 1): sandboxes, builds cut off before\n * they were complete, verdicts' temporary files and the screenshot directories no verdict names\n * (Opus review finding 9). Call it before any run starts.\n */\nexport async function recoverVerify(home: string, log: Log): Promise<void> {\n await recoverSandboxes(home, log);\n const buildsDir = join(home, \"cache\", \"builds\");\n for (const name of await readdir(buildsDir).catch(() => [] as string[])) {\n if (name.includes(\".tmp-\")) await rm(join(buildsDir, name), { recursive: true, force: true });\n }\n const cacheDir = join(home, \"cache\", \"verify\");\n const entries = await readdir(cacheDir, { withFileTypes: true }).catch(() => []);\n const verdicts = new Set(\n entries.filter((entry) => entry.name.endsWith(\".json\")).map((entry) => entry.name.slice(0, -5)),\n );\n for (const entry of entries) {\n const path = join(cacheDir, entry.name);\n if (entry.name.endsWith(\".tmp\")) await rm(path, { force: true });\n else if (entry.isDirectory() && path !== sandboxRoot(home) && !verdicts.has(entry.name))\n await rm(path, { recursive: true, force: true });\n }\n}\n\n/** Creates the verifier. */\nexport function createVerifier(options: VerifierOptions): Verifier {\n const { home, log, registry } = options;\n const buildsDir = join(home, \"cache\", \"builds\");\n const cacheDir = join(home, \"cache\", \"verify\");\n /** Builds a run is serving from its sandbox: the cap never removes them (finding 9). */\n const inUse = new Map<string, number>();\n const completeBuild = (versionId: string): string | undefined => {\n const dir = join(buildsDir, versionId);\n return existsSync(join(dir, \"manifest.json\")) ? dir : undefined;\n };\n\n /** Keeps the build cache under its cap, oldest first, never `keep`. */\n const pruneBuilds = async (keep: string): Promise<void> => {\n const entries = await readdir(buildsDir, { withFileTypes: true }).catch(() => []);\n const builds = await Promise.all(\n entries\n .filter((entry) => entry.isDirectory() && !entry.name.includes(\".tmp-\"))\n .map(async (entry) => {\n const dir = join(buildsDir, entry.name);\n return {\n dir,\n name: entry.name,\n mtime: (await stat(dir)).mtimeMs,\n size: await sizeOf(dir),\n };\n }),\n );\n let total = builds.reduce((acc, build) => acc + build.size, 0);\n for (const build of builds.sort((a, b) => a.mtime - b.mtime)) {\n if (total <= BUILD_CACHE_BYTES) break;\n if (build.name === keep || (inUse.get(build.name) ?? 0) > 0) continue;\n await rm(build.dir, { recursive: true, force: true });\n total -= build.size;\n }\n };\n\n /**\n * Keeps the newest verdicts, and removes screenshot directories no verdict names (an uncached\n * run's) once they are an hour old and no run is writing them (finding 9).\n */\n const pruneVerdicts = async (): Promise<void> => {\n const all = await readdir(cacheDir, { withFileTypes: true }).catch(() => []);\n const verdicts = new Set(\n all.filter((entry) => entry.name.endsWith(\".json\")).map((entry) => entry.name.slice(0, -5)),\n );\n for (const entry of all) {\n if (!entry.isDirectory() || verdicts.has(entry.name) || running.has(entry.name)) continue;\n const path = join(cacheDir, entry.name);\n if (path === sandboxRoot(home)) continue;\n const age = Date.now() - ((await stat(path).catch(() => undefined))?.mtimeMs ?? Date.now());\n if (age > 60 * 60 * 1000) await rm(path, { recursive: true, force: true });\n }\n const names = [...verdicts].map((name) => `${name}.json`);\n if (names.length <= VERDICT_CACHE_ENTRIES) return;\n const dated = await Promise.all(\n names.map(async (name) => ({ name, mtime: (await stat(join(cacheDir, name))).mtimeMs })),\n );\n for (const { name } of dated\n .sort((a, b) => a.mtime - b.mtime)\n .slice(0, names.length - VERDICT_CACHE_ENTRIES)) {\n await rm(join(cacheDir, name), { force: true });\n await rm(join(cacheDir, name.slice(0, -\".json\".length)), { recursive: true, force: true });\n }\n };\n\n /** The newest version of the artifact whose recorded verdict passed (D138 item 4). */\n const baselineOf = (\n artifactId: string,\n ):\n | { readonly versionId: string; readonly dir: string }\n | { readonly missing: string }\n | undefined => {\n const passed = registry.passedVersion(artifactId);\n if (passed === undefined) return undefined;\n const dir = registry.store.versionDir(passed);\n return existsSync(join(dir, \"manifest.json\")) && existsSync(join(dir, \"registry.json\"))\n ? { versionId: passed, dir }\n : { missing: passed };\n };\n\n /** The answers the home holds under a field ID of an artifact (orphans to be, D42). */\n const savedAnswers = (artifactId: string, fieldId: string): number =>\n options.ledger.read(\n (db) =>\n db.get<{ count: number }>(\n \"SELECT COUNT(*) AS count FROM field JOIN document ON document.id = field.document_id WHERE document.artifact_id = ? AND field.field_id = ? AND field.deleted = 0\",\n artifactId,\n fieldId,\n )?.count ?? 0,\n );\n\n const readRegistry = (dir: string): VersionRegistry =>\n JSON.parse(readFileSync(join(dir, \"registry.json\"), \"utf8\")) as VersionRegistry;\n\n const sandboxVersion = (versionId: string, dir: string): SandboxVersion => {\n const manifest = JSON.parse(readFileSync(join(dir, \"manifest.json\"), \"utf8\")) as {\n manifest: ArtifactManifest;\n sourceDigest: string;\n envDigest: string;\n outputDigest: string;\n };\n return {\n versionId,\n dir,\n manifest: manifest.manifest,\n sourceDigest: manifest.sourceDigest,\n envDigest: manifest.envDigest,\n outputDigest: manifest.outputDigest,\n };\n };\n\n /** Builds the source into the build cache (atomically), or reuses a complete build. */\n const buildInto = async (prepared: PreparedSource, run: VerifyRun): Promise<BuildOutcome> => {\n const existing = completeBuild(prepared.versionId);\n if (existing && (await options.sandbox.damage(existing)) === undefined) {\n // Used again: newest for the cap, which goes by the time a build was last used.\n const now = new Date();\n await utimes(existing, now, now).catch(() => undefined);\n return {\n ok: true,\n outputDigest: (\n JSON.parse(readFileSync(join(existing, \"manifest.json\"), \"utf8\")) as {\n outputDigest: string;\n }\n ).outputDigest,\n registry: readRegistry(existing),\n };\n }\n await mkdir(buildsDir, { recursive: true, mode: 0o700 });\n const temporary = join(buildsDir, `${prepared.versionId}.tmp-${process.pid}-${Date.now()}`);\n try {\n const outcome = await run.build(temporary);\n if (!outcome.ok) return outcome;\n await rm(join(buildsDir, prepared.versionId), { recursive: true, force: true });\n await renamePath(temporary, join(buildsDir, prepared.versionId));\n await pruneBuilds(prepared.versionId);\n return outcome;\n } finally {\n await rm(temporary, { recursive: true, force: true });\n }\n };\n\n const verify = async (prepared: PreparedSource, run: VerifyRun): Promise<VerifyOutcome> => {\n inUse.set(prepared.versionId, (inUse.get(prepared.versionId) ?? 0) + 1);\n try {\n return await verifyInUse(prepared, run);\n } finally {\n const count = (inUse.get(prepared.versionId) ?? 1) - 1;\n if (count > 0) inUse.set(prepared.versionId, count);\n else inUse.delete(prepared.versionId);\n }\n };\n\n const verifyInUse = async (prepared: PreparedSource, run: VerifyRun): Promise<VerifyOutcome> => {\n const started = Date.now();\n const timings: Record<string, number> = {};\n const time = (stage: string, since: number): void => {\n timings[stage] = Date.now() - since;\n };\n const diagnostics: Diagnostic[] = [...prepared.warnings];\n const key = verdictKey(prepared.sourceDigest, prepared.envDigest);\n const artifactsDir = join(cacheDir, key);\n await rm(artifactsDir, { recursive: true, force: true });\n await mkdir(artifactsDir, { recursive: true, mode: 0o700 });\n const { viewports, unknown } = viewportsFor(prepared.manifest.verify?.viewports);\n if (unknown.length > 0) log.warn(\"verify.unknown_viewports\", { unknown });\n\n // 1. Compile: the build and the type check beside it.\n run.progress?.(\"compile\");\n const compileStart = Date.now();\n const hasLive = existsSync(join(prepared.stagingDir, \"source\", \"live.ts\"));\n let buildDiagnostics: readonly Diagnostic[] = [];\n const [built, checked] = await Promise.all([\n buildInto(prepared, run).then((outcome) => {\n time(\"build\", compileStart);\n if (!outcome.ok) buildDiagnostics = outcome.diagnostics;\n return outcome;\n }),\n typecheck({\n processes: options.sandbox.processes,\n log,\n env: options.sandbox.env,\n sourceDir: join(prepared.stagingDir, \"source\"),\n workDir: `${prepared.stagingDir}-check`,\n nodeModules: prepared.nodeModules,\n hasLive,\n alreadyReported: (specifier) => reportedByBuild(buildDiagnostics, specifier),\n }).then((outcome) => {\n time(\"typecheck\", compileStart);\n return outcome;\n }),\n ]);\n diagnostics.push(...(built.ok ? [] : built.diagnostics));\n // A module the build already couldn't resolve isn't reported twice (D138 item 8). The type\n // check's own callback may run before the build ends, so its TS2307s are matched again here.\n diagnostics.push(\n ...checked.diagnostics.filter((diagnostic) => {\n if (built.ok || diagnostic.code !== \"MOSTRA_TYPE_ERROR\") return true;\n const missing = /^TS2307: .*?'([^']+)'/.exec(diagnostic.message)?.[1];\n return missing === undefined || !reportedByBuild(built.diagnostics, missing);\n }),\n );\n\n const regressions: {\n against?: string;\n aria?: string;\n pixels?: { viewport: string; ratio: number }[];\n contracts?: string[];\n } = {};\n const screenshots: VerdictScreenshot[] = [];\n const aria: VerdictAria[] = [];\n const smoke = { interactions: 0, skippedActions: [] as string[], stateChanges: 0 };\n\n if (built.ok) {\n // 2. Lint: the static field-ID scan.\n const lintStart = Date.now();\n const coverage = built.registry.fields;\n diagnostics.push(...staticFieldLint(coverage));\n time(\"lint\", lintStart);\n\n const baseline = prepared.identityKnown ? baselineOf(prepared.artifactId) : undefined;\n if (!baseline) {\n diagnostics.push(\n createDiagnostic(\"MOSTRA_VERIFY_NO_BASELINE\", {\n message: \"No earlier version of this artifact passed verify, so nothing was compared.\",\n }),\n );\n } else if (\"missing\" in baseline) {\n diagnostics.push(\n createDiagnostic(\"MOSTRA_VERIFY_BASELINE_MISSING\", {\n message: `The last passing version's build (${baseline.missing}) isn't in the home any more, so nothing was compared.`,\n }),\n );\n }\n const compared =\n baseline && !(\"missing\" in baseline) && baseline.versionId !== prepared.versionId\n ? baseline\n : undefined;\n if (baseline && !(\"missing\" in baseline)) regressions.against = baseline.versionId;\n if (prepared.identityKnown) options.clearPark(prepared.artifactId);\n\n // 3 to 5: boot, render, smoke and regressions, within 120 s.\n const deadline = Date.now() + (options.limits?.timeoutMs ?? VERIFY_TIMEOUT_MS);\n const candidateDir = join(buildsDir, prepared.versionId);\n let sandbox: Sandbox | undefined;\n let stage = \"boot\";\n try {\n run.progress?.(\"boot\");\n const bootStart = Date.now();\n sandbox = await startSandbox(options.sandbox, {\n artifactId: prepared.artifactId,\n versions: [\n ...(compared ? [sandboxVersion(compared.versionId, compared.dir)] : []),\n sandboxVersion(prepared.versionId, candidateDir),\n ],\n sourceDir: prepared.sourceDir,\n });\n const health = await fetch(`${sandbox.shellOrigin}/a/${prepared.artifactId}`).catch(\n () => undefined,\n );\n if (!health?.ok) throw new Error(\"The verify sandbox's shell didn't answer.\");\n time(\"boot\", bootStart);\n\n const clockMs = Math.floor(started / 1000) * 1000;\n const render = async (\n versionId: string,\n viewport: VerifyViewport,\n name: string,\n collect: RenderRequest[\"collect\"],\n ): Promise<RenderResult> => {\n const result = await options.runner\n .render({\n url: (sandbox as Sandbox).link(versionId),\n viewport,\n clockMs,\n outDir: artifactsDir,\n name,\n collect,\n deadline,\n })\n .catch((error: unknown) => {\n if (error instanceof RpcError && error.diagnostic.code === \"MOSTRA_VERIFY_TIMEOUT\")\n return { timedOut: true } as RenderResult;\n throw error;\n });\n // Every ARIA snapshot verify keeps is written through the redactor, the baseline's too\n // (D138 item 1, Opus review finding 8); the runner only reads it.\n if (result.aria) {\n const text = options.redactor.redact(result.aria.text);\n await writeFile(result.aria.path, text);\n (result as { aria: { path: string; text: string } }).aria = {\n path: result.aria.path,\n text,\n };\n }\n if (result.timedOut) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_VERIFY_TIMEOUT\", {\n message: `Verify ran out of its ${Math.round((options.limits?.timeoutMs ?? VERIFY_TIMEOUT_MS) / 1000)} s during the ${stage} stage (${name}).`,\n }),\n );\n }\n return result;\n };\n\n stage = \"render\";\n run.progress?.(\"render\");\n const renderStart = Date.now();\n const candidateShots = new Map<string, RenderResult>();\n const renderCandidate = async (\n index: number,\n viewport: VerifyViewport,\n ): Promise<RenderResult> => {\n const result = await render(prepared.versionId, viewport, viewport.name, {\n screenshot: true,\n aria: true,\n axe: true,\n fields: index === 0,\n });\n candidateShots.set(viewport.name, result);\n diagnostics.push(...result.findings);\n if (result.screenshot) {\n screenshots.push({\n viewport: viewport.name,\n path: result.screenshot.path,\n width: result.screenshot.width,\n height: result.screenshot.height,\n tokensEstimate: estimateImageTokens(\n result.screenshot.width,\n result.screenshot.height,\n ),\n returned: false,\n });\n }\n if (result.aria) {\n aria.push({\n viewport: viewport.name,\n path: result.aria.path,\n summary: ariaSummary(result.aria.text),\n });\n }\n return result;\n };\n // The source's first viewport first: a page that never gets ready ends the browser stages\n // here, rather than waiting the same way at every other render.\n const opening = await renderCandidate(0, viewports[0] as VerifyViewport);\n const baselineShots = new Map<string, RenderResult>();\n if (opening.ready) {\n if (compared) {\n stage = \"baseline render\";\n for (const viewport of viewports) {\n baselineShots.set(\n viewport.name,\n await render(compared.versionId, viewport, `baseline-${viewport.name}`, {\n screenshot: true,\n aria: true,\n axe: false,\n fields: false,\n }),\n );\n }\n }\n stage = \"render\";\n for (const [index, viewport] of viewports.entries()) {\n if (index > 0) await renderCandidate(index, viewport);\n }\n }\n time(\"render\", renderStart);\n\n if (!opening.ready) throw new NotReady();\n // The second boot with identical inputs, for field IDs that change between renders.\n const first = viewports[0] as VerifyViewport;\n const firstFields: readonly ProbedField[] = candidateShots.get(first.name)?.fields ?? [];\n diagnostics.push(...probedFieldLint(firstFields, first.name, coverage));\n stage = \"field stability\";\n const again = await render(prepared.versionId, first, `${first.name}-again`, {\n screenshot: false,\n aria: false,\n axe: false,\n fields: true,\n });\n // A difference is confirmed by a third boot before it is reported: an ID that changes is\n // different every time, while one that only arrived late on the first, cold boot (a run\n // started at mount, a worker starting) is the same on the two warm ones (Opus review\n // finding 1).\n if (unstableFieldLint(firstFields, again.fields ?? [], coverage, first.name).length > 0) {\n const third = await render(prepared.versionId, first, `${first.name}-third`, {\n screenshot: false,\n aria: false,\n axe: false,\n fields: true,\n });\n diagnostics.push(\n ...unstableFieldLint(again.fields ?? [], third.fields ?? [], coverage, first.name),\n );\n }\n\n if (prepared.manifest.verify?.smoke !== false) {\n stage = \"smoke\";\n run.progress?.(\"smoke\");\n const smokeStart = Date.now();\n const result = await render(prepared.versionId, first, `${first.name}-smoke`, {\n screenshot: false,\n aria: false,\n axe: false,\n fields: false,\n smoke: {\n ...SMOKE_BUDGET,\n ...(options.limits?.smokeInteractions !== undefined\n ? { maxInteractions: options.limits.smokeInteractions }\n : {}),\n },\n });\n diagnostics.push(...result.findings);\n smoke.interactions = result.smoke?.interactions ?? 0;\n smoke.stateChanges = result.smoke?.stateChanges ?? 0;\n time(\"smoke\", smokeStart);\n }\n\n stage = \"regression\";\n run.progress?.(\"regression\");\n const regressionStart = Date.now();\n if (compared) {\n const contracts = contractRegressions(\n readRegistry(compared.dir),\n built.registry,\n (fieldId) => savedAnswers(prepared.artifactId, fieldId),\n );\n diagnostics.push(...contracts.diagnostics);\n if (contracts.summary.length > 0) regressions.contracts = contracts.summary;\n const ariaSummaries: string[] = [];\n const pixels: { viewport: string; ratio: number }[] = [];\n for (const viewport of viewports) {\n const before = baselineShots.get(viewport.name);\n const after = candidateShots.get(viewport.name);\n if (!before || !after) continue;\n if (before.aria && after.aria) {\n const found = ariaRegression(before.aria.text, after.aria.text, viewport.name);\n if (found) {\n diagnostics.push(found.diagnostic);\n ariaSummaries.push(found.summary);\n }\n }\n if (before.screenshot && after.screenshot) {\n const diff = join(artifactsDir, `diff-${viewport.name}.png`);\n const compared = await options.runner.compare(\n { a: before.screenshot.path, b: after.screenshot.path, diff },\n deadline,\n );\n pixels.push({ viewport: viewport.name, ratio: compared.ratio });\n const found = pixelRegression(\n compared.ratio,\n compared.sizeChanged,\n viewport.name,\n diff,\n );\n if (found) diagnostics.push(found);\n }\n }\n if (ariaSummaries.length > 0) regressions.aria = ariaSummaries.join(\"; \");\n if (pixels.length > 0) regressions.pixels = pixels;\n }\n time(\"regression\", regressionStart);\n\n for (const crash of sandbox.crashes()) {\n if (crash.versionId !== prepared.versionId) continue; // the baseline's isn't this source's\n diagnostics.push(\n createDiagnostic(\"MOSTRA_RUNTIME_WORKER_CRASHED\", {\n message: `The source's server code crashed while verify rendered the page (${crash.kind}): ${crash.cause}`,\n }),\n );\n }\n for (const failure of sandbox.liveFailures()) {\n diagnostics.push(\n createDiagnostic(\n failure.code === \"MOSTRA_SECRET_MISSING\"\n ? \"MOSTRA_VERIFY_SECRET_MISSING\"\n : \"MOSTRA_VERIFY_LIVE_FAILED\",\n {\n message: `The live source ${failure.key} failed while verify rendered the page: ${failure.message}`,\n },\n ),\n );\n }\n } catch (error) {\n if (error instanceof NotReady) {\n // Reported by the render already; nothing after it can run.\n } else if (error instanceof RpcError) diagnostics.push(error.diagnostic);\n else {\n log.error(\"verify.stage_failed\", { stage, error });\n diagnostics.push(\n createDiagnostic(\"MOSTRA_VERIFY_CRASHED\", {\n message: `Verify stopped during the ${stage} stage: ${(error as Error).message ?? String(error)}`,\n }),\n );\n }\n } finally {\n if (sandbox) {\n for (const fn of sandbox.skipped) {\n smoke.skippedActions.push(fn);\n diagnostics.push(\n createDiagnostic(\"MOSTRA_VERIFY_ACTION_SKIPPED\", {\n message: `Verify didn't run the server function ${fn}: it doesn't check dryRun().`,\n }),\n );\n }\n await sandbox.close();\n }\n }\n }\n\n timings[\"total\"] = Date.now() - started;\n const merged = mergeDiagnostics(diagnostics).map((diagnostic) => ({\n ...diagnostic,\n message: options.redactor.redact(diagnostic.message),\n }));\n const failed = hasError(merged);\n const policy = run.screenshots ?? \"on-failure\";\n const verdict: VerifyVerdict = {\n status: failed ? \"fail\" : \"pass\",\n artifact: {\n ...(prepared.identityKnown\n ? { id: prepared.artifactId, versionId: prepared.versionId }\n : {}),\n path: prepared.path,\n sourceDigest: prepared.sourceDigest,\n envDigest: prepared.envDigest,\n },\n diagnostics: merged,\n screenshots: screenshots.map((shot) => ({\n ...shot,\n returned: policy === \"always\" || (policy === \"on-failure\" && failed),\n })),\n aria,\n smoke,\n regressions,\n timingsMs: timings,\n };\n const checkedVerdict = VerifyVerdict.parse(verdict);\n if (\n !merged.some(\n (diagnostic) => diagnostic.severity === \"error\" && UNCACHEABLE.test(diagnostic.code),\n )\n ) {\n await mkdir(cacheDir, { recursive: true, mode: 0o700 });\n const target = join(cacheDir, `${key}.json`);\n const temporary = `${target}.${process.pid}-${randomUUID()}.tmp`;\n await writeFile(\n temporary,\n `${JSON.stringify({ verdict: checkedVerdict, built: built.ok }, null, 2)}\\n`,\n );\n await renamePath(temporary, target);\n await pruneVerdicts();\n } else {\n // Its screenshots stay for the caller who reads this verdict; the cache's pruning removes\n // them later, as no cached verdict names them (finding 9).\n await rm(join(cacheDir, `${key}.json`), { force: true });\n await pruneVerdicts();\n }\n log.info(\"verify.finished\", {\n status: verdict.status,\n errors: merged\n .filter((diagnostic) => diagnostic.severity === \"error\")\n .map((diagnostic) => diagnostic.code),\n totalMs: timings[\"total\"],\n });\n return { verdict: checkedVerdict, built: built.ok };\n };\n\n // Runs that share a cache key (identical sources at two paths) share its verdict file and its\n // screenshot directory, so they run one at a time (GPT review finding 2).\n const running = new Map<string, Promise<unknown>>();\n const serialized = (prepared: PreparedSource, run: VerifyRun): Promise<VerifyOutcome> => {\n const key = verdictKey(prepared.sourceDigest, prepared.envDigest);\n const previous = running.get(key) ?? Promise.resolve();\n const next = previous.then(\n () => verify(prepared, run),\n () => verify(prepared, run),\n );\n const settled = next.catch(() => undefined);\n running.set(key, settled);\n void settled.then(() => {\n if (running.get(key) === settled) running.delete(key);\n });\n return next;\n };\n\n return {\n cacheDir,\n run: serialized,\n cached(prepared) {\n const file = join(cacheDir, `${verdictKey(prepared.sourceDigest, prepared.envDigest)}.json`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n return undefined;\n }\n const entry = raw as { verdict?: unknown; built?: unknown } | null;\n if (typeof entry?.built !== \"boolean\") return undefined;\n const parsed = VerifyVerdict.safeParse(entry.verdict);\n if (!parsed.success) return undefined;\n const id = parsed.data.artifact.id;\n // A verdict made for another artifact (a copy with the same files) isn't this one's.\n if (id !== undefined && prepared.identityKnown && id !== prepared.artifactId)\n return undefined;\n return { verdict: parsed.data, built: entry.built };\n },\n builtVersion: completeBuild,\n collect: (dryRun) =>\n collectVerifyCaches(home, {\n dryRun,\n inUse: (name) => (inUse.get(name) ?? 0) > 0,\n running: (name) => running.has(name),\n }),\n };\n}\n\n/**\n * What gc may take from verify's caches (D140 item 14): least recently used builds past the 5 GB\n * cap and screenshot directories no cached verdict names, never one a run uses. It reads only the\n * home's files, so it works before any verify ran in this process; the caller holds the\n * instance's gate alone, so no run starts meanwhile.\n */\nexport async function collectVerifyCaches(\n home: string,\n options: {\n readonly dryRun: boolean;\n readonly inUse?: (build: string) => boolean;\n readonly running?: (key: string) => boolean;\n },\n): Promise<{ readonly count: number; readonly bytes: number }> {\n const buildsDir = join(home, \"cache\", \"builds\");\n const cacheDir = join(home, \"cache\", \"verify\");\n const inUse = options.inUse ?? (() => false);\n const running = options.running ?? (() => false);\n const dryRun = options.dryRun;\n const removable: { readonly dir: string; readonly size: number }[] = [];\n const entries = await readdir(buildsDir, { withFileTypes: true }).catch(() => []);\n const builds = await Promise.all(\n entries\n .filter((entry) => entry.isDirectory() && !entry.name.includes(\".tmp-\"))\n .map(async (entry) => {\n const dir = join(buildsDir, entry.name);\n return {\n dir,\n name: entry.name,\n mtime: (await stat(dir)).mtimeMs,\n size: await sizeOf(dir),\n };\n }),\n );\n let total = builds.reduce((acc, build) => acc + build.size, 0);\n for (const build of builds.sort((a, b) => a.mtime - b.mtime || (a.name < b.name ? -1 : 1))) {\n if (total <= BUILD_CACHE_BYTES) break;\n if (inUse(build.name)) continue;\n removable.push(build);\n total -= build.size;\n }\n const all = await readdir(cacheDir, { withFileTypes: true }).catch(() => []);\n const verdicts = new Set(\n all.filter((entry) => entry.name.endsWith(\".json\")).map((entry) => entry.name.slice(0, -5)),\n );\n for (const entry of all.sort((a, b) => (a.name < b.name ? -1 : 1))) {\n if (!entry.isDirectory() || verdicts.has(entry.name) || running(entry.name)) continue;\n const dir = join(cacheDir, entry.name);\n if (dir === sandboxRoot(home)) continue;\n removable.push({ dir, size: await sizeOf(dir) });\n }\n if (!dryRun) {\n for (const { dir } of removable) await rm(dir, { recursive: true, force: true });\n }\n return {\n count: removable.length,\n bytes: removable.reduce((acc, item) => acc + item.size, 0),\n };\n}\n\n/**\n * Folds identical diagnostics (same code and message) into one. Several renders of one page report\n * the same fault once each, so the fold keeps the largest count rather than adding them.\n */\nfunction mergeDiagnostics(diagnostics: readonly Diagnostic[]): Diagnostic[] {\n const seen = new Map<string, Diagnostic>();\n for (const diagnostic of diagnostics) {\n const key = `${diagnostic.code}\\u0000${diagnostic.message}`;\n const known = seen.get(key);\n if (known) {\n const count = Math.max(known.count ?? 1, diagnostic.count ?? 1);\n seen.set(key, count > 1 ? { ...known, count } : known);\n } else seen.set(key, diagnostic);\n }\n const order = { error: 0, warning: 1, hint: 2 };\n return [...seen.values()].sort((a, b) => order[a.severity] - order[b.severity]);\n}\n\n/** The error codes of a verdict, each once, in order: what `--force` records (D41). */\nexport function errorCodes(verdict: VerifyVerdict): string[] {\n return [\n ...new Set(\n verdict.diagnostics\n .filter((diagnostic) => diagnostic.severity === \"error\")\n .map((diagnostic) => diagnostic.code),\n ),\n ];\n}\n","/**\n * Identity and digests (DATA_MODEL §2, D77, D89). Pure functions over bytes and listings; the\n * snapshot module feeds them files, and publish combines them into the version ID.\n */\nimport { createHash } from \"node:crypto\";\nimport { VersionId } from \"@mostra/protocol\";\n\n/** One file of a canonical listing. */\nexport interface ListedFile {\n /** Relative, `/`-separated, NFC path. */\n readonly path: string;\n /** Whether any execute bit is set. */\n readonly executable: boolean;\n /** SHA-256 of the file's bytes, lowercase hex. */\n readonly sha256: string;\n}\n\n/** The environment a version is built in; its canonical JSON's SHA-256 is `envDigest`. */\nexport interface BuildEnvironment {\n readonly mostraVersion: string;\n /** The kit's release, or `null` while the runtime ships no kit (WP-18). */\n readonly kitVersion: string | null;\n readonly kitBase: \"base\" | \"radix\";\n readonly mode: \"spa\";\n /** SHA-256 of the frozen lockfile (`lock.yaml`). */\n readonly lockDigest: string;\n /** SHA-256 of the render mode's build settings and target list. */\n readonly buildConfigDigest: string;\n /** The browser protocol revision the client runtime speaks, or `null` before WP-07 defines it. */\n readonly browserProtocolRevision: string | null;\n}\n\n/** SHA-256 as lowercase hex. */\nexport function sha256Hex(data: string | Uint8Array): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\n/**\n * Canonical JSON (RFC 8785 for the values Mostra hashes: objects with string keys, arrays,\n * strings, finite numbers, booleans and null): keys sorted by UTF-16 code units, no whitespace.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw new TypeError(\"Canonical JSON has no representation for a non-finite number.\");\n }\n if (value === undefined) throw new TypeError(\"Canonical JSON has no undefined.\");\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, item]) => item !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(\",\")}}`;\n}\n\n/** Orders paths by their UTF-8 bytes, so the listing is the same on every platform. */\nfunction byUtf8(a: string, b: string): number {\n return Buffer.compare(Buffer.from(a, \"utf8\"), Buffer.from(b, \"utf8\"));\n}\n\n/**\n * The SHA-256 of a tree's canonical listing (DATA_MODEL §2): the JSON array of\n * `[path, executable, sha256]` for every file, sorted by the path's UTF-8 bytes.\n */\nexport function listingDigest(files: readonly ListedFile[]): string {\n const sorted = [...files].sort((a, b) => byUtf8(a.path, b.path));\n return sha256Hex(JSON.stringify(sorted.map((file) => [file.path, file.executable, file.sha256])));\n}\n\n/** `envDigest`: the SHA-256 of the environment's canonical JSON. */\nexport function environmentDigest(environment: BuildEnvironment): string {\n return sha256Hex(canonicalJson(environment));\n}\n\n/**\n * The version ID (D89): SHA-256 over the artifact ID's UTF-8 bytes, one `0x00` byte, then the\n * 32 bytes of `sourceDigest` and of `envDigest`, encoded by `VersionId.fromSha256` (D77).\n */\nexport function versionIdFor(artifactId: string, sourceDigest: string, envDigest: string): string {\n const hash = createHash(\"sha256\");\n hash.update(Buffer.from(artifactId, \"utf8\"));\n hash.update(Buffer.from([0]));\n hash.update(Buffer.from(sourceDigest, \"hex\"));\n hash.update(Buffer.from(envDigest, \"hex\"));\n return VersionId.fromSha256(new Uint8Array(hash.digest()));\n}\n","/**\n * Static manifest extraction (D51, AU-07): reads an entry's manifest without running any of the\n * artifact's code. A TSX or JSX entry is parsed with Oxc and its `export const artifact =\n * defineArtifact({...})` is read as a literal; an MDX entry's YAML frontmatter is the manifest.\n * Values that need evaluation are `MOSTRA_MANIFEST_NOT_LITERAL`; values the manifest doesn't allow\n * are `MOSTRA_MANIFEST_INVALID`; unknown keys are `MOSTRA_MANIFEST_UNKNOWN_KEY` warnings.\n */\n\nimport { createRequire } from \"node:module\";\nimport {\n ARTIFACT_MANIFEST_KEYS,\n ArtifactManifest,\n createDiagnostic,\n type Diagnostic,\n RpcError,\n} from \"@mostra/protocol\";\nimport type * as Oxc from \"oxc-parser\";\nimport { parseDocument } from \"yaml\";\n\nlet oxc: typeof Oxc | undefined;\n/**\n * Loads the native parser on first use: importing this module loads no native code, so the\n * platform gate answers before anything platform-specific loads (RT-07), as the ledger does.\n */\nfunction parser(): typeof Oxc {\n oxc ??= createRequire(import.meta.url)(\"oxc-parser\") as typeof Oxc;\n return oxc;\n}\n\n/** What an entry declares. */\nexport interface ExtractedManifest {\n /** The validated manifest, or `undefined` when the entry declares none (defaults apply). */\n readonly manifest: ArtifactManifest | undefined;\n /** Whether the entry has a default export (the page, or with `pages/` the layout). */\n readonly hasDefaultExport: boolean;\n /** Warnings, such as unknown keys. */\n readonly warnings: readonly Diagnostic[];\n}\n\ninterface Node {\n readonly type: string;\n readonly start: number;\n readonly end: number;\n readonly [key: string]: unknown;\n}\n\nconst REACT_PACKAGE = \"@mostra/react\";\n\n/** Line and column (1-based) of a UTF-16 offset. */\nfunction position(text: string, offset: number): { line: number; column: number } {\n let line = 1;\n let lineStart = 0;\n for (\n let index = text.indexOf(\"\\n\");\n index !== -1 && index < offset;\n index = text.indexOf(\"\\n\", index + 1)\n ) {\n line += 1;\n lineStart = index + 1;\n }\n return { line, column: offset - lineStart + 1 };\n}\n\nclass Extraction {\n readonly file: string;\n readonly text: string;\n\n constructor(file: string, text: string) {\n this.file = file;\n this.text = text;\n }\n\n fail(\n code: \"MOSTRA_MANIFEST_NOT_LITERAL\" | \"MOSTRA_MANIFEST_INVALID\" | \"MOSTRA_BUILD_FAILED\",\n message: string,\n offset: number,\n ): never {\n throw new RpcError(\n createDiagnostic(code, {\n message,\n location: { file: this.file, ...position(this.text, offset) },\n }),\n );\n }\n}\n\n/** Unwraps `( … )`, `x as const`, `x satisfies T` and `x!`. */\nfunction unwrap(node: Node): Node {\n let current = node;\n while (\n current.type === \"ParenthesizedExpression\" ||\n current.type === \"TSAsExpression\" ||\n current.type === \"TSSatisfiesExpression\" ||\n current.type === \"TSNonNullExpression\"\n ) {\n current = current[\"expression\"] as Node;\n }\n return current;\n}\n\n/** Converts a literal expression to its value, or fails with NOT_LITERAL at the first value that isn't one. */\nfunction literal(node: Node, x: Extraction): unknown {\n const value = unwrap(node);\n switch (value.type) {\n case \"Literal\": {\n const raw = value[\"value\"];\n if (value[\"regex\"] !== undefined || typeof raw === \"bigint\") {\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n \"A regular expression or BigInt isn't a manifest value.\",\n value.start,\n );\n }\n return raw;\n }\n case \"TemplateLiteral\": {\n const expressions = value[\"expressions\"] as Node[];\n if (expressions.length > 0) {\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n \"A template literal with a placeholder needs evaluation; write the string itself.\",\n value.start,\n );\n }\n const [quasi] = value[\"quasis\"] as { value: { cooked: string } }[];\n return quasi?.value.cooked ?? \"\";\n }\n case \"UnaryExpression\": {\n const argument = unwrap(value[\"argument\"] as Node);\n if (\n (value[\"operator\"] === \"-\" || value[\"operator\"] === \"+\") &&\n argument.type === \"Literal\" &&\n typeof argument[\"value\"] === \"number\"\n ) {\n return value[\"operator\"] === \"-\" ? -argument[\"value\"] : argument[\"value\"];\n }\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n \"Only a sign in front of a number is allowed.\",\n value.start,\n );\n }\n case \"ArrayExpression\":\n return (value[\"elements\"] as (Node | null)[]).map((element) => {\n if (element === null || element.type === \"SpreadElement\") {\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n \"Arrays in the manifest list their items: no holes or spreads.\",\n element?.start ?? value.start,\n );\n }\n return literal(element, x);\n });\n case \"ObjectExpression\": {\n const result: Record<string, unknown> = {};\n for (const property of value[\"properties\"] as Node[]) {\n if (\n property.type !== \"Property\" ||\n property[\"computed\"] ||\n property[\"method\"] ||\n property[\"kind\"] !== \"init\"\n ) {\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n property.type === \"SpreadElement\"\n ? \"A spread needs evaluation; write the properties out.\"\n : \"Manifest objects have plain `key: value` properties: no computed keys, methods or accessors.\",\n property.start,\n );\n }\n if (property[\"shorthand\"]) {\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n \"A shorthand property refers to a variable; write its value.\",\n property.start,\n );\n }\n const key = property[\"key\"] as Node;\n const name =\n key.type === \"Identifier\"\n ? (key[\"name\"] as string)\n : key.type === \"Literal\"\n ? String(key[\"value\"])\n : undefined;\n if (name === undefined) {\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n \"Property names must be plain names or strings.\",\n key.start,\n );\n }\n result[name] = literal(property[\"value\"] as Node, x);\n }\n return result;\n }\n default:\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n value.type === \"Identifier\"\n ? `\\`${String(value[\"name\"])}\\` is a variable; Mostra reads the manifest without running code, so write its value.`\n : \"This value needs evaluation; Mostra reads the manifest without running code, so write it as a literal.\",\n value.start,\n );\n }\n}\n\ninterface ModuleFacts {\n /** The node exported as `artifact`, if any: the initializer of the exported (or re-exported) const. */\n readonly artifact: { readonly init: Node | undefined; readonly at: number } | undefined;\n readonly hasDefaultExport: boolean;\n /** Local names bound to `defineArtifact` from `@mostra/react`. */\n readonly defineArtifact: ReadonlySet<string>;\n /** Local namespace names of `@mostra/react`. */\n readonly namespaces: ReadonlySet<string>;\n}\n\nfunction moduleFacts(program: Node): ModuleFacts {\n const body = program[\"body\"] as Node[];\n const defineNames = new Set<string>();\n const namespaces = new Set<string>();\n const locals = new Map<string, { init: Node | undefined; at: number; constant: boolean }>();\n let artifact: ModuleFacts[\"artifact\"];\n let hasDefaultExport = false;\n let exportedLocal: { name: string; at: number } | undefined;\n\n const declare = (declaration: Node, exported: boolean): void => {\n if (declaration.type !== \"VariableDeclaration\") return;\n for (const declarator of declaration[\"declarations\"] as Node[]) {\n const id = declarator[\"id\"] as Node;\n if (id.type !== \"Identifier\") continue;\n const entry = {\n init: (declarator[\"init\"] as Node | null) ?? undefined,\n at: declarator.start,\n constant: declaration[\"kind\"] === \"const\",\n };\n locals.set(id[\"name\"] as string, entry);\n if (exported && id[\"name\"] === \"artifact\")\n artifact = { init: entry.constant ? entry.init : undefined, at: entry.at };\n }\n };\n\n for (const statement of body) {\n if (\n statement.type === \"ImportDeclaration\" &&\n (statement[\"source\"] as Node)[\"value\"] === REACT_PACKAGE\n ) {\n for (const specifier of statement[\"specifiers\"] as Node[]) {\n const local = (specifier[\"local\"] as Node)[\"name\"] as string;\n if (specifier.type === \"ImportNamespaceSpecifier\") namespaces.add(local);\n if (specifier.type === \"ImportSpecifier\") {\n const imported = specifier[\"imported\"] as Node;\n if ((imported[\"name\"] ?? imported[\"value\"]) === \"defineArtifact\") defineNames.add(local);\n }\n }\n } else if (statement.type === \"ExportDefaultDeclaration\") {\n hasDefaultExport = true;\n } else if (statement.type === \"ExportNamedDeclaration\") {\n const declaration = statement[\"declaration\"] as Node | null;\n if (declaration) declare(declaration, true);\n for (const specifier of (statement[\"specifiers\"] as Node[]) ?? []) {\n const exported = specifier[\"exported\"] as Node;\n const name = (exported[\"name\"] ?? exported[\"value\"]) as string;\n const local = (specifier[\"local\"] as Node)[\"name\"] as string;\n if (name === \"default\") hasDefaultExport = true;\n if (name === \"artifact\") {\n if (statement[\"source\"]) artifact = { init: undefined, at: specifier.start };\n else exportedLocal = { name: local, at: specifier.start };\n }\n }\n } else {\n declare(statement, false);\n }\n }\n if (exportedLocal) {\n const local = locals.get(exportedLocal.name);\n artifact = {\n init: local?.constant ? local.init : undefined,\n at: local?.at ?? exportedLocal.at,\n };\n }\n return { artifact, hasDefaultExport, defineArtifact: defineNames, namespaces };\n}\n\n/** Validates an extracted object as a manifest, with unknown keys as warnings. */\nfunction validate(\n raw: unknown,\n x: Extraction,\n at: number,\n): { manifest: ArtifactManifest; warnings: Diagnostic[] } {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return x.fail(\n \"MOSTRA_MANIFEST_INVALID\",\n \"The manifest must be an object with at least a title.\",\n at,\n );\n }\n const warnings: Diagnostic[] = [];\n const known = new Set<string>(ARTIFACT_MANIFEST_KEYS);\n for (const key of Object.keys(raw)) {\n if (!known.has(key)) {\n warnings.push(\n createDiagnostic(\"MOSTRA_MANIFEST_UNKNOWN_KEY\", {\n message: `The manifest key \\`${key}\\` isn't one this Mostra release knows; it is ignored.`,\n location: { file: x.file, ...position(x.text, at) },\n }),\n );\n }\n }\n const checked = ArtifactManifest.safeParse(raw);\n if (!checked.success) {\n const issue = checked.error.issues[0];\n const path = issue?.path.join(\".\") || \"(manifest)\";\n return x.fail(\n \"MOSTRA_MANIFEST_INVALID\",\n `The manifest field \\`${path}\\` is invalid: ${issue?.message ?? \"unexpected value\"}.`,\n at,\n );\n }\n return { manifest: checked.data, warnings };\n}\n\nfunction extractScript(file: string, text: string): ExtractedManifest {\n const x = new Extraction(file, text);\n const parsed = parser().parseSync(file, text, { lang: file.endsWith(\".jsx\") ? \"jsx\" : \"tsx\" });\n const [error] = parsed.errors;\n if (error) {\n return x.fail(\n \"MOSTRA_BUILD_FAILED\",\n `${error.message} in ${file}.`,\n error.labels[0]?.start ?? 0,\n );\n }\n const facts = moduleFacts(parsed.program as unknown as Node);\n if (facts.artifact === undefined) {\n return { manifest: undefined, hasDefaultExport: facts.hasDefaultExport, warnings: [] };\n }\n const { init, at } = facts.artifact;\n if (init === undefined) {\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n \"Declare the manifest as `export const artifact = defineArtifact({ ... })` so Mostra can read it without running code.\",\n at,\n );\n }\n const call = unwrap(init);\n const callee = call.type === \"CallExpression\" ? unwrap(call[\"callee\"] as Node) : undefined;\n const isDefineArtifact =\n callee !== undefined &&\n ((callee.type === \"Identifier\" && facts.defineArtifact.has(callee[\"name\"] as string)) ||\n (callee.type === \"MemberExpression\" &&\n !callee[\"computed\"] &&\n (callee[\"object\"] as Node).type === \"Identifier\" &&\n facts.namespaces.has((callee[\"object\"] as Node)[\"name\"] as string) &&\n (callee[\"property\"] as Node)[\"name\"] === \"defineArtifact\"));\n if (callee?.type === \"Identifier\" && callee[\"name\"] === \"defineArtifact\" && !isDefineArtifact) {\n return x.fail(\n \"MOSTRA_MANIFEST_INVALID\",\n '`defineArtifact` isn\\'t imported: add `import { defineArtifact } from \"@mostra/react\"`.',\n call.start,\n );\n }\n const args = call[\"arguments\"] as Node[] | undefined;\n const [argument] = args ?? [];\n if (\n !isDefineArtifact ||\n args?.length !== 1 ||\n argument === undefined ||\n unwrap(argument).type !== \"ObjectExpression\"\n ) {\n return x.fail(\n \"MOSTRA_MANIFEST_NOT_LITERAL\",\n \"The exported `artifact` must be `defineArtifact({ ... })` with one object literal.\",\n call.start,\n );\n }\n const { manifest, warnings } = validate(literal(argument, x), x, argument.start);\n return { manifest, hasDefaultExport: facts.hasDefaultExport, warnings };\n}\n\n/** An MDX entry's frontmatter: a `---` fenced YAML block on the first line. */\nfunction extractFrontmatter(file: string, text: string): ExtractedManifest {\n const x = new Extraction(file, text);\n const match = /^---[ \\t]*\\r?\\n([\\s\\S]*?)\\r?\\n---[ \\t]*(?:\\r?\\n|$)/.exec(text);\n if (!match) return { manifest: undefined, hasDefaultExport: true, warnings: [] };\n const yamlText = match[1] ?? \"\";\n const document = parseDocument(yamlText, { prettyErrors: false, uniqueKeys: true });\n const [error] = document.errors;\n if (error) {\n const offset = 4 + (error.pos[0] ?? 0);\n return x.fail(\n \"MOSTRA_MANIFEST_INVALID\",\n `The frontmatter isn't valid YAML: ${error.message.split(\"\\n\")[0]}`,\n offset,\n );\n }\n const raw = document.toJS() as unknown;\n if (raw === null || raw === undefined)\n return { manifest: undefined, hasDefaultExport: true, warnings: [] };\n const { manifest, warnings } = validate(raw, x, 0);\n return { manifest, hasDefaultExport: true, warnings };\n}\n\n/**\n * Reads the manifest of an entry file's `text`. `file` is the entry's path inside the artifact,\n * used for the language and in diagnostics' locations.\n */\nexport function extractManifest(file: string, text: string): ExtractedManifest {\n return file.endsWith(\".mdx\") ? extractFrontmatter(file, text) : extractScript(file, text);\n}\n","/**\n * What `artifact/create` (`mostra new`) writes into an empty directory: the entry with the\n * artifact's generated `id`, an `AGENTS.md` for the agent that edits it next (AX-06, WP-14), and a\n * `CLAUDE.md` that imports it, since Claude Code loads a subdirectory's `CLAUDE.md` when it works\n * there but not its `AGENTS.md`. Every file is source like any other: it is in the version's\n * snapshot and its digest.\n */\n\n/** What a new artifact's files are made from. */\nexport interface ScaffoldInput {\n readonly artifactId: string;\n readonly title: string;\n /** This runtime's release, which `npx -y @mostra/cli@<version>` pins. */\n readonly version: string;\n}\n\n/** The files a new artifact gets, in the order `artifact/create` reports them. */\nexport const SCAFFOLD_PATHS: readonly string[] = [\"index.tsx\", \"AGENTS.md\", \"CLAUDE.md\"];\n\nfunction entry({ artifactId, title }: ScaffoldInput): string {\n return [\n 'import { defineArtifact } from \"@mostra/react\";',\n \"\",\n \"export const artifact = defineArtifact({\",\n ` id: ${JSON.stringify(artifactId)},`,\n ` title: ${JSON.stringify(title)},`,\n \"});\",\n \"\",\n \"export default function Page() {\",\n \" return (\",\n ' <main className=\"mx-auto max-w-2xl p-8\">',\n ' <h1 className=\"text-2xl font-semibold\">{artifact.title}</h1>',\n \" </main>\",\n \" );\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** A Markdown heading's text: one line, nothing that reads as Markdown syntax at its start. */\nfunction headingText(title: string): string {\n const line = title.replace(/\\s+/g, \" \").trim();\n return line === \"\" ? \"Mostra artifact\" : line;\n}\n\nfunction agents({ title, version }: ScaffoldInput): string {\n return [\n `# ${headingText(title)}`,\n \"\",\n \"This directory is a Mostra artifact: a page people open from a private link, read, answer and act on. Their answers come back to you as results.\",\n \"\",\n \"## Work on it\",\n \"\",\n \"1. Edit `index.tsx`: ordinary React 19 and TypeScript with Tailwind CSS 4, with no `package.json` or build configuration.\",\n \"2. Run `mostra verify .` until it reports `pass`, and look at both screenshots it lists (`--screenshots always` lists them every time).\",\n \"3. Run `mostra publish .`. It prints the private link: whoever holds it can use the page.\",\n \"4. Give the link to the person, saying who is asking and why. Then run `mostra wait . --until submitted` and `mostra results .`.\",\n \"\",\n `Where \\`mostra\\` isn't installed, run \\`npx -y @mostra/cli@${version}\\` in its place.`,\n \"\",\n \"## Keep in mind\",\n \"\",\n '- Every answer is a field with an ID that stays the same on every render and in every version: `useField(\"budget\", 0, { label: \"Budget\" })`, or a template on your data\\'s own ID for a list. Answers carry over to a new version by ID.',\n \"- Keep the `id` in `defineArtifact`: it is this artifact's identity. Manifest values are literals.\",\n '- Code that must run on this machine (send, save, call an API) goes in a module that starts with `\"use server\"`; live data in `live.ts`; static files in `public/`.',\n \"- Imports stay inside this directory, or name an npm package.\",\n \"\",\n \"## More\",\n \"\",\n \"`mostra docs guide` is the full guide to writing artifacts, and `mostra docs <CODE>` explains any diagnostic. The same guide is the Mostra Agent Skill: `npx skills add mostra-dev/mostra`.\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** The files of a new artifact, by path. */\nexport function scaffoldFiles(input: ScaffoldInput): Map<string, string> {\n return new Map([\n [\"index.tsx\", entry(input)],\n [\"AGENTS.md\", agents(input)],\n [\"CLAUDE.md\", \"@AGENTS.md\\n\"],\n ]);\n}\n","/**\n * Artifact sources (INTERFACES §2.1, DATA_MODEL §2): finding an artifact's entry, listing its files\n * with Mostra's ignore rules, and copying them into a staging snapshot whose digest is computed from\n * the copy, so what is built and recorded is exactly what was snapshotted, whatever the author\n * edits meanwhile.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { createReadStream, constants as fsConstants } from \"node:fs\";\nimport {\n access,\n chmod,\n copyFile,\n mkdir,\n readdir,\n readFile,\n realpath,\n stat,\n} from \"node:fs/promises\";\nimport { basename, dirname, extname, join } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport ignore from \"ignore\";\nimport { nameKey, WINDOWS } from \"../platform/index.ts\";\nimport type { ListedFile } from \"./digest.ts\";\n\n/** The entry files a directory artifact may have, in INTERFACES §2.1's order. */\nconst ENTRY_NAMES = [\"index.tsx\", \"index.jsx\", \"index.mdx\"] as const;\n/** The extensions a single-file artifact may have. */\nconst SINGLE_FILE = new Set([\".tsx\", \".jsx\", \".mdx\"]);\n/** Directories never part of a source tree (DATA_MODEL §2). */\nconst IGNORED_DIRS = new Set([\"node_modules\", \".git\", \".mostra\"]);\n/** Editor swap and backup files, and Finder's metadata (DATA_MODEL §2). */\nconst IGNORED_FILE = /^(?:\\.DS_Store|\\.#.*|#.*#|.*~|.*\\.sw[a-px])$/;\n\n/** An artifact's source, resolved on disk. */\nexport interface ResolvedSource {\n /** A single file, or a directory with an entry. */\n readonly kind: \"file\" | \"dir\";\n /** The canonical path an artifact without a manifest `id` is bound to (D51): the real path. */\n readonly bindingPath: string;\n /** The directory holding the files (the file's directory for a single file). */\n readonly root: string;\n /** The entry, relative to the snapshot root. */\n readonly entry: string;\n}\n\n/** One file of a source tree. */\nexport interface SourceFile {\n /** Relative, `/`-separated, NFC path inside the snapshot. */\n readonly path: string;\n /** Where it is read from. */\n readonly absolute: string;\n}\n\nfunction artifactError(\n code:\n | \"MOSTRA_ARTIFACT_SOURCE_MISSING\"\n | \"MOSTRA_ARTIFACT_NO_ENTRY\"\n | \"MOSTRA_ARTIFACT_ENTRY_AMBIGUOUS\"\n | \"MOSTRA_ARTIFACT_SOURCE_UNREADABLE\",\n message: string,\n): RpcError {\n return new RpcError(createDiagnostic(code, { message }));\n}\n\nconst errno = (error: unknown): string | undefined => (error as NodeJS.ErrnoException).code;\n\n/** Finds an artifact's entry at `path` (INTERFACES §2.1). */\nexport async function resolveSource(path: string): Promise<ResolvedSource> {\n let real: string;\n try {\n real = await realpath(path);\n } catch (error) {\n if (errno(error) === \"ENOENT\" || errno(error) === \"ENOTDIR\") {\n throw artifactError(\"MOSTRA_ARTIFACT_SOURCE_MISSING\", `The source ${path} doesn't exist.`);\n }\n throw artifactError(\n \"MOSTRA_ARTIFACT_SOURCE_UNREADABLE\",\n `The source ${path} can't be read (${errno(error) ?? \"error\"}).`,\n );\n }\n const info = await stat(real);\n if (info.isFile()) {\n if (!SINGLE_FILE.has(extname(real))) {\n throw artifactError(\n \"MOSTRA_ARTIFACT_NO_ENTRY\",\n `${path} isn't an artifact: a single-file artifact is a .tsx, .jsx or .mdx file.`,\n );\n }\n return {\n kind: \"file\",\n bindingPath: real,\n root: dirname(real),\n entry: basename(real).normalize(\"NFC\"),\n };\n }\n if (!info.isDirectory()) {\n throw artifactError(\"MOSTRA_ARTIFACT_NO_ENTRY\", `${path} is neither a file nor a directory.`);\n }\n const names = new Set(await readdir(real));\n const entries = ENTRY_NAMES.filter((name) => names.has(name));\n if (entries.length === 0) {\n throw artifactError(\n \"MOSTRA_ARTIFACT_NO_ENTRY\",\n `The directory ${path} has no entry: add index.tsx, index.jsx or index.mdx.`,\n );\n }\n if (entries.length > 1) {\n throw artifactError(\n \"MOSTRA_ARTIFACT_ENTRY_AMBIGUOUS\",\n `The directory ${path} has ${entries.join(\" and \")}; an artifact has one entry.`,\n );\n }\n return { kind: \"dir\", bindingPath: real, root: real, entry: entries[0] as string };\n}\n\n/**\n * Lists a source's files: the single file, or every file under the directory except the ignored\n * ones (DATA_MODEL §2) and those `.mostraignore` matches. Symbolic links are followed; a link\n * that loops back into its own ancestry is skipped.\n */\nexport async function listSource(source: ResolvedSource): Promise<SourceFile[]> {\n if (source.kind === \"file\") {\n return [{ path: source.entry, absolute: source.bindingPath }];\n }\n const rules = ignore();\n try {\n rules.add(await readFile(join(source.root, \".mostraignore\"), \"utf8\"));\n } catch (error) {\n if (errno(error) !== \"ENOENT\") throw unreadable(join(source.root, \".mostraignore\"), error);\n }\n const files: SourceFile[] = [];\n const seen = new Map<string, string>();\n const walk = async (\n dir: string,\n relative: string,\n ancestors: ReadonlySet<string>,\n ): Promise<void> => {\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (error) {\n throw unreadable(dir, error);\n }\n for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {\n const absolute = join(dir, entry.name);\n const path = (relative ? `${relative}/${entry.name}` : entry.name).normalize(\"NFC\");\n let kind: \"file\" | \"dir\" | \"other\" = entry.isFile()\n ? \"file\"\n : entry.isDirectory()\n ? \"dir\"\n : \"other\";\n if (entry.isSymbolicLink()) {\n try {\n const target = await stat(absolute);\n kind = target.isFile() ? \"file\" : target.isDirectory() ? \"dir\" : \"other\";\n } catch {\n continue; // A dangling link has no content to snapshot.\n }\n }\n if (kind === \"dir\") {\n if (IGNORED_DIRS.has(nameKey(entry.name)) || rules.ignores(`${path}/`)) continue;\n let real: string;\n try {\n real = await realpath(absolute);\n } catch (error) {\n throw unreadable(absolute, error);\n }\n if (ancestors.has(real)) continue;\n await walk(absolute, path, new Set([...ancestors, real]));\n } else if (kind === \"file\") {\n if (IGNORED_FILE.test(entry.name) || rules.ignores(path)) continue;\n // Two names one file system tells apart and another doesn't (NFC forms, or case on\n // Windows) would become one file in the snapshot.\n const clash = seen.get(nameKey(path));\n if (clash !== undefined) {\n throw artifactError(\n \"MOSTRA_ARTIFACT_SOURCE_UNREADABLE\",\n `${clash} and ${absolute} have the same name after Unicode normalization (NFC)${WINDOWS ? \" and ignoring case, as Windows compares names\" : \"\"}.`,\n );\n }\n seen.set(nameKey(path), absolute);\n files.push({ path, absolute });\n }\n }\n };\n await walk(source.root, \"\", new Set([source.root]));\n if (!files.some((file) => file.path === source.entry)) {\n throw artifactError(\n \"MOSTRA_ARTIFACT_NO_ENTRY\",\n `${source.entry} is excluded by ${join(source.root, \".mostraignore\")}; an artifact's entry can't be ignored.`,\n );\n }\n return files;\n}\n\nfunction unreadable(path: string, error: unknown): RpcError {\n return artifactError(\n \"MOSTRA_ARTIFACT_SOURCE_UNREADABLE\",\n `${path} can't be read (${errno(error) ?? (error as Error).message}).`,\n );\n}\n\nasync function hashFile(path: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(path)) hash.update(chunk as Buffer);\n return hash.digest(\"hex\");\n}\n\n/**\n * Copies `files` into `target` (the staging snapshot) and lists the copies with their digests.\n * Hashing the copy, not the original, means the listing describes exactly the bytes that are\n * built and archived.\n */\nexport async function copySnapshot(\n files: readonly SourceFile[],\n target: string,\n): Promise<ListedFile[]> {\n const listed: ListedFile[] = [];\n for (const file of files) {\n const destination = join(target, ...file.path.split(\"/\"));\n let info: Awaited<ReturnType<typeof stat>>;\n try {\n info = await stat(file.absolute);\n } catch (error) {\n throw unreadable(file.absolute, error);\n }\n try {\n await mkdir(dirname(destination), { recursive: true });\n await copyFile(file.absolute, destination, fsConstants.COPYFILE_FICLONE);\n const executable = (info.mode & 0o111) !== 0;\n await chmod(destination, executable ? 0o755 : 0o644);\n listed.push({ path: file.path, executable, sha256: await hashFile(destination) });\n } catch (error) {\n throw await snapshotError(error, file.absolute);\n }\n }\n return listed;\n}\n\n/**\n * Says which side of a snapshot copy failed (D80 Claude review finding 6): a full disk is the\n * home's (`MOSTRA_HOME_DISK_FULL`, FAILURE_MODEL §3); a source the author can no longer read is\n * the author's; anything else happened in the home's staging and stays an internal failure,\n * logged with its cause, rather than being blamed on the author's file.\n */\nexport async function snapshotError(error: unknown, source: string): Promise<unknown> {\n const code = errno(error);\n if (code === \"ENOSPC\" || code === \"EDQUOT\") {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOME_DISK_FULL\", {\n message: `The disk holding the home is full; ${source} couldn't be snapshotted, and nothing was published.`,\n }),\n );\n }\n try {\n await access(source, fsConstants.R_OK);\n } catch (readError) {\n return unreadable(source, readError);\n }\n return error;\n}\n\n/** Reads an artifact's entry from disk, with the same diagnostics as the rest of its source. */\nexport async function readEntry(source: ResolvedSource): Promise<string> {\n const path = source.kind === \"file\" ? source.bindingPath : join(source.root, source.entry);\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if (errno(error) === \"ENOENT\") {\n throw artifactError(\"MOSTRA_ARTIFACT_SOURCE_MISSING\", `The entry ${path} disappeared.`);\n }\n throw unreadable(path, error);\n }\n}\n","/**\n * A minimal, deterministic POSIX tar (pax interchange format) for source snapshots (DATA_MODEL §1):\n * regular files only, in the order given, with mode 0644 or 0755, owner 0, modification time 0 and\n * a pax `path` record for any path longer than 100 bytes or outside ASCII. The same tree always\n * gives the same bytes. {@link readTar} reads what {@link tarFile} writes.\n */\n\nconst BLOCK = 512;\n\n/** One file in an archive. */\nexport interface TarFile {\n /** Relative, `/`-separated path. */\n readonly path: string;\n readonly executable: boolean;\n readonly data: Uint8Array;\n}\n\nfunction octal(value: number, width: number): string {\n return `${value.toString(8).padStart(width - 1, \"0\")}\\0`;\n}\n\nfunction header(name: string, size: number, type: \"0\" | \"x\", mode: number): Buffer {\n const block = Buffer.alloc(BLOCK, 0);\n block.write(name, 0, 100, \"utf8\");\n block.write(octal(mode, 8), 100, 8, \"ascii\");\n block.write(octal(0, 8), 108, 8, \"ascii\");\n block.write(octal(0, 8), 116, 8, \"ascii\");\n block.write(octal(size, 12), 124, 12, \"ascii\");\n block.write(octal(0, 12), 136, 12, \"ascii\");\n block.write(\" \", 148, 8, \"ascii\");\n block.write(type, 156, 1, \"ascii\");\n block.write(\"ustar\\0\", 257, 6, \"ascii\");\n block.write(\"00\", 263, 2, \"ascii\");\n let sum = 0;\n for (const byte of block) sum += byte;\n block.write(`${sum.toString(8).padStart(6, \"0\")}\\0 `, 148, 8, \"ascii\");\n return block;\n}\n\nfunction padding(size: number): Buffer {\n const rest = size % BLOCK;\n return Buffer.alloc(rest === 0 ? 0 : BLOCK - rest, 0);\n}\n\n/** A pax record `\"<length> path=<value>\\n\"`, where the length counts the whole record. */\nfunction paxRecord(key: string, value: string): Buffer {\n const body = ` ${key}=${value}\\n`;\n const bodyLength = Buffer.byteLength(body, \"utf8\");\n let length = bodyLength + 1;\n while (String(length).length + bodyLength !== length) length = String(length).length + bodyLength;\n return Buffer.from(`${length}${body}`, \"utf8\");\n}\n\n/** The archive blocks of one file: an optional pax header, the header, the data and padding. */\nexport function tarFile(file: TarFile): Buffer[] {\n const mode = file.executable ? 0o755 : 0o644;\n const blocks: Buffer[] = [];\n const plain = /^[\\x20-\\x7e]*$/.test(file.path) && Buffer.byteLength(file.path) <= 100;\n if (!plain) {\n const record = paxRecord(\"path\", file.path);\n blocks.push(header(\"PaxHeader\", record.length, \"x\", 0o644), record, padding(record.length));\n }\n // Readers that ignore pax still get a printable stand-in; the pax record carries the real path.\n const name = plain ? file.path : file.path.replace(/[^\\x20-\\x7e]/g, \"_\").slice(-100);\n blocks.push(\n header(name, file.data.length, \"0\", mode),\n Buffer.from(file.data),\n padding(file.data.length),\n );\n return blocks;\n}\n\n/** The end of an archive: two zero blocks. */\nexport const TAR_END: Buffer = Buffer.alloc(BLOCK * 2, 0);\n\n/** Reads an archive written by {@link tarFile}. Throws on anything malformed. */\nexport function readTar(archive: Uint8Array): TarFile[] {\n const buffer = Buffer.from(archive.buffer, archive.byteOffset, archive.byteLength);\n const files: TarFile[] = [];\n let offset = 0;\n let paxPath: string | undefined;\n while (offset + BLOCK <= buffer.length) {\n const block = buffer.subarray(offset, offset + BLOCK);\n if (block.every((byte) => byte === 0)) break;\n const field = (start: number, length: number): string =>\n block\n .subarray(start, start + length)\n .toString(\"latin1\")\n .replace(/\\0.*$/s, \"\");\n const size = Number.parseInt(field(124, 12), 8);\n const type = field(156, 1);\n if (!Number.isSafeInteger(size) || size < 0)\n throw new Error(`Malformed tar header at ${offset}.`);\n const dataStart = offset + BLOCK;\n const data = buffer.subarray(dataStart, dataStart + size);\n if (data.length !== size) throw new Error(\"Truncated tar archive.\");\n offset = dataStart + size + padding(size).length;\n if (type === \"x\") {\n const match = /(?:^|\\n)\\d+ path=([^\\n]*)\\n/.exec(data.toString(\"utf8\"));\n paxPath = match?.[1];\n continue;\n }\n if (type !== \"0\" && type !== \"\") throw new Error(`Unexpected tar entry type \"${type}\".`);\n const path = paxPath ?? field(0, 100);\n paxPath = undefined;\n const mode = Number.parseInt(field(100, 8), 8);\n files.push({ path, executable: (mode & 0o111) !== 0, data: new Uint8Array(data) });\n }\n return files;\n}\n","/**\n * Publish (ARCHITECTURE §3, VR-01, VR-02, VR-11): freezes an artifact's source into an immutable,\n * content-addressed version. Steps, any of which can fail and leave no visible version:\n *\n * 1. snapshot the source into staging and read its manifest from the snapshot (never running it);\n * 2. resolve and freeze the dependencies into `lock.yaml` (D95), installing what's missing;\n * 3. compute `sourceDigest`, `envDigest` and the version ID (D89);\n * 4. (the verify gate, WP-09);\n * 5. build in a builder child, archive the source snapshot into `sources/`, seal the output and\n * rename it into `versions/`;\n * 6. commit the version, the source binding and `version.published` in one ledger transaction;\n * 7. return the receipt.\n *\n * Staging lives in the home, and a version directory without its ledger row is removed at the next\n * start, so a crash at any step leaves nothing visible (FAILURE_MODEL §3).\n */\n\nimport { createHash } from \"node:crypto\";\nimport { createReadStream, createWriteStream, existsSync, readFileSync } from \"node:fs\";\nimport {\n chmod,\n mkdir,\n mkdtemp,\n readdir,\n readFile,\n realpath,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\";\nimport { basename, dirname, extname, join } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { createZstdCompress } from \"node:zlib\";\nimport {\n type ArtifactCreateParams,\n type ArtifactCreateResult,\n ArtifactId,\n type ArtifactManifest,\n type ArtifactPublishParams,\n type ArtifactVerifyParams,\n BROWSER_PROTOCOL_REVISION,\n createDiagnostic,\n type DepsAddParams,\n type DepsAddResult,\n type Diagnostic,\n type PublishReceipt,\n RpcError,\n type SourceRef,\n type SubmissionPolicy,\n type VerifyVerdict,\n} from \"@mostra/protocol\";\nimport type { RenderMode } from \"../builder/index.ts\";\nimport { type Dependencies, lockKey, type Resolution } from \"../deps/index.ts\";\nimport { type Faults, noFaults } from \"../faults.ts\";\nimport type { Gate } from \"../gate.ts\";\nimport {\n InflightRequests,\n type Ledger,\n type RequestKey,\n recordedResult,\n recordResult,\n requestKey,\n} from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { renamePath } from \"../platform/index.ts\";\nimport { fsyncPath, type Registry, removeTree } from \"../registry/index.ts\";\nimport {\n type BuildOutcome,\n errorCodes,\n type PreparedSource,\n VERIFY_REVISION,\n type Verifier,\n} from \"../verify/index.ts\";\nimport {\n type BuildEnvironment,\n canonicalJson,\n environmentDigest,\n type ListedFile,\n listingDigest,\n sha256Hex,\n versionIdFor,\n} from \"./digest.ts\";\nimport { extractManifest } from \"./manifest.ts\";\nimport { SCAFFOLD_PATHS, type ScaffoldInput, scaffoldFiles } from \"./scaffold.ts\";\nimport {\n copySnapshot,\n listSource,\n type ResolvedSource,\n readEntry,\n resolveSource,\n} from \"./source.ts\";\nimport { TAR_END, tarFile } from \"./tar.ts\";\n\n/** Options for {@link createPublisher}. */\nexport interface PublisherOptions {\n readonly registry: Registry;\n readonly ledger: Ledger;\n readonly renderMode: RenderMode;\n /** Resolves each build's packages and lockfile (D95). */\n readonly dependencies: Dependencies;\n /** This runtime's release (`mostraVersion` in `envDigest`). */\n readonly runtimeVersion: string;\n readonly log: Log;\n /** Test fault points `publish:*` (VR-02). */\n readonly faults?: Faults;\n /** The home's submission policy (`HomeConfig.submission`, D102), read at each publish. */\n readonly homePolicy?: () => SubmissionPolicy | undefined;\n /** The verifier, made on first use: publish's gate and `artifact/verify` (D41, D138). */\n readonly verifier: () => Verifier;\n /**\n * Tests of other features only (`MOSTRA_TEST_UNVERIFIED_PUBLISH`): publish without the gate.\n * Such a version records no verdict, so it never counts as passing (D138 item 4).\n */\n readonly unverified?: boolean;\n /**\n * The instance's gate (D140 item 14): publishes, verify runs and dependency additions hold it\n * shared, so `gc` never removes files they use.\n */\n readonly gate?: Gate;\n}\n\n/** Publishes and creates artifacts. */\nexport interface Publisher {\n /** `artifact/publish`: gated by verify (D41). */\n publish(params: ArtifactPublishParams): Promise<PublishReceipt>;\n /** `artifact/verify`: one run, its verdict cached for the publish that follows (D138). */\n verify(params: ArtifactVerifyParams, progress?: (stage: string) => void): Promise<VerifyVerdict>;\n /** `artifact/create`. */\n create(params: ArtifactCreateParams): Promise<ArtifactCreateResult>;\n /** `deps/add`: adds packages to an artifact's working lockfile (D95). */\n addDependencies(params: DepsAddParams): Promise<DepsAddResult>;\n}\n\nconst ENTRY_NAMES = [\"index.tsx\", \"index.jsx\", \"index.mdx\"];\n\n/** The title of an artifact without a manifest: its directory's name, or a single file's own name. */\nexport function defaultTitle(source: ResolvedSource): string {\n if (source.kind === \"dir\") return basename(source.root);\n const stem = basename(source.entry, extname(source.entry));\n return stem === \"page\" || stem === \"index\" ? basename(source.root) : stem;\n}\n\n/**\n * Whether the source at `path` still claims `artifactId` in its manifest (D51). Synchronous: it\n * runs inside the commit transaction. Anything unreadable no longer claims anything.\n */\nfunction stillClaims(path: string, artifactId: string): boolean {\n // Read, never check-then-read: the source may change between the two (CodeQL js/file-system-race).\n const claims = (file: string): boolean | undefined => {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\" || code === \"EISDIR\" || code === \"ENOTDIR\") return undefined;\n return false;\n }\n try {\n return extractManifest(basename(file), text).manifest?.id === artifactId;\n } catch {\n return false;\n }\n };\n const asFile = claims(path);\n if (asFile !== undefined) return asFile;\n for (const name of ENTRY_NAMES) {\n const result = claims(join(path, name));\n if (result !== undefined) return result;\n }\n return false;\n}\n\nasync function hashFile(path: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(path)) hash.update(chunk as Buffer);\n return hash.digest(\"hex\");\n}\n\n/**\n * The canonical listing of a version's output (DATA_MODEL §2, `outputDigest`): every file under\n * `client/` and `server/`, and `registry.json`, with paths relative to the version directory.\n * The version is sealed read-only (0444), so no file is listed as executable: the digest\n * describes the stored tree exactly and can be recomputed from it.\n */\nasync function outputListing(versionDir: string): Promise<ListedFile[]> {\n const files: ListedFile[] = [];\n const walk = async (current: string, relative: string): Promise<void> => {\n for (const entry of await readdir(current, { withFileTypes: true })) {\n const path = `${relative}/${entry.name}`;\n const absolute = join(current, entry.name);\n if (entry.isDirectory()) await walk(absolute, path);\n else if (entry.isFile()) {\n files.push({ path, executable: false, sha256: await hashFile(absolute) });\n }\n }\n };\n for (const top of [\"client\", \"server\"]) {\n if (existsSync(join(versionDir, top))) await walk(join(versionDir, top), top);\n }\n files.push({\n path: \"registry.json\",\n executable: false,\n sha256: await hashFile(join(versionDir, \"registry.json\")),\n });\n return files;\n}\n\n/**\n * Writes the source snapshot archive (`sources/<artifact>/<sourceDigest>.tar.zst`), atomically.\n * Returns whether it wrote one: an existing archive holds the same tree (content-addressed).\n */\nasync function archiveSnapshot(\n source: string,\n files: readonly ListedFile[],\n target: string,\n): Promise<boolean> {\n if (existsSync(target)) return false;\n const created = !existsSync(dirname(target));\n await mkdir(dirname(target), { recursive: true, mode: 0o700 });\n // A new artifact directory in sources/ must be durable too.\n if (created) fsyncPath(dirname(dirname(target)), true);\n const temporary = `${target}.${process.pid}.tmp`;\n const sorted = [...files].sort((a, b) =>\n Buffer.compare(Buffer.from(a.path), Buffer.from(b.path)),\n );\n async function* blocks(): AsyncGenerator<Buffer> {\n for (const file of sorted) {\n const data = await readFile(join(source, ...file.path.split(\"/\")));\n yield* tarFile({ path: file.path, executable: file.executable, data });\n }\n yield TAR_END;\n }\n // Written owner-writable, synced, then made read-only: Windows flushes a file only through a\n // handle that may write, which a read-only file never opens again.\n try {\n await pipeline(\n Readable.from(blocks()),\n createZstdCompress(),\n createWriteStream(temporary, { mode: 0o600 }),\n );\n fsyncPath(temporary);\n await chmod(temporary, 0o400);\n } catch (error) {\n await removeTree(temporary).catch(() => {});\n throw error;\n }\n await renamePath(temporary, target);\n fsyncPath(dirname(target), true);\n return true;\n}\n\n/**\n * What `artifact/create` records for its `requestId`: its result, and the exact text of each file\n * it writes, so a retry, by this runtime or a newer one, completes exactly the bytes the first\n * attempt began (WP-14's GPT and Opus reviews).\n */\ninterface CreateRecord {\n readonly result: ArtifactCreateResult;\n readonly scaffold: { readonly files: Readonly<Record<string, string>> };\n}\n\n/** The text of each of `paths` (of {@link scaffoldFiles}) for `input`. */\nfunction scaffoldText(paths: readonly string[], input: ScaffoldInput): Record<string, string> {\n const all = scaffoldFiles(input);\n return Object.fromEntries(\n paths.flatMap((path) => {\n const text = all.get(path);\n return text === undefined ? [] : [[path, text]];\n }),\n );\n}\n\n/**\n * Writes `artifact/create`'s files (`files`, path to text) into `dir`, completing an interrupted\n * write: an existing file whose bytes are the expected text's or a prefix of them (a write cut\n * short, even inside a character) ends as the expected text, and anything else the author has\n * written since is left alone.\n */\nasync function writeScaffold(dir: string, files: Readonly<Record<string, string>>): Promise<void> {\n await mkdir(dir, { recursive: true });\n let wrote = false;\n for (const [path, text] of Object.entries(files)) {\n const expected = Buffer.from(text, \"utf8\");\n const file = join(dir, path);\n let current: Buffer | undefined;\n try {\n current = await readFile(file);\n } catch {\n current = undefined;\n }\n if (current !== undefined) {\n const prefix =\n current.length <= expected.length && expected.subarray(0, current.length).equals(current);\n if (!prefix || current.length === expected.length) continue;\n }\n await writeFile(file, expected);\n fsyncPath(file);\n wrote = true;\n }\n if (wrote) fsyncPath(dir, true);\n}\n\n/**\n * The output digest of a version directory's files (DATA_MODEL §2): what its manifest records and\n * the integrity checks compare. Tests that freeze a version for VR-10 recompute it.\n */\nexport async function versionOutputDigest(dir: string): Promise<string> {\n return listingDigest(await outputListing(dir));\n}\n\n/**\n * What is wrong with a stored version directory, or `undefined` when it is intact: its\n * `manifest.json` names an output digest, and its `client/`, `server/` and `registry.json` still\n * have that digest (DATA_MODEL §2).\n */\n/**\n * What is wrong with a stored version directory, or `undefined` when its files still match the\n * output digest its manifest records (FAILURE_MODEL §3). Publish rebuilds a damaged directory; the\n * gateway refuses to show one.\n */\nexport async function versionDamage(dir: string): Promise<string | undefined> {\n let recorded: unknown;\n try {\n recorded = (\n JSON.parse(await readFile(join(dir, \"manifest.json\"), \"utf8\")) as { outputDigest?: unknown }\n ).outputDigest;\n } catch (error) {\n return `its manifest.json can't be read (${(error as NodeJS.ErrnoException).code ?? \"invalid JSON\"})`;\n }\n try {\n const actual = listingDigest(await outputListing(dir));\n return actual === recorded ? undefined : \"its files no longer match their output digest\";\n } catch (error) {\n return `its files can't be read (${(error as NodeJS.ErrnoException).code ?? \"error\"})`;\n }\n}\n\n/** Serializes work per key, so two publishes of one artifact never race (FAILURE_MODEL §1 rule 2). */\nclass KeyedQueue {\n readonly #tails = new Map<string, Promise<unknown>>();\n run<T>(key: string, task: () => Promise<T>): Promise<T> {\n const previous = this.#tails.get(key) ?? Promise.resolve();\n const next = previous.then(task, task);\n const tail = next.then(\n () => undefined,\n () => undefined,\n );\n this.#tails.set(key, tail);\n void tail.then(() => {\n if (this.#tails.get(key) === tail) this.#tails.delete(key);\n });\n return next;\n }\n}\n\n/** The first diagnostic of a failed build, or a generic one. */\nfunction firstDiagnostic(diagnostics: readonly Diagnostic[]): Diagnostic {\n return (\n diagnostics[0] ?? createDiagnostic(\"MOSTRA_BUILD_FAILED\", { message: \"The build failed.\" })\n );\n}\n\n/**\n * The verdict of a source verify couldn't prepare (an invalid manifest, dependencies that can't be\n * resolved): that diagnostic alone, never cached (D138 item 3).\n */\nfunction failedVerdict(path: string, diagnostic: Diagnostic): VerifyVerdict {\n return {\n status: diagnostic.severity === \"error\" ? \"fail\" : \"pass\",\n artifact: { path, sourceDigest: \"\", envDigest: \"\" },\n diagnostics: [diagnostic],\n screenshots: [],\n aria: [],\n smoke: { interactions: 0, skippedActions: [], stateChanges: 0 },\n regressions: {},\n timingsMs: { total: 0 },\n };\n}\n\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/**\n * Verify's stand-in artifact ID for a source no manifest `id` or binding names yet: derived from\n * its real path, shaped like a ULID (D77's alphabet), and never committed anywhere.\n */\nfunction stableProvisional(bindingPath: string): string {\n const hash = createHash(\"sha256\")\n .update(`mostra verify provisional\\u0000${bindingPath}`)\n .digest();\n let body = CROCKFORD[(hash[0] as number) % 8] as string;\n for (let index = 1; index < 26; index += 1) body += CROCKFORD[(hash[index] as number) % 32];\n return ArtifactId.parse(`art_${body}`);\n}\n\n/** Creates the publisher of one instance. */\nexport function createPublisher(options: PublisherOptions): Publisher {\n const { registry, ledger, renderMode, dependencies, log, verifier } = options;\n const faults = options.faults ?? noFaults;\n const queue = new KeyedQueue();\n const buildConfigDigest = sha256Hex(canonicalJson(renderMode.buildConfig));\n const inflight = new InflightRequests();\n\n /**\n * Replays the result recorded for a repeated `requestId` with the same parameters (H-03), joins\n * an attempt still running, or runs `task` once. The same `requestId` with other parameters is\n * `MOSTRA_HOST_REQUEST_ID_REUSED`.\n */\n const idempotent = async <T>(key: RequestKey | undefined, task: () => Promise<T>): Promise<T> => {\n if (key === undefined) return task();\n const recorded = ledger.read((db) => recordedResult<T>(db, key));\n if (recorded !== undefined) return recorded;\n return inflight.run(key, task);\n };\n\n const record = (key: RequestKey | undefined, result: unknown): void => {\n if (key === undefined) return;\n ledger.write((db) => recordResult(db, key, result));\n };\n\n /** The path a `SourceRef` names: itself, or the path an artifact was last published from. */\n const pathOf = (ref: SourceRef): string => {\n if (\"path\" in ref) return ref.path;\n const bound = registry.sourceOf(ref.artifactId);\n if (bound === undefined) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ARTIFACT_NOT_FOUND\", {\n message: `No artifact ${ref.artifactId} was published in this home; name it by its source path.`,\n }),\n );\n }\n return bound;\n };\n\n /** What {@link prepare} read of a snapshot, besides the {@link PreparedSource}. */\n interface Staged {\n readonly prepared: PreparedSource;\n readonly source: ResolvedSource;\n readonly listed: readonly ListedFile[];\n readonly entryHasDefault: boolean;\n readonly environment: BuildEnvironment;\n readonly deps: Resolution;\n }\n\n /**\n * Steps 1 to 3 of a publish, shared with verify (D41, D95): the snapshot, its manifest, the\n * dependencies (resolved exactly as publish does, through the same working lockfile) and the\n * digests. Throws the manifest's or the dependencies' diagnostic.\n */\n const prepare = async (\n path: string,\n source: ResolvedSource,\n provisional: string,\n identityKnown: boolean,\n staging: string,\n ): Promise<Staged> => {\n // 1. Snapshot, then read the manifest from the snapshot: what is built is what was read.\n const files = await listSource(source);\n const listed = await copySnapshot(files, join(staging, \"source\"));\n faults.at(\"publish:after-snapshot\");\n const extracted = extractManifest(\n source.entry,\n await readFile(join(staging, \"source\", source.entry), \"utf8\"),\n );\n for (const warning of extracted.warnings)\n log.warn(\"publish.manifest_warning\", { code: warning.code, message: warning.message });\n const manifest: ArtifactManifest = extracted.manifest ?? { title: defaultTitle(source) };\n const artifactId = registry.identityFor(source.bindingPath, manifest.id, () => provisional);\n if (artifactId !== provisional) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_PUBLISH_SOURCE_CHANGED\", {\n message: `The manifest of ${path} changed while it was being published.`,\n }),\n );\n }\n\n // 2. The dependencies, from the snapshot's imports and the artifact's working lockfile.\n const deps = await dependencies.resolve({\n key: lockKey(manifest.id ?? registry.artifactAt(source.bindingPath), source.bindingPath),\n sourceDir: join(staging, \"source\"),\n artifactDir: source.root,\n artifactPath: path,\n });\n faults.at(\"publish:after-dependencies\");\n\n // 3. Digests (DATA_MODEL §2).\n const sourceDigest = listingDigest(listed);\n const environment: BuildEnvironment = {\n mostraVersion: options.runtimeVersion,\n kitVersion: null,\n kitBase: manifest.kit?.base ?? \"base\",\n mode: manifest.mode ?? \"spa\",\n lockDigest: deps.lockDigest,\n buildConfigDigest,\n // The browser protocol the version's client runtime speaks (VR-10, D106).\n browserProtocolRevision: BROWSER_PROTOCOL_REVISION,\n };\n const envDigest = environmentDigest(environment);\n const versionId = versionIdFor(artifactId, sourceDigest, envDigest);\n faults.at(\"publish:after-digests\");\n return {\n prepared: {\n path,\n stagingDir: staging,\n sourceDir: source.root,\n manifest,\n warnings: extracted.warnings,\n artifactId,\n identityKnown,\n sourceDigest,\n envDigest,\n versionId,\n nodeModules: deps.nodeModules,\n },\n source,\n listed,\n entryHasDefault: extracted.hasDefaultExport,\n environment,\n deps,\n };\n };\n\n /**\n * Step 5's build, laid out as a version directory in `out`: the client and server builds,\n * `registry.json`, `lock.yaml` and `manifest.json` (whose `forcedCodes` and `verify` publish\n * fills in when it promotes; neither is part of the output digest).\n */\n const stageBuild = async (staged: Staged, out: string): Promise<BuildOutcome> => {\n const { prepared } = staged;\n const built = await renderMode.build({\n stagingDir: prepared.stagingDir,\n entry: staged.source.entry,\n entryHasDefault: staged.entryHasDefault,\n manifest: prepared.manifest,\n versionId: prepared.versionId,\n nodeModules: staged.deps.nodeModules,\n outDir: out,\n });\n if (!built.ok) return { ok: false, diagnostics: built.diagnostics };\n faults.at(\"publish:after-build\");\n await writeFile(join(out, \"registry.json\"), `${JSON.stringify(built.registry, null, 2)}\\n`);\n await writeFile(join(out, \"lock.yaml\"), staged.deps.lock);\n const outputDigest = listingDigest(await outputListing(out));\n await writeVersionManifest(out, staged, {\n outputDigest,\n server: built.server,\n forcedCodes: [],\n });\n return { ok: true, outputDigest, registry: built.registry };\n };\n\n /** Writes a version directory's `manifest.json`. */\n const writeVersionManifest = async (\n out: string,\n staged: Staged,\n fields: {\n readonly outputDigest: string;\n readonly server: boolean;\n readonly forcedCodes: readonly string[];\n readonly verify?: { readonly status: \"pass\" | \"fail\"; readonly verifyRevision: string };\n },\n ): Promise<void> => {\n const { prepared } = staged;\n await writeFile(\n join(out, \"manifest.json\"),\n `${JSON.stringify(\n {\n schemaVersion: 1,\n artifactId: prepared.artifactId,\n versionId: prepared.versionId,\n mode: staged.environment.mode,\n entry: staged.source.entry,\n server: fields.server,\n manifest: prepared.manifest,\n sourceDigest: prepared.sourceDigest,\n envDigest: prepared.envDigest,\n environment: staged.environment,\n outputDigest: fields.outputDigest,\n forcedCodes: fields.forcedCodes,\n ...(fields.verify ? { verify: fields.verify } : {}),\n },\n null,\n 2,\n )}\\n`,\n );\n };\n\n /**\n * Runs `fn` with the source's identity decided and its staging directory made: one at a time per\n * source path, then per artifact (always in that order, so they can't deadlock), so a path-bound\n * artifact's identity is decided once and two copies claiming one ID never promote the same\n * version directory at once. The commit checks the identity again inside its transaction.\n */\n const staged = async <T>(\n ref: SourceRef,\n fn: (input: {\n readonly path: string;\n readonly source: ResolvedSource;\n readonly provisional: string;\n readonly identityKnown: boolean;\n readonly staging: string;\n }) => Promise<T>,\n how?: { readonly stableProvisional?: boolean },\n ): Promise<T> => {\n const path = pathOf(ref);\n const source = await resolveSource(path);\n return queue.run(`path:${source.bindingPath}`, async () => {\n // A manifest that can't be read here is reported by `prepare`, from the snapshot.\n let peeked: string | undefined;\n try {\n peeked = extractManifest(source.entry, await readEntry(source)).manifest?.id;\n } catch {\n peeked = undefined;\n }\n const known = peeked ?? registry.artifactAt(source.bindingPath);\n // An unbound source's artifact is decided at its first publish (D51). Verify's stand-in is\n // derived from the path, so verifying unchanged source again reuses its build; a publish's\n // is new, as the artifact's real ID (Opus review finding 9).\n const provisional =\n known ??\n (how?.stableProvisional ? stableProvisional(source.bindingPath) : ArtifactId.create());\n return queue.run(`artifact:${provisional}`, async () => {\n const staging = await mkdtemp(join(registry.store.stagingDir, \"publish-\"));\n try {\n return await fn({\n path,\n source,\n provisional,\n identityKnown: known !== undefined,\n staging,\n });\n } finally {\n await removeTree(staging);\n await removeTree(`${staging}-check`);\n }\n });\n });\n };\n\n const verifyOnce = (params: ArtifactVerifyParams, progress?: (stage: string) => void) =>\n staged(\n params.source,\n async ({ path, source, provisional, identityKnown, staging }) => {\n progress?.(\"prepare\");\n let ready: Staged;\n try {\n ready = await prepare(path, source, provisional, identityKnown, staging);\n } catch (error) {\n // A manifest or the dependencies that can't be read are the verdict, not a failure of verify.\n if (\n error instanceof RpcError &&\n /^MOSTRA_(MANIFEST|DEP|ARTIFACT|BUILD)_/.test(error.diagnostic.code)\n ) {\n return failedVerdict(path, error.diagnostic);\n }\n throw error;\n }\n // Verify records the working lockfile like publish (D95), so the publish that follows\n // resolves the same versions and its environment digest matches the cached verdict.\n ledger.write((db) =>\n ready.deps.save(\n db,\n lockKey(\n ready.prepared.manifest.id ?? registry.artifactAt(source.bindingPath),\n source.bindingPath,\n ),\n ),\n );\n const outcome = await verifier().run(ready.prepared, {\n build: (out) => stageBuild(ready, out),\n ...(params.screenshots ? { screenshots: params.screenshots } : {}),\n ...(progress ? { progress } : {}),\n });\n return outcome.verdict;\n },\n { stableProvisional: true },\n );\n\n const publishOnce = (params: ArtifactPublishParams): Promise<PublishReceipt> =>\n staged(params.source, async ({ path, source, provisional, identityKnown, staging }) => {\n // What this publish placed in the store before its commit; removed again if it fails\n // (the next start removes it too, should this process die first: FAILURE_MODEL §3).\n const undo: (() => Promise<void>)[] = [];\n let committed = false;\n try {\n const ready = await prepare(path, source, provisional, identityKnown, staging);\n const { prepared } = ready;\n const { artifactId, versionId, sourceDigest, envDigest, manifest } = prepared;\n\n // 4 and 5. Gate, build, archive and promote, unless this artifact already has this exact\n // version. A version whose directory is missing or no longer matches its own recorded\n // output digest is rebuilt from the same source and environment, and put back in place;\n // its ledger row stays as it was (FAILURE_MODEL §3, D80 Claude review finding 3).\n let outputDigest: string | undefined;\n let forcedCodes: string[] = [];\n let verifyRecord: { status: \"pass\" | \"fail\"; verifyRevision: string } | undefined;\n const recorded = registry.version(versionId);\n const exists = recorded !== undefined;\n // An existing version keeps what it was published with: its forced codes reach this\n // receipt and event too, and a repaired directory gets them back (D41, D138).\n if (recorded) {\n forcedCodes = [...recorded.forcedCodes];\n verifyRecord = recorded.verify;\n }\n const damage = exists\n ? await versionDamage(registry.store.versionDir(versionId))\n : undefined;\n if (damage !== undefined) log.warn(\"publish.version_damaged\", { versionId, damage });\n if (!exists || damage !== undefined) {\n const out = join(staging, \"out\");\n if (exists || options.unverified === true) {\n // A repair (the version passed, or was forced, when it was published), or a test of\n // another feature that publishes without the gate.\n const built = await stageBuild(ready, out);\n if (!built.ok) throw new RpcError(firstDiagnostic(built.diagnostics));\n outputDigest = built.outputDigest;\n if (exists) {\n await writeVersionManifest(out, ready, {\n outputDigest,\n server: existsSync(join(out, \"server\", \"entry.mjs\")),\n forcedCodes,\n ...(verifyRecord ? { verify: verifyRecord } : {}),\n });\n }\n } else {\n // 4. The gate (D41, D138): the verdict cached for these digests, or a run now.\n const outcome =\n verifier().cached(prepared) ??\n (await verifier().run(prepared, { build: (dir) => stageBuild(ready, dir) }));\n const { verdict } = outcome;\n // What didn't build can't be published, whatever the flags (D138 item 7): the run\n // recorded whether compile produced a build, so no code is matched to decide it.\n if (!outcome.built) {\n throw new RpcError(\n verdict.diagnostics.find(\n (diagnostic) => diagnostic.severity === \"error\" && diagnostic.phase === \"compile\",\n ) ??\n verdict.diagnostics.find((diagnostic) => diagnostic.severity === \"error\") ??\n createDiagnostic(\"MOSTRA_BUILD_FAILED\", { message: \"The build failed.\" }),\n );\n }\n const errors = errorCodes(verdict);\n // Verify couldn't run (no browser): without --force, publish fails with that\n // environment error itself, so the caller knows it isn't the artifact (D138 item 7).\n const environmental = verdict.diagnostics.find(\n (diagnostic) =>\n diagnostic.severity === \"error\" && diagnostic.code.startsWith(\"MOSTRA_ENV_\"),\n );\n if (environmental && params.force !== true) throw new RpcError(environmental);\n if (errors.length > 0 && params.force !== true) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_PUBLISH_VERIFY_FAILED\", {\n message: `Verify found errors, so nothing was published: ${errors.join(\", \")}.`,\n }),\n );\n }\n forcedCodes = params.force === true ? errors : [];\n verifyRecord = {\n status: errors.length === 0 ? \"pass\" : \"fail\",\n verifyRevision: VERIFY_REVISION,\n };\n // 5. Verify's build, promoted as it is when it was made for this version ID; built\n // again from the same snapshot otherwise (D138 item 5).\n const cachedBuild = verifier().builtVersion(versionId);\n if (cachedBuild && (await versionDamage(cachedBuild)) === undefined) {\n await renamePath(cachedBuild, out);\n outputDigest = (\n JSON.parse(await readFile(join(out, \"manifest.json\"), \"utf8\")) as {\n outputDigest: string;\n }\n ).outputDigest;\n } else {\n log.info(\"publish.rebuild\", {\n versionId,\n reason: cachedBuild ? \"damaged\" : \"not cached\",\n });\n const built = await stageBuild(ready, out);\n if (!built.ok) throw new RpcError(firstDiagnostic(built.diagnostics));\n outputDigest = built.outputDigest;\n }\n const server = existsSync(join(out, \"server\", \"entry.mjs\"));\n await writeVersionManifest(out, ready, {\n outputDigest,\n server,\n forcedCodes,\n verify: verifyRecord,\n });\n }\n const archive = registry.store.snapshotPath(artifactId, sourceDigest);\n if (await archiveSnapshot(join(staging, \"source\"), ready.listed, archive)) {\n undo.push(() => rm(archive, { force: true }));\n }\n faults.at(\"publish:after-archive\");\n if (damage !== undefined) await removeTree(registry.store.versionDir(versionId));\n undo.push(() => removeTree(registry.store.versionDir(versionId)));\n await registry.store.promote(out, versionId);\n faults.at(\"publish:after-promote\");\n }\n\n // 6. One transaction: identity, version, binding, events.\n const result = registry.commit({\n artifactId,\n bindingPath: source.bindingPath,\n manifestId: manifest.id,\n versionId,\n sourceDigest,\n envDigest,\n outputDigest,\n manifest,\n // D102: the registry resolves the policy in force from these, the earlier publishes'\n // choice and the manifest's request.\n policy: params.policy,\n homePolicy: options.homePolicy?.(),\n forcedCodes,\n ...(verifyRecord ? { verify: verifyRecord } : {}),\n stillClaims,\n faults,\n request: requestKey(\"artifact/publish\", params),\n // The resolution becomes the artifact's working lockfile only with the version (D95):\n // a refused publish, such as a copy claiming another artifact's ID, changes nothing.\n inTransaction: (db) => ready.deps.save(db, artifactId),\n });\n committed = true;\n faults.at(\"publish:after-commit\");\n log.info(\"publish.committed\", {\n artifactId,\n versionId,\n version: result.version,\n reused: result.reused,\n ...(forcedCodes.length > 0 ? { forcedCodes } : {}),\n });\n return {\n artifactId,\n versionId,\n version: result.version,\n cursor: result.cursor,\n reused: result.reused,\n ...(forcedCodes.length > 0 ? { forcedDiagnostics: forcedCodes } : {}),\n };\n } catch (error) {\n if (!committed) {\n for (const step of undo.reverse()) {\n await step().catch((cleanup: unknown) =>\n log.warn(\"publish.undo_failed\", { error: cleanup }),\n );\n }\n }\n throw error;\n }\n });\n\n const gated = <T>(fn: () => Promise<T>): Promise<T> =>\n options.gate ? options.gate.shared(fn) : fn();\n\n return {\n publish: (params) =>\n gated(() =>\n idempotent(requestKey(\"artifact/publish\", params), async () => {\n // The receipt is recorded inside the commit's transaction (Registry.commit).\n return publishOnce(params);\n }),\n ),\n verify: (params, progress) => gated(() => verifyOnce(params, progress)),\n // Creates run one at a time: two requests for one directory, or one request sent twice, can\n // never both find it empty.\n create: (params) => queue.run(\"create\", () => create(params)),\n // Runs in the source path's queue, like its publishes, so a publish that binds the path never\n // races an addition to the path-keyed lockfile it re-keys.\n addDependencies: (params) => gated(() => addDependencies(params)),\n };\n\n async function addDependencies(params: DepsAddParams): Promise<DepsAddResult> {\n {\n const path = pathOf(params.artifact);\n const source = await resolveSource(path);\n return queue.run(`path:${source.bindingPath}`, async () => {\n const manifestId = extractManifest(source.entry, await readEntry(source)).manifest?.id;\n return dependencies.add({\n key: lockKey(manifestId ?? registry.artifactAt(source.bindingPath), source.bindingPath),\n artifactDir: source.root,\n artifactPath: path,\n packages: params.packages,\n request: requestKey(\"deps/add\", params),\n });\n });\n }\n }\n\n async function create(params: ArtifactCreateParams): Promise<ArtifactCreateResult> {\n // A retried request completes what the first attempt recorded (H-03): the files are written\n // only after the result is durable, so a crash in between leaves something to finish. The\n // record also keeps the files' exact text, so a retry by a newer runtime completes exactly\n // what the first attempt began (WP-14's GPT and Opus reviews); the client gets the result\n // alone.\n const key = requestKey(\"artifact/create\", params);\n if (key !== undefined) {\n const recorded = ledger.read((db) =>\n recordedResult<CreateRecord | ArtifactCreateResult>(db, key),\n );\n if (recorded !== undefined) {\n if (\"result\" in recorded) {\n await writeScaffold(recorded.result.dir, recorded.scaffold.files);\n return recorded.result;\n }\n // A record from before WP-14 is the result itself, whose one file, the entry, names no\n // release: it is written as this runtime writes it.\n await writeScaffold(\n recorded.dir,\n scaffoldText(recorded.files, {\n artifactId: recorded.artifactId,\n title: params.title ?? basename(recorded.dir),\n version: options.runtimeVersion,\n }),\n );\n return recorded;\n }\n }\n if (params.template !== undefined) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ARTIFACT_TEMPLATE_UNKNOWN\", {\n message: `This Mostra release provides no template \"${params.template}\"; create the artifact without one.`,\n }),\n );\n }\n if (existsSync(params.dir)) {\n const info = await stat(params.dir);\n if (!info.isDirectory() || (await readdir(params.dir)).length > 0) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ARTIFACT_DIR_NOT_EMPTY\", {\n message: `${params.dir} already exists and isn't an empty directory.`,\n }),\n );\n }\n }\n await mkdir(params.dir, { recursive: true });\n const dir = await realpath(params.dir);\n const result: ArtifactCreateResult = {\n artifactId: ArtifactId.create(),\n dir,\n files: [...SCAFFOLD_PATHS],\n };\n const files = scaffoldText(result.files, {\n artifactId: result.artifactId,\n title: params.title ?? basename(dir),\n version: options.runtimeVersion,\n });\n const recordedCreate: CreateRecord = { result, scaffold: { files } };\n record(key, recordedCreate);\n faults.at(\"create:after-record\");\n await writeScaffold(dir, files);\n return result;\n }\n}\n","/**\n * `instance/check` (D140 item 18): the checks only the supervisor can run, because it holds the\n * ledger's lock (D81). `mostra doctor` shows them beside the checks the CLI runs itself.\n */\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createDiagnostic, type InstanceCheck, RpcError } from \"@mostra/protocol\";\nimport type { Ledger } from \"../ledger/index.ts\";\nimport type { Registry } from \"../registry/index.ts\";\nimport { versionDamage } from \"./publisher.ts\";\n\n/** What the checks read. */\nexport interface InstanceCheckInputs {\n /** Also hash every version against its output digest. */\n readonly deep: boolean;\n readonly ledger: Ledger;\n readonly registry: Registry;\n /** The shell's built files, when the runtime found them. */\n readonly shellDir: string | undefined;\n /** Finds the warm set; throws `MOSTRA_ENV_WARM_MISSING` when it is incomplete. */\n readonly warm: () => unknown;\n}\n\n/** Runs the checks in order: the ledger, the version store, the shell, the warm set. */\nexport async function instanceChecks(inputs: InstanceCheckInputs): Promise<InstanceCheck[]> {\n const checks: InstanceCheck[] = [];\n const integrity = inputs.ledger.checkIntegrity();\n checks.push(\n integrity.ok\n ? { name: \"ledger\", status: \"ok\" }\n : {\n name: \"ledger\",\n status: \"error\",\n diagnostic: createDiagnostic(\"MOSTRA_HOME_LEDGER_UNREADABLE\", {\n message: `SQLite's integrity check of the ledger failed: ${integrity.problems.slice(0, 3).join(\"; \")}.`,\n }),\n },\n );\n // Collected versions have no files by design (D140 item 14); every other version must.\n const versions = inputs.ledger.read((db) =>\n db.all<{ id: string; number: number; artifact_id: string }>(\n \"SELECT id, number, artifact_id FROM version WHERE id NOT IN (SELECT version_id FROM version_collected) ORDER BY artifact_id, number\",\n ),\n );\n const damaged: string[] = [];\n for (const version of versions) {\n const dir = inputs.registry.store.versionDir(version.id);\n const damage = inputs.deep\n ? await versionDamage(dir)\n : existsSync(join(dir, \"manifest.json\"))\n ? undefined\n : \"its files are missing\";\n if (damage !== undefined)\n damaged.push(`${version.artifact_id} version ${version.number}: ${damage}`);\n }\n checks.push(\n damaged.length === 0\n ? { name: \"versions\", status: \"ok\" }\n : {\n name: \"versions\",\n status: \"error\",\n diagnostic: createDiagnostic(\"MOSTRA_HOME_INTEGRITY\", {\n message: `${damaged.length} published ${damaged.length === 1 ? \"version is\" : \"versions are\"} damaged: ${damaged.slice(0, 3).join(\"; \")}${damaged.length > 3 ? \" …\" : \"\"}.`,\n }),\n },\n );\n checks.push(\n inputs.shellDir !== undefined\n ? { name: \"shell\", status: \"ok\" }\n : {\n name: \"shell\",\n status: \"error\",\n diagnostic: createDiagnostic(\"MOSTRA_ENV_SHELL_MISSING\", {\n message: \"The runtime has no built shell, so no capability link can open.\",\n }),\n },\n );\n try {\n inputs.warm();\n checks.push({ name: \"warm\", status: \"ok\" });\n } catch (error) {\n checks.push({\n name: \"warm\",\n status: \"error\",\n diagnostic:\n error instanceof RpcError\n ? error.diagnostic\n : createDiagnostic(\"MOSTRA_ENV_WARM_MISSING\", { message: String(error) }),\n });\n }\n return checks;\n}\n","/**\n * The authoring methods of the host protocol (INTERFACES §6): `artifact/create`,\n * `artifact/publish`, `artifact/list`, `artifact/get` and `deps/add`.\n */\nimport { realpathSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport {\n ARTIFACT_PROGRESS,\n type ArtifactRef,\n artifactCreateMethod,\n artifactGetMethod,\n artifactListMethod,\n artifactPublishMethod,\n artifactVerifyMethod,\n depsAddMethod,\n type SourceRef,\n} from \"@mostra/protocol\";\nimport { handler, type MethodHandler } from \"../protocol-server/index.ts\";\nimport type { Registry } from \"../registry/index.ts\";\nimport type { Publisher } from \"./publisher.ts\";\n\n/**\n * A path as bindings store it (D51): its real path, or, for a path that no longer exists, the real\n * path of its nearest existing ancestor joined with the rest.\n */\nfunction canonical(path: string): string {\n const absolute = resolve(path);\n try {\n // The native realpath(3), as `resolveSource` uses: on a case- or normalization-insensitive\n // file system it returns the on-disk spelling the binding was stored with.\n return realpathSync.native(absolute);\n } catch {\n const parent = dirname(absolute);\n return parent === absolute ? absolute : join(canonical(parent), basename(absolute));\n }\n}\n\n/**\n * A path as an `ArtifactRef` names it: canonical, so a moved or deleted source still names its\n * artifact (INTERFACES §6).\n */\nexport function canonicalRef(ref: ArtifactRef): ArtifactRef {\n return \"path\" in ref ? { path: canonical(ref.path) } : ref;\n}\n\n/**\n * The handlers of the authoring methods. `publisher` is called on first use, so an instance\n * whose runtime lacks the warm set still starts and reports `MOSTRA_ENV_WARM_MISSING` per call.\n */\nexport function artifactMethods(options: {\n readonly registry: Registry;\n readonly publisher: () => Publisher;\n /**\n * The artifact's default capability link (D90, D97 item 3), added to every receipt, replays\n * included. Recorded receipts never hold it: the ledger keeps no link's secret.\n */\n readonly link?: (\n artifactId: string,\n ) =>\n | { readonly url: string; readonly tokenId: string }\n | Promise<{ readonly url: string; readonly tokenId: string }>;\n /**\n * Hears every publish that succeeded, a reused version too: a publish clears the artifact's\n * parked workers (FAILURE_MODEL §2).\n */\n readonly published?: (artifactId: string) => void;\n /** `deps/add` changed an artifact's working lockfile: its `mostra dev` sessions resolve again. */\n readonly dependenciesAdded?: (artifact: SourceRef) => void;\n /** Sends a notification on a session's connection (`artifact/progress`). */\n readonly notify?: (session: number, method: string, params: Record<string, unknown>) => void;\n}): MethodHandler[] {\n const { registry } = options;\n return [\n handler(artifactCreateMethod, (params) => options.publisher().create(params)),\n handler(artifactPublishMethod, async (params) => {\n const receipt = await options.publisher().publish(params);\n options.published?.(receipt.artifactId);\n return options.link ? { ...receipt, ...(await options.link(receipt.artifactId)) } : receipt;\n }),\n handler(depsAddMethod, async (params) => {\n const added = await options.publisher().addDependencies(params);\n options.dependenciesAdded?.(params.artifact);\n return added;\n }),\n handler(artifactVerifyMethod, (params, session) => {\n const token = params.progressToken;\n // Progress only to a client that asked for it and accepts the notification (D84).\n const progress =\n token !== undefined && session.notifications.has(ARTIFACT_PROGRESS) && options.notify\n ? (stage: string) =>\n options.notify?.(session.id, ARTIFACT_PROGRESS, { progressToken: token, stage })\n : undefined;\n return options.publisher().verify(params, progress);\n }),\n handler(artifactListMethod, (params) => ({ artifacts: registry.list(params.filter ?? {}) })),\n handler(artifactGetMethod, (params) => {\n return registry.get(canonicalRef(params.artifact));\n }),\n ];\n}\n","/**\n * `mostra dev` (VR-08, D140 item 12): a development preview of an artifact's unpublished source,\n * with Vite's hot reload, its server code, live sources and submissions working, kept apart from\n * everything a viewer can reach.\n *\n * A session is a sandbox like a verify run's (D138 item 1): a scratch ledger in\n * `cache/dev/<session>/`, its own worker pool, and two loopback listeners on ports the operating\n * system picks, reached only with the link minted in that scratch ledger; the artifact origin's\n * files and HMR WebSocket come from a Vite server in a builder child, behind the gateway's checks.\n * The source is mirrored into the session's root (Mostra never writes into the artifact's\n * directory) and kept in step as it changes. Nothing reaches the home's drafts, state, events,\n * hosts or deliveries; submissions are reported to the session's connection with their Results.\n *\n * A session belongs to the connection that started it and ends with it (or `dev/stop`); open\n * sessions keep a daemon from its idle exit (D133). Recovery at start removes leftovers.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { type FSWatcher, watch } from \"node:fs\";\nimport { copyFile, mkdir, readdir, readFile, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport {\n ArtifactId,\n type ArtifactManifest,\n createDiagnostic,\n DEV_NOTIFY,\n type DevEventKind,\n type DevNotifyParams,\n type Diagnostic,\n devStartMethod,\n devStopMethod,\n RpcError,\n type SourceRef,\n VersionId,\n} from \"@mostra/protocol\";\nimport type { DevChange, DevChild, DevServerBuild, RenderMode } from \"../builder/index.ts\";\nimport { type Dependencies, lockKey } from \"../deps/index.ts\";\nimport type { Faults } from \"../faults.ts\";\nimport type { Gate } from \"../gate.ts\";\nimport type { Log } from \"../log.ts\";\nimport { removeTree } from \"../platform/index.ts\";\nimport { handler, type MethodHandler, type Session } from \"../protocol-server/index.ts\";\nimport { defaultTitle, extractManifest, listSource, resolveSource } from \"../publish/index.ts\";\nimport type { Registry } from \"../registry/index.ts\";\nimport { type Sandbox, type SandboxOptions, startSandbox } from \"../verify/index.ts\";\n\n/** How often the mirror is compared with the source, besides file-system events. */\nconst POLL_MS = 1000;\n/** How long the source must be still before the mirror catches up. */\nconst SETTLE_MS = 60;\n\n/** Options for {@link createDev}. */\nexport interface DevOptions {\n /** The home's real path. */\n readonly home: string;\n readonly log: Log;\n readonly registry: Registry;\n readonly renderMode: () => RenderMode;\n readonly dependencies: () => Dependencies;\n readonly gate: Gate;\n /** What a sandbox needs of the instance, as verify's. */\n readonly sandbox: () => SandboxOptions;\n /** The address the instance's gateway binds: dev refuses to run beside a non-loopback bind. */\n readonly bindAddress: string;\n /** Sends a notification to one connection; false when it couldn't. */\n readonly notify: (session: number, method: string, params: DevNotifyParams) => boolean;\n /** Test fault points (`dev:after-child`: setting up a dev server that started fails). */\n readonly faults?: Faults;\n}\n\n/** The dev sessions of an instance. */\nexport interface Dev {\n methods(): MethodHandler[];\n /** How many sessions are open: each keeps a daemon from its idle exit. */\n count(): number;\n /** An artifact's dependencies changed (`deps/add`): its sessions resolve them again. */\n dependenciesChanged(artifact: SourceRef): void;\n /**\n * The lockfiles open sessions run on, which gc keeps (Opus review finding 2): a session's\n * packages may be named by no working lockfile and no version.\n */\n locks(): string[];\n stopAll(): Promise<void>;\n}\n\n/** The directory every session lives in. */\nexport const devRoot = (home: string): string => join(home, \"cache\", \"dev\");\n\n/** Removes the sessions a stopped instance left; call it before any session starts. */\nexport async function recoverDev(home: string, log: Log): Promise<void> {\n let left: string[];\n try {\n left = await readdir(devRoot(home));\n } catch {\n return;\n }\n for (const name of left) await removeTree(join(devRoot(home), name));\n if (left.length > 0) log.info(\"dev.sessions_removed\", { count: left.length });\n}\n\nconst LOOPBACK = new Set([\"127.0.0.1\", \"::1\", \"localhost\"]);\n\ninterface Running {\n readonly id: string;\n readonly owner: number;\n readonly artifactId: string;\n readonly bindingPath: string;\n stop(): Promise<void>;\n resolveAgain(): void;\n}\n\n/** Creates the instance's dev sessions. */\nexport function createDev(options: DevOptions): Dev {\n const { log } = options;\n const sessions = new Map<string, Running>();\n /** Each session's current lockfile, from its resolution until its dev server stopped. */\n const locksInUse = new Map<string, string>();\n\n const start = async (\n params: {\n readonly source: { readonly path: string } | { readonly artifactId: string };\n readonly port?: number;\n },\n connection: Session,\n ): Promise<{ url: string; port: number; sessionId: string }> => {\n if (!LOOPBACK.has(options.bindAddress)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BIND_FAILED\", {\n message: `mostra dev serves only on loopback, and this instance binds ${options.bindAddress}.`,\n hint: \"Run mostra dev against an instance started without --bind.\",\n }),\n );\n }\n const path =\n \"path\" in params.source\n ? params.source.path\n : (options.registry.sourceOf(params.source.artifactId) ??\n (() => {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ARTIFACT_NOT_FOUND\", {\n message: `No artifact ${params.source.artifactId} was published in this home; name it by its source path.`,\n }),\n );\n })());\n const source = await resolveSource(path);\n const sessionId = `dev_${ArtifactId.create().slice(\"art_\".length)}`;\n const dir = join(devRoot(options.home), sessionId);\n const root = join(dir, \"root\");\n const versionDir = join(dir, \"version\");\n await mkdir(join(root, \"source\"), { recursive: true, mode: 0o700 });\n await mkdir(versionDir, { recursive: true });\n const secret = randomBytes(32).toString(\"base64url\");\n const versionId = VersionId.fromSha256(\n new Uint8Array(createHash(\"sha256\").update(`mostra dev ${sessionId}`).digest()),\n );\n const notify = (kind: DevEventKind, extra: Partial<DevNotifyParams> = {}): void => {\n options.notify(connection.id, DEV_NOTIFY, {\n sessionId,\n kind,\n at: new Date().toISOString(),\n ...extra,\n });\n };\n\n let closed = false;\n let child: DevChild | undefined;\n let sandbox: Sandbox | undefined;\n let watcher: FSWatcher | undefined;\n let poll: ReturnType<typeof setInterval> | undefined;\n let settleTimer: ReturnType<typeof setTimeout> | undefined;\n let outputDigest = \"\";\n let nodeModules = \"\";\n let manifestKey = \"\";\n let artifactId = \"\";\n const mirrored = new Map<string, string>();\n /** When each mirrored file was first missed: a save that moves the old file aside first. */\n const missing = new Map<string, number>();\n\n /**\n * Copies changed files into the mirror and removes deleted ones; what changed. Editors save\n * in several ways (in place, a temporary file renamed over the old one, the old one renamed\n * to a backup first), and on Windows an editor may hold a file it is writing so that nothing\n * else can read it: a file that can't be read now is left for the next sync, never recorded,\n * and a file is removed from the mirror only once it has been missing for\n * {@link MISSING_GRACE_MS}, so a save never looks like a deletion (WP-W2).\n */\n const sync = async (): Promise<DevChange[]> => {\n const files = await listSource(source);\n const changed: DevChange[] = [];\n const seen = new Set<string>();\n for (const file of files) {\n seen.add(file.path);\n missing.delete(file.path);\n let info: Awaited<ReturnType<typeof stat>>;\n try {\n info = await stat(file.absolute);\n } catch {\n continue;\n }\n const key = `${info.size}:${info.mtimeMs}:${info.ino}`;\n const before = mirrored.get(file.path);\n if (before === key) continue;\n const target = join(root, \"source\", ...file.path.split(\"/\"));\n try {\n await mkdir(dirname(target), { recursive: true });\n await copyFile(file.absolute, target);\n } catch (error) {\n log.info(\"dev.sync_deferred\", { sessionId, file: file.path, error });\n continue;\n }\n mirrored.set(file.path, key);\n changed.push({ file: file.path, kind: before === undefined ? \"add\" : \"change\" });\n }\n const now = Date.now();\n for (const path of [...mirrored.keys()]) {\n if (seen.has(path)) continue;\n const since = missing.get(path) ?? now;\n missing.set(path, since);\n if (now - since < MISSING_GRACE_MS) continue;\n missing.delete(path);\n mirrored.delete(path);\n await unlink(join(root, \"source\", ...path.split(\"/\"))).catch(() => {});\n changed.push({ file: path, kind: \"unlink\" });\n }\n return changed;\n };\n\n /** The manifest and identity of the mirrored source. */\n const describe = async (): Promise<{\n manifest: ArtifactManifest;\n artifactId: string;\n entryHasDefault: boolean;\n warnings: readonly Diagnostic[];\n }> => {\n const extracted = extractManifest(\n source.entry,\n await readFile(join(root, \"source\", source.entry), \"utf8\"),\n );\n const manifest = extracted.manifest ?? { title: defaultTitle(source) };\n const artifactId =\n manifest.id ??\n options.registry.artifactAt(source.bindingPath) ??\n stableId(source.bindingPath);\n return {\n manifest,\n artifactId,\n entryHasDefault: extracted.hasDefaultExport,\n warnings: extracted.warnings,\n };\n };\n\n /** Resolves the packages, and writes the lockfile the worker resolves server packages by. */\n const resolve = async (manifestId: string | undefined): Promise<string> => {\n // The lock is known to gc before the gate is released, so no gc can take its layout\n // between the resolution and the dev server's start.\n const resolution = await options.gate.shared(async () => {\n const resolved = await options.dependencies().resolve({\n key: lockKey(\n manifestId ?? options.registry.artifactAt(source.bindingPath),\n source.bindingPath,\n ),\n sourceDir: join(root, \"source\"),\n artifactDir: source.root,\n artifactPath: path,\n });\n if (!closed) locksInUse.set(sessionId, resolved.lock);\n return resolved;\n });\n await writeFile(join(versionDir, \"lock.yaml\"), resolution.lock);\n return resolution.nodeModules;\n };\n\n /** Writes the dev version's manifest with a new output digest for its new server bundle. */\n const writeVersion = async (\n manifest: ArtifactManifest,\n artifactId: string,\n server: boolean,\n ): Promise<void> => {\n outputDigest = createHash(\"sha256\")\n .update(`${sessionId}:${Date.now()}:${randomBytes(8).toString(\"hex\")}`)\n .digest(\"hex\");\n await writeFile(\n join(versionDir, \"manifest.json\"),\n `${JSON.stringify({ schemaVersion: 1, artifactId, versionId, mode: \"spa\", entry: source.entry, server, manifest, outputDigest, forcedCodes: [], dev: true }, null, 2)}\\n`,\n );\n };\n\n const reported = (build: DevServerBuild): void => {\n if (!build.ok) notify(\"diagnostics\", { diagnostics: build.diagnostics });\n };\n\n /** Starts (or restarts) the dev child over the current mirror. */\n const startChild = async (\n described: Awaited<ReturnType<typeof describe>>,\n ): Promise<DevChild> => {\n const started = await options.renderMode().dev(\n {\n root,\n entry: source.entry,\n entryHasDefault: described.entryHasDefault,\n manifest: described.manifest,\n versionId,\n nodeModules,\n outDir: versionDir,\n secret,\n },\n {\n server: (build, files) => {\n void (async () => {\n if (build.ok) {\n await writeVersion(described.manifest, described.artifactId, build.server);\n await sandbox?.replaceServer();\n await child?.reload().catch(() => {});\n notify(\"server-restarted\", { files });\n } else reported(build);\n })().catch((error: unknown) => log.warn(\"dev.server_reload_failed\", { error }));\n },\n update: (files) => notify(\"built\", { files }),\n },\n );\n void started.exited.then(() => {\n if (!closed && child === started) {\n log.warn(\"dev.child_exited\", { sessionId });\n notify(\"diagnostics\", {\n diagnostics: [\n createDiagnostic(\"MOSTRA_BUILD_CRASHED\", { message: \"The dev server stopped.\" }),\n ],\n });\n }\n });\n // A dev server this function can't hand back (its version's manifest can't be written,\n // because a stop removed the session meanwhile) is stopped here: nobody else knows it.\n try {\n options.faults?.at(\"dev:after-child\");\n if (started.ready.build.ok)\n await writeVersion(described.manifest, described.artifactId, started.ready.build.server);\n else reported(started.ready.build);\n } catch (error) {\n await started.stop().catch(() => {});\n throw error;\n }\n return started;\n };\n\n /** Catches the mirror up; resolves packages again and restarts the dev server when they or\n * the manifest changed. */\n let catching: Promise<void> = Promise.resolve();\n const catchUp = (forceResolve = false): void => {\n catching = catching\n .then(async () => {\n if (closed) return;\n const changed = await sync();\n if (changed.length === 0 && !forceResolve) return;\n const described = await describe();\n const key = JSON.stringify(described.manifest);\n const next = await resolve(described.manifest.id).catch((error: unknown) => {\n if (error instanceof RpcError)\n notify(\"diagnostics\", { diagnostics: [error.diagnostic] });\n return nodeModules;\n });\n const files = changed.map((change) => change.file);\n if (next !== nodeModules || key !== manifestKey) {\n // Other packages or another manifest: a new dev server over the same mirror, its\n // server bundle in the worker, and every page loaded again (D140 item 12).\n nodeModules = next;\n manifestKey = key;\n const old = child;\n child = await startChild(described);\n await old?.stop();\n await sandbox?.replaceServer();\n notify(\"reloaded\", { files });\n } else if (changed.length > 0) {\n await child?.changed(changed);\n }\n })\n .catch((error: unknown) => log.warn(\"dev.sync_failed\", { sessionId, error }));\n };\n\n /** Releases everything the session holds; safe to run again, and while it still starts. */\n const release = async (): Promise<void> => {\n clearInterval(poll);\n clearTimeout(settleTimer);\n watcher?.close();\n await catching.catch(() => {});\n await child?.stop().catch(() => {});\n await sandbox?.close().catch(() => {});\n locksInUse.delete(sessionId);\n // Through the platform layer: on Windows a file the dev server or an antivirus scan still\n // holds for a moment refuses removal, which it retries (D150 item 8).\n await removeTree(dir);\n };\n const stop = async (): Promise<void> => {\n if (closed) return;\n closed = true;\n sessions.delete(sessionId);\n await release();\n log.info(\"dev.stopped\", { sessionId });\n };\n /** The connection that started the session closed while it started: nothing may outlive it. */\n const abandoned = (): RpcError =>\n new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: \"The connection that started this dev session closed while it started.\",\n }),\n );\n\n // The session ends with its connection (D140 item 12), from the first moment: a connection\n // that closes while packages resolve or the dev server starts leaves nothing running. While\n // the session starts, its start owns the cleanup: a close marks it, and the start stops what\n // it started at its next step, then removes the session's directory. A close that removed\n // the directory at once did so under a dev server still writing into it (its staging files,\n // its `node_modules` link, Vite's cache), the removal failed on the files it wrote, and the\n // failure took the whole instance down (#35). Once started, a close stops the session, and\n // a stop that fails is logged: it never ends the instance.\n let starting = true;\n connection.signal.addEventListener(\n \"abort\",\n () => {\n if (starting) closed = true;\n else stop().catch((error: unknown) => log.warn(\"dev.stop_failed\", { sessionId, error }));\n },\n { once: true },\n );\n try {\n if (connection.signal.aborted) throw abandoned();\n // A close stops the start at its next step, before resolving packages least of all, which\n // may install under the shared gate (the Opus review of MT-02).\n await sync();\n if (closed) throw abandoned();\n const described = await describe();\n if (closed) throw abandoned();\n manifestKey = JSON.stringify(described.manifest);\n nodeModules = await resolve(described.manifest.id);\n artifactId = described.artifactId;\n if (closed) throw abandoned();\n child = await startChild(described);\n if (closed) throw abandoned();\n const upstream = (): { port: number; secret: string } | undefined =>\n child ? { port: child.ready.port, secret } : undefined;\n sandbox = await startSandbox(options.sandbox(), {\n artifactId: described.artifactId,\n versions: [\n {\n versionId,\n dir: versionDir,\n manifest: described.manifest,\n sourceDigest: \"0\".repeat(64),\n envDigest: \"0\".repeat(64),\n get outputDigest() {\n return outputDigest;\n },\n },\n ],\n sourceDir: source.root,\n runDir: join(dir, \"sandbox\"),\n dev: { upstream },\n ...(params.port !== undefined ? { shellPort: params.port } : {}),\n });\n if (closed) throw abandoned();\n // Nothing below awaits, so no close can fall between this and the session's registration.\n starting = false;\n sandbox.onSubmission((results) => notify(\"submission\", { results }));\n } catch (error) {\n closed = true;\n sessions.delete(sessionId);\n // Every step that started something has returned, so nothing writes into the session's\n // directory once its dev server and sandbox stopped.\n await release();\n if (connection.signal.aborted) log.info(\"dev.stopped\", { sessionId });\n throw error;\n }\n\n // Keep the mirror in step: file-system events when the platform gives them, a poll anyway.\n try {\n watcher = watch(source.kind === \"dir\" ? source.root : join(source.root, source.entry), {\n recursive: source.kind === \"dir\",\n persistent: false,\n });\n watcher.on(\"change\", () => {\n clearTimeout(settleTimer);\n settleTimer = setTimeout(() => catchUp(), SETTLE_MS);\n });\n watcher.on(\"error\", () => watcher?.close());\n } catch {\n watcher = undefined;\n }\n poll = setInterval(() => catchUp(), POLL_MS);\n poll.unref();\n\n sessions.set(sessionId, {\n id: sessionId,\n owner: connection.id,\n artifactId,\n bindingPath: source.bindingPath,\n stop,\n resolveAgain: () => catchUp(true),\n });\n const url = sandbox.link(versionId);\n log.info(\"dev.started\", { sessionId, artifactId });\n notify(\"built\");\n return { url, port: Number(new URL(url).port), sessionId };\n };\n\n return {\n methods: () => [\n handler(devStartMethod, (params, session) => start(params, session)),\n handler(devStopMethod, async (params, session) => {\n const running = sessions.get(params.sessionId);\n if (!running || running.owner !== session.id) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", {\n message: `This connection has no dev session ${params.sessionId}.`,\n }),\n );\n }\n await running.stop();\n return {};\n }),\n ],\n count: () => sessions.size,\n locks: () => [...locksInUse.values()],\n dependenciesChanged: (artifact) => {\n void (async () => {\n const bindingPath =\n \"path\" in artifact\n ? (await resolveSource(artifact.path).catch(() => undefined))?.bindingPath\n : undefined;\n for (const running of sessions.values()) {\n const same =\n \"artifactId\" in artifact\n ? running.artifactId === artifact.artifactId\n : running.bindingPath === bindingPath;\n if (same) running.resolveAgain();\n }\n })();\n },\n stopAll: async () => {\n await Promise.all([...sessions.values()].map((running) => running.stop()));\n },\n };\n}\n\n/**\n * How long a mirrored file must stay missing before `mostra dev` removes it: an editor that moves\n * the old file aside before writing the new one leaves a gap of milliseconds, a deletion lasts.\n * The 1 s comparison notices the removal within this and a second more.\n */\nconst MISSING_GRACE_MS = 1500;\n\nconst CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/** A stand-in artifact ID for a source no manifest `id` or binding names: stable per path. */\nfunction stableId(bindingPath: string): string {\n const hash = createHash(\"sha256\").update(`mostra dev provisional\\u0000${bindingPath}`).digest();\n let body = CROCKFORD[(hash[0] as number) % 8] as string;\n for (let index = 1; index < 26; index += 1) body += CROCKFORD[(hash[index] as number) % 32];\n return ArtifactId.parse(`art_${body}`);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * One gate per instance between `gc` and the work whose files it would remove (D140 item 14):\n * publishes, verify runs, dependency additions and layout installs hold it shared, so they run\n * side by side as before; a gc run holds it alone. Writers are preferred: once a gc waits, new\n * shared work waits behind it, so a busy home can't keep gc out forever. Shared work started\n * inside shared work (a verify run starting a worker whose layout installs) joins its caller's\n * hold rather than waiting, so a waiting gc never deadlocks it.\n */\nexport class Gate {\n readonly #holding = new AsyncLocalStorage<true>();\n #shared = 0;\n #exclusive = false;\n #waitingExclusive = 0;\n readonly #wakers: (() => void)[] = [];\n\n /** Runs `fn` beside other shared work, never during a gc run. */\n async shared<T>(fn: () => Promise<T>): Promise<T> {\n if (this.#holding.getStore() === true) return fn();\n while (this.#exclusive || this.#waitingExclusive > 0) await this.#wait();\n this.#shared += 1;\n try {\n return await this.#holding.run(true, fn);\n } finally {\n this.#shared -= 1;\n this.#wake();\n }\n }\n\n /** Runs `fn` alone: after shared work in flight ends, and before any that arrives meanwhile. */\n async exclusive<T>(fn: () => Promise<T>): Promise<T> {\n this.#waitingExclusive += 1;\n try {\n while (this.#exclusive || this.#shared > 0) await this.#wait();\n } finally {\n this.#waitingExclusive -= 1;\n }\n this.#exclusive = true;\n try {\n return await this.#holding.run(true, fn);\n } finally {\n this.#exclusive = false;\n this.#wake();\n }\n }\n\n #wait(): Promise<void> {\n return new Promise((resolve) => this.#wakers.push(resolve));\n }\n\n #wake(): void {\n for (const wake of this.#wakers.splice(0)) wake();\n }\n}\n","/**\n * `mostra gc` (VR-06, D47, D140 item 14): removes what nothing references, on request only.\n *\n * - **Versions.** A version is kept while any {@link REFERENCE_SOURCES} names it. One nothing names\n * loses its files; its ledger row, ID and number stay forever, and `version_collected` records\n * the collection, so a content-addressed ID never gets a second number. Publishing its exact\n * source again restores the files (publish's repair path) and clears the record.\n * - **Everything else** gc collects belongs to the module that owns it: lock layouts and the store\n * (`deps`), verify's caches (`verify`), events (`interaction`'s compaction, only when asked).\n * - **Order.** A run holds the instance's gate alone, so no publish, verify or install runs beside\n * it. It decides and records the collected versions in one transaction, then removes their files\n * after the commit; when the process dies in between, recovery at start removes what the record\n * says is gone. A real run lists exactly what a dry run lists.\n */\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n createDiagnostic,\n type Diagnostic,\n type GcCompacted,\n type GcRunParams,\n type GcRunResult,\n type GcVersion,\n gcRunMethod,\n RpcError,\n} from \"@mostra/protocol\";\nimport type { Dependencies } from \"../deps/index.ts\";\nimport type { Faults } from \"../faults.ts\";\nimport type { Gate } from \"../gate.ts\";\nimport { compactEvents } from \"../interaction/index.ts\";\nimport type { Ledger, LedgerDb } from \"../ledger/index.ts\";\nimport type { Log } from \"../log.ts\";\nimport { handler, type MethodHandler } from \"../protocol-server/index.ts\";\nimport { type Registry, removeTree } from \"../registry/index.ts\";\n\n/** One reason a version is kept: a named source over the ledger columns it accounts for. */\nexport interface ReferenceSource {\n /** What references the version, in words: `submissions`, `pinned links` … */\n readonly name: string;\n /** The ledger columns it accounts for, as `table.column` (the schema test checks them). */\n readonly covers: readonly string[];\n /** The version IDs it keeps, read inside gc's transaction at `now` (RFC 3339). */\n keep(db: LedgerDb, now: string): Iterable<string>;\n}\n\n/** A ledger column that names a version but keeps none, with the reason. */\nexport interface ExemptColumn {\n readonly column: string;\n readonly reason: string;\n}\n\n/** Every version ID written in a text: snapshots, anchors and review choices name them (D89). */\nconst VERSION_IDS = /ver_[0-9A-HJKMNP-TV-Z]{26}/g;\n\nfunction* idsIn(texts: Iterable<string | null>): Iterable<string> {\n for (const text of texts) if (text) yield* text.match(VERSION_IDS) ?? [];\n}\n\nconst column = <T>(db: LedgerDb, sql: string, ...params: string[]): T[] =>\n db.all<{ value: T }>(sql, ...params).map((row) => row.value);\n\nconst tableExists = (db: LedgerDb, table: string): boolean =>\n db.get(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\", table) !== undefined;\n\n/** The version a number names within its artifact: `SELECT id FROM version` joined by number. */\nconst BY_NUMBER = (alias: string, numberColumn: string): string =>\n `(SELECT version.id FROM version WHERE version.artifact_id = ${alias}.artifact_id AND version.number = ${alias}.${numberColumn})`;\n\n/**\n * Why versions are kept, one named source each (D140 item 14). A table that names versions joins\n * this list, or {@link EXEMPT_COLUMNS} with a reason; the schema test fails until it does.\n */\nexport const REFERENCE_SOURCES: readonly ReferenceSource[] = [\n {\n name: \"latest versions\",\n covers: [\"artifact.latest_version_id\"],\n keep: (db) =>\n column<string>(\n db,\n \"SELECT latest_version_id AS value FROM artifact WHERE latest_version_id IS NOT NULL\",\n ),\n },\n {\n // Following loads each new latest version (D63, LL-03): the latest is kept above, and this\n // source says so, so a change to either rule shows in its test.\n name: \"followed artifacts\",\n covers: [],\n keep: (db) =>\n column<string>(\n db,\n \"SELECT artifact.latest_version_id AS value FROM follow JOIN artifact ON artifact.id = follow.artifact_id WHERE artifact.latest_version_id IS NOT NULL\",\n ),\n },\n {\n name: \"submissions\",\n covers: [\n \"submission.version_id\",\n \"submission.latest_version_number\",\n \"submission.snapshot_json\",\n ],\n keep: function* (db) {\n yield* column<string>(db, \"SELECT version_id AS value FROM submission\");\n yield* column<string>(\n db,\n `SELECT ${BY_NUMBER(\"submission\", \"latest_version_number\")} AS value FROM submission WHERE latest_version_number IS NOT NULL`,\n ).filter((id) => id !== null);\n yield* idsIn(column<string>(db, \"SELECT snapshot_json AS value FROM submission\"));\n },\n },\n {\n name: \"views\",\n covers: [\"view.version_id\"],\n keep: (db) => column<string>(db, \"SELECT version_id AS value FROM view\"),\n },\n {\n name: \"comment threads\",\n covers: [\"thread.version_id\", \"thread.anchor_json\"],\n keep: function* (db) {\n if (!tableExists(db, \"thread\")) return;\n yield* column<string>(db, \"SELECT version_id AS value FROM thread\");\n yield* idsIn(column<string>(db, \"SELECT anchor_json AS value FROM thread\"));\n },\n },\n {\n name: \"action runs\",\n covers: [\"action_run.version_id\"],\n keep: (db) => column<string>(db, \"SELECT version_id AS value FROM action_run\"),\n },\n {\n name: \"live sessions\",\n covers: [\"session.version_id\"],\n keep: (db) =>\n column<string>(db, \"SELECT version_id AS value FROM session WHERE version_id IS NOT NULL\"),\n },\n {\n name: \"live producer values\",\n covers: [\"live_value.producer_version_id\"],\n keep: (db) =>\n column<string>(\n db,\n \"SELECT producer_version_id AS value FROM live_value WHERE producer_version_id IS NOT NULL\",\n ),\n },\n {\n // A review set's candidates may be versions (D23); a choice, a draft's or the artifact\n // state's, names the one chosen. The version whose view last wrote a field is its orphan's\n // `fromVersion` (D109).\n name: \"review sets and fields\",\n covers: [\"field.value_json\", \"field.version_number\"],\n keep: function* (db) {\n yield* idsIn(\n column<string>(db, \"SELECT value_json AS value FROM field WHERE field_id LIKE 'review.%'\"),\n );\n yield* column<string>(\n db,\n `SELECT (SELECT version.id FROM version WHERE version.artifact_id = document.artifact_id AND version.number = field.version_number) AS value FROM field JOIN document ON document.id = field.document_id WHERE field.version_number IS NOT NULL`,\n ).filter((id) => id !== null);\n },\n },\n {\n name: \"pinned links\",\n covers: [\"token.pinned_version\"],\n keep: (db, now) =>\n column<string>(\n db,\n `SELECT ${BY_NUMBER(\"token\", \"pinned_version\")} AS value FROM token WHERE pinned_version IS NOT NULL AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > ?)`,\n now,\n ).filter((id) => id !== null),\n },\n {\n // The regression baseline (D138 item 4): the newest version whose recorded verdict passed.\n name: \"regression baselines\",\n covers: [\"version.verify_json\"],\n keep: (db) =>\n column<string>(\n db,\n \"SELECT (SELECT id FROM version AS newest WHERE newest.artifact_id = artifact.id AND json_extract(newest.verify_json, '$.status') = 'pass' ORDER BY newest.number DESC LIMIT 1) AS value FROM artifact\",\n ).filter((id) => id !== null),\n },\n];\n\n/** Columns that name versions but keep none. */\nexport const EXEMPT_COLUMNS: readonly ExemptColumn[] = [\n { column: \"version.id\", reason: \"the version itself\" },\n { column: \"version.number\", reason: \"the version itself\" },\n {\n column: \"version_collected.version_id\",\n reason: \"the record that gc collected the version\",\n },\n {\n column: \"schema_migration.version\",\n reason: \"the ledger's schema version, not an artifact version\",\n },\n {\n column: \"dependency_package.version\",\n reason: \"an npm package's version in the store index, not an artifact version\",\n },\n {\n column: \"schema_migration.runtime_version\",\n reason: \"the runtime release that ran a migration\",\n },\n];\n\n/** The versions some source keeps. */\nexport function keptVersions(db: LedgerDb, now: string): Set<string> {\n const kept = new Set<string>();\n for (const source of REFERENCE_SOURCES) for (const id of source.keep(db, now)) kept.add(id);\n return kept;\n}\n\n/** A version gc would collect: not collected yet, and kept by no source. */\nexport interface Candidate {\n readonly artifactId: string;\n readonly versionId: string;\n readonly number: number;\n readonly sourceDigest: string;\n}\n\n/** The versions gc collects now: not collected yet, and kept by no {@link REFERENCE_SOURCES}. */\nexport function collectableVersions(db: LedgerDb, now: string): Candidate[] {\n const kept = keptVersions(db, now);\n return db\n .all<{ id: string; artifact_id: string; number: number; source_digest: string }>(\n \"SELECT id, artifact_id, number, source_digest FROM version WHERE id NOT IN (SELECT version_id FROM version_collected) ORDER BY artifact_id, number\",\n )\n .filter((row) => !kept.has(row.id))\n .map((row) => ({\n artifactId: row.artifact_id,\n versionId: row.id,\n number: row.number,\n sourceDigest: row.source_digest,\n }));\n}\n\n/** What gc needs of its instance. */\nexport interface GcOptions {\n readonly ledger: Ledger;\n readonly registry: Registry;\n readonly log: Log;\n /** The instance's gate: gc holds it alone. */\n readonly gate: Gate;\n readonly dependencies: () => Dependencies;\n /** Verify's caches past their cap; absent while verify was never used. */\n readonly caches: (dryRun: boolean) => Promise<{ readonly count: number; readonly bytes: number }>;\n /** The clock (tests move it); default `Date.now`. */\n readonly now?: () => number;\n /**\n * Lockfiles in use outside the ledger: open dev sessions run on them (Opus review finding 2).\n * Read under the gate, which a session's resolution shares, so none appears mid-run.\n */\n readonly locksInUse?: () => readonly string[];\n /** Test fault points: `gc:dependencies` fails the dependency step. */\n readonly faults?: Faults;\n}\n\n/** The home's garbage collector. */\nexport interface Gc {\n /** `gc/run`: collects, or with `dryRun` lists, what nothing references. */\n run(params: GcRunParams): Promise<GcRunResult>;\n}\n\n/** Creates the garbage collector of one instance. */\nexport function createGc(options: GcOptions): Gc {\n const { ledger, registry, log } = options;\n const now = options.now ?? Date.now;\n\n /** The bytes a directory or file holds; 0 when it is gone. */\n const sizeOf = async (path: string): Promise<number> => {\n const info = await stat(path).catch(() => undefined);\n if (!info) return 0;\n if (!info.isDirectory()) return info.size;\n let total = 0;\n for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {\n total += await sizeOf(join(path, entry.name));\n }\n return total;\n };\n\n return {\n run: (params) =>\n options.gate.exclusive(async () => {\n const dryRun = params.dryRun === true;\n const at = new Date(now()).toISOString();\n // 1. Decide, and for a real run record, in one transaction.\n const chosen = ledger.write((db) => {\n const found = collectableVersions(db, at);\n if (!dryRun) {\n for (const candidate of found) {\n db.run(\n \"INSERT INTO version_collected (version_id, collected_at) VALUES (?, ?)\",\n candidate.versionId,\n at,\n );\n }\n }\n return found;\n });\n // Source snapshots, and lockfiles, of the versions that keep their files.\n const chosenIds = new Set(chosen.map((candidate) => candidate.versionId));\n const keptRows = ledger\n .read((db) =>\n db.all<{ id: string; artifact_id: string; source_digest: string }>(\n \"SELECT id, artifact_id, source_digest FROM version WHERE id NOT IN (SELECT version_id FROM version_collected)\",\n ),\n )\n .filter((row) => !chosenIds.has(row.id));\n const keptSnapshots = new Set(\n keptRows.map((row) => `${row.artifact_id}/${row.source_digest}`),\n );\n const snapshots = [\n ...new Set(\n chosen\n .map((candidate) => `${candidate.artifactId}/${candidate.sourceDigest}`)\n .filter((key) => !keptSnapshots.has(key)),\n ),\n ];\n // A step that fails leaves its files and becomes a warning; what earlier steps removed\n // is still reported (Opus review finding 1). The tombstones are committed: recovery at\n // start removes any version file a failed removal left.\n const warnings: Diagnostic[] = [];\n const incomplete = (step: string, error: unknown): void => {\n const cause =\n error instanceof RpcError\n ? `${error.diagnostic.code}: ${error.diagnostic.message}`\n : error instanceof Error\n ? error.message\n : String(error);\n warnings.push(\n createDiagnostic(\"MOSTRA_HOME_GC_INCOMPLETE\", {\n message: `gc couldn't finish ${step}: ${cause}`,\n }),\n );\n log.warn(\"gc.incomplete\", { step, cause });\n };\n // 2. Sizes, then the files: after the commit, so a crash leaves only what recovery removes.\n const versions: GcVersion[] = [];\n for (const candidate of chosen) {\n const dir = registry.store.versionDir(candidate.versionId);\n versions.push({\n artifactId: candidate.artifactId,\n versionId: candidate.versionId,\n number: candidate.number,\n bytes: await sizeOf(dir),\n });\n if (!dryRun)\n await removeTree(dir).catch((error: unknown) =>\n incomplete(`removing ${candidate.versionId}'s files`, error),\n );\n }\n let snapshotBytes = 0;\n for (const key of snapshots) {\n const [artifactId, sourceDigest] = key.split(\"/\") as [string, string];\n const path = registry.store.snapshotPath(artifactId, sourceDigest);\n snapshotBytes += await sizeOf(path);\n if (!dryRun)\n await removeTree(path).catch((error: unknown) =>\n incomplete(\"removing a source snapshot\", error),\n );\n }\n // 3. Lock layouts and the store: what the versions that keep their files still need.\n const keep: string[] = [...(options.locksInUse?.() ?? [])];\n for (const row of keptRows) {\n const text = await readFile(\n join(registry.store.versionDir(row.id), \"lock.yaml\"),\n \"utf8\",\n ).catch(() => undefined);\n if (text !== undefined) keep.push(text);\n }\n const none = { count: 0, bytes: 0 };\n const deps = await Promise.resolve()\n .then(() => {\n options.faults?.at(\"gc:dependencies\");\n return options.dependencies().collect({ keep, dryRun });\n })\n .catch((error: unknown) => {\n incomplete(\"collecting lock layouts and the package store\", error);\n return {\n lockLayouts: { ...none, names: [] as string[] },\n storePackages: { ...none, packages: [] as string[] },\n };\n });\n if (\"failed\" in deps.storePackages && deps.storePackages.failed)\n incomplete(\"pruning the package store\", new RpcError(deps.storePackages.failed));\n // 4. Verify's caches.\n const caches = await options.caches(dryRun).catch((error: unknown) => {\n incomplete(\"collecting verify's caches\", error);\n return none;\n });\n // 5. Events, only when asked (D47).\n let compacted: GcCompacted | undefined;\n if (params.compactEvents !== undefined) {\n const before = Number(params.compactEvents.before);\n const pending = (db: LedgerDb, artifactId: string): number =>\n db.get<{ n: number }>(\n \"SELECT COUNT(*) AS n FROM event WHERE artifact_id = ? AND cursor < ? AND type <> 'artifact.compacted'\",\n artifactId,\n before,\n )?.n ?? 0;\n const compact = (db: LedgerDb): GcCompacted => {\n const done: { artifactId: string; removed: number }[] = [];\n for (const { artifact_id: artifactId } of db.all<{ artifact_id: string }>(\n \"SELECT DISTINCT artifact_id FROM event WHERE cursor < ? AND artifact_id IS NOT NULL ORDER BY artifact_id\",\n before,\n )) {\n const removed = pending(db, artifactId);\n if (removed === 0) continue;\n if (!dryRun) compactEvents(db, artifactId, before);\n done.push({ artifactId, removed });\n }\n return { artifacts: done, removed: done.reduce((acc, item) => acc + item.removed, 0) };\n };\n try {\n compacted = dryRun ? ledger.read(compact) : ledger.write(compact);\n } catch (error) {\n incomplete(\"compacting events\", error);\n }\n }\n const result: GcRunResult = {\n dryRun,\n versions,\n snapshots: { count: snapshots.length, bytes: snapshotBytes },\n lockLayouts: { count: deps.lockLayouts.count, bytes: deps.lockLayouts.bytes },\n storePackages: { count: deps.storePackages.count, bytes: deps.storePackages.bytes },\n caches,\n bytes:\n versions.reduce((acc, version) => acc + version.bytes, 0) +\n snapshotBytes +\n deps.lockLayouts.bytes +\n deps.storePackages.bytes +\n caches.bytes,\n ...(compacted ? { compacted } : {}),\n ...(warnings.length > 0 ? { warnings } : {}),\n };\n log.info(dryRun ? \"gc.planned\" : \"gc.collected\", {\n versions: versions.length,\n snapshots: snapshots.length,\n lockLayouts: deps.lockLayouts.count,\n storePackages: deps.storePackages.count,\n caches: caches.count,\n bytes: result.bytes,\n ...(compacted ? { compactedEvents: compacted.removed } : {}),\n });\n return result;\n }),\n };\n}\n\n/** The handler of `gc/run`. */\nexport function gcMethods(gc: Gc): MethodHandler[] {\n return [handler(gcRunMethod, (params) => gc.run(params))];\n}\n","/**\n * Where a home and its control endpoint live (DATA_MODEL §1, D82, D84, D85). Resolving a path never\n * touches the file system; preparing a directory creates it owner-only, tightens one the user\n * owns, and refuses one owned by someone else. The per-system details are the platform layer's.\n */\nimport { createHash } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { VersionId } from \"@mostra/protocol\";\nimport type { Environment } from \"../log.ts\";\nimport {\n controlEndpoint,\n defaultHome,\n socketPathLimit as limitFor,\n OS,\n ownedDirectory,\n type PreparedDirectory,\n pathsOf,\n type RuntimeDirChoice,\n runtimeDirFor,\n} from \"../platform/index.ts\";\n\nexport type { PreparedDirectory, RuntimeDirChoice };\n\n/** What path resolution reads: the flag, the environment and the platform. */\nexport interface PathInputs {\n /** `--home`, when given. */\n readonly home?: string | undefined;\n readonly env: Environment;\n readonly platform?: string;\n /** The user's home directory. Default `os.homedir()`. */\n readonly userHome?: string;\n /** Resolves a relative `--home` or `MOSTRA_HOME`. Default `process.cwd()`. */\n readonly cwd?: string;\n}\n\nconst nonEmpty = (value: string | undefined): string | undefined =>\n value === undefined || value === \"\" ? undefined : value;\n\n/**\n * The home path, resolved in D84's order: `--home`, then `MOSTRA_HOME`, then the platform default\n * (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux,\n * `%LOCALAPPDATA%\\mostra` on Windows). An SDK passes its `home` option as `--home`.\n */\nexport function resolveHomePath(inputs: PathInputs): string {\n const cwd = inputs.cwd ?? process.cwd();\n const chosen = nonEmpty(inputs.home) ?? nonEmpty(inputs.env[\"MOSTRA_HOME\"]);\n if (chosen !== undefined) return pathsOf(inputs.platform ?? OS).resolve(cwd, chosen);\n return defaultHome(inputs.platform ?? OS, inputs.env, inputs.userHome ?? homedir());\n}\n\n/**\n * The runtime directory for control sockets (D82): `MOSTRA_RUNTIME_DIR`; else `~/.mostra/run` on\n * macOS; on Linux `$XDG_RUNTIME_DIR/mostra` when `$XDG_RUNTIME_DIR` is a directory the user owns\n * that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`. On\n * Windows `undefined`: the control pipe lives in the system's pipe namespace.\n */\nexport function resolveRuntimeDir(inputs: Omit<PathInputs, \"home\">): RuntimeDirChoice | undefined {\n return runtimeDirFor({\n os: inputs.platform ?? OS,\n env: inputs.env,\n userHome: inputs.userHome ?? homedir(),\n cwd: inputs.cwd ?? process.cwd(),\n });\n}\n\n/** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */\nexport function socketPathLimit(platform: string = OS): number {\n return limitFor(platform);\n}\n\n/**\n * A home's hash (D82): 16 Crockford base32 characters of the SHA-256 of its real path, which\n * names its socket and its login service.\n */\nexport function homeHash(realHome: string): string {\n const digest = createHash(\"sha256\").update(realHome, \"utf8\").digest();\n // VersionId.fromSha256 is the one Crockford encoder (D77); its body starts with the same 16\n // characters any encoding of this digest would.\n return VersionId.fromSha256(new Uint8Array(digest)).slice(\"ver_\".length, \"ver_\".length + 16);\n}\n\n/**\n * The control endpoint for a home (D82), named by its {@link homeHash}: the socket in `runtimeDir`\n * on POSIX, throwing `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit; on Windows the pipe\n * name that each bind completes with a random part.\n */\nexport function socketPathFor(\n runtimeDir: string | undefined,\n realHome: string,\n platform: string = OS,\n): string {\n return controlEndpoint(runtimeDir, homeHash(realHome), platform);\n}\n\n/**\n * Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,\n * tightens one the user owns (mode 0700, or an owner-only access list on Windows), and throws\n * `MOSTRA_HOME_NOT_OWNED` for one owned by another user or a path that isn't a directory.\n */\nexport function prepareOwnedDirectory(path: string): PreparedDirectory {\n return ownedDirectory(path);\n}\n","/**\n * `instance.json` (D81): how starters and clients find the supervisor that owns a home. It is a\n * discovery record, never a lock: the ledger lock decides ownership. The owner writes it\n * atomically after binding its socket and removes it on a clean exit; a record whose PID and\n * start time match no live process is stale.\n */\nimport { readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as z from \"zod\";\nimport { isSameProcess, renamePathSync } from \"../platform/index.ts\";\n\n/** The record's file name in the home. */\nexport const INSTANCE_FILE = \"instance.json\";\n\n/** What `instance.json` holds. */\nexport interface InstanceRecord {\n /** The owner's process ID. */\n readonly pid: number;\n /** The owner's process start time (processes/identity.ts). */\n readonly startTime: string;\n /** The control socket clients attach to. */\n readonly socket: string;\n /** The owner's runtime release. */\n readonly runtimeVersion: string;\n /** The host protocol revisions the owner speaks. */\n readonly revisions: readonly string[];\n /** `host` or `daemon` (`InstanceInfo.mode`). */\n readonly mode: \"host\" | \"daemon\";\n /** When the owner took the home (RFC 3339). */\n readonly startedAt: string;\n}\n\nconst InstanceRecordSchema = z.object({\n pid: z.int().min(1),\n startTime: z.string(),\n socket: z.string(),\n runtimeVersion: z.string(),\n revisions: z.array(z.string()),\n mode: z.enum([\"host\", \"daemon\"]),\n startedAt: z.string(),\n});\n\n/** Reads the record, or `undefined` when it is missing or unreadable. */\nexport function readInstanceRecord(home: string): InstanceRecord | undefined {\n try {\n const parsed = InstanceRecordSchema.safeParse(\n JSON.parse(readFileSync(join(home, INSTANCE_FILE), \"utf8\")),\n );\n return parsed.success ? parsed.data : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Reads the record when it names a live process: the owner, or a starter's view of it. */\nexport async function readLiveInstanceRecord(home: string): Promise<InstanceRecord | undefined> {\n const record = readInstanceRecord(home);\n if (!record) return undefined;\n return (await isSameProcess(record.pid, record.startTime)) ? record : undefined;\n}\n\n/** Writes the record atomically (a temporary file, then a rename), mode 0600. */\nexport function writeInstanceRecord(home: string, record: InstanceRecord): void {\n const file = join(home, INSTANCE_FILE);\n const temp = `${file}.${process.pid}.tmp`;\n writeFileSync(temp, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 });\n renamePathSync(temp, file);\n}\n\n/** Removes the record when it is still this process's (a clean exit). */\nexport function removeInstanceRecord(home: string, pid: number, startTime: string): void {\n const record = readInstanceRecord(home);\n if (record && record.pid === pid && record.startTime === startTime) {\n rmSync(join(home, INSTANCE_FILE), { force: true });\n }\n}\n","/**\n * Taking a home (D81, D82, D85; FAILURE_MODEL §2, §3). The ledger's exclusive lock decides who\n * owns the home; the socket and `instance.json` are how everyone else finds the owner. A starter\n * that doesn't get the lock attaches to the owner (a daemon starter) or reports\n * `MOSTRA_HOME_LOCKED` (`mostra host`, or an owner it can't reach).\n */\nimport { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n type ClientInfo,\n createDiagnostic,\n type Diagnostic,\n HOST_PROTOCOL_REVISIONS,\n type MostraInitializeResult,\n RpcError,\n} from \"@mostra/protocol\";\nimport { LEDGER_FILE, type Ledger, openLedger } from \"../ledger/index.ts\";\nimport { type Environment, type Log, openFileLog, Redactor } from \"../log.ts\";\nimport { readProcess } from \"../processes/index.ts\";\nimport { attach, type SocketClient } from \"../protocol-server/index.ts\";\nimport {\n prepareOwnedDirectory,\n type RuntimeDirChoice,\n resolveRuntimeDir,\n socketPathFor,\n} from \"./paths.ts\";\nimport {\n type InstanceRecord,\n readInstanceRecord,\n readLiveInstanceRecord,\n removeInstanceRecord,\n writeInstanceRecord,\n} from \"./record.ts\";\n\n/** How long a starter waits for the owner of a locked home to become reachable, by default. */\nconst DEFAULT_WAIT_MS = 20_000;\n/** How often the owner checks that its home still exists, by default (at most 10 s, D81). */\nconst DEFAULT_WATCH_MS = 5000;\n\n/** Options for {@link acquireHome}. */\nexport interface AcquireHomeOptions {\n /** The resolved home path (`resolveHomePath`). */\n readonly home: string;\n readonly env: Environment;\n /** `host` never attaches to another instance; `daemon` does. */\n readonly mode: \"host\" | \"daemon\";\n readonly runtimeVersion: string;\n /** How a losing daemon starter introduces itself when it attaches. */\n readonly client: ClientInfo;\n /** How long to wait for a locked home's owner. Default 20 s. */\n readonly waitMs?: number;\n /** Where warnings and errors are mirrored besides the log file, such as stderr. */\n readonly mirror?: (line: string) => void;\n}\n\n/** A home this process owns. Holding it holds the home's ledger lock. */\nexport interface OwnedHome {\n /** The home's real path. */\n readonly path: string;\n /**\n * The control endpoint's base: the socket path on POSIX; on Windows the pipe name each bind\n * completes. `instance.json` records the endpoint actually bound.\n */\n readonly socketPath: string;\n /** The runtime directory; `undefined` on Windows, which has none. */\n readonly runtimeDir: RuntimeDirChoice | undefined;\n readonly ledger: Ledger;\n readonly log: Log;\n /** Removes secrets and capability material from everything the instance logs or reports. */\n readonly redactor: Redactor;\n /** This process's identity, as recorded in `ledger_lock` and `instance.json`. */\n readonly self: { readonly pid: number; readonly startTime: string };\n /** When this process took the home (RFC 3339). */\n readonly startedAt: string;\n /** Writes `instance.json` naming the bound endpoint; call it once it listens, and again when it moves. */\n publish(mode: \"host\" | \"daemon\", socket: string): void;\n /**\n * Calls `onGone` once with `MOSTRA_HOME_GONE` if the home or its ledger disappears or is\n * replaced. Checks every `intervalMs`, at most 10 s.\n */\n watch(onGone: (diagnostic: Diagnostic) => void, intervalMs?: number): void;\n /** Removes `instance.json` if it is still this process's, and releases the lock. Idempotent. */\n release(): void;\n}\n\n/** The outcome of {@link acquireHome}. */\nexport type HomeAcquisition =\n | { readonly kind: \"owner\"; readonly home: OwnedHome }\n | {\n readonly kind: \"attached\";\n /** The owner, as `instance.json` names it. */\n readonly record: InstanceRecord;\n /** An initialized session with the owner; the caller closes it. */\n readonly connection: SocketClient;\n readonly result: MostraInitializeResult;\n };\n\nconst delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction locked(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_HOME_LOCKED\", { message }));\n}\n\n/**\n * Takes the home, or finds its owner. Throws an `RpcError` with `MOSTRA_HOME_NOT_OWNED`,\n * `MOSTRA_HOME_SOCKET_TOO_LONG`, `MOSTRA_HOME_LOCKED`, `MOSTRA_HOME_TOO_NEW`,\n * `MOSTRA_HOME_LEDGER_UNREADABLE` or `MOSTRA_HOST_REVISION_UNSUPPORTED` when it can do neither.\n * Call it only after the platform gate.\n */\nexport async function acquireHome(options: AcquireHomeOptions): Promise<HomeAcquisition> {\n const prepared = prepareOwnedDirectory(options.home);\n const home = prepared.realPath;\n const runtimeDir = resolveRuntimeDir({ env: options.env });\n // Check the length before creating anything in the runtime directory, then again with its real\n // path, which is the one bound (on macOS, /tmp is /private/tmp). Windows has no runtime\n // directory: its control pipe lives in the system's pipe namespace.\n let socketPath: string;\n if (runtimeDir === undefined) {\n socketPath = socketPathFor(undefined, home);\n } else {\n socketPathFor(runtimeDir.dir, home);\n socketPath = socketPathFor(prepareOwnedDirectory(runtimeDir.dir).realPath, home);\n }\n const redactor = new Redactor();\n redactor.protectEnvironment(options.env);\n const log = openFileLog({\n dir: join(home, \"logs\"),\n redactor,\n ...(options.mirror ? { mirror: options.mirror } : {}),\n });\n if (prepared.tightenedFrom !== undefined) {\n log.warn(\"home.tightened\", { home, from: prepared.tightenedFrom, to: \"owner only\" });\n }\n if (runtimeDir?.rejected !== undefined) {\n log.warn(\"home.xdg_runtime_dir_rejected\", {\n reason: runtimeDir.rejected,\n using: runtimeDir.dir,\n });\n }\n\n const me = await readProcess(process.pid);\n if (!me) throw new Error(\"Couldn't read this process's own start time.\");\n const self = { pid: me.pid, startTime: me.startTime };\n const deadline = Date.now() + (options.waitMs ?? DEFAULT_WAIT_MS);\n let seen: InstanceRecord | undefined;\n\n for (;;) {\n const opening = openLedger({\n storeDir: join(home, \"store\"),\n runtimeVersion: options.runtimeVersion,\n owner: self,\n log,\n });\n if (opening.ok) {\n log.info(\"home.acquired\", { home, socket: socketPath, pid: self.pid });\n return {\n kind: \"owner\",\n home: own({\n home,\n socketPath,\n runtimeDir,\n ledger: opening.ledger,\n log,\n redactor,\n self,\n options,\n }),\n };\n }\n\n const record = await readLiveInstanceRecord(home);\n if (record) {\n seen = record;\n if (options.mode === \"host\") {\n throw locked(\n `The home ${home} is already owned by a Mostra ${record.mode} (PID ${record.pid}); \\`mostra host\\` needs a home no other instance owns.`,\n );\n }\n try {\n const { client, result } = await attach(record.socket, options.client, 2000);\n log.info(\"home.attached\", { home, owner: record.pid, socket: record.socket });\n return { kind: \"attached\", record, connection: client, result };\n } catch (error) {\n // Only an unreachable socket is worth waiting for; a refusal is final.\n if (\n !(error instanceof RpcError) ||\n error.diagnostic.code !== \"MOSTRA_HOST_CONNECTION_CLOSED\"\n ) {\n throw error;\n }\n }\n }\n\n if (Date.now() >= deadline) {\n const owner = seen ?? readInstanceRecord(home);\n throw locked(\n owner\n ? `The home ${home} is owned by PID ${owner.pid}, but its socket ${owner.socket} can't be reached.`\n : `Another process holds the ledger lock of the home ${home} and published no instance record.`,\n );\n }\n await delay(100);\n }\n}\n\ninterface OwnInputs {\n readonly home: string;\n /**\n * The control endpoint's base: the socket path on POSIX; on Windows the pipe name each bind\n * completes. `instance.json` records the endpoint actually bound.\n */\n readonly socketPath: string;\n /** The runtime directory; `undefined` on Windows, which has none. */\n readonly runtimeDir: RuntimeDirChoice | undefined;\n readonly ledger: Ledger;\n readonly log: Log;\n readonly redactor: Redactor;\n readonly self: { readonly pid: number; readonly startTime: string };\n readonly options: AcquireHomeOptions;\n}\n\nfunction identity(path: string): string | undefined {\n try {\n const stats = statSync(path);\n return `${stats.dev}:${stats.ino}`;\n } catch {\n return undefined;\n }\n}\n\nfunction own(inputs: OwnInputs): OwnedHome {\n const { home, socketPath, runtimeDir, ledger, log, redactor, self } = inputs;\n const startedAt = new Date().toISOString();\n const homeId = identity(home);\n const ledgerId = identity(join(home, \"store\", LEDGER_FILE));\n let timer: ReturnType<typeof setInterval> | undefined;\n let released = false;\n return {\n path: home,\n socketPath,\n runtimeDir,\n ledger,\n log,\n redactor,\n self,\n startedAt,\n publish(mode, socket) {\n writeInstanceRecord(home, {\n pid: self.pid,\n startTime: self.startTime,\n socket,\n runtimeVersion: inputs.options.runtimeVersion,\n revisions: [...HOST_PROTOCOL_REVISIONS],\n mode,\n startedAt,\n });\n },\n watch(onGone, intervalMs = DEFAULT_WATCH_MS) {\n if (timer) clearInterval(timer);\n timer = setInterval(\n () => {\n const homeNow = identity(home);\n const ledgerNow = identity(join(home, \"store\", LEDGER_FILE));\n if (homeNow === homeId && ledgerNow === ledgerId) return;\n if (timer) clearInterval(timer);\n onGone(\n createDiagnostic(\"MOSTRA_HOME_GONE\", {\n message:\n homeNow === homeId\n ? `The ledger of the home ${home} was removed or replaced while the instance was running.`\n : `The home ${home} was removed or replaced while the instance was running.`,\n }),\n );\n },\n Math.min(intervalMs, 10_000),\n );\n timer.unref();\n },\n release() {\n if (released) return;\n released = true;\n if (timer) clearInterval(timer);\n try {\n removeInstanceRecord(home, self.pid, self.startTime);\n } catch (error) {\n log.warn(\"home.record_remove_failed\", { error });\n }\n ledger.close();\n log.info(\"home.released\", { home });\n },\n };\n}\n","/**\n * The unsupported-platform gate (D35, D146, RT-07). Every entry point calls it before it touches\n * the home: Mostra runs on macOS, Linux and Windows, on x64 and arm64, and fails closed elsewhere.\n * Windows was built behind a development switch by WP-W1 to WP-W3, and is supported since WP-W3\n * like the others.\n */\nimport { createDiagnostic, type Diagnostic } from \"@mostra/protocol\";\nimport { OS } from \"../platform/index.ts\";\n\nconst OPERATING_SYSTEMS: readonly string[] = [\"darwin\", \"linux\", \"win32\"];\nconst ARCHITECTURES: readonly string[] = [\"x64\", \"arm64\"];\n\n/** The platform as `<os>-<arch>`, as `InstanceInfo.platform` reports it. */\nexport function platformName(platform: string = OS, arch: string = process.arch): string {\n return `${platform}-${arch}`;\n}\n\n/**\n * Returns `MOSTRA_PLATFORM_UNSUPPORTED` for a platform Mostra doesn't run on, or `undefined` for\n * a supported one.\n */\nexport function checkPlatform(\n platform: string = OS,\n arch: string = process.arch,\n): Diagnostic | undefined {\n if (ARCHITECTURES.includes(arch) && OPERATING_SYSTEMS.includes(platform)) return undefined;\n const name =\n platform === \"win32\"\n ? `Windows (${platformName(platform, arch)})`\n : platformName(platform, arch);\n return createDiagnostic(\"MOSTRA_PLATFORM_UNSUPPORTED\", {\n message: `Mostra doesn't run on ${name}; it supports macOS, Linux and Windows on x64 and arm64.`,\n });\n}\n","/**\n * The home's settings (`config.json`, DATA_MODEL §1): what hosts set through `HomeConfig` and\n * what every later client of the home then shares: the dependency policy (D43, D95), the home's\n * submission policy (D102), the ports each host always provides (D105) and the submit channels the\n * home accepts (D108).\n * Written atomically (a temporary file, then a rename); read fresh by whoever needs a setting, so\n * a host's change applies to the next request.\n */\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n createDiagnostic,\n type DependencyPolicy,\n RpcError,\n SubmissionPolicy,\n} from \"@mostra/protocol\";\nimport * as z from \"zod\";\nimport { fsyncPath, renamePathSync } from \"../platform/index.ts\";\n\n/** The settings `config.json` holds. Unknown keys are kept, so newer settings survive. */\nexport interface HomeSettings {\n readonly dependencies?: DependencyPolicy;\n /** The policy for artifacts whose publish names none, before the manifest's (D102). */\n readonly submission?: SubmissionPolicy;\n /** The ports each host always provides, by its client name (D105). */\n readonly expectedPorts?: Readonly<Record<string, readonly string[]>>;\n /** The submit channels the home accepts, when a host narrowed them (D108). */\n readonly submitChannels?: readonly (\"shell\" | \"artifact\")[];\n /**\n * The first host that configured this home (D140 item 4): written once, never removed. The\n * standalone CLI sends no telemetry for a home that carries it.\n */\n readonly hostConfigured?: { readonly client: string; readonly at: string };\n}\n\nconst Settings = z.looseObject({\n dependencies: z.enum([\"auto\", \"explicit\"]).optional(),\n submission: SubmissionPolicy.optional(),\n expectedPorts: z.record(z.string(), z.array(z.string())).optional(),\n submitChannels: z\n .array(z.enum([\"shell\", \"artifact\"]))\n .min(1)\n .max(2)\n .optional(),\n hostConfigured: z.object({ client: z.string(), at: z.string() }).optional(),\n});\n\n/** The settings file of a home. */\nexport const SETTINGS_FILE = \"config.json\";\n\nfunction unreadable(home: string, reason: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOME_INTEGRITY\", {\n message: `The home's ${join(home, SETTINGS_FILE)} can't be read: ${reason}.`,\n hint: `Repair or remove ${SETTINGS_FILE} in the home; a host sets its settings again when it connects.`,\n }),\n );\n}\n\n/**\n * The home's settings; none when `config.json` doesn't exist. A file that isn't valid settings\n * fails closed: guessing the policy could install packages a host forbade.\n */\nexport function readHomeSettings(home: string): HomeSettings & Record<string, unknown> {\n let text: string;\n try {\n text = readFileSync(join(home, SETTINGS_FILE), \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw unreadable(home, (error as NodeJS.ErrnoException).code ?? \"error\");\n }\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch {\n throw unreadable(home, \"it isn't JSON\");\n }\n const parsed = Settings.safeParse(data);\n if (!parsed.success) throw unreadable(home, \"its settings are invalid\");\n return parsed.data as HomeSettings & Record<string, unknown>;\n}\n\n/** Merges `change` into the home's settings, durably. */\nexport function writeHomeSettings(home: string, change: HomeSettings): void {\n const next = { ...readHomeSettings(home), ...change };\n const file = join(home, SETTINGS_FILE);\n const temporary = `${file}.${process.pid}.tmp`;\n writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\\n`, { mode: 0o600 });\n fsyncPath(temporary);\n renamePathSync(temporary, file);\n fsyncPath(home, true);\n}\n\n/**\n * Marks the home as configured by a host (D140 item 4), once: the first host's client name and\n * when. A home already marked keeps its mark.\n */\nexport function markHostConfigured(home: string, client: string, at: Date = new Date()): boolean {\n if (readHomeSettings(home).hostConfigured !== undefined) return false;\n writeHomeSettings(home, { hostConfigured: { client, at: at.toISOString() } });\n return true;\n}\n","/**\n * Secrets (D44, AC-06): named values server code reads with `secret(name)`, kept outside artifact\n * source in the home's owner-only store, `secrets/<scope>/<name>` (mode 0600, directories 0700),\n * where the scope is `home` for a secret every artifact shares or the artifact's ID for its own.\n * A host may supply secrets through its `secrets` port instead (a host's own credential store).\n *\n * Every value Mostra holds or hands out is registered with the instance's redactor, so it never\n * reaches a log, a run log, an event, a diagnostic or a report. Nothing derived from a value is\n * ever written to the ledger.\n */\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n type ArtifactRef,\n createDiagnostic,\n RpcError,\n SECRET_NAME_PATTERN,\n SECRET_VALUE_MAX,\n type SecretEntry,\n secretDeleteMethod,\n secretListMethod,\n secretSetMethod,\n} from \"@mostra/protocol\";\nimport type { Log, Redactor } from \"../log.ts\";\nimport { renamePathSync } from \"../platform/index.ts\";\nimport { handler, type MethodHandler } from \"../protocol-server/index.ts\";\n\n/** Where a secret lives: the home's shared store, or one artifact's. */\nexport type SecretScope =\n | { readonly kind: \"home\" }\n | { readonly kind: \"artifact\"; readonly artifactId: string };\n\n/** Asks a host's `secrets` port; `null` when it has none, an error when it failed. */\nexport type SecretsPort = (request: { artifactId: string; name: string }) => Promise<string | null>;\n\n/** The home's secrets. */\nexport interface Secrets {\n /** Stores a secret, replacing an earlier value. */\n set(name: string, value: string, scope: SecretScope): SecretEntry;\n /** The names in the home's scope, and in the artifact's when one is named. */\n list(artifactId?: string): SecretEntry[];\n /** Deletes a secret; `false` when there was none. */\n delete(name: string, scope: SecretScope): boolean;\n /**\n * The value server code of `artifactId` gets for `name`: the host's port first, then the\n * artifact's own secret, then the home's shared one.\n *\n * @throws RpcError `MOSTRA_SECRET_MISSING` when no store holds it, or the port failed.\n */\n resolve(artifactId: string, name: string): Promise<string>;\n}\n\n/** Options for {@link openSecrets}. */\nexport interface SecretsOptions {\n /** The home's real path. */\n readonly home: string;\n readonly redactor: Redactor;\n readonly log: Log;\n /** The host's `secrets` port, while a connected host registered it. */\n readonly port?: () => SecretsPort | undefined;\n}\n\nconst HOME_SCOPE = \"home\";\nconst ARTIFACT_SCOPE = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;\n\nfunction missing(name: string, detail?: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_SECRET_MISSING\", {\n message: `No secret named ${name} is set${detail ? ` (${detail})` : \"\"}.`,\n hint: `Set it with \\`mostra secret set ${name}\\`, reading the value from stdin.`,\n }),\n );\n}\n\nfunction invalidName(name: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", {\n message: `${JSON.stringify(name).slice(0, 80)} isn't a secret name: a letter or \"_\", then up to 127 letters, digits, \"_\", \".\" and \"-\".`,\n }),\n );\n}\n\n/** Opens the home's secret store, registering every stored value with the redactor. */\nexport function openSecrets(options: SecretsOptions): Secrets {\n const root = join(options.home, \"secrets\");\n mkdirSync(root, { recursive: true, mode: 0o700 });\n chmodSync(root, 0o700);\n\n const dirOf = (scope: SecretScope): string =>\n join(root, scope.kind === \"home\" ? HOME_SCOPE : scope.artifactId);\n\n const read = (dir: string, name: string): string | undefined => {\n try {\n return readFileSync(join(dir, name), \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw error;\n }\n };\n\n // Every value already stored is protected before anything is logged.\n for (const scope of existsSync(root) ? readdirSync(root) : []) {\n if (scope !== HOME_SCOPE && !ARTIFACT_SCOPE.test(scope)) continue;\n for (const name of readdirSync(join(root, scope))) {\n if (!SECRET_NAME_PATTERN.test(name)) continue;\n const value = read(join(root, scope), name);\n if (value !== undefined) options.redactor.protectSecret(value);\n }\n }\n\n const entry = (dir: string, name: string, scope: SecretScope): SecretEntry => ({\n name,\n scope: scope.kind,\n ...(scope.kind === \"artifact\" ? { artifactId: scope.artifactId } : {}),\n updatedAt: statSync(join(dir, name)).mtime.toISOString(),\n });\n\n const listScope = (scope: SecretScope): SecretEntry[] => {\n const dir = dirOf(scope);\n if (!existsSync(dir)) return [];\n return readdirSync(dir)\n .filter((name) => SECRET_NAME_PATTERN.test(name))\n .sort()\n .map((name) => entry(dir, name, scope));\n };\n\n return {\n set(name, value, scope) {\n if (!SECRET_NAME_PATTERN.test(name)) throw invalidName(name);\n if (value.length === 0 || Buffer.byteLength(value, \"utf8\") > SECRET_VALUE_MAX) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", {\n message: `The value of the secret ${name} must be 1 byte to 64 KiB of UTF-8.`,\n }),\n );\n }\n options.redactor.protectSecret(value);\n const dir = dirOf(scope);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n // Written beside it, then renamed: a reader never sees half a value.\n const temporary = join(dir, `.${name}.${process.pid}.tmp`);\n writeFileSync(temporary, value, { mode: 0o600, flag: \"w\" });\n chmodSync(temporary, 0o600);\n renamePathSync(temporary, join(dir, name));\n options.log.info(\"secret.set\", { name, scope: scope.kind });\n return entry(dir, name, scope);\n },\n list(artifactId) {\n return [\n ...listScope({ kind: \"home\" }),\n ...(artifactId ? listScope({ kind: \"artifact\", artifactId }) : []),\n ];\n },\n delete(name, scope) {\n if (!SECRET_NAME_PATTERN.test(name)) throw invalidName(name);\n const file = join(dirOf(scope), name);\n if (!existsSync(file)) return false;\n rmSync(file, { force: true });\n options.log.info(\"secret.deleted\", { name, scope: scope.kind });\n return true;\n },\n async resolve(artifactId, name) {\n if (!SECRET_NAME_PATTERN.test(name)) throw missing(name, \"not a secret name\");\n const port = options.port?.();\n if (port) {\n let value: string | null;\n try {\n value = await port({ artifactId, name });\n } catch (error) {\n options.log.warn(\"secret.port_failed\", {\n name,\n error: String((error as Error)?.message ?? error),\n });\n throw missing(name, \"the host's secrets port didn't answer\");\n }\n if (typeof value === \"string\") {\n options.redactor.protectSecret(value);\n return value;\n }\n }\n const value =\n read(dirOf({ kind: \"artifact\", artifactId }), name) ?? read(dirOf({ kind: \"home\" }), name);\n if (value === undefined) throw missing(name);\n // A file written into the store by hand since start-up is protected before it leaves.\n options.redactor.protectSecret(value);\n return value;\n },\n };\n}\n\n/** The `secret/*` methods (D44): set by name from the value given, list names, delete. */\nexport function secretMethods(\n secrets: Secrets,\n resolveArtifact: (ref: ArtifactRef) => string,\n): MethodHandler[] {\n const scopeOf = (artifact: ArtifactRef | undefined): SecretScope =>\n artifact === undefined\n ? { kind: \"home\" }\n : { kind: \"artifact\", artifactId: resolveArtifact(artifact) };\n return [\n handler(secretSetMethod, (params) =>\n secrets.set(params.name, params.value, scopeOf(params.artifact)),\n ),\n handler(secretListMethod, (params) => ({\n secrets: secrets.list(\n params.artifact === undefined ? undefined : resolveArtifact(params.artifact),\n ),\n })),\n handler(secretDeleteMethod, (params) => ({\n deleted: secrets.delete(params.name, scopeOf(params.artifact)),\n })),\n ];\n}\n","/**\n * The daemon's idle exit (D62, RT-08): a daemon keeps running while it has open views, pending\n * deliveries, running action runs, live producers, host subscriptions or attached clients, and\n * otherwise exits after 30 idle minutes. A host-spawned instance lives exactly as long as its\n * stdio, and a daemon started `--always-on` (the login service) never exits for lack of work.\n */\n\n/** What keeps a daemon running, as counts; any non-zero one is work. */\nexport type Busy = () => Readonly<Record<string, number>>;\n\n/** The default idle time before a daemon exits. */\nexport const IDLE_EXIT_MS: number = 30 * 60_000;\n\n/** The idle watch. */\nexport interface IdleWatch {\n /** When the daemon exits if nothing happens, or `undefined` while it's busy or never exits. */\n exitAt(): string | undefined;\n stop(): void;\n}\n\n/** Options for {@link watchIdle}. */\nexport interface IdleOptions {\n readonly busy: Busy;\n /** Called once, when the daemon has been idle for `idleMs`. */\n readonly onIdle: () => void;\n readonly idleMs?: number;\n /** How often the counts are read; default 5 s, or a tenth of `idleMs` when that is shorter. */\n readonly checkMs?: number;\n readonly now?: () => number;\n}\n\n/** Starts watching; the daemon exits through `onIdle` once nothing has kept it for `idleMs`. */\nexport function watchIdle(options: IdleOptions): IdleWatch {\n const idleMs = options.idleMs ?? IDLE_EXIT_MS;\n const now = options.now ?? Date.now;\n let idleSince: number | undefined = now();\n let fired = false;\n const check = (): void => {\n const counts = options.busy();\n const busy = Object.values(counts).some((count) => count > 0);\n if (busy) {\n idleSince = undefined;\n return;\n }\n idleSince ??= now();\n if (!fired && now() - idleSince >= idleMs) {\n fired = true;\n options.onIdle();\n }\n };\n const timer = setInterval(check, options.checkMs ?? Math.min(5_000, Math.max(50, idleMs / 10)));\n timer.unref?.();\n return {\n exitAt() {\n check();\n return idleSince === undefined || fired\n ? undefined\n : new Date(idleSince + idleMs).toISOString();\n },\n stop() {\n clearInterval(timer);\n },\n };\n}\n","/**\n * The home's login service (D62, D63, RT-08, RT-11): `mostra daemon install` registers the home's\n * daemon with the user's service manager, so an artifact answers at any hour, even after a reboot.\n * A launchd agent on macOS, a systemd user unit on Linux, a Task Scheduler task at the user's logon\n * on Windows (D151); each runs `mostra-runtime daemon --always-on --home <home>`, which never\n * exits for lack of work, and restarts it when it ends unexpectedly. On Windows the task runs the\n * daemon through `mostra-win-service`, a launcher without a console, so no window opens at logon,\n * which also does the restarting (Task Scheduler's own setting didn't, VERIFIED_FACTS WP-W2). The\n * definition carries no secret: the daemon reads them from the home (D44).\n */\nimport { execFile, execFileSync } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, win32 } from \"node:path\";\nimport {\n type ClientInfo,\n createDiagnostic,\n mostraShutdownMethod,\n RpcError,\n} from \"@mostra/protocol\";\nimport { homeHash, readLiveInstanceRecord } from \"../home/index.ts\";\nimport type { Environment } from \"../log.ts\";\nimport {\n currentUserSid,\n isSameProcess,\n OS,\n serviceLauncherPath,\n stopServiceLauncher,\n} from \"../platform/index.ts\";\nimport { attach } from \"../protocol-server/index.ts\";\n\n/** Where a home's service is, and whether it is there. */\nexport interface ServiceStatus {\n /** `launchd` (macOS), `systemd` (Linux) or `task-scheduler` (Windows). */\n readonly manager: \"launchd\" | \"systemd\" | \"task-scheduler\";\n /** The service's name: the launchd label, the systemd unit, or the scheduled task. */\n readonly name: string;\n /**\n * The file that defines it. On Windows the task's definition as Mostra registered it, kept in\n * the home (`<home>\\service\\task.xml`): Task Scheduler keeps its own copy.\n */\n readonly file: string;\n /** Whether the file exists. */\n readonly installed: boolean;\n /** What it runs. */\n readonly command: readonly string[];\n}\n\n/** What a service runs and where. */\nexport interface ServiceSpec {\n /** The home's real path. */\n readonly home: string;\n /** The Node executable and the runtime's entry, `mostra-runtime`. */\n readonly node: string;\n readonly entry: string;\n readonly env?: Environment;\n /** The operating system (`OS` of the platform layer). */\n readonly platform?: string;\n /** Windows: the user the task runs as, a SID; default the current user. */\n readonly user?: string;\n /** Windows: the launcher; default `mostra-win-service.exe` beside the helper. */\n readonly launcher?: string;\n}\n\nfunction failed(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_SERVICE_FAILED\", { message }));\n}\n\nfunction userHome(env: Environment): string {\n return env[\"HOME\"] ?? homedir();\n}\n\n/** The service a home's daemon would be, installed or not. */\nexport function serviceFor(spec: ServiceSpec): ServiceStatus {\n const env = spec.env ?? process.env;\n const platform = spec.platform ?? OS;\n const hash = homeHash(spec.home);\n const command = [spec.node, spec.entry, \"daemon\", \"--always-on\", \"--home\", spec.home];\n if (platform === \"darwin\") {\n const name = `dev.mostra.daemon.${hash}`;\n return {\n manager: \"launchd\",\n name,\n file: join(userHome(env), \"Library\", \"LaunchAgents\", `${name}.plist`),\n installed: existsSync(join(userHome(env), \"Library\", \"LaunchAgents\", `${name}.plist`)),\n command,\n };\n }\n if (platform === \"linux\") {\n const config = env[\"XDG_CONFIG_HOME\"] || join(userHome(env), \".config\");\n const name = `mostra-${hash.toLowerCase()}.service`;\n const file = join(config, \"systemd\", \"user\", name);\n return { manager: \"systemd\", name, file, installed: existsSync(file), command };\n }\n if (platform === \"win32\") {\n const file = win32.join(spec.home, \"service\", \"task.xml\");\n return {\n manager: \"task-scheduler\",\n name: `mostra-${hash.toLowerCase()}`,\n file,\n installed: existsSync(file),\n command: [\n spec.launcher ?? launcherOrName(),\n \"--stop-event\",\n stopEventOf(file) ?? newStopEvent(hash),\n \"--log\",\n win32.join(spec.home, \"logs\", \"service.log\"),\n ...windowsServiceVariables(env).flatMap(([name, value]) => [\"--env\", `${name}=${value}`]),\n \"--\",\n ...command,\n ],\n };\n }\n throw new RpcError(\n createDiagnostic(\"MOSTRA_PLATFORM_UNSUPPORTED\", {\n message: `Mostra can't install a login service on ${platform}.`,\n }),\n );\n}\n\n/**\n * What a Windows task passes on besides the user's logon environment, which Task Scheduler gives\n * it: the helper a checkout names, and the locale and time zone, as the POSIX units carry theirs.\n * Nothing secret.\n */\nfunction windowsServiceVariables(env: Environment): [string, string][] {\n return [\"MOSTRA_WIN_HELPER\", \"LANG\", \"TZ\"].flatMap((name) => {\n const value = env[name];\n return value ? [[name, value] as [string, string]] : [];\n });\n}\n\n/**\n * A new name for the event that asks a home's launcher to stop: in `Local\\` (the logon session's\n * namespace, the only one an ordinary user may create names in), with a random part, so nobody who\n * can't read the task or the home can create it first (Opus review of WP-W2, finding 6).\n */\nconst newStopEvent = (hash: string): string =>\n `Local\\\\mostra-service-${hash.toLowerCase()}-${randomBytes(8).toString(\"hex\")}`;\n\n/** The stop event a definition Mostra wrote names, if the file is there. */\nfunction stopEventOf(file: string): string | undefined {\n try {\n const text = readFileSync(file).toString(\"utf16le\");\n return /--stop-event (Local\\\\mostra-service-[0-9a-z]+-[0-9a-f]{16})\\b/.exec(text)?.[1];\n } catch {\n return undefined;\n }\n}\n\n/** The launcher's path, or its bare name where it isn't installed (a status only reads it). */\nfunction launcherOrName(): string {\n try {\n return serviceLauncherPath();\n } catch {\n return \"mostra-win-service.exe\";\n }\n}\n\n/** One word of a Windows command line, quoted as the Microsoft C runtime parses it. */\nexport function windowsArgument(word: string): string {\n if (word !== \"\" && !/[\\s\"]/.test(word)) return word;\n let out = '\"';\n let backslashes = 0;\n for (const char of word) {\n if (char === \"\\\\\") {\n backslashes += 1;\n continue;\n }\n out += \"\\\\\".repeat(char === '\"' ? backslashes * 2 + 1 : backslashes) + char;\n backslashes = 0;\n }\n return `${out}${\"\\\\\".repeat(backslashes * 2)}\"`;\n}\n\n/** The Task Scheduler definition (schema 1.2) of a home's task. */\nfunction taskFile(spec: ServiceSpec, status: ServiceStatus): string {\n const user = xml(spec.user ?? currentUserSid());\n const [program = \"\", ...args] = status.command;\n return `<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<Task version=\"1.2\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n <RegistrationInfo>\n <Description>${xml(`Mostra daemon for ${spec.home}`)}</Description>\n </RegistrationInfo>\n <Triggers>\n <LogonTrigger>\n <Enabled>true</Enabled>\n <UserId>${user}</UserId>\n </LogonTrigger>\n </Triggers>\n <Principals>\n <Principal id=\"Author\">\n <UserId>${user}</UserId>\n <LogonType>InteractiveToken</LogonType>\n <RunLevel>LeastPrivilege</RunLevel>\n </Principal>\n </Principals>\n <Settings>\n <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>\n <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>\n <AllowHardTerminate>true</AllowHardTerminate>\n <StartWhenAvailable>false</StartWhenAvailable>\n <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\n <IdleSettings>\n <StopOnIdleEnd>false</StopOnIdleEnd>\n <RestartOnIdle>false</RestartOnIdle>\n </IdleSettings>\n <AllowStartOnDemand>true</AllowStartOnDemand>\n <Enabled>true</Enabled>\n <Hidden>false</Hidden>\n <RunOnlyIfIdle>false</RunOnlyIfIdle>\n <WakeToRun>false</WakeToRun>\n <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\n <Priority>5</Priority>\n </Settings>\n <Actions Context=\"Author\">\n <Exec>\n <Command>${xml(program)}</Command>\n <Arguments>${xml(args.map(windowsArgument).join(\" \"))}</Arguments>\n </Exec>\n </Actions>\n</Task>\n`;\n}\n\n/**\n * Whether `home` has a login service installed: its daemon then never exits for lack of work,\n * whoever started it, so a daemon started by hand before `install` keeps the artifacts answering.\n */\nexport function hasLoginService(home: string, env: Environment = process.env): boolean {\n try {\n const status = serviceFor({ home, node: \"\", entry: \"\", env });\n if (!status.installed) return false;\n return status.manager !== \"task-scheduler\" || registeredLately(status);\n } catch {\n return false;\n }\n}\n\n/** What the idle check last learnt of each task: whether Task Scheduler holds it, and when. */\nconst registrations = new Map<string, { registered?: boolean; at: number; asking: boolean }>();\n\n/**\n * Whether Task Scheduler held the task when last asked, asking again in the background at most\n * once a minute: the idle check runs every few seconds and must never wait for `schtasks`. A task\n * removed in Task Scheduler's own window then stops counting, so a daemon started by hand exits\n * when idle again (Opus review of WP-W2, finding 5). Until the first answer, the definition in the\n * home counts.\n */\nfunction registeredLately(status: ServiceStatus): boolean {\n const interval = Number(process.env[\"MOSTRA_TEST_SERVICE_QUERY_MS\"]) || 60_000;\n const entry = registrations.get(status.name) ?? { at: Number.NEGATIVE_INFINITY, asking: false };\n registrations.set(status.name, entry);\n if (!entry.asking && Date.now() - entry.at >= interval) {\n entry.asking = true;\n execFile(\n \"schtasks\",\n [\"/Query\", \"/TN\", status.name],\n { timeout: 30_000, windowsHide: true },\n (error) => {\n entry.registered = error === null;\n entry.at = Date.now();\n entry.asking = false;\n },\n );\n }\n return entry.registered ?? true;\n}\n\nconst xml = (text: string): string =>\n text.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/\"/g, \""\");\n\n/** systemd's quoting for one `ExecStart` word. */\nconst systemdWord = (word: string): string =>\n /^[A-Za-z0-9_./:@=+-]+$/.test(word)\n ? word\n : `\"${word\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/%/g, \"%%\")\n .replace(/\\$/g, \"$$$$\")}\"`;\n\n/** The environment a service gets: what finding programs and the home needs, nothing secret. */\nfunction serviceEnvironment(env: Environment): Record<string, string> {\n const out: Record<string, string> = {\n PATH: env[\"PATH\"] ?? \"/usr/local/bin:/usr/bin:/bin\",\n HOME: userHome(env),\n };\n for (const name of [\"MOSTRA_RUNTIME_DIR\", \"LANG\", \"TZ\"]) {\n const value = env[name];\n if (value) out[name] = value;\n }\n return out;\n}\n\n/** The text of the service's file. */\nexport function serviceFile(spec: ServiceSpec, status: ServiceStatus): string {\n // The task runs in the user's own logon environment, as any program they start does.\n if (status.manager === \"task-scheduler\") return taskFile(spec, status);\n const env = serviceEnvironment(spec.env ?? process.env);\n const log = join(spec.home, \"logs\", \"service.log\");\n if (status.manager === \"launchd\") {\n const args = status.command.map((word) => ` <string>${xml(word)}</string>`).join(\"\\n\");\n const vars = Object.entries(env)\n .map(([key, value]) => ` <key>${xml(key)}</key>\\n <string>${xml(value)}</string>`)\n .join(\"\\n\");\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n <dict>\n <key>Label</key>\n <string>${xml(status.name)}</string>\n <key>ProgramArguments</key>\n <array>\n${args}\n </array>\n <key>EnvironmentVariables</key>\n <dict>\n${vars}\n </dict>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <dict>\n <key>SuccessfulExit</key>\n <false/>\n </dict>\n <key>ThrottleInterval</key>\n <integer>10</integer>\n <key>StandardOutPath</key>\n <string>${xml(log)}</string>\n <key>StandardErrorPath</key>\n <string>${xml(log)}</string>\n </dict>\n</plist>\n`;\n }\n const environment = Object.entries(env)\n .map(([key, value]) => `Environment=${systemdWord(`${key}=${value}`)}`)\n .join(\"\\n\");\n return `[Unit]\nDescription=Mostra daemon for ${spec.home.replace(/\\n/g, \" \").replace(/%/g, \"%%\")}\nAfter=network.target\n\n[Service]\nType=simple\nExecStart=${status.command.map(systemdWord).join(\" \")}\n${environment}\nRestart=on-failure\nRestartSec=10\n\n[Install]\nWantedBy=default.target\n`;\n}\n\n/** Options of an install or uninstall. */\nexport interface ServiceOptions {\n /** Write the file only, without asking the service manager to start it (tests). */\n readonly noStart?: boolean;\n /** Who asks, when a Windows uninstall stops the daemon over its pipe. */\n readonly client?: ClientInfo;\n}\n\nfunction run(command: string, args: readonly string[]): void {\n try {\n execFileSync(command, [...args], { stdio: [\"ignore\", \"pipe\", \"pipe\"], timeout: 30_000 });\n } catch (error) {\n const failure = error as { stderr?: Buffer; message: string };\n const detail = failure.stderr?.toString().trim() || failure.message;\n throw failed(`${command} ${args.join(\" \")} failed: ${detail.slice(0, 400)}`);\n }\n}\n\nconst uid = (): number => process.getuid?.() ?? 0;\n\n/** The definition's bytes: Task Scheduler reads UTF-16 with its byte order mark. */\nfunction encoded(status: ServiceStatus, text: string): Buffer | string {\n return status.manager === \"task-scheduler\" ? Buffer.from(`\\ufeff${text}`, \"utf16le\") : text;\n}\n\n/** The definition as written, decoded as {@link encoded} wrote it. */\nfunction readDefinition(status: ServiceStatus): string {\n const bytes = readFileSync(status.file);\n if (status.manager !== \"task-scheduler\") return bytes.toString(\"utf8\");\n return bytes.toString(\"utf16le\").replace(/^\\ufeff/, \"\");\n}\n\n/** Installs the home's daemon as a login service and starts it, replacing an earlier one. */\nexport async function installService(\n spec: ServiceSpec,\n options: ServiceOptions = {},\n): Promise<ServiceStatus> {\n // On Windows a launcher that isn't there is MOSTRA_ENV_HELPER_MISSING before anything is written.\n const status = serviceFor(\n (spec.platform ?? OS) === \"win32\" && spec.launcher === undefined\n ? { ...spec, launcher: serviceLauncherPath() }\n : spec,\n );\n const text = serviceFile(spec, status);\n // Windows: the home keeps the definition only once Task Scheduler took it, so a definition in\n // the home names a task that was registered (Opus review of WP-W2, finding 5).\n const registering = status.manager === \"task-scheduler\" && !options.noStart;\n const written = registering ? `${status.file}.new` : status.file;\n try {\n mkdirSync(dirname(status.file), { recursive: true });\n mkdirSync(join(spec.home, \"logs\"), { recursive: true, mode: 0o700 });\n if (status.installed && !options.noStart) await stopService(status, spec.home, options);\n writeFileSync(written, encoded(status, text), { mode: 0o644 });\n } catch (error) {\n if (error instanceof RpcError) throw error;\n throw failed(`Writing ${status.file} failed: ${(error as Error).message}`);\n }\n if (registering) {\n try {\n run(\"schtasks\", [\"/Create\", \"/TN\", status.name, \"/XML\", written, \"/F\"]);\n renameSync(written, status.file);\n } finally {\n rmSync(written, { force: true });\n }\n registrations.delete(status.name);\n }\n if (!options.noStart) {\n if (status.manager === \"launchd\") {\n run(\"launchctl\", [\"bootstrap\", `gui/${uid()}`, status.file]);\n } else if (status.manager === \"systemd\") {\n run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n run(\"systemctl\", [\"--user\", \"enable\", \"--now\", status.name]);\n } else {\n // Registered above for the user's own logons, which needs no elevation (InteractiveToken),\n // and started now, as launchd's RunAtLoad and systemd's `--now` start theirs.\n run(\"schtasks\", [\"/Run\", \"/TN\", status.name]);\n }\n }\n return { ...status, installed: true };\n}\n\nasync function stopService(\n status: ServiceStatus,\n home: string,\n options: ServiceOptions,\n): Promise<void> {\n try {\n if (status.manager === \"launchd\") run(\"launchctl\", [\"bootout\", `gui/${uid()}/${status.name}`]);\n else if (status.manager === \"systemd\")\n run(\"systemctl\", [\"--user\", \"disable\", \"--now\", status.name]);\n else await stopTask(status, home, options);\n } catch {\n // Not loaded: nothing to stop.\n }\n}\n\n/**\n * Stops and deletes a home's task, the daemon first and in order (D87), as launchd's `bootout`\n * and systemd's `disable --now` send it SIGTERM:\n * - through the launcher's stop event, when this logon session has it: the launcher gives the\n * daemon Ctrl+Break, which the runtime handles as `mostra/shutdown`;\n * - otherwise (the launcher runs in another session, as when the user is logged on at the console\n * and uninstalls over SSH, or the home lost the definition naming the event) with\n * `mostra/shutdown` over the home's pipe, which reaches the daemon from any session; its exit\n * with code 0 ends the launcher (Opus review of WP-W2, finding 4);\n *\n * then the task is ended, which ends whatever its job still holds, and deleted.\n */\nasync function stopTask(\n status: ServiceStatus,\n home: string,\n options: ServiceOptions,\n): Promise<void> {\n const event = status.installed\n ? status.command[status.command.indexOf(\"--stop-event\") + 1]\n : undefined;\n let signalled = false;\n // A test stands for another session's launcher, whose event this session can't see.\n if (event !== undefined && process.env[\"MOSTRA_TEST_SERVICE_STOP\"] !== \"pipe\") {\n try {\n signalled = stopServiceLauncher(event).signalled;\n } catch {\n // The helper couldn't ask: the pipe below stops the daemon.\n }\n }\n if (!signalled) await shutDownInstance(home, options.client);\n try {\n run(\"schtasks\", [\"/End\", \"/TN\", status.name]);\n } catch {\n // Not running.\n }\n run(\"schtasks\", [\"/Delete\", \"/TN\", status.name, \"/F\"]);\n registrations.delete(status.name);\n}\n\n/** Asks the home's running daemon, if any, to stop (`mostra/shutdown`), and waits until it has. */\nasync function shutDownInstance(home: string, client: ClientInfo | undefined): Promise<void> {\n const record = await readLiveInstanceRecord(home);\n if (record === undefined || record.mode !== \"daemon\") return;\n try {\n const session = await attach(record.socket, client ?? { name: \"mostra-service\", version: \"0\" });\n await session.client.peer\n .call(mostraShutdownMethod, {}, { timeoutMs: 10_000 })\n .catch(() => undefined);\n session.client.close();\n } catch {\n // Unreachable: ending the task stops it.\n return;\n }\n const deadline = Date.now() + 20_000;\n while (Date.now() < deadline && (await isSameProcess(record.pid, record.startTime))) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n}\n\n/** Whether Task Scheduler holds the home's task. */\nfunction taskRegistered(status: ServiceStatus): boolean {\n try {\n run(\"schtasks\", [\"/Query\", \"/TN\", status.name]);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Stops and removes the home's login service; a home without one is left as it is. On Windows a\n * task Task Scheduler still holds is removed though the home lost its definition (restored from a\n * backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review\n * of WP-W2, finding 5).\n */\nexport async function uninstallService(\n spec: ServiceSpec,\n options: ServiceOptions = {},\n): Promise<ServiceStatus> {\n const status = serviceFor(spec);\n const orphaned =\n !status.installed &&\n status.manager === \"task-scheduler\" &&\n !options.noStart &&\n taskRegistered(status);\n if (!status.installed && !orphaned) return status;\n if (!options.noStart) await stopService(status, spec.home, options);\n rmSync(status.file, { force: true });\n if (!options.noStart && status.manager === \"systemd\") {\n try {\n run(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n } catch {\n // The file is gone either way.\n }\n }\n return { ...status, installed: false };\n}\n\n/**\n * Whether the home has a login service whose file runs this home's daemon (`mostra doctor`); on\n * Windows also whether Task Scheduler holds its task (`registered`).\n */\nexport function serviceStatus(\n spec: ServiceSpec,\n): ServiceStatus & { readonly current: boolean; readonly registered?: boolean } {\n const status = serviceFor(spec);\n const registered =\n status.manager === \"task-scheduler\" ? { registered: taskRegistered(status) } : {};\n if (!status.installed) return { ...status, current: false, ...registered };\n return {\n ...status,\n current: readDefinition(status) === serviceFile(spec, status),\n ...registered,\n };\n}\n","/**\n * A tunnel tool's process (D158 item 4): `tailscale serve`, `tailscale funnel` or `cloudflared`,\n * started through the process manager (recorded, gated, reaped after a crash, RT-09), its output\n * read line by line until it says it serves, fails, or runs out of time. A tunnel that serves\n * keeps running until it is stopped; `ended` says when it ends by itself.\n */\nimport { createDiagnostic, type Diagnostic, RpcError } from \"@mostra/protocol\";\nimport type { Log } from \"../log.ts\";\nimport type { ChildHandle, ProcessManager } from \"../processes/index.ts\";\n\n/** What a tunnel's output line means while it starts. */\nexport type LineVerdict =\n | { readonly kind: \"serving\"; readonly origin?: string }\n | { readonly kind: \"origin\"; readonly origin: string }\n | { readonly kind: \"failed\"; readonly diagnostic: Diagnostic }\n | undefined;\n\n/** A tunnel that serves. */\nexport interface Tunnel {\n /** The tunnel's external origin. */\n readonly origin: string;\n /** Resolves when the tunnel's process ends by itself (a stop doesn't resolve it). */\n readonly ended: Promise<{ readonly code: number | null; readonly lines: readonly string[] }>;\n /** Stops the tunnel's process. */\n stop(): Promise<void>;\n}\n\n/** Options for {@link runTunnel}. */\nexport interface TunnelOptions {\n readonly processes: ProcessManager;\n readonly log: Log;\n /** The child's kind in the process manager's records. */\n readonly kind: string;\n /** What it serves (a face's key). */\n readonly ownerRef: string;\n readonly command: string;\n readonly args: readonly string[];\n readonly env: Readonly<Record<string, string | undefined>>;\n /** Reads each line of output: it serves, it names its address, it failed, or nothing yet. */\n readonly read: (line: string) => LineVerdict;\n /** The origin when the tool never names one (Tailscale's comes from the device's name). */\n readonly origin?: string;\n /** How long it may take to serve. */\n readonly timeoutMs: number;\n /** What the tunnel is, for messages: \"Tailscale Serve\", \"a Cloudflare quick tunnel\". */\n readonly label: string;\n}\n\nconst TAIL = 20;\n\n/** Starts a tunnel tool and resolves once it serves; rejects with a `MOSTRA_SHARE_*` RpcError. */\nexport async function runTunnel(options: TunnelOptions): Promise<Tunnel> {\n const lines: string[] = [];\n let origin = options.origin;\n let settle: ((outcome: { ok: true } | { ok: false; diagnostic: Diagnostic }) => void) | undefined;\n const settled = new Promise<{ ok: true } | { ok: false; diagnostic: Diagnostic }>((resolve) => {\n settle = resolve;\n });\n let serving = false;\n const onLine = (line: string): void => {\n lines.push(line);\n if (lines.length > TAIL) lines.shift();\n if (serving) return;\n const verdict = options.read(line);\n if (verdict === undefined) return;\n if (verdict.kind === \"origin\") {\n origin = verdict.origin;\n return;\n }\n if (verdict.kind === \"failed\") {\n settle?.({ ok: false, diagnostic: verdict.diagnostic });\n return;\n }\n if (verdict.origin !== undefined) origin = verdict.origin;\n if (origin !== undefined) {\n serving = true;\n settle?.({ ok: true });\n }\n };\n let child: ChildHandle;\n try {\n child = await options.processes.spawn({\n kind: options.kind,\n ownerRef: options.ownerRef,\n command: options.command,\n args: options.args,\n env: options.env,\n onStdout: onLine,\n onStderr: onLine,\n });\n } catch (error) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_TOOL_NOT_READY\", {\n message: `${options.label} couldn't start: ${(error as Error).message}`,\n }),\n );\n }\n let stopping = false;\n const exited = child.exited.then((exit) => {\n if (!serving) {\n settle?.({\n ok: false,\n diagnostic: createDiagnostic(\"MOSTRA_SHARE_TUNNEL_FAILED\", {\n message: `${options.label} ended before it served (exit ${exit.code ?? exit.signal}): ${lastWords(lines)}`,\n }),\n });\n }\n return exit;\n });\n const timer = setTimeout(() => {\n settle?.({\n ok: false,\n diagnostic: createDiagnostic(\"MOSTRA_SHARE_TUNNEL_FAILED\", {\n message: `${options.label} didn't serve within ${Math.round(options.timeoutMs / 1000)} s: ${lastWords(lines)}`,\n }),\n });\n }, options.timeoutMs);\n const outcome = await settled;\n clearTimeout(timer);\n if (!outcome.ok) {\n stopping = true;\n await child.stop(3000).catch(() => undefined);\n throw new RpcError(outcome.diagnostic);\n }\n options.log.info(\"share.tunnel_serving\", { kind: options.kind, owner: options.ownerRef, origin });\n const ended = exited.then(\n (exit) =>\n new Promise<{ code: number | null; lines: readonly string[] }>((resolve) => {\n if (!stopping) resolve({ code: exit.code, lines: [...lines] });\n }),\n );\n return {\n origin: origin as string,\n ended,\n async stop() {\n stopping = true;\n await child.stop(3000).catch(() => undefined);\n },\n };\n}\n\n/** The last meaningful lines of a tool's output, for a message. */\nfunction lastWords(lines: readonly string[]): string {\n const meaningful = lines.filter((line) => line.trim() !== \"\").slice(-3);\n return meaningful.length === 0 ? \"it said nothing\" : meaningful.join(\" / \").slice(0, 600);\n}\n\n/**\n * Runs a tool to its end and resolves with its standard output (a status query), or rejects with\n * `MOSTRA_SHARE_TOOL_NOT_READY` naming what it said.\n */\nexport async function runToCompletion(options: {\n readonly processes: ProcessManager;\n readonly kind: string;\n readonly ownerRef: string;\n readonly command: string;\n readonly args: readonly string[];\n readonly env: Readonly<Record<string, string | undefined>>;\n readonly timeoutMs: number;\n readonly label: string;\n}): Promise<{ readonly code: number | null; readonly stdout: string; readonly stderr: string }> {\n const stdout: string[] = [];\n const stderr: string[] = [];\n let child: ChildHandle;\n try {\n child = await options.processes.spawn({\n kind: options.kind,\n ownerRef: options.ownerRef,\n command: options.command,\n args: options.args,\n env: options.env,\n onStdout: (line) => stdout.push(line),\n onStderr: (line) => stderr.push(line),\n });\n } catch (error) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_TOOL_NOT_READY\", {\n message: `${options.label} couldn't start: ${(error as Error).message}`,\n }),\n );\n }\n const timer = setTimeout(() => void child.stop(1000), options.timeoutMs);\n const exit = await child.exited;\n clearTimeout(timer);\n return { code: exit.code, stdout: stdout.join(\"\\n\"), stderr: stderr.join(\"\\n\") };\n}\n","/**\n * The Cloudflare driver (D158 item 4): a Cloudflare quick tunnel per face, `cloudflared tunnel\n * --url http://127.0.0.1:<port>`, which needs no account and gets a random `trycloudflare.com`\n * hostname. Each hostname is its own site (`trycloudflare.com` is a public suffix), so a share's\n * shell and artifact are cross-site and its frames use worker mode (D70). Quick tunnels hold every\n * response back until it ends, so pages long-poll (VERIFIED_FACTS, WP-13). A quick tunnel's\n * hostname dies with its process, so a Cloudflare share ends with its tunnel.\n */\nimport { Resolver } from \"node:dns/promises\";\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { Log } from \"../log.ts\";\nimport { installHint, type ToolCommand, toolCommand } from \"../platform/index.ts\";\nimport type { ProcessManager } from \"../processes/index.ts\";\nimport { type LineVerdict, runTunnel, type Tunnel } from \"./tunnel.ts\";\n\n/** How long a quick tunnel may take to serve: registering and the hostname's first answer. */\nconst QUICK_TUNNEL_TIMEOUT_MS = 60_000;\n\n/** What the driver needs. */\nexport interface CloudflareContext {\n readonly processes: ProcessManager;\n readonly log: Log;\n readonly env: Readonly<Record<string, string | undefined>>;\n /** A directory of the home's cache for the tunnel's empty configuration file. */\n readonly cacheDir: string;\n}\n\n/** How `cloudflared` runs, or `MOSTRA_SHARE_TOOL_MISSING`. */\nexport function cloudflared(context: CloudflareContext): ToolCommand {\n const tool = toolCommand(\"cloudflared\", context.env);\n if (!tool) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_TOOL_MISSING\", {\n message: `cloudflared isn't installed on this machine. ${installHint(\"cloudflared\")}`,\n }),\n );\n }\n return tool;\n}\n\n/**\n * Reads `cloudflared`'s log: it names the quick tunnel's address in a banner, and serves once a\n * connection to Cloudflare's edge is registered.\n */\nfunction quickTunnelReader(fake: boolean): (line: string) => LineVerdict {\n return (line) => {\n // The test fake's tunnels are sites of their own on loopback, as quick tunnels are.\n const local = fake ? /\\b(http:\\/\\/[a-z0-9-]+\\.localhost:\\d+)\\b/.exec(line) : null;\n if (local) return { kind: \"origin\", origin: (local[1] as string).toLowerCase() };\n const address = /https:\\/\\/([a-z0-9-]+\\.trycloudflare\\.com)\\b/i.exec(line);\n if (address)\n return { kind: \"origin\", origin: `https://${(address[1] as string).toLowerCase()}` };\n if (/Registered tunnel connection/i.test(line)) return { kind: \"serving\" };\n if (\n /failed to (request|create) quick tunnel|error unmarshaling QuickTunnel|429 Too Many Requests/i.test(\n line,\n )\n ) {\n return {\n kind: \"failed\",\n diagnostic: createDiagnostic(\"MOSTRA_SHARE_TUNNEL_FAILED\", {\n message: `Cloudflare didn't open a quick tunnel: ${line.trim().slice(0, 300)}`,\n }),\n };\n }\n return undefined;\n };\n}\n\n/**\n * Opens a quick tunnel to `local`. It never reads the user's own `cloudflared` configuration (a\n * file with ingress rules would turn the quick tunnel off): it runs with an empty one of its own.\n */\nexport function quickTunnel(\n context: CloudflareContext,\n input: { readonly local: string; readonly ownerRef: string },\n): Promise<Tunnel> {\n const tool = cloudflared(context);\n mkdirSync(context.cacheDir, { recursive: true, mode: 0o700 });\n const config = join(context.cacheDir, \"cloudflared.yml\");\n writeFileSync(\n config,\n \"# Mostra's quick tunnels read no other configuration.\\nno-autoupdate: true\\n\",\n { mode: 0o600 },\n );\n return runTunnel({\n processes: context.processes,\n log: context.log,\n kind: \"tunnel-cloudflare\",\n ownerRef: input.ownerRef,\n command: tool.command,\n args: [\n ...tool.args,\n \"tunnel\",\n \"--config\",\n config,\n \"--no-autoupdate\",\n \"--metrics\",\n \"127.0.0.1:0\",\n \"--management-diagnostics=false\",\n \"--url\",\n input.local,\n ],\n env: context.env,\n read: quickTunnelReader(tool.fake),\n timeoutMs: QUICK_TUNNEL_TIMEOUT_MS,\n label: \"A Cloudflare quick tunnel\",\n });\n}\n\n/**\n * Waits until a quick tunnel's hostname resolves at Cloudflare's own resolvers (1.1.1.1 and\n * 1.0.0.1), asked directly, past this machine's cache. A new `trycloudflare.com` name takes a few\n * seconds to appear, and a resolver that is asked too early caches the miss for many minutes\n * (observed: the link never opened on this machine after an early probe, WP-13), so neither this\n * machine nor a viewer's phone may ask before the name exists. Resolves `false` when the budget\n * runs out (a network that blocks outside resolvers): the share goes on, since a viewer's\n * resolver may still answer.\n */\nexport async function hostnameResolves(hostname: string, budgetMs: number): Promise<boolean> {\n const resolver = new Resolver({ timeout: 2_000, tries: 1 });\n resolver.setServers([\"1.1.1.1\", \"1.0.0.1\"]);\n const until = Date.now() + budgetMs;\n while (Date.now() < until) {\n try {\n const addresses = await resolver.resolve4(hostname);\n if (addresses.length > 0) return true;\n } catch {\n // Not there yet, or the resolvers can't be reached: ask again shortly.\n }\n await new Promise((resolve) => setTimeout(resolve, 1_000));\n }\n return false;\n}\n","/**\n * The Tailscale driver (D158 item 4): Tailscale Serve for tailnet shares and Funnel for public\n * ones, through foreground `tailscale serve` and `tailscale funnel` children, one per address.\n * A foreground configuration lives as long as its command, so a stopped or crashed share leaves\n * nothing exposed. The device's name comes from `tailscale status --json`; a port this device's\n * own configuration already uses is never taken over.\n */\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { Log } from \"../log.ts\";\nimport { installHint, type ToolCommand, toolCommand } from \"../platform/index.ts\";\nimport type { ProcessManager } from \"../processes/index.ts\";\nimport { type LineVerdict, runToCompletion, runTunnel, type Tunnel } from \"./tunnel.ts\";\n\n/** Funnel's ports (VERIFIED_FACTS): the shell takes 443, two artifacts the others (D158 item 4). */\nexport const FUNNEL_SHELL_PORT = 443;\nexport const FUNNEL_ARTIFACT_PORTS: readonly number[] = [8443, 10000];\n\n/** How long `tailscale serve` or `funnel` may take to serve. */\nconst SERVE_TIMEOUT_MS = 30_000;\n\n/** What the driver needs. */\nexport interface TailscaleContext {\n readonly processes: ProcessManager;\n readonly log: Log;\n /** The environment the tool runs in (the artifact allowlist) and is looked up in. */\n readonly env: Readonly<Record<string, string | undefined>>;\n}\n\n/** This device on its tailnet. */\nexport interface TailnetDevice {\n /** How the tool runs. */\n readonly tool: ToolCommand;\n /** The device's MagicDNS name, such as `laptop.tail1234.ts.net`. */\n readonly hostname: string;\n /** The ports this device serves already (any configuration, its own or Mostra's). */\n readonly served: ReadonlySet<number>;\n}\n\nconst missing = (): RpcError =>\n new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_TOOL_MISSING\", {\n message: `Tailscale isn't installed on this machine (no \\`tailscale\\` found). ${installHint(\"tailscale\")}`,\n }),\n );\n\n/** Finds Tailscale and this device, or explains what is missing. */\nexport async function tailnetDevice(context: TailscaleContext): Promise<TailnetDevice> {\n const tool = toolCommand(\"tailscale\", context.env);\n if (!tool) throw missing();\n const status = await runToCompletion({\n processes: context.processes,\n kind: \"tunnel-query\",\n ownerRef: \"tailscale\",\n command: tool.command,\n args: [...tool.args, \"status\", \"--json\"],\n env: context.env,\n timeoutMs: 15_000,\n label: \"Tailscale\",\n });\n let parsed: {\n BackendState?: string;\n Self?: { DNSName?: string };\n CurrentTailnet?: { MagicDNSEnabled?: boolean };\n };\n try {\n parsed = JSON.parse(status.stdout) as typeof parsed;\n } catch {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_TOOL_NOT_READY\", {\n message: `Tailscale didn't report its status: ${(status.stderr || status.stdout).trim().slice(0, 400) || `exit ${status.code}`}. Start Tailscale and sign in (\\`tailscale up\\`).`,\n }),\n );\n }\n if (parsed.BackendState !== \"Running\") {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_TOOL_NOT_READY\", {\n message: `Tailscale is ${parsed.BackendState ?? \"not running\"} on this machine. Start it and sign in (\\`tailscale up\\`).`,\n }),\n );\n }\n const dns = parsed.Self?.DNSName?.replace(/\\.$/, \"\").toLowerCase();\n if (!dns || parsed.CurrentTailnet?.MagicDNSEnabled === false) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_NOT_ENABLED\", {\n message:\n \"This tailnet has MagicDNS off, which Tailscale Serve and Funnel need for the device's name. Turn it on in the tailnet's DNS settings (https://login.tailscale.com/admin/dns).\",\n }),\n );\n }\n return { tool, hostname: dns, served: await servedPorts(context, tool) };\n}\n\n/** The ports this device's Serve and Funnel configuration uses now. */\nasync function servedPorts(context: TailscaleContext, tool: ToolCommand): Promise<Set<number>> {\n const status = await runToCompletion({\n processes: context.processes,\n kind: \"tunnel-query\",\n ownerRef: \"tailscale\",\n command: tool.command,\n args: [...tool.args, \"serve\", \"status\", \"--json\"],\n env: context.env,\n timeoutMs: 15_000,\n label: \"Tailscale\",\n });\n const ports = new Set<number>();\n try {\n const config = JSON.parse(status.stdout || \"{}\") as {\n TCP?: Record<string, unknown>;\n Foreground?: Record<string, { TCP?: Record<string, unknown> }>;\n };\n for (const key of Object.keys(config.TCP ?? {})) ports.add(Number(key));\n for (const session of Object.values(config.Foreground ?? {})) {\n for (const key of Object.keys(session.TCP ?? {})) ports.add(Number(key));\n }\n } catch {\n // An unreadable configuration hides nothing Tailscale itself would refuse.\n }\n return ports;\n}\n\n/**\n * Reads `tailscale serve` and `funnel` output: they serve once they print where; a tailnet\n * without the feature prints the address where an admin turns it on, which the share reports.\n */\nfunction serveReader(\n feature: \"Serve\" | \"Funnel\",\n device: TailnetDevice,\n port: number,\n): (line: string) => LineVerdict {\n let notEnabled = false;\n const expected = tailnetOrigin(device.hostname, port);\n return (line) => {\n const text = line.trim();\n // The address it prints is the one it serves: the device's name at the port asked for, or,\n // from the test fakes only, plain HTTP on loopback.\n const printed = /^(https?:\\/\\/\\S+?)\\/?$/.exec(text)?.[1]?.toLowerCase();\n if (\n printed !== undefined &&\n (printed === expected ||\n (device.tool.fake && /^http:\\/\\/(\\[::1\\]|127\\.0\\.0\\.1|localhost):\\d+$/.test(printed)))\n ) {\n return { kind: \"origin\", origin: printed };\n }\n if (/not enabled on your tailnet|isn't enabled|is not enabled/i.test(text)) {\n notEnabled = true;\n return undefined;\n }\n const consent = /https:\\/\\/login\\.tailscale\\.com\\/\\S+/.exec(text);\n if (consent && notEnabled) {\n return {\n kind: \"failed\",\n diagnostic: createDiagnostic(\"MOSTRA_SHARE_NOT_ENABLED\", {\n message: `Tailscale ${feature} isn't enabled for this device's tailnet. An admin of the tailnet turns it on at ${consent[0]}`,\n }),\n };\n }\n if (\n /^Available (within your tailnet|on the internet)/i.test(text) ||\n /Press Ctrl\\+C to exit/i.test(text)\n ) {\n return { kind: \"serving\" };\n }\n if (/already|in use|conflict/i.test(text) && /port|serve|listen/i.test(text)) {\n return {\n kind: \"failed\",\n diagnostic: createDiagnostic(\"MOSTRA_SHARE_PORTS_EXHAUSTED\", {\n message: `Tailscale refused the port: ${text.slice(0, 300)}`,\n }),\n };\n }\n if (/^(error|failed)|permission denied|access denied/i.test(text)) {\n return {\n kind: \"failed\",\n diagnostic: createDiagnostic(\"MOSTRA_SHARE_TOOL_NOT_READY\", {\n message: `Tailscale ${feature} refused the share: ${text.slice(0, 300)}`,\n }),\n };\n }\n return undefined;\n };\n}\n\n/**\n * Serves `local` at `https://<device>:<port>` on the tailnet (`serve`) or on the internet\n * (`funnel`), until the tunnel is stopped.\n */\nexport function expose(\n context: TailscaleContext,\n device: TailnetDevice,\n input: {\n readonly feature: \"serve\" | \"funnel\";\n readonly port: number;\n readonly local: string;\n readonly ownerRef: string;\n },\n): Promise<Tunnel> {\n const label = input.feature === \"serve\" ? \"Tailscale Serve\" : \"Tailscale Funnel\";\n return runTunnel({\n processes: context.processes,\n log: context.log,\n kind: `tunnel-${input.feature}`,\n ownerRef: input.ownerRef,\n command: device.tool.command,\n args: [...device.tool.args, input.feature, `--https=${input.port}`, input.local],\n env: context.env,\n read: serveReader(input.feature === \"serve\" ? \"Serve\" : \"Funnel\", device, input.port),\n // A release that doesn't print its address still serves the device's name at that port.\n ...(device.tool.fake ? {} : { origin: tailnetOrigin(device.hostname, input.port) }),\n timeoutMs: SERVE_TIMEOUT_MS,\n label,\n });\n}\n\n/** `https://<device>` with the port only when it isn't 443, as a browser writes the origin. */\nexport function tailnetOrigin(hostname: string, port: number): string {\n return port === 443 ? `https://${hostname}` : `https://${hostname}:${port}`;\n}\n","/**\n * Shares (HY-04, HY-05, D158): an artifact opened to viewers beyond this machine through a tunnel\n * the instance drives. A share opens the gateway's faces for its tunnel (D158 item 1), the tunnel\n * tool's processes that forward to them, and a link of its own at the tunnel's shell address\n * (D97 item 10); it ends at its TTL, on `share/stop`, when its link is revoked, or when its tunnel\n * can't continue, and every end revokes its link and stops what only it used.\n *\n * - **Tailnet** (Tailscale Serve): the shell's and each artifact's face keep leased ports, served\n * on the device's name at the same port numbers, so tailnet links survive restarts. Requests\n * carry the tailnet person, who becomes the viewer (D158 item 2).\n * - **Funnel**: the shell on 443 and two artifacts on 8443 and 10000 (D158 item 4), public.\n * - **Cloudflare** quick tunnels: one per face, each a site of its own, so worker-mode frames\n * (D70), and pages long-poll, since quick tunnels hold responses back. A quick tunnel's address\n * dies with its process, so its share ends with it, a restart included.\n *\n * ```ts\n * const shares = createShares({ ledger, log, gateway, capabilities, interaction, artifacts, … });\n * const share = await shares.start({ artifact: { artifactId }, via: \"cloudflare\", ttl: \"1h\" });\n * share.url; // https://<random>.trycloudflare.com/a/art_…#t=…\n * ```\n */\nimport { join } from \"node:path\";\nimport {\n type ArtifactDetail,\n type ArtifactRef,\n createDiagnostic,\n durationMs,\n PUBLIC_SHARE_DEFAULT_TTL,\n PUBLIC_SHARE_MAX_TTL_MS,\n RpcError,\n type Share,\n ShareId,\n type ShareListParams,\n type ShareStartParams,\n type ShareStartResult,\n type ShareStopParams,\n type ShareVia,\n shareListMethod,\n shareStartMethod,\n shareStopMethod,\n} from \"@mostra/protocol\";\nimport type { Capabilities, FaceHandle, FaceSpec, Gateway } from \"../gateway/index.ts\";\nimport { faceKey } from \"../gateway/index.ts\";\nimport { appendEvent, type Interaction } from \"../interaction/index.ts\";\nimport {\n InflightRequests,\n type Ledger,\n type LedgerDb,\n recordedResult,\n recordResult,\n requestKey,\n} from \"../ledger/index.ts\";\nimport type { Environment, Log } from \"../log.ts\";\nimport type { ProcessManager } from \"../processes/index.ts\";\nimport { handler, type MethodHandler } from \"../protocol-server/index.ts\";\nimport { hostnameResolves, quickTunnel } from \"./cloudflare.ts\";\nimport {\n expose,\n FUNNEL_ARTIFACT_PORTS,\n FUNNEL_SHELL_PORT,\n type TailnetDevice,\n tailnetDevice,\n} from \"./tailscale.ts\";\nimport type { Tunnel } from \"./tunnel.ts\";\n\n/** How often active shares are checked for an expired or revoked link. */\nconst SWEEP_MS = 30_000;\n\n/** How a tailnet or Funnel tunnel that ended by itself is set up again: after 1, 4 and 16 s. */\nconst RESTART_DELAYS_MS: readonly number[] = [1_000, 4_000, 16_000];\n\n/** How long a restart keeps trying to set a share up again before ending it (Tailscale starting). */\nconst RECOVERY_DELAYS_MS: readonly number[] = [0, 5_000, 15_000, 30_000, 60_000];\n\n/** How long a quick tunnel's name may take to appear before its link is handed out anyway. */\nconst PROBE_MS = 30_000;\n\n/** Options for {@link createShares}. */\nexport interface SharesOptions {\n readonly ledger: Ledger;\n readonly log: Log;\n readonly gateway: Gateway;\n readonly capabilities: Capabilities;\n readonly interaction: Interaction;\n readonly artifacts: { get(ref: ArtifactRef): ArtifactDetail };\n readonly processes: ProcessManager;\n /** Where the tools are looked up (`PATH`, `MOSTRA_TAILSCALE`, `MOSTRA_CLOUDFLARED`). */\n readonly environment: Environment;\n /** The tools' own environment: the artifact allowlist (proxies, certificates, `PATH`). */\n readonly toolEnvironment: Environment;\n /** The home's cache, for the quick tunnel's empty configuration. */\n readonly cacheDir: string;\n /** The clock, in milliseconds. */\n readonly now: () => number;\n /** How long a public address is probed before its link goes out; 0 turns probing off (tests). */\n readonly probeMs?: number;\n /** How often active shares are checked for an expired or revoked link (tests shorten it). */\n readonly sweepMs?: number;\n}\n\n/** The shares of one instance. */\nexport interface Shares {\n /** `share/start`, `share/stop` and `share/list`. */\n methods(): MethodHandler[];\n /** How many shares are active: each keeps a daemon from its idle exit (D133). */\n count(): number;\n /** The active shares, for `instance/status`: without their links, which carry secrets. */\n active(): Share[];\n /** Sets tailnet and Funnel shares up again after a restart, and ends what can't continue. */\n recover(): Promise<void>;\n /** Stops every tunnel; shares stay active in the ledger, for the next start to set up again. */\n close(): Promise<void>;\n}\n\ninterface ShareRow {\n id: string;\n artifact_id: string;\n via: ShareVia;\n hostname: string;\n token_id: string;\n mode: \"cookie\" | \"worker\";\n plan_json: string;\n started_at: string;\n expires_at: string | null;\n stopped_at: string | null;\n stop_reason: string | null;\n}\n\n/** One face a share uses, as its plan records it. */\ninterface PlannedFace {\n readonly key: string;\n readonly listener: \"shell\" | \"artifact\";\n /** The tunnel's external port (Tailscale), or none (Cloudflare). */\n readonly external?: number;\n}\n\ninterface Plan {\n readonly faces: readonly PlannedFace[];\n}\n\n/** A running tunnel and the shares that use it. */\ninterface Exposure {\n tunnel: Tunnel;\n readonly refs: Set<string>;\n readonly start: () => Promise<Tunnel>;\n readonly via: ShareVia;\n restarting: boolean;\n}\n\n/** Creates the shares of one instance. */\nexport function createShares(options: SharesOptions): Shares {\n const { ledger, log, gateway, capabilities, interaction } = options;\n const exposures = new Map<string, Exposure>();\n const timers = new Map<string, ReturnType<typeof setTimeout>>();\n const inflight = new InflightRequests();\n let closed = false;\n let chain: Promise<unknown> = Promise.resolve();\n /** Share starts and stops run one at a time, so refcounts and port plans never race. */\n const serial = <T>(task: () => Promise<T>): Promise<T> => {\n const run = chain.then(task, task);\n chain = run.catch(() => undefined);\n return run;\n };\n const toolContext = {\n processes: options.processes,\n log,\n env: { ...options.toolEnvironment, ...pick(options.environment) },\n };\n const iso = (ms: number): string => new Date(ms).toISOString();\n\n const row = (shareId: string): ShareRow | undefined =>\n ledger.read((db) => db.get<ShareRow>(\"SELECT * FROM share WHERE id = ?\", shareId));\n\n const toShare = (found: ShareRow): Share => {\n // A share follows its link through rotations (`view/rotate`): its token now.\n const tokenId = capabilities.current(found.token_id);\n const url = found.stopped_at === null ? gateway.reveal(tokenId) : undefined;\n const artifactKey = (JSON.parse(found.plan_json) as Plan).faces.find(\n (face) => face.listener === \"artifact\",\n )?.key;\n const artifactOrigin =\n found.stopped_at === null && artifactKey !== undefined\n ? gateway.face(artifactKey)?.origin()\n : undefined;\n return {\n shareId: found.id,\n artifactId: found.artifact_id,\n via: found.via,\n ...(url !== undefined ? { url } : {}),\n hostname: found.hostname,\n ...(artifactOrigin !== undefined ? { artifactOrigin } : {}),\n mode: found.mode,\n tokenId,\n startedAt: found.started_at,\n ...(found.expires_at !== null ? { expiresAt: found.expires_at } : {}),\n state: found.stopped_at === null ? \"active\" : \"stopped\",\n ...(found.stopped_at !== null ? { stoppedAt: found.stopped_at } : {}),\n ...(found.stop_reason !== null ? { stopReason: found.stop_reason } : {}),\n };\n };\n\n const activeRows = (): ShareRow[] =>\n ledger.read((db) =>\n db.all<ShareRow>(\"SELECT * FROM share WHERE stopped_at IS NULL ORDER BY started_at DESC\"),\n );\n\n // ── Tunnels ──────────────────────────────────────────────────────────────────────────────\n\n /**\n * The tunnel of a face, started for `shareId` or joined when it runs already. A tunnel that\n * ends by itself is set up again (Tailscale, whose address is the device's) or ends every share\n * that used it (Cloudflare, whose address died with it).\n */\n const acquire = async (\n key: string,\n shareId: string,\n via: ShareVia,\n start: () => Promise<Tunnel>,\n ): Promise<Tunnel> => {\n const running = exposures.get(key);\n if (running?.restarting) {\n // Its process ended and is being started again (Opus review of WP-13): a new share never\n // gets a link through a tunnel that isn't there. This runs inside the lifecycle's turn,\n // which the restart waits for, so it can't wait for the restart in turn.\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_TUNNEL_FAILED\", {\n message:\n \"This share's tunnel stopped a moment ago and is being started again; try again in a few seconds.\",\n }),\n );\n }\n if (running) {\n running.refs.add(shareId);\n return running.tunnel;\n }\n const tunnel = await start();\n const exposure: Exposure = { tunnel, refs: new Set([shareId]), start, via, restarting: false };\n exposures.set(key, exposure);\n watch(key, exposure);\n return tunnel;\n };\n\n const watch = (key: string, exposure: Exposure): void => {\n const current = exposure.tunnel;\n void current.ended.then(async (end) => {\n if (closed || exposures.get(key) !== exposure || exposure.tunnel !== current) return;\n log.warn(\"share.tunnel_dropped\", { key, code: end.code, lines: end.lines.slice(-3) });\n if (exposure.via !== \"cloudflare\") {\n exposure.restarting = true;\n for (const delay of RESTART_DELAYS_MS) {\n await new Promise((resolve) => setTimeout(resolve, delay));\n if (closed || exposures.get(key) !== exposure) return;\n try {\n // One at a time with starts and stops (GPT review of WP-13): a share stopped while\n // this start was under way must not be left with the tunnel it started.\n const restored = await serial(async () => {\n if (closed || exposures.get(key) !== exposure) return false;\n const tunnel = await exposure.start();\n if (closed || exposures.get(key) !== exposure) {\n await tunnel.stop();\n return false;\n }\n exposure.tunnel = tunnel;\n return true;\n });\n if (!restored) return;\n exposure.restarting = false;\n log.info(\"share.tunnel_restored\", { key });\n watch(key, exposure);\n return;\n } catch (error) {\n log.warn(\"share.tunnel_restart_failed\", { key, error: (error as Error).message });\n }\n }\n }\n // The tunnel can't continue: every share that used it ends, and says why.\n for (const shareId of [...exposure.refs]) {\n await serial(() => stop(shareId, \"tunnel\")).catch((error: unknown) =>\n log.error(\"share.stop_failed\", { shareId, error }),\n );\n }\n });\n };\n\n /** Drops a share's hold on a face's tunnel, stopping it and closing the face when unused. */\n const release = async (key: string, shareId: string): Promise<void> => {\n const exposure = exposures.get(key);\n if (exposure) {\n exposure.refs.delete(shareId);\n if (exposure.refs.size > 0) return;\n exposures.delete(key);\n await exposure.tunnel.stop();\n }\n // Its external port (Funnel's 8443 or 10000) is free for the next share (GPT review of WP-13).\n externalPorts.delete(key);\n // A tailnet face keeps its lease, so the next tailnet share has the same address.\n await gateway.closeFace(key, !key.startsWith(\"tailnet:\"));\n };\n\n // ── Starting ─────────────────────────────────────────────────────────────────────────────\n\n /** The ttl a share's link gets: public shares 1 hour by default and at most 7 days (D158). */\n const lifetime = (via: ShareVia, ttl: ShareStartParams[\"ttl\"]): number | undefined => {\n if (via === \"tailnet\") return ttl === undefined ? undefined : durationMs(ttl);\n const ms = durationMs(ttl ?? PUBLIC_SHARE_DEFAULT_TTL);\n if (ms > PUBLIC_SHARE_MAX_TTL_MS) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_TTL_INVALID\", {\n message: `A public share lasts at most 7 days; ${ttl} is longer.`,\n }),\n );\n }\n return ms;\n };\n\n /** Opens a face and its tunnel for a share, or joins the ones that run already. */\n const faceFor = async (\n spec: FaceSpec,\n shareId: string,\n tunnel: (face: FaceHandle) => Promise<Tunnel>,\n held: string[],\n ): Promise<FaceHandle> => {\n const face = await gateway.openFace(spec);\n held.push(face.key);\n const running = await acquire(face.key, shareId, spec.by as ShareVia, () => tunnel(face));\n face.setOrigin(running.origin);\n return face;\n };\n\n /** Sets up a share's faces and tunnels; on failure releases what it took. */\n const setUp = async (\n shareId: string,\n artifactId: string,\n via: ShareVia,\n planned: Plan | undefined,\n ): Promise<{ shell: FaceHandle; artifact: FaceHandle; plan: Plan; hostname: string }> => {\n const held: string[] = [];\n try {\n if (via === \"cloudflare\") {\n const group = `cloudflare:${shareId}`;\n const context = { ...toolContext, cacheDir: options.cacheDir };\n const spec = (listener: \"shell\" | \"artifact\"): FaceSpec => ({\n by: \"cloudflare\",\n group,\n listener,\n ...(listener === \"artifact\" ? { artifactId, mode: \"worker\" as const } : {}),\n via: \"token\",\n lease: false,\n streams: false,\n });\n // Both tunnels start at once; both outcomes are awaited before either is judged, so a\n // failure never releases a sibling still starting, whose tunnel would outlive it (GPT\n // review of WP-13).\n const settled = await Promise.allSettled([\n faceFor(\n spec(\"shell\"),\n shareId,\n (face) => quickTunnel(context, { local: face.local, ownerRef: face.key }),\n held,\n ),\n faceFor(\n spec(\"artifact\"),\n shareId,\n (face) => quickTunnel(context, { local: face.local, ownerRef: face.key }),\n held,\n ),\n ]);\n const failed = settled.find((outcome) => outcome.status === \"rejected\");\n if (failed) throw failed.reason;\n const [shell, artifact] = settled.map(\n (outcome) => (outcome as PromiseFulfilledResult<FaceHandle>).value,\n ) as [FaceHandle, FaceHandle];\n await Promise.all([probe(shell.origin()), probe(artifact.origin())]);\n return {\n shell,\n artifact,\n plan: {\n faces: [\n { key: shell.key, listener: \"shell\" },\n { key: artifact.key, listener: \"artifact\" },\n ],\n },\n hostname: new URL(shell.origin() as string).hostname,\n };\n }\n const device = await tailnetDevice(toolContext);\n const ours = (port: number): boolean =>\n [...exposures.entries()].some(\n ([key, exposure]) => exposure.via !== \"cloudflare\" && planPort(key) === port,\n );\n const free = (port: number): boolean => !device.served.has(port) || ours(port);\n if (via === \"tailnet\") {\n const spec = (listener: \"shell\" | \"artifact\"): FaceSpec => ({\n by: \"tailnet\",\n group: \"tailnet\",\n listener,\n ...(listener === \"artifact\" ? { artifactId } : {}),\n via: \"tailnet\",\n lease: true,\n });\n const serveAt = (face: FaceHandle): Promise<Tunnel> => {\n if (!free(face.port)) throw portTaken(face.port, \"Serve\");\n return tailnetTunnel(device, \"serve\", face.port, face);\n };\n const shell = await faceFor(spec(\"shell\"), shareId, serveAt, held);\n const artifact = await faceFor(spec(\"artifact\"), shareId, serveAt, held);\n return {\n shell,\n artifact,\n plan: {\n faces: [\n { key: shell.key, listener: \"shell\", external: shell.port },\n { key: artifact.key, listener: \"artifact\", external: artifact.port },\n ],\n },\n hostname: device.hostname,\n };\n }\n // Funnel: the shell on 443, each artifact on one of the two other ports.\n const spec = (listener: \"shell\" | \"artifact\"): FaceSpec => ({\n by: \"funnel\",\n group: \"funnel\",\n listener,\n ...(listener === \"artifact\" ? { artifactId } : {}),\n via: \"token\",\n // Leased, so a restart reopens its faces on the same local ports and the session cookies\n // their names carry keep working at the same public addresses (GPT review of WP-13).\n lease: true,\n });\n const shellKey = faceKey(\"funnel\", \"shell\");\n if (!exposures.has(shellKey) && !free(FUNNEL_SHELL_PORT))\n throw portTaken(FUNNEL_SHELL_PORT, \"Funnel\");\n const shell = await faceFor(\n spec(\"shell\"),\n shareId,\n (face) => tailnetTunnel(device, \"funnel\", FUNNEL_SHELL_PORT, face),\n held,\n );\n const artifactKey = faceKey(\"funnel\", \"artifact\", artifactId);\n const plannedPort = planned?.faces.find((face) => face.key === artifactKey)?.external;\n const port =\n planPort(artifactKey) ??\n // The port its recorded plan names (after a restart) when no other face took it, else\n // the first free one.\n [plannedPort, ...FUNNEL_ARTIFACT_PORTS].find(\n (candidate): candidate is number =>\n candidate !== undefined &&\n free(candidate) &&\n ![...externalPorts].some(([key, taken]) => key !== artifactKey && taken === candidate),\n );\n if (port === undefined) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_PORTS_EXHAUSTED\", {\n message: `Tailscale Funnel's ports for artifacts (${FUNNEL_ARTIFACT_PORTS.join(\" and \")}) are in use: two artifacts are shared through Funnel already, or this device's own configuration uses them.`,\n }),\n );\n }\n const artifact = await faceFor(\n spec(\"artifact\"),\n shareId,\n (face) => tailnetTunnel(device, \"funnel\", port, face),\n held,\n );\n return {\n shell,\n artifact,\n plan: {\n faces: [\n { key: shell.key, listener: \"shell\", external: FUNNEL_SHELL_PORT },\n { key: artifact.key, listener: \"artifact\", external: port },\n ],\n },\n hostname: device.hostname,\n };\n } catch (error) {\n for (const key of held) await release(key, shareId).catch(() => undefined);\n throw error;\n }\n };\n\n /** The external ports of running Tailscale tunnels, by face key. */\n const externalPorts = new Map<string, number>();\n const planPort = (key: string): number | undefined => externalPorts.get(key);\n\n const tailnetTunnel = async (\n device: TailnetDevice,\n feature: \"serve\" | \"funnel\",\n port: number,\n face: FaceHandle,\n ): Promise<Tunnel> => {\n const tunnel = await expose(toolContext, device, {\n feature,\n port,\n local: face.local,\n ownerRef: face.key,\n });\n externalPorts.set(face.key, port);\n return tunnel;\n };\n\n const portTaken = (port: number, feature: string): RpcError =>\n new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_PORTS_EXHAUSTED\", {\n message: `Port ${port} of this device is in use by its own Tailscale ${feature} configuration, which Mostra never takes over.`,\n }),\n );\n\n /**\n * Waits until a quick tunnel's name exists at Cloudflare's resolvers, so the link never meets a\n * cached miss on this machine or a viewer's phone; nothing here resolves it before then.\n */\n const probe = async (origin: string | undefined): Promise<void> => {\n const budget = options.probeMs ?? PROBE_MS;\n if (origin === undefined || budget <= 0) return;\n const hostname = new URL(origin).hostname;\n // Only a real quick tunnel's name is new to the world's resolvers.\n if (!hostname.endsWith(\".trycloudflare.com\")) return;\n if (!(await hostnameResolves(hostname, budget))) {\n log.warn(\"share.name_unresolved\", { hostname, budgetMs: budget });\n }\n };\n\n const start = async (params: ShareStartParams): Promise<ShareStartResult> => {\n const detail = options.artifacts.get(params.artifact);\n if (!detail.latestVersion && detail.versions.length === 0) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ARTIFACT_VERSION_NOT_FOUND\", {\n message: `The artifact ${detail.id} has no published version to share.`,\n }),\n );\n }\n const key = requestKey(\"share/start\", params);\n if (key !== undefined) {\n const replay = ledger.read((db) => recordedResult<{ shareId: string }>(db, key));\n const found = replay ? row(replay.shareId) : undefined;\n if (found) return withUrl(toShare(found));\n }\n const ttlMs = lifetime(params.via, params.ttl);\n const shareId = ShareId.create();\n const { shell, artifact, plan, hostname } = await setUp(\n shareId,\n detail.id,\n params.via,\n undefined,\n );\n const shellOrigin = shell.origin() as string;\n const startedAt = options.now();\n const record = (): ReturnType<typeof gateway.mintAt> =>\n ledger.write((db) => {\n const viewerId =\n params.viewer === undefined ? undefined : interaction.viewerForSpec(db, params.viewer);\n const link = gateway.mintAt(\n { artifactId: detail.id, shellOrigin, scopes: params.scopes, ttlMs, viewerId },\n db,\n );\n db.run(\n \"INSERT INTO share (id, artifact_id, via, hostname, token_id, mode, plan_json, started_at, expires_at, stopped_at, stop_reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)\",\n shareId,\n detail.id,\n params.via,\n hostname,\n link.tokenId,\n params.via === \"cloudflare\" ? \"worker\" : \"cookie\",\n JSON.stringify(plan),\n iso(startedAt),\n link.expiresAt ?? null,\n );\n appendEvent(db, {\n artifactId: detail.id,\n type: \"share.started\",\n payload: { shareId, via: params.via, hostname, artifactOrigin: artifact.origin() },\n });\n if (key !== undefined) recordResult(db, key, { shareId });\n return link;\n });\n let minted: ReturnType<typeof gateway.mintAt>;\n try {\n minted = record();\n } catch (error) {\n // Nothing was recorded: what the share set up goes again.\n for (const face of plan.faces) await release(face.key, shareId).catch(() => undefined);\n throw error;\n }\n schedule(shareId, minted.expiresAt);\n log.info(\"share.started\", { shareId, artifactId: detail.id, via: params.via, hostname });\n const started = row(shareId) as ShareRow;\n return { ...toShare(started), url: minted.url };\n };\n\n const withUrl = (share: Share): ShareStartResult => ({\n ...share,\n url: share.url ?? gateway.reveal(share.tokenId) ?? \"\",\n });\n\n // ── Ending ───────────────────────────────────────────────────────────────────────────────\n\n const schedule = (shareId: string, expiresAt: string | undefined): void => {\n if (expiresAt === undefined) return;\n const delay = Math.max(0, Date.parse(expiresAt) - options.now());\n // Timers past ~24.8 days overflow; the sweep ends those.\n if (delay > 2 ** 31 - 1) return;\n const timer = setTimeout(() => {\n timers.delete(shareId);\n void serial(() => stop(shareId, \"expired\")).catch((error: unknown) =>\n log.error(\"share.stop_failed\", { shareId, error }),\n );\n }, delay);\n timer.unref?.();\n timers.set(shareId, timer);\n };\n\n /**\n * Ends a share once: its link is revoked (unless it expired or was revoked already), the\n * ledger records why, and its faces' tunnels stop when no other share uses them.\n */\n const stop = async (shareId: string, reason: string): Promise<Share | undefined> => {\n const found = row(shareId);\n if (!found || found.stopped_at !== null) return undefined;\n const at = options.now();\n ledger.write((db: LedgerDb) => {\n db.run(\n \"UPDATE share SET stopped_at = ?, stop_reason = ? WHERE id = ?\",\n iso(at),\n reason,\n shareId,\n );\n if (reason !== \"expired\" && reason !== \"revoked\") {\n capabilities.revoke(capabilities.current(found.token_id), db);\n }\n appendEvent(db, {\n artifactId: found.artifact_id,\n type: \"share.stopped\",\n payload: { shareId, via: found.via, hostname: found.hostname, reason },\n });\n });\n const timer = timers.get(shareId);\n if (timer !== undefined) clearTimeout(timer);\n timers.delete(shareId);\n const plan = JSON.parse(found.plan_json) as Plan;\n for (const face of plan.faces) await release(face.key, shareId);\n log.info(\"share.stopped\", { shareId, via: found.via, reason });\n return toShare(row(shareId) as ShareRow);\n };\n\n /** Ends shares whose link expired or was revoked since (`view/revoke` of a share's link). */\n const sweep = async (): Promise<void> => {\n for (const found of activeRows()) {\n const grant = capabilities.grant(capabilities.current(found.token_id));\n if (grant?.live) continue;\n const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();\n await serial(() => stop(found.id, expired ? \"expired\" : \"revoked\"));\n }\n };\n const sweeper = setInterval(() => {\n void sweep().catch((error: unknown) => log.error(\"share.sweep_failed\", { error }));\n }, options.sweepMs ?? SWEEP_MS);\n sweeper.unref?.();\n\n // ── After a restart ──────────────────────────────────────────────────────────────────────\n\n const restore = async (found: ShareRow): Promise<void> => {\n const plan = JSON.parse(found.plan_json) as Plan;\n let last: unknown;\n for (const delay of RECOVERY_DELAYS_MS) {\n if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));\n if (closed) return;\n try {\n // The share is judged inside the lifecycle's turn (Opus review of WP-13): a `share/stop`\n // queued meanwhile ran first, and nothing is set up for a share that ended.\n const restored = await serial(async () => {\n const current = row(found.id);\n if (closed || !current || current.stopped_at !== null) return false;\n await setUp(found.id, found.artifact_id, found.via, plan);\n return true;\n });\n if (!restored) return;\n schedule(found.id, found.expires_at ?? undefined);\n log.info(\"share.restored\", { shareId: found.id, via: found.via });\n return;\n } catch (error) {\n last = error;\n log.warn(\"share.restore_failed\", { shareId: found.id, error: (error as Error).message });\n }\n }\n log.warn(\"share.restore_gave_up\", {\n shareId: found.id,\n error: last instanceof Error ? last.message : String(last),\n });\n await serial(() => stop(found.id, \"tunnel\"));\n };\n\n return {\n methods: () => [\n handler(shareStartMethod, (params) => {\n const key = requestKey(\"share/start\", params);\n const run = (): Promise<ShareStartResult> => serial(() => start(params));\n return key === undefined ? run() : inflight.run(key, run);\n }),\n handler(shareStopMethod, (params: ShareStopParams) =>\n serial(async () => {\n if ((params.shareId === undefined) === (params.artifact === undefined)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", {\n message: \"share/stop names either `shareId` or `artifact`, not both or neither.\",\n }),\n -32602,\n );\n }\n let ids: string[];\n if (params.shareId !== undefined) {\n if (!row(params.shareId)) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_SHARE_NOT_FOUND\", {\n message: `No share ${params.shareId} exists in this home.`,\n }),\n );\n }\n ids = [params.shareId];\n } else {\n const artifactId = options.artifacts.get(params.artifact as ArtifactRef).id;\n ids = activeRows()\n .filter((found) => found.artifact_id === artifactId)\n .map((found) => found.id);\n }\n const stopped: Share[] = [];\n for (const id of ids) {\n const ended = await stop(id, \"stopped\");\n if (ended) stopped.push(ended);\n }\n return { stopped };\n }),\n ),\n handler(shareListMethod, (params: ShareListParams) => {\n const artifactId =\n params.artifact === undefined ? undefined : options.artifacts.get(params.artifact).id;\n const rows = ledger.read((db) =>\n db.all<ShareRow>(\n params.all === true\n ? \"SELECT * FROM share ORDER BY stopped_at IS NOT NULL, started_at DESC\"\n : \"SELECT * FROM share WHERE stopped_at IS NULL ORDER BY started_at DESC\",\n ),\n );\n return {\n shares: rows\n .filter((found) => artifactId === undefined || found.artifact_id === artifactId)\n .map(toShare),\n };\n }),\n ],\n count: () =>\n ledger.read(\n (db) =>\n db.get<{ count: number }>(\"SELECT COUNT(*) AS count FROM share WHERE stopped_at IS NULL\")\n ?.count ?? 0,\n ),\n // Status is read by tools that print it (`mostra inspect`, bug reports): a share's link and\n // its secret appear only where asked for, `share/start` and `share/list` (Opus review of\n // WP-13; capability tokens stay out of every other output).\n active: () =>\n activeRows().map((found) => {\n const { url: _url, ...rest } = toShare(found);\n return rest;\n }),\n async recover() {\n const pending: Promise<void>[] = [];\n for (const found of activeRows()) {\n const grant = capabilities.grant(capabilities.current(found.token_id));\n const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();\n if (expired || !grant?.live) {\n await serial(() => stop(found.id, expired ? \"expired\" : \"revoked\"));\n } else if (found.via === \"cloudflare\") {\n // A quick tunnel's address died with the instance that ran it.\n await serial(() => stop(found.id, \"restart\"));\n } else {\n pending.push(restore(found));\n }\n }\n await Promise.all(pending);\n },\n async close() {\n closed = true;\n clearInterval(sweeper);\n for (const timer of timers.values()) clearTimeout(timer);\n timers.clear();\n const running = [...exposures.values()];\n exposures.clear();\n await Promise.all(running.map((exposure) => exposure.tunnel.stop()));\n },\n };\n}\n\n/** The variables that name the tools outright, passed to the lookup from the instance's own. */\nfunction pick(env: Environment): Environment {\n const out: Record<string, string> = {};\n // The test fakes (`MOSTRA_TEST_TUNNELS`) and what they are told to play.\n if (env[\"MOSTRA_TEST_TUNNELS\"]) {\n for (const [name, value] of Object.entries(env)) {\n if (\n (name === \"MOSTRA_TEST_TUNNELS\" || name.startsWith(\"MOSTRA_FAKE_\")) &&\n value !== undefined\n ) {\n out[name] = value;\n }\n }\n }\n for (const name of [\n \"MOSTRA_TAILSCALE\",\n \"MOSTRA_CLOUDFLARED\",\n \"PATH\",\n \"Path\",\n \"ProgramFiles\",\n \"ProgramFiles(x86)\",\n ]) {\n const value = env[name];\n if (value !== undefined) out[name] = value;\n }\n return out;\n}\n\n/** The directory of a home's share files (the quick tunnel's empty configuration). */\nexport function shareCacheDir(home: string): string {\n return join(home, \"cache\", \"share\");\n}\n","/**\n * The instance (D45, D85, D87): the composition root. It assembles the home, the ledger, the\n * process manager and the protocol server in their start-up order and stops them in reverse. It\n * holds no policy of its own; each rule lives in the module that owns it.\n *\n * ```ts\n * const started = await startInstance({ mode: \"daemon\", home: \"/path/to/home\" });\n * if (started.kind === \"attached\") console.log(`already running as ${started.record.pid}`);\n * else await started.instance.stopped;\n * ```\n */\nimport { readFileSync, statSync } from \"node:fs\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport type { Readable, Writable } from \"node:stream\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n ARTIFACT_PROGRESS,\n BROWSER_PROTOCOL_REVISIONS,\n type ClientInfo,\n DEV_NOTIFY,\n type Diagnostic,\n EVENTS_NOTIFY,\n type InstanceInfo,\n type JsonRpcParams,\n type MostraInitializeResult,\n type PortTrustedControlsActivatedParams,\n portAddressingExternalBaseMethod,\n portIdentityResolveMethod,\n portSecretsGetMethod,\n portTrustedControlsActivatedMethod,\n portTrustedControlsPolicyMethod,\n RpcError,\n} from \"@mostra/protocol\";\nimport { createActions } from \"../actions/index.ts\";\nimport { createAddressing, resolveBind } from \"../addressing/index.ts\";\nimport {\n coverageMatcher,\n createSpaRenderMode,\n type RenderMode,\n readFieldCoverage,\n readLiveSources,\n readServerFunctions,\n} from \"../builder/index.ts\";\nimport {\n createDependencies,\n type Dependencies,\n locateWarmSet,\n recoverDependencies,\n runtimeRoot,\n} from \"../deps/index.ts\";\nimport { createDev, type Dev, recoverDev } from \"../dev/index.ts\";\nimport { faultsFrom } from \"../faults.ts\";\nimport { Gate } from \"../gate.ts\";\nimport {\n Capabilities,\n CONTROLS_POLICY_TIMEOUT_MS,\n capabilityKey,\n controlsPolicy,\n createGateway,\n type Gateway,\n IDENTITY_TIMEOUT_MS,\n locateShell,\n resolveIdentity,\n} from \"../gateway/index.ts\";\nimport { createGc, gcMethods } from \"../gc/index.ts\";\nimport {\n acquireHome,\n checkPlatform,\n type InstanceRecord,\n markHostConfigured,\n type OwnedHome,\n platformName,\n readHomeSettings,\n resolveHomePath,\n writeHomeSettings,\n} from \"../home/index.ts\";\nimport {\n createEphemeralBus,\n createInteraction,\n type Interaction,\n redactEvents,\n} from \"../interaction/index.ts\";\nimport { createLive, type LatestLive, liveMethods } from \"../live/index.ts\";\nimport type { Environment, Log } from \"../log.ts\";\nimport { helperPath, type LaunchPipe, realPath } from \"../platform/index.ts\";\nimport {\n artifactEnvironment,\n openProcessManager,\n type ProcessManager,\n type ReapedChild,\n} from \"../processes/index.ts\";\nimport { ProtocolServer, sessionMethods } from \"../protocol-server/index.ts\";\nimport {\n artifactMethods,\n canonicalRef,\n createPublisher,\n instanceChecks,\n type Publisher,\n versionDamage,\n} from \"../publish/index.ts\";\nimport { openRegistry } from \"../registry/index.ts\";\nimport { openSecrets, secretMethods } from \"../secrets/index.ts\";\nimport { hasLoginService, type IdleWatch, watchIdle } from \"../service/index.ts\";\nimport { createShares, type Shares, shareCacheDir } from \"../share/index.ts\";\nimport {\n collectVerifyCaches,\n createRunnerClient,\n createVerifier,\n locateRunner,\n type RunnerClient,\n recoverVerify,\n type SandboxOptions,\n type Verifier,\n} from \"../verify/index.ts\";\nimport {\n createWorkerPool,\n localLauncher,\n locateWorker,\n socketLauncher,\n type WorkerLauncher,\n type WorkerVersion,\n workerLimits,\n} from \"../workers/index.ts\";\n\n/** Options for {@link startInstance}. */\nexport interface StartInstanceOptions {\n /** `host`: serve `stdio` and live as long as it; `daemon`: serve the socket until stopped. */\n readonly mode: \"host\" | \"daemon\";\n /** `--home`. */\n readonly home?: string | undefined;\n /** The environment: `MOSTRA_HOME`, `MOSTRA_RUNTIME_DIR`, XDG variables. Default `process.env`. */\n readonly env?: Environment;\n /** The host's connection, required in `host` mode. */\n readonly stdio?: { readonly input: Readable; readonly output: Writable };\n /** How long a starter waits for a locked home's owner. Default 20 s. */\n readonly waitMs?: number;\n /** How often the socket and the home are checked, in ms (at most 10 s). Default 5 s. */\n readonly checkIntervalMs?: number;\n /** Where warnings and errors are mirrored besides the log, such as stderr. */\n readonly mirror?: (line: string) => void;\n /** `--bind`: the address the gateway listens on; `127.0.0.1` when absent (D99). */\n readonly bind?: string | undefined;\n /** `--url-host`: the host name URLs use; required with a wildcard `--bind` (D99). */\n readonly urlHost?: string | undefined;\n /**\n * `--always-on`: a daemon that never exits for lack of work, as the login service runs it\n * (D62). Without it a daemon exits after 30 idle minutes.\n */\n readonly alwaysOn?: boolean;\n}\n\n/** How a stopped instance ended. */\nexport interface InstanceStop {\n /** Why it stopped. */\n readonly reason: string;\n /** 0 for a requested stop; 3 when the home disappeared; 1 for an unexpected failure. */\n readonly exitCode: number;\n /** The diagnostic, when it stopped because of one. */\n readonly diagnostic?: Diagnostic;\n}\n\n/** A running instance that owns its home. */\nexport interface Instance {\n /** What `mostra/initialize` reports. */\n readonly info: InstanceInfo;\n /** The control socket clients attach to. */\n readonly socketPath: string;\n /** The process manager every child goes through. */\n readonly processes: ProcessManager;\n /** What start-up reaped from an earlier supervisor of this home. */\n readonly reaped: readonly ReapedChild[];\n /** Resolves when the instance has stopped and released its home. */\n readonly stopped: Promise<InstanceStop>;\n /** Stops the instance (D87). Idempotent; resolves with the first stop's outcome. */\n stop(reason: string, exitCode?: number, diagnostic?: Diagnostic): Promise<InstanceStop>;\n}\n\n/** The outcome of {@link startInstance}. */\nexport type StartedInstance =\n | { readonly kind: \"owner\"; readonly instance: Instance }\n | {\n readonly kind: \"attached\";\n /** The instance that owns the home. */\n readonly record: InstanceRecord;\n readonly result: MostraInitializeResult;\n };\n\nlet version: string | undefined;\n/** This runtime's release, from its package.json. */\nexport function runtimeVersion(): string {\n if (version !== undefined) return version;\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n try {\n const manifest = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\")) as {\n name?: string;\n version?: string;\n };\n if (manifest.name === \"@mostra/runtime\" && manifest.version) {\n version = manifest.version;\n return version;\n }\n } catch {\n // Keep looking upwards.\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(\"Couldn't find @mostra/runtime's package.json.\");\n dir = parent;\n }\n}\n\nconst CLIENT: ClientInfo = { name: \"mostra-runtime\", version: \"\" };\n\n/** Every port this instance calls when a client registers it (`capabilities.ports`). */\nexport const SUPPORTED_PORTS: readonly string[] = [\n \"identity\",\n \"submissions\",\n \"drafts\",\n \"trustedControls\",\n \"secrets\",\n \"addressing\",\n];\n\n/** How long a host's `addressing` port has to answer: a page or a minted link waits (D158). */\nconst ADDRESSING_TIMEOUT_MS = 5_000;\n\n/**\n * Starts an instance for a home (RT-06): the platform gate, then the home's lock, migrations,\n * reaping, the socket and `instance.json`. A daemon starter that finds the home owned attaches\n * to the owner instead. Throws an `RpcError` carrying the diagnostic when it can do neither.\n */\nexport async function startInstance(options: StartInstanceOptions): Promise<StartedInstance> {\n const gate = checkPlatform();\n if (gate) throw new RpcError(gate);\n if (options.mode === \"host\" && !options.stdio) throw new Error(\"host mode needs stdio.\");\n // Wrong bind flags fail before the home is touched (D99).\n resolveBind({ bind: options.bind, urlHost: options.urlHost });\n const env = options.env ?? process.env;\n const acquisition = await acquireHome({\n home: resolveHomePath({ home: options.home, env }),\n env,\n mode: options.mode,\n runtimeVersion: runtimeVersion(),\n client: { ...CLIENT, version: runtimeVersion() },\n ...(options.waitMs !== undefined ? { waitMs: options.waitMs } : {}),\n ...(options.mirror ? { mirror: options.mirror } : {}),\n });\n if (acquisition.kind === \"attached\") {\n acquisition.connection.close();\n return { kind: \"attached\", record: acquisition.record, result: acquisition.result };\n }\n try {\n return { kind: \"owner\", instance: await assemble(acquisition.home, options) };\n } catch (error) {\n acquisition.home.release();\n throw error;\n }\n}\n\nfunction sameHome(home: string, path: string): boolean {\n // The client's spelling may differ from the instance's: a link, or on Windows a short (8.3)\n // name or another case (the CLI's `%TEMP%` is often `C:\\Users\\RUNNER~1\\…`, WP-W2). The home is\n // its native real path, and so is the client's once resolved: the file system itself spells\n // both, so they compare exactly. Folding case here would join directories the file system keeps\n // apart: a case-sensitive directory's `Home` and `home`, or a name with the Kelvin sign and one\n // with `k`, which NTFS tells apart and JavaScript's lower case doesn't (Opus review of WP-W2,\n // finding 7).\n try {\n return realPath(path) === home;\n } catch {\n // A path that can't be resolved (it doesn't exist) is compared as written.\n return resolve(path) === home;\n }\n}\n\nasync function assemble(home: OwnedHome, options: StartInstanceOptions): Promise<Instance> {\n const { log } = home;\n const environment = options.env ?? process.env;\n const faults = faultsFrom(environment);\n const { manager, reaped } = await openProcessManager({\n ledger: home.ledger,\n log,\n redactor: home.redactor,\n faults,\n });\n const registry = await openRegistry({ home: home.path, ledger: home.ledger });\n const recovered = await registry.recover();\n if (recovered.versions.length > 0 || recovered.snapshots.length > 0) {\n log.info(\"publish.recovered\", { ...recovered });\n }\n await recoverDependencies({ home: home.path, log });\n // What a stopped instance left of verify: sandboxes, unfinished builds, orphan files (D138 item 1).\n await recoverVerify(home.path, log);\n // And of `mostra dev`: its sessions' mirrors, builds and scratch ledgers (D140 item 12).\n await recoverDev(home.path, log);\n // Building and serving go through the render mode (D19 seam 5): SPA, v1's only one. Made on\n // first use, like the publisher, so a runtime missing its build packages still starts.\n let spa: RenderMode | undefined;\n const renderMode = (): RenderMode => {\n spa ??= createSpaRenderMode({\n processes: manager,\n log,\n env: environment,\n faults,\n // Tests shorten the 180 s build limit to exercise MOSTRA_BUILD_TIMEOUT.\n ...(Number(environment[\"MOSTRA_TEST_BUILD_TIMEOUT_MS\"]) > 0\n ? { timeoutMs: Number(environment[\"MOSTRA_TEST_BUILD_TIMEOUT_MS\"]) }\n : {}),\n });\n return spa;\n };\n // Built on first use: a runtime without its warm set still starts and says what's missing.\n let dependencies: Dependencies | undefined;\n // gc runs alone; publishes, verify runs and installs share the gate (D140 item 14).\n const gate = new Gate();\n const getDependencies = (): Dependencies =>\n (dependencies ??= createDependencies({\n gate,\n home: home.path,\n ledger: home.ledger,\n processes: manager,\n log,\n env: environment,\n warm: locateWarmSet(environment),\n policy: () => readHomeSettings(home.path).dependencies ?? \"auto\",\n faults,\n // Tests shorten the 300 s install limit to exercise MOSTRA_DEP_TIMEOUT.\n ...(Number(environment[\"MOSTRA_TEST_INSTALL_TIMEOUT_MS\"]) > 0\n ? { installTimeoutMs: Number(environment[\"MOSTRA_TEST_INSTALL_TIMEOUT_MS\"]) }\n : {}),\n }));\n // Suites of other features publish without verify's gate; the switch is loud (D138).\n const unverifiedPublish = Boolean(environment[\"MOSTRA_TEST_UNVERIFIED_PUBLISH\"]);\n if (unverifiedPublish) log.warn(\"instance.test_unverified_publish\", {});\n let publisher: Publisher | undefined;\n const getPublisher = (): Publisher => {\n if (publisher) return publisher;\n publisher = createPublisher({\n gate,\n registry,\n ledger: home.ledger,\n dependencies: getDependencies(),\n renderMode: renderMode(),\n runtimeVersion: runtimeVersion(),\n log,\n faults,\n homePolicy: () => readHomeSettings(home.path).submission,\n verifier: getVerifier,\n unverified: unverifiedPublish,\n });\n return publisher;\n };\n // verify (WP-09, D138): the runner child with its warm browser, and the sandbox each run serves\n // its build from. Made on first use, like the publisher.\n const revisions = servedRevisions(environment[\"MOSTRA_TEST_BROWSER_REVISION_NEXT\"], log);\n let runner: RunnerClient | undefined;\n let verifier: Verifier | undefined;\n // What a sandbox needs of the instance: verify's runs and `mostra dev`'s sessions (D138, D140).\n const sandboxOptions = (): SandboxOptions => {\n const workerLocation = locateWorker(environment, runtimeRoot());\n return {\n home: home.path,\n log,\n redactor: home.redactor,\n processes: manager,\n runtimeVersion: runtimeVersion(),\n worker: { entry: workerLocation.entry, nodeArgs: workerLocation.nodeArgs },\n modules: (target) => getDependencies().runtimeModules(target),\n secrets,\n env: artifactEnvironment(environment),\n shellDir: locateShell(environment),\n revisions,\n serverEntry: (dir) => renderMode().serverEntry(dir),\n damage: (dir) => versionDamage(dir),\n };\n };\n const getVerifier = (): Verifier => {\n if (verifier) return verifier;\n const located = locateRunner(environment, runtimeRoot());\n runner = createRunnerClient({\n processes: manager,\n log,\n env: environment,\n entry: located.entry,\n nodeArgs: located.nodeArgs,\n browsers: located.browsers,\n });\n verifier = createVerifier({\n home: home.path,\n ledger: home.ledger,\n registry,\n log,\n redactor: home.redactor,\n runner,\n sandbox: sandboxOptions(),\n // Tests shorten verify's 120 s and its smoke test's 200 interactions.\n limits: {\n ...(Number(environment[\"MOSTRA_TEST_VERIFY_TIMEOUT_MS\"]) > 0\n ? { timeoutMs: Number(environment[\"MOSTRA_TEST_VERIFY_TIMEOUT_MS\"]) }\n : {}),\n ...(Number(environment[\"MOSTRA_TEST_SMOKE_INTERACTIONS\"]) > 0\n ? { smokeInteractions: Number(environment[\"MOSTRA_TEST_SMOKE_INTERACTIONS\"]) }\n : {}),\n },\n // verify clears the artifact's park, for its calls and its live producers (D133).\n clearPark: (artifactId) => {\n pool.clear(artifactId);\n live.unpark(artifactId);\n },\n });\n return verifier;\n };\n // The hosts that always provide a port (`HomeConfig.ports`, D105), by client name.\n const expectedOwners = (port: string): string[] =>\n Object.entries(readHomeSettings(home.path).expectedPorts ?? {})\n .filter(([, ports]) => ports.includes(port))\n .map(([owner]) => owner);\n // The gateway (WP-05): leased ports, capability links and sessions, static versions.\n const clockOffset = testClockOffset(environment[\"MOSTRA_TEST_CLOCK_OFFSET_MS\"], log);\n const addressing = createAddressing({\n ledger: home.ledger,\n log,\n bind: resolveBind({ bind: options.bind, urlHost: options.urlHost }),\n });\n const capabilities = new Capabilities({\n ledger: home.ledger,\n log,\n key: capabilityKey(home.path, log),\n // Tests move the gateway's clock to check link lifetimes (LL-05, HY-03).\n now: () => Date.now() + clockOffset,\n shellOrigin: () => gateway.shellOrigin(),\n // Launch tickets only for links whose shell address the gateway serves now (D158).\n servesShell: (origin) => gateway.servesShell(origin),\n });\n // The interaction core (WP-06): drafts, state, submissions, the outbox, events and waits. Its\n // host connections are the protocol server's, built below.\n const interaction: Interaction = createInteraction({\n ledger: home.ledger,\n log,\n faults,\n hosts: {\n registrants: (port) => server.registrants(port),\n call: (session, method, params, timeoutMs) =>\n server.callSession(session, method, params as JsonRpcParams, timeoutMs),\n notify: (session, method, params) => server.notify(session, method, params as JsonRpcParams),\n drained: (session) => server.drained(session),\n },\n // The hosts that always provide the submissions port (D105).\n expectedHosts: () =>\n Object.entries(readHomeSettings(home.path).expectedPorts ?? {})\n .filter(([, ports]) => ports.includes(\"submissions\"))\n .map(([owner]) => owner),\n artifacts: { resolve: (ref) => registry.get(canonicalRef(ref)).id },\n // Which field IDs each version covers (D109); versions are immutable, so it is read once.\n coverage: (() => {\n const cache = new Map<string, (fieldId: string) => boolean>();\n return (versionId: string) => {\n let matcher = cache.get(versionId);\n if (!matcher) {\n matcher = coverageMatcher(readFieldCoverage(registry.store.versionDir(versionId)));\n if (cache.size >= 512) cache.delete(cache.keys().next().value as string);\n cache.set(versionId, matcher);\n }\n return matcher;\n };\n })(),\n // Tests shorten the 30 s port-call limit to exercise a host that never answers.\n ...(Number(environment[\"MOSTRA_TEST_PORT_TIMEOUT_MS\"]) > 0\n ? { portTimeoutMs: Number(environment[\"MOSTRA_TEST_PORT_TIMEOUT_MS\"]) }\n : {}),\n });\n // Server code (WP-08): secrets, the worker pool, action runs and live sources. Every secret the\n // home holds is protected from the log and the event log before anything runs.\n const stopRedactingEvents = redactEvents(home.redactor);\n const secrets = openSecrets({\n home: home.path,\n redactor: home.redactor,\n log,\n port: () => {\n const registrant = server.registrants(\"secrets\").at(-1);\n if (!registrant) return undefined;\n return async (request) => {\n const value = await server.callSession(\n registrant.session,\n portSecretsGetMethod.method,\n request as unknown as JsonRpcParams,\n PORT_TIMEOUT_MS,\n );\n return typeof value === \"string\" ? value : null;\n };\n },\n });\n // Tests shorten the one-minute lease a page's interest in a run or live source holds.\n const testLease = Number(environment[\"MOSTRA_TEST_INTEREST_LEASE_MS\"]);\n const bus = createEphemeralBus(testLease > 0 ? { leaseMs: testLease } : {});\n // The local launcher forks workers from this home's versions; tests prove the seam with a worker\n // host started on its own, reached over a socket (D124).\n const workerSocket = environment[\"MOSTRA_TEST_WORKER_HOST\"];\n const located = locateWorker(environment, runtimeRoot());\n const launcher: WorkerLauncher = workerSocket\n ? socketLauncher(workerSocket)\n : localLauncher({\n processes: manager,\n home: home.path,\n workerEntry: located.entry,\n nodeArgs: located.nodeArgs,\n // A version's packages run from the layout it was built against (D135).\n modules: (target) => getDependencies().runtimeModules(target),\n });\n if (workerSocket) log.warn(\"workers.test_host\", { socket: workerSocket });\n const workerVersions = new Map<string, WorkerVersion | null>();\n /** What a version's worker needs, or `null` for a version without server code (RT-05). */\n const workerVersion = (versionId: string): WorkerVersion | undefined => {\n const cached = workerVersions.get(versionId);\n if (cached !== undefined) return cached ?? undefined;\n const version = registry.version(versionId);\n const dir = registry.store.versionDir(versionId);\n // The render mode says what a worker loads from a version (D19 seam 5).\n const served = version ? renderMode().serverEntry(dir) : undefined;\n const entry = served === undefined ? undefined : relative(dir, served);\n if (!version || entry === undefined) {\n if (version) workerVersions.set(versionId, null);\n return undefined;\n }\n const source = registry.sourceOf(version.artifactId);\n const sourceDir = source ? sourceDirectory(source) : undefined;\n const resolved: WorkerVersion = {\n artifactId: version.artifactId,\n ref: { versionId, outputDigest: version.outputDigest, locator: `home:versions/${versionId}` },\n entry,\n limits: workerLimits(version.manifest),\n functions: readServerFunctions(dir),\n ...(sourceDir ? { sourceDir } : {}),\n };\n workerVersions.set(versionId, resolved);\n return resolved;\n };\n const testIdleMs = Number(environment[\"MOSTRA_TEST_WORKER_IDLE_MS\"]);\n const pool = createWorkerPool({\n launcher,\n log,\n // The artifact's allowlisted environment (D95), never the supervisor's secrets (D124).\n env: artifactEnvironment(environment),\n bridge: {\n request: (worker, method, params, call) =>\n actions.bridge.request(worker, method, params, call),\n log: (worker, line) => actions.bridge.log(worker, line),\n liveValue: (worker, params) => live.produced(worker, params),\n },\n onCrash: (crash) => {\n actions.crashed(crash);\n live.crashed(crash);\n try {\n interaction.workerCrashed(crash);\n } catch (error) {\n log.error(\"workers.crash_record_failed\", { error });\n }\n },\n ...(testIdleMs > 0 ? { idleMsOverride: testIdleMs } : {}),\n // Tests shorten the 1 s first backoff to crash a worker into its park quickly.\n ...(Number(environment[\"MOSTRA_TEST_WORKER_BACKOFF_MS\"]) > 0\n ? { backoffMinMs: Number(environment[\"MOSTRA_TEST_WORKER_BACKOFF_MS\"]) }\n : {}),\n });\n const actions = createActions({\n interaction,\n pool,\n bus,\n secrets,\n redactor: home.redactor,\n log,\n version: workerVersion,\n });\n // Versions are immutable, so each one's live sources are read from its registry once. Which\n // version is each artifact's latest is read from the ledger once, then kept up to date from\n // `version.published`, so a reconcile costs nothing per artifact without live sources, however\n // many the home holds (D132; Opus review 2).\n const liveSourcesOf = new Map<string, ReturnType<typeof readLiveSources>>();\n const sourcesOf = (versionId: string): ReturnType<typeof readLiveSources> => {\n let sources = liveSourcesOf.get(versionId);\n if (!sources) {\n sources = readLiveSources(registry.store.versionDir(versionId));\n liveSourcesOf.set(versionId, sources);\n }\n return sources;\n };\n /** The latest version of each artifact whose latest version defines live sources. */\n const latestWithLive = new Map<string, string>();\n const noteLatest = (artifactId: string, versionId: string): void => {\n if (sourcesOf(versionId).length > 0) latestWithLive.set(artifactId, versionId);\n else latestWithLive.delete(artifactId);\n };\n for (const [artifactId, versionId] of registry.latestVersions())\n noteLatest(artifactId, versionId);\n const latestLive = (artifactId: string): LatestLive | undefined => {\n const versionId = latestWithLive.get(artifactId);\n return versionId ? { versionId, sources: sourcesOf(versionId) } : undefined;\n };\n const live = createLive({\n ledger: home.ledger,\n log,\n bus,\n pool,\n interaction,\n latest: latestLive,\n redactor: home.redactor,\n artifactsWithLive: () => [...latestWithLive.keys()],\n version: workerVersion,\n ...(testLease > 0 ? { reconcileMs: Math.max(100, testLease / 4) } : {}),\n });\n // A new latest version moves its artifact's producers to it (ARCHITECTURE §7).\n const stopWatchingPublishes = interaction.onPublished((artifactId, versionId) => {\n noteLatest(artifactId, versionId);\n live.reconcile();\n });\n // Runs a stopped instance left open end now (D24: never retried).\n actions.recover();\n\n const shellDir = locateShell(environment);\n if (shellDir === undefined)\n log.warn(\"gateway.shell_missing\", { code: \"MOSTRA_ENV_SHELL_MISSING\" });\n const traceRequests = Boolean(environment[\"MOSTRA_TEST_REQUEST_LOG\"]);\n if (traceRequests) log.warn(\"instance.test_request_log\", {});\n // Shares run the local fakes instead of Tailscale and cloudflared (tests and the kit only).\n if (environment[\"MOSTRA_TEST_TUNNELS\"]) log.warn(\"instance.test_tunnels\", {});\n const gateway: Gateway = createGateway({\n ledger: home.ledger,\n log,\n ...(traceRequests ? { traceRequests } : {}),\n addressing,\n capabilities,\n artifacts: {\n get: (ref) => registry.get(canonicalRef(ref)),\n versionDir: (versionId) => registry.store.versionDir(versionId),\n damage: (versionId) => versionDamage(registry.store.versionDir(versionId)),\n },\n shellDir,\n interaction,\n actions,\n live,\n bus,\n parked: (versionId) =>\n pool.status().some((w) => w.versionId === versionId && w.state === \"parked\"),\n revisions,\n controls: (artifact) =>\n controlsPolicy({\n artifact,\n log,\n home: () => readHomeSettings(home.path).submitChannels,\n expected: () => expectedOwners(\"trustedControls\"),\n registrant: () => server.registrants(\"trustedControls\").at(-1),\n call: (session, params) =>\n server.callSession(\n session,\n portTrustedControlsPolicyMethod.method,\n params as unknown as JsonRpcParams,\n CONTROLS_POLICY_TIMEOUT_MS,\n ),\n }),\n // Who a browser is, for links without a viewer (D143 item 2).\n identity: (input) =>\n resolveIdentity({\n ...input,\n log,\n // A host that is connected but serves no identity port (it stopped serving one, and its\n // record says it still does) isn't away: the home's default holds (Opus review of\n // WP-12, finding 7).\n expected: () => {\n const connected = server.connectedClients();\n return expectedOwners(\"identity\").filter((owner) => !connected.has(owner));\n },\n registrant: () => server.registrants(\"identity\").at(-1),\n call: (session, params) =>\n server.callSession(\n session,\n portIdentityResolveMethod.method,\n params as JsonRpcParams,\n IDENTITY_TIMEOUT_MS,\n ),\n }),\n // A host's external addresses for an artifact's links and frame (HO-10, D158 item 6).\n externalBase: {\n registered: () => server.registrants(\"addressing\").length > 0,\n ask: async (input) => {\n const registrant = server.registrants(\"addressing\").at(-1);\n if (!registrant) return { kind: \"away\" };\n try {\n const answer = await server.callSession(\n registrant.session,\n portAddressingExternalBaseMethod.method,\n input as unknown as JsonRpcParams,\n ADDRESSING_TIMEOUT_MS,\n );\n const parsed = portAddressingExternalBaseMethod.result.safeParse(answer);\n if (!parsed.success) {\n log.warn(\"gateway.addressing_invalid\", {\n owner: registrant.owner,\n artifactId: input.artifactId,\n });\n return { kind: \"failed\" };\n }\n return parsed.data === null\n ? { kind: \"none\" }\n : { kind: \"base\", base: parsed.data, owner: registrant.owner };\n } catch (error) {\n log.warn(\"gateway.addressing_failed\", {\n owner: registrant.owner,\n artifactId: input.artifactId,\n error: (error as Error).message,\n });\n return { kind: \"failed\" };\n }\n },\n },\n activated: (event) => {\n // Best effort and never retried, like draft mirrors (D105, D108): the change is durable.\n for (const registrant of server.registrants(\"trustedControls\")) {\n const params: PortTrustedControlsActivatedParams = {\n artifactId: event.artifactId,\n control: event.control,\n viewer: interaction.viewer(event.viewerId),\n viewId: event.viewId,\n detail: event.detail,\n };\n server\n .callSession(\n registrant.session,\n portTrustedControlsActivatedMethod.method,\n params as unknown as JsonRpcParams,\n CONTROLS_POLICY_TIMEOUT_MS,\n )\n .catch((error: unknown) =>\n log.warn(\"gateway.activated_failed\", {\n owner: registrant.owner,\n error: (error as Error).message,\n }),\n );\n }\n },\n });\n // Shares (WP-13, D158): tunnels to the gateway's faces, each with a link of its own.\n const shares: Shares = createShares({\n ledger: home.ledger,\n log,\n gateway,\n capabilities,\n interaction,\n artifacts: { get: (ref) => registry.get(canonicalRef(ref)) },\n processes: manager,\n environment,\n toolEnvironment: artifactEnvironment(environment),\n cacheDir: shareCacheDir(home.path),\n now: () => Date.now() + clockOffset,\n ...(environment[\"MOSTRA_TEST_SHARE_PROBE_MS\"] !== undefined\n ? { probeMs: Number(environment[\"MOSTRA_TEST_SHARE_PROBE_MS\"]) }\n : {}),\n ...(environment[\"MOSTRA_TEST_SHARE_SWEEP_MS\"] !== undefined\n ? { sweepMs: Number(environment[\"MOSTRA_TEST_SHARE_SWEEP_MS\"]) }\n : {}),\n });\n let gatewayStarted = false;\n let idle: IdleWatch | undefined;\n const info: InstanceInfo = {\n version: runtimeVersion(),\n home: home.path,\n platform: platformName(),\n pid: process.pid,\n mode: options.mode,\n };\n\n let stopping: Promise<InstanceStop> | undefined;\n let markStopped: (stop: InstanceStop) => void = () => {};\n const stopped = new Promise<InstanceStop>((done) => {\n markStopped = done;\n });\n\n // `mostra dev`'s sessions (D140 item 12), each owned by the connection that started it.\n const dev: Dev = createDev({\n home: home.path,\n log,\n registry,\n renderMode,\n dependencies: getDependencies,\n gate,\n sandbox: sandboxOptions,\n bindAddress: addressing.bindAddress,\n faults,\n notify: (session, method, params) =>\n server.notify(session, method, params as unknown as JsonRpcParams),\n });\n const server: ProtocolServer = new ProtocolServer({\n log,\n describe: () => info,\n servesHome: (path) => sameHome(home.path, path),\n // A host's settings persist in the home's config.json for every later client (D95, D102,\n // D105).\n configureHome: (config, client) => {\n const current = readHomeSettings(home.path);\n const expectedPorts = { ...(current.expectedPorts ?? {}) };\n if (config.ports !== undefined) {\n if (config.ports.length === 0) delete expectedPorts[client.name];\n else expectedPorts[client.name] = [...new Set(config.ports)].sort();\n }\n const change = {\n ...(config.dependencies !== undefined ? { dependencies: config.dependencies } : {}),\n ...(config.submission !== undefined ? { submission: config.submission } : {}),\n ...(config.ports !== undefined ? { expectedPorts } : {}),\n ...(config.submitChannels !== undefined\n ? { submitChannels: [...new Set(config.submitChannels)].sort() }\n : {}),\n };\n if (Object.keys(change).length === 0) return;\n writeHomeSettings(home.path, change);\n log.info(\"home.settings_written\", {\n client: client.name,\n ...(config.dependencies !== undefined ? { dependencies: config.dependencies } : {}),\n ...(config.submission !== undefined ? { submission: config.submission } : {}),\n ...(config.ports !== undefined ? { ports: config.ports } : {}),\n ...(config.submitChannels !== undefined ? { submitChannels: config.submitChannels } : {}),\n });\n },\n // A host's home never sends the standalone CLI's telemetry (D140 item 4).\n markHostConfigured: (client) => {\n if (markHostConfigured(home.path, client.name))\n log.info(\"home.host_configured\", { client: client.name });\n },\n // The ports this instance calls (D143 item 1); `addressing` arrives with WP-13, `reviews` and\n // `capture` with WP-20, `pty` with WP-23.\n supportedPorts: SUPPORTED_PORTS,\n notifications: [EVENTS_NOTIFY, ARTIFACT_PROGRESS, DEV_NOTIFY],\n onInitialized: (session) => interaction.connected(session),\n onClosed: (session) => interaction.disconnected(session),\n redact: (text) => home.redactor.redact(text),\n handlers: [\n ...artifactMethods({\n registry,\n publisher: getPublisher,\n link: (artifactId) => gateway.defaultLink(artifactId),\n // Any publish clears the artifact's park, a reused version too (FAILURE_MODEL §2): its\n // calls and its live producers both start again.\n published: (artifactId) => {\n pool.clear(artifactId);\n live.unpark(artifactId);\n },\n notify: (session, method, params) => {\n server.notify(session, method, params as JsonRpcParams);\n },\n dependenciesAdded: (artifact) => dev.dependenciesChanged(artifact),\n }),\n ...dev.methods(),\n ...gateway.methods(),\n ...shares.methods(),\n ...interaction.methods(),\n ...secretMethods(secrets, (ref) => registry.get(canonicalRef(ref)).id),\n ...gcMethods(\n createGc({\n ledger: home.ledger,\n registry,\n log,\n gate,\n dependencies: getDependencies,\n // Verify's caches outlive the process that wrote them: gc reads them from the home\n // whether or not verify ran since this instance started (GPT review finding 7).\n caches: (dryRun) =>\n verifier ? verifier.collect(dryRun) : collectVerifyCaches(home.path, { dryRun }),\n now: () => Date.now() + clockOffset,\n locksInUse: () => dev.locks(),\n faults,\n }),\n ),\n ...liveMethods(live, (ref) => registry.get(canonicalRef(ref)).id),\n ...sessionMethods({\n describe: () => info,\n startedAt: home.startedAt,\n socketPath: () => server.socketPath ?? home.socketPath,\n connections: () => server.connections,\n processes: () => manager.list(),\n gateway: () =>\n gatewayStarted\n ? {\n bind: addressing.bindAddress,\n shell: gateway.shellOrigin(),\n artifacts: [...gateway.artifactOrigins()].map(([artifactId, origin]) => ({\n artifactId,\n origin,\n })),\n faces: [...gateway.faces()],\n }\n : undefined,\n shares: () => shares.active(),\n deliveries: () => interaction.deliveries(),\n workers: () => pool.status(),\n idleExitAt: () => idle?.exitAt(),\n checks: (deep) =>\n instanceChecks({\n deep,\n ledger: home.ledger,\n registry,\n shellDir,\n warm: () => locateWarmSet(environment),\n }),\n shutdown: (reason) => void instance.stop(reason, 0),\n }),\n ],\n });\n\n const instance: Instance = {\n info,\n get socketPath() {\n return server.socketPath ?? home.socketPath;\n },\n processes: manager,\n reaped,\n stopped,\n stop(reason, exitCode = 0, diagnostic) {\n stopping ??= (async () => {\n log.info(\"instance.stopping\", { reason, exitCode, ...(diagnostic ? { diagnostic } : {}) });\n idle?.stop();\n stopWatchingPublishes();\n live.stop();\n interaction.stop();\n // Before any child stops: on Windows the pipe's helper is a child, and it hands clients\n // the answers already sent (the `mostra/shutdown` reply among them) before it exits.\n await server.close();\n await dev.stopAll();\n await shares.close();\n await gateway.close();\n await pool.stopAll();\n await runner?.close();\n bus.close();\n stopRedactingEvents();\n try {\n await manager.stopAll();\n } catch (error) {\n log.error(\"instance.children_stop_failed\", { error });\n }\n home.release();\n const outcome: InstanceStop = diagnostic\n ? { reason, exitCode, diagnostic }\n : { reason, exitCode };\n log.info(\"instance.stopped\", { reason, exitCode });\n markStopped(outcome);\n return outcome;\n })();\n return stopping;\n },\n };\n\n try {\n await gateway.start();\n gatewayStarted = true;\n // On Windows the helper serves the owner-only pipe, as a child like any other (RT-10).\n const launchPipe: LaunchPipe = async (name) => {\n const child = await manager.spawn({\n kind: \"control-pipe\",\n ownerRef: home.path,\n command: helperPath(),\n args: [\"pipe\", name],\n channel: true,\n });\n if (!child.channel) throw new Error(\"The control pipe's helper has no channel.\");\n return { channel: child.channel, exited: child.exited, stop: () => child.stop(2000) };\n };\n await server.listen(home.socketPath, options.checkIntervalMs, {\n launchPipe,\n onMoved: (path) => {\n faults.at(\"endpoint:moved\");\n home.publish(options.mode, path);\n log.warn(\"home.endpoint_moved\", { socket: path });\n },\n });\n // Deliveries pending from before a restart go out again (FAILURE_MODEL §4).\n interaction.start();\n // Producers that `always` run, and those hosts subscribe to, start now (LL-04).\n live.start();\n // Tailnet and Funnel shares come back; what can't continue ends, with its reason (D158).\n void shares.recover().catch((error: unknown) => log.error(\"share.recover_failed\", { error }));\n home.publish(options.mode, server.socketPath ?? home.socketPath);\n // A host-spawned instance marks its home as a host's (D140 item 4).\n if (options.mode === \"host\" && markHostConfigured(home.path, \"mostra-runtime host\"))\n log.info(\"home.host_configured\", { client: \"mostra-runtime host\" });\n } catch (error) {\n // Undo what started before the home is released, so no listener or child outlives it.\n live.stop();\n interaction.stop();\n await server.close();\n await gateway.close();\n await pool.stopAll();\n await manager.stopAll();\n bus.close();\n stopRedactingEvents();\n throw error;\n }\n // A daemon exits after 30 idle minutes unless it was started always-on (D62, RT-08); a\n // host-spawned instance lives as long as its stdio.\n if (options.mode === \"daemon\" && !options.alwaysOn) {\n const testIdle = Number(environment[\"MOSTRA_TEST_IDLE_EXIT_MS\"]);\n idle = watchIdle({\n ...(testIdle > 0 ? { idleMs: testIdle } : {}),\n busy: () => ({\n clients: server.connections,\n views: bus.activeViews(),\n deliveries: interaction.deliveries().reduce((sum, owner) => sum + owner.pending, 0),\n runs: actions.activity(),\n producers: live.activity(),\n subscriptions: interaction.subscriptionCount(),\n devSessions: dev.count(),\n // An active share keeps a daemon from its idle exit (D133, WP-13).\n shares: shares.count(),\n // A home with a login service is always-on, whoever started its daemon (D133).\n loginService: hasLoginService(home.path, environment) ? 1 : 0,\n }),\n onIdle: () => {\n log.info(\"instance.idle_exit\", {});\n void instance.stop(\"idle\", 0);\n },\n });\n }\n home.watch((diagnostic) => {\n log.error(\"instance.home_gone\", { message: diagnostic.message });\n server.refuse(diagnostic);\n void instance.stop(\"home gone\", 3, diagnostic);\n }, options.checkIntervalMs);\n if (options.mode === \"host\" && options.stdio) {\n server.serve(\"stdio\", options.stdio.input, options.stdio.output, () => {\n void instance.stop(\"the host closed stdio\", 0);\n });\n }\n log.info(\"instance.started\", {\n mode: options.mode,\n pid: process.pid,\n socket: server.socketPath ?? home.socketPath,\n shell: gateway.shellOrigin(),\n });\n return instance;\n}\n\n/** The longest test clock offset accepted: ten years. */\nconst MAX_CLOCK_OFFSET_MS = 10 * 365 * 24 * 60 * 60 * 1000;\n\n/**\n * `MOSTRA_TEST_CLOCK_OFFSET_MS`, the forward move of the gateway's clock that tests use to check\n * link lifetimes. Only a whole number of milliseconds from 0 to ten years counts: a negative one\n * would keep expiring links alive and a huge one would break every date. An offset in use is\n * logged, so a forgotten one is visible.\n */\nfunction testClockOffset(value: string | undefined, log: Log): number {\n if (value === undefined || value === \"\") return 0;\n const offset = Number(value);\n if (!Number.isSafeInteger(offset) || offset < 0 || offset > MAX_CLOCK_OFFSET_MS) {\n log.warn(\"instance.test_clock_ignored\", { value });\n return 0;\n }\n if (offset > 0) log.warn(\"instance.test_clock\", { offsetMs: offset });\n return offset;\n}\n\n/**\n * The browser-protocol revisions the gateway serves: every one Mostra shipped, plus, in tests, a\n * newer test-only revision (`MOSTRA_TEST_BROWSER_REVISION_NEXT`), so a version frozen at today's\n * revision is proven against a gateway at the next one (VR-10, D111). A value that isn't a dated\n * revision newer than the newest is ignored and logged.\n */\nfunction servedRevisions(next: string | undefined, log: Log): readonly string[] {\n const shipped: readonly string[] = BROWSER_PROTOCOL_REVISIONS;\n if (next === undefined || next === \"\") return shipped;\n const newest = shipped.at(-1) ?? \"\";\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(next) || next <= newest) {\n log.warn(\"instance.test_revision_ignored\", { next });\n return shipped;\n }\n log.warn(\"instance.test_revision\", { next });\n return [...shipped, next];\n}\n\n/** How long a host's `secrets` port has to answer (FAILURE_MODEL §9). */\nconst PORT_TIMEOUT_MS = 30_000;\n\n/** The directory of an artifact's source: the directory itself, or a single file's directory. */\nfunction sourceDirectory(path: string): string | undefined {\n try {\n return statSync(path).isDirectory() ? path : dirname(path);\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,WAAW;;AAGxB,MAAM,oBAAoB;;AAG1B,MAAM,cACJ;;AAGF,MAAM,oBAAoB;;AAG1B,MAAM,0BAA0B;;AAGhC,MAAM,yBAAyB;;;;;;AAO/B,IAAa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