@agent-surface/cli 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,10 +19,11 @@ A presentation surface only exists once components mount — it is a projection
19
19
  ```tsx
20
20
  // agent-surface.config.tsx
21
21
  import { defineSurface } from "@agent-surface/cli";
22
- import { createApp } from "./src/agent/setup.js"; // already exists
22
+ import { agentManifest, createApp } from "./src/agent/setup.js"; // already exists
23
23
  import { App } from "./src/app/App.js"; // already exists
24
24
 
25
25
  export default defineSurface({
26
+ manifest: agentManifest,
26
27
  mount: ({ user }) => {
27
28
  const app = createApp({ environment: "test", user });
28
29
  return { registry: app.registry, ui: <App app={app} />, app };
@@ -42,13 +43,13 @@ Loading goes through vite-node on your own `vite.config.*`, so your aliases, plu
42
43
  agent-surface init # read the codebase, then scaffold a config
43
44
  agent-surface inspect [scenario] # what an agent can reach, and what it cannot
44
45
  agent-surface snapshot [scenario] # write/refresh the committed baseline
45
- agent-surface check [scenario] # exit non-zero on drift, or on a capability no scenario reaches
46
+ agent-surface check [scenario] # fail drift, gaps, rejections, stale scenarios
46
47
  ```
47
48
 
48
49
  Every command covers all scenarios in the config unless you name one. `inspect` prints each in turn:
49
50
 
50
51
  ```text
51
- 10 authored (upper bound) · 10 call sites across 21 files · domain not analyzed, it comes from the oRPC router
52
+ 11 authored (upper bound) · 10 call sites across 21 files · 1 domain manifest capability
52
53
 
53
54
  scenario admin route /devices
54
55
  9 callable, 2 visible-disabled, 0 hidden
@@ -62,12 +63,12 @@ devices.table.sort action local-state callable idempotent · reve
62
63
  devices.disable procedure destructive disabled confirmation:required · deviceIds bound+locked
63
64
  ⤷ Select at least one device first
64
65
 
65
- 10 authored · 10 reached · 0 unreached · 1 scenario (admin)
66
+ 11 authored · 11 reached · 0 unreached · 1 scenario (admin)
66
67
  ```
67
68
 
68
69
  Every count names what it is relative to — the scenario always, the scope when one is active. A surface is a projection of one mounted context, never "the app".
69
70
 
70
- `--detail` swaps the table for one paragraph per capability; `--explain` and `--schemas` imply it.
71
+ `--detail` shows full capability, origin, and diagnostic detail; `--explain` and `--schemas` imply it.
71
72
 
72
73
  ### Depth
73
74
 
package/dist/bin.js CHANGED
@@ -56,7 +56,7 @@ Options
56
56
  --config <path> path to agent-surface.config.* (default: nearest, searching upward)
57
57
  --baseline-dir where baselines live (default: .agent-surface next to the config)
58
58
  --scope <prefix> restrict to a component-type prefix (repeatable)
59
- --detail one paragraph per capability instead of the table
59
+ --detail full capability, origin, and diagnostic detail
60
60
  --explain name the policies behind every decision (implies --detail)
61
61
  --schemas include input/output JSON Schemas (implies --detail)
62
62
  --tsconfig <path> tsconfig the source read uses (default: nearest to the config)
@@ -131,7 +131,7 @@ async function main(argv = process.argv.slice(2)) {
131
131
  const depth = values.depth;
132
132
  try {
133
133
  if (command === "init") {
134
- const { runInit } = await import("./init-ODFEGU3P.js");
134
+ const { runInit } = await import("./init-LFQ5R3G7.js");
135
135
  return await runInit({
136
136
  cwd: process.cwd(),
137
137
  ...values.tsconfig ? { tsconfig: values.tsconfig } : {},
@@ -158,7 +158,7 @@ async function main(argv = process.argv.slice(2)) {
158
158
  ...values["baseline-dir"] ? { baselineDir: values["baseline-dir"] } : {}
159
159
  };
160
160
  if (command === "inspect") {
161
- const { runInspect } = await import("./inspect-6XKULUH2.js");
161
+ const { runInspect } = await import("./inspect-XMDZBSK2.js");
162
162
  return await runInspect({
163
163
  ...shared,
164
164
  ...values.detail ? { detail: true } : {},
@@ -167,12 +167,13 @@ async function main(argv = process.argv.slice(2)) {
167
167
  });
168
168
  }
169
169
  if (command === "snapshot") {
170
- const { runSnapshot } = await import("./snapshot-YGEDJVTG.js");
170
+ const { runSnapshot } = await import("./snapshot-FLXE5UC6.js");
171
171
  return await runSnapshot(shared);
172
172
  }
173
- const { runCheck } = await import("./check-XU3FYNGJ.js");
173
+ const { runCheck } = await import("./check-POE5VRSE.js");
174
174
  return await runCheck({
175
175
  ...shared,
176
+ ...values.detail ? { detail: true } : {},
176
177
  ...values["allow-unresolved"] ? { allowUnresolved: true } : {}
177
178
  });
178
179
  } catch (error) {
@@ -228,7 +229,14 @@ function exitWhenWedged(code) {
228
229
  if (held.length > 0) {
229
230
  const kinds = [...new Set(held)].sort().join(", ");
230
231
  writeError(
231
- `agent-surface: the output above is complete, but ${held.length} handle(s) are still open (${kinds}) \u2014 something started during the mount is still running, so this command would have waited instead of exiting. Common causes: a polling interval, a websocket, or a data layer whose cache timer outlives the render. Exiting ${code}.`
232
+ [
233
+ "",
234
+ "PROCESS CLEANUP WARN",
235
+ `Open handles ${held.length} (${kinds})`,
236
+ "Impact report complete; exit code unchanged; process exit forced",
237
+ "Likely cause polling, websocket, or a cache timer created during mount",
238
+ `Exit ${code}`
239
+ ].join("\n")
232
240
  );
233
241
  }
234
242
  void flushOutput().then(() => process.exit(code));
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bin.ts","../src/dom.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport { DEPTHS, isDepth } from \"./contract.js\";\nimport { installDom } from \"./dom.js\";\nimport { findConfig } from \"./load.js\";\nimport { writeError, write } from \"./output.js\";\n\nconst USAGE = `agent-surface — the agent surface your app exposes\n\nUsage\n agent-surface init read the codebase, then scaffold a config\n agent-surface inspect [scenario] what an agent can reach, and what it cannot\n agent-surface snapshot [scenario] write/refresh the committed baseline\n agent-surface check [scenario] fail on drift, or on a capability no scenario reaches\n\nEvery command covers all scenarios in the config unless you name one.\n\nDepth\n --depth full read the source AND mount the scenarios, and report the gap (default)\n --depth static read the source only — no Vite, no jsdom, no mount, no scenarios needed\n --depth runtime mount only — skip the TypeScript program on a repo wide enough to feel it\n\nOptions\n --config <path> path to agent-surface.config.* (default: nearest, searching upward)\n --baseline-dir where baselines live (default: .agent-surface next to the config)\n --scope <prefix> restrict to a component-type prefix (repeatable)\n --detail one paragraph per capability instead of the table\n --explain name the policies behind every decision (implies --detail)\n --schemas include input/output JSON Schemas (implies --detail)\n --tsconfig <path> tsconfig the source read uses (default: nearest to the config)\n --allow-unresolved check: do not fail on a call site that could not be read\n --yes init: write without asking\n --json emit data instead of a rendered view\n --plain force plain text (implied when piped, or under CI / NO_COLOR)\n -h, --help show this\n -v, --version print the version\n\nExit codes are the contract: 0 clean, 1 a finding, 2 the command could not run.\n`;\n\nconst COMMANDS = [\"init\", \"inspect\", \"snapshot\", \"check\"];\n\n/** Commands that were cut, and where their answer went (0.11.0). */\nconst RETIRED: Record<string, string> = {\n capabilities: \"agent-surface inspect --depth static\",\n coverage: \"agent-surface inspect (or `check`, which now fails on the gap)\",\n};\n\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<number> {\n let parsed;\n try {\n parsed = parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n config: { type: \"string\" },\n \"baseline-dir\": { type: \"string\" },\n scope: { type: \"string\", multiple: true },\n depth: { type: \"string\", default: \"full\" },\n detail: { type: \"boolean\", default: false },\n explain: { type: \"boolean\", default: false },\n schemas: { type: \"boolean\", default: false },\n tsconfig: { type: \"string\" },\n \"allow-unresolved\": { type: \"boolean\", default: false },\n yes: { type: \"boolean\", default: false },\n json: { type: \"boolean\", default: false },\n plain: { type: \"boolean\", default: false },\n help: { type: \"boolean\", short: \"h\", default: false },\n version: { type: \"boolean\", short: \"v\", default: false },\n },\n });\n } catch (error) {\n writeError(error instanceof Error ? error.message : String(error));\n writeError(USAGE);\n return 2;\n }\n\n const { values, positionals } = parsed;\n if (values.help) {\n write(USAGE);\n return 0;\n }\n if (values.version) {\n write(await readVersion());\n return 0;\n }\n\n const [command, scenario] = positionals;\n if (!command) {\n write(USAGE);\n return 2;\n }\n if (!COMMANDS.includes(command)) {\n const moved = RETIRED[command];\n writeError(\n moved\n ? `\"${command}\" was removed in 0.11 — its answer is now \\`${moved}\\`. ` +\n \"The static catalog and the live projection are one command, so the gap between \" +\n \"them is reported rather than left for whoever remembers to look.\"\n : `unknown command \"${command}\"`,\n );\n if (!moved) writeError(USAGE);\n return 2;\n }\n\n if (!isDepth(values.depth)) {\n writeError(`--depth must be one of ${DEPTHS.join(\", \")} — got \"${values.depth}\"`);\n return 2;\n }\n const depth = values.depth;\n\n try {\n if (command === \"init\") {\n // Nothing to find and nothing to mount: `init` is the command that runs\n // before a config exists.\n const { runInit } = await import(\"./commands/init.js\");\n return await runInit({\n cwd: process.cwd(),\n ...(values.tsconfig ? { tsconfig: values.tsconfig } : {}),\n ...(values.yes ? { yes: true } : {}),\n ...(values.plain ? { plain: true } : {}),\n });\n }\n\n const configPath = values.config ?? findConfig();\n if (!configPath) {\n writeError(\n \"no agent-surface.config.* found (searched upward from the working directory).\\n\" +\n \"Run `agent-surface init`, or see https://agent-surface-docs.vercel.app/20-cli\",\n );\n return 2;\n }\n\n // A presentation surface needs a DOM to mount into, and react-dom reads\n // these globals at import time — so this must happen before any app module\n // loads. It stays installed for the life of the process, on purpose\n // (see dom.ts).\n //\n // `--depth static` is the exception, and deliberately so: it reads the\n // TypeScript program and mounts nothing, so it must not pay for — or be\n // able to be affected by — a DOM it never renders into.\n if (depth !== \"static\") installDom();\n\n const shared = {\n configPath,\n depth,\n ...(scenario ? { scenario } : {}),\n ...(values.scope ? { scope: values.scope } : {}),\n ...(values.tsconfig ? { tsconfig: values.tsconfig } : {}),\n ...(values.json ? { json: true } : {}),\n ...(values.plain ? { plain: true } : {}),\n ...(values[\"baseline-dir\"] ? { baselineDir: values[\"baseline-dir\"] } : {}),\n };\n\n if (command === \"inspect\") {\n const { runInspect } = await import(\"./commands/inspect.js\");\n return await runInspect({\n ...shared,\n ...(values.detail ? { detail: true } : {}),\n ...(values.explain ? { explain: true } : {}),\n ...(values.schemas ? { schemas: true } : {}),\n });\n }\n if (command === \"snapshot\") {\n const { runSnapshot } = await import(\"./commands/snapshot.js\");\n return await runSnapshot(shared);\n }\n const { runCheck } = await import(\"./commands/check.js\");\n return await runCheck({\n ...shared,\n ...(values[\"allow-unresolved\"] ? { allowUnresolved: true } : {}),\n });\n } catch (error) {\n writeError(error instanceof Error ? error.message : String(error));\n if (error instanceof Error && error.stack && process.env[\"AGENT_SURFACE_DEBUG\"]) {\n writeError(error.stack);\n }\n // `2` — the command could not run, as opposed to running and finding\n // something. CI has to tell those apart: a gate that exits 1 both when the\n // surface changed and when the tool never loaded the app is a gate whose\n // green is the only signal worth anything, and whose red says nothing.\n return 2;\n }\n}\n\nasync function readVersion(): Promise<string> {\n try {\n const { readFileSync } = await import(\"node:fs\");\n const path = fileURLToPath(new URL(\"../package.json\", import.meta.url));\n return (JSON.parse(readFileSync(path, \"utf8\")) as { version: string }).version;\n } catch {\n return \"unknown\";\n }\n}\n\n/**\n * Self-execute only as a binary; importing this module (tests) must not run it.\n * `argv[1]` is compared through `realpathSync` because package managers install\n * the bin as a symlink — comparing the raw path silently never matches, and the\n * CLI exits 0 having done nothing.\n */\nfunction invokedAsBinary(): boolean {\n const entry = process.argv[1];\n if (!entry) return false;\n try {\n return fileURLToPath(import.meta.url) === realpathSync(entry);\n } catch {\n return false;\n }\n}\n\n/**\n * How long a finished command is allowed to keep running before it is treated\n * as wedged. Costs a hung run one extra second; costs a healthy run nothing,\n * because a healthy run has already exited by then.\n */\nconst GRACE_MS = 1000;\n\n/**\n * What this process's own stdin/stdout/stderr are called, depending on where\n * they were pointed: a terminal, a `|`, or a `>`. None of the three holds the\n * event loop open — a clean run exits naturally through all of them — so when\n * something *else* has wedged the command they are still in the handle table,\n * and naming them would send the reader after the one thing that is not the\n * cause. Their own leak would be the CLI's bug to fix, not the app's to hear\n * about.\n */\nconst OWN_STDIO = new Set([\"TTYWrap\", \"PipeWrap\", \"FileWrap\"]);\n\n/** Resource types still holding the loop once the command is provably wedged. */\nfunction heldHandles(): string[] {\n const active = process.getActiveResourcesInfo?.() ?? [];\n return active.filter((resource) => !OWN_STDIO.has(resource));\n}\n\n/**\n * `process.exit()` discards whatever is still buffered on a pipe, so a\n * redirected run could lose its last lines — and redirected runs are the ones\n * that matter (`--json`, CI logs). Drain both streams first, but never wait\n * indefinitely: a reader that has stopped consuming must not turn a forced exit\n * back into the hang it exists to prevent.\n */\nasync function flushOutput(): Promise<void> {\n const drained = Promise.all(\n [process.stdout, process.stderr].map(\n (stream) =>\n new Promise<void>((resolve) => {\n if (stream.writableLength === 0) resolve();\n else stream.write(\"\", () => resolve());\n }),\n ),\n );\n const deadline = new Promise<void>((resolve) => {\n setTimeout(resolve, 2000).unref();\n });\n await Promise.race([drained, deadline]);\n}\n\n/**\n * Ends the process, and says why it had to be ended when that is the case.\n *\n * The mount is an arbitrary React tree, not code written for a one-shot\n * process: a polling interval, a websocket, an animation loop or a data layer's\n * cache timer all keep Node's event loop alive long after the surface has been\n * rendered. Setting `process.exitCode` alone means such a command prints its\n * full, correct output and then appears to hang — with a successful exit code\n * already set, and nothing on screen to explain the wait (`AS-CLI-005`).\n *\n * The detector is the timer itself, not a reading of the handle table. An\n * unref'd timer does not hold the loop open, so a command with nothing left to\n * do exits naturally on `process.exitCode` and this never fires. Its firing is\n * therefore the diagnosis — this run *was* about to hang — and whatever it then\n * finds in the handle table is genuinely the cause. Reading the table eagerly\n * instead would blame the app for the CLI's own teardown: vite's dev server is\n * still closing its socket at the moment the last scenario is rendered, so\n * every healthy run would accuse its own app of leaking a `TCPServerWrap`.\n *\n * Naming the handles is the same move the package already makes for\n * capabilities: the invisible thing becomes inspectable. Exiting anyway is what\n * makes the tool usable unattended.\n */\nfunction exitWhenWedged(code: number): void {\n process.exitCode = code;\n setTimeout(() => {\n const held = heldHandles();\n if (held.length > 0) {\n const kinds = [...new Set(held)].sort().join(\", \");\n writeError(\n `agent-surface: the output above is complete, but ${held.length} handle(s) are still ` +\n `open (${kinds}) — something started during the mount is still running, so this ` +\n `command would have waited instead of exiting. Common causes: a polling interval, a ` +\n `websocket, or a data layer whose cache timer outlives the render. Exiting ${code}.`,\n );\n }\n void flushOutput().then(() => process.exit(code));\n }, GRACE_MS).unref();\n}\n\nif (invokedAsBinary()) {\n main().then(\n (code) => exitWhenWedged(code),\n (error: unknown) => {\n writeError(error instanceof Error ? error.message : String(error));\n exitWhenWedged(1);\n },\n );\n}\n","import { JSDOM } from \"jsdom\";\n\n/**\n * A presentation surface only exists once components mount, and mounting needs\n * a DOM. Vitest gets one from its `jsdom` environment; a plain Node process has\n * to install one itself — *before* anything imports `react-dom`, which reads\n * these globals at module scope.\n *\n * Process-wide on purpose, and permanent: the app tree runs inside the\n * vite-node graph, which shares this realm's globals, and there is deliberately\n * no way to take the DOM back down — see the note on teardown below. Returning\n * nothing is the honest signature; an installer that handed back a disposer\n * doing nothing would read, at every call site, as cleanup that happens.\n */\nexport function installDom(url = \"http://localhost/\"): void {\n const globals = globalThis as Record<string, unknown>;\n if (typeof globals[\"document\"] !== \"undefined\") return;\n\n const dom = new JSDOM(\"<!doctype html><html><body></body></html>\", {\n url,\n pretendToBeVisual: true,\n });\n const { window } = dom;\n\n // Everything jsdom's window defines that this realm does not already have.\n // Skipping existing keys matters: Node's own `fetch`, `URL` and timers are\n // more capable than jsdom's shims, and clobbering them breaks app code.\n for (const key of Object.getOwnPropertyNames(window)) {\n if (key.startsWith(\"_\")) continue;\n if (key in globals) continue;\n const descriptor = Object.getOwnPropertyDescriptor(window, key);\n if (!descriptor) continue;\n Object.defineProperty(globals, key, descriptor);\n }\n\n for (const key of [\"window\", \"document\", \"navigator\"] as const) {\n if (!(key in globals)) {\n Object.defineProperty(globals, key, { value: window[key], configurable: true });\n }\n }\n}\n\n/**\n * There is deliberately no teardown, and the DOM is deliberately process-wide.\n *\n * `react-dom` captures `window`/`document` when it is first imported. Removing\n * the globals — or worse, calling `window.close()` — leaves that captured\n * reference pointing at a dead realm, so the *next* mount in the same process\n * fails in a way that looks nothing like its cause. A CLI invocation ends by\n * exiting (see `exitWhenWedged` in `bin.ts`), so there is nothing to reclaim; only\n * in-process callers (the test suite) run more than one command, and those are\n *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AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/bin.ts","../src/dom.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport { DEPTHS, isDepth } from \"./contract.js\";\nimport { installDom } from \"./dom.js\";\nimport { findConfig } from \"./load.js\";\nimport { writeError, write } from \"./output.js\";\n\nconst USAGE = `agent-surface — the agent surface your app exposes\n\nUsage\n agent-surface init read the codebase, then scaffold a config\n agent-surface inspect [scenario] what an agent can reach, and what it cannot\n agent-surface snapshot [scenario] write/refresh the committed baseline\n agent-surface check [scenario] fail on drift, or on a capability no scenario reaches\n\nEvery command covers all scenarios in the config unless you name one.\n\nDepth\n --depth full read the source AND mount the scenarios, and report the gap (default)\n --depth static read the source only — no Vite, no jsdom, no mount, no scenarios needed\n --depth runtime mount only — skip the TypeScript program on a repo wide enough to feel it\n\nOptions\n --config <path> path to agent-surface.config.* (default: nearest, searching upward)\n --baseline-dir where baselines live (default: .agent-surface next to the config)\n --scope <prefix> restrict to a component-type prefix (repeatable)\n --detail full capability, origin, and diagnostic detail\n --explain name the policies behind every decision (implies --detail)\n --schemas include input/output JSON Schemas (implies --detail)\n --tsconfig <path> tsconfig the source read uses (default: nearest to the config)\n --allow-unresolved check: do not fail on a call site that could not be read\n --yes init: write without asking\n --json emit data instead of a rendered view\n --plain force plain text (implied when piped, or under CI / NO_COLOR)\n -h, --help show this\n -v, --version print the version\n\nExit codes are the contract: 0 clean, 1 a finding, 2 the command could not run.\n`;\n\nconst COMMANDS = [\"init\", \"inspect\", \"snapshot\", \"check\"];\n\n/** Commands that were cut, and where their answer went (0.11.0). */\nconst RETIRED: Record<string, string> = {\n capabilities: \"agent-surface inspect --depth static\",\n coverage: \"agent-surface inspect (or `check`, which now fails on the gap)\",\n};\n\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<number> {\n let parsed;\n try {\n parsed = parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n config: { type: \"string\" },\n \"baseline-dir\": { type: \"string\" },\n scope: { type: \"string\", multiple: true },\n depth: { type: \"string\", default: \"full\" },\n detail: { type: \"boolean\", default: false },\n explain: { type: \"boolean\", default: false },\n schemas: { type: \"boolean\", default: false },\n tsconfig: { type: \"string\" },\n \"allow-unresolved\": { type: \"boolean\", default: false },\n yes: { type: \"boolean\", default: false },\n json: { type: \"boolean\", default: false },\n plain: { type: \"boolean\", default: false },\n help: { type: \"boolean\", short: \"h\", default: false },\n version: { type: \"boolean\", short: \"v\", default: false },\n },\n });\n } catch (error) {\n writeError(error instanceof Error ? error.message : String(error));\n writeError(USAGE);\n return 2;\n }\n\n const { values, positionals } = parsed;\n if (values.help) {\n write(USAGE);\n return 0;\n }\n if (values.version) {\n write(await readVersion());\n return 0;\n }\n\n const [command, scenario] = positionals;\n if (!command) {\n write(USAGE);\n return 2;\n }\n if (!COMMANDS.includes(command)) {\n const moved = RETIRED[command];\n writeError(\n moved\n ? `\"${command}\" was removed in 0.11 — its answer is now \\`${moved}\\`. ` +\n \"The static catalog and the live projection are one command, so the gap between \" +\n \"them is reported rather than left for whoever remembers to look.\"\n : `unknown command \"${command}\"`,\n );\n if (!moved) writeError(USAGE);\n return 2;\n }\n\n if (!isDepth(values.depth)) {\n writeError(`--depth must be one of ${DEPTHS.join(\", \")} — got \"${values.depth}\"`);\n return 2;\n }\n const depth = values.depth;\n\n try {\n if (command === \"init\") {\n // Nothing to find and nothing to mount: `init` is the command that runs\n // before a config exists.\n const { runInit } = await import(\"./commands/init.js\");\n return await runInit({\n cwd: process.cwd(),\n ...(values.tsconfig ? { tsconfig: values.tsconfig } : {}),\n ...(values.yes ? { yes: true } : {}),\n ...(values.plain ? { plain: true } : {}),\n });\n }\n\n const configPath = values.config ?? findConfig();\n if (!configPath) {\n writeError(\n \"no agent-surface.config.* found (searched upward from the working directory).\\n\" +\n \"Run `agent-surface init`, or see https://agent-surface-docs.vercel.app/20-cli\",\n );\n return 2;\n }\n\n // A presentation surface needs a DOM to mount into, and react-dom reads\n // these globals at import time — so this must happen before any app module\n // loads. It stays installed for the life of the process, on purpose\n // (see dom.ts).\n //\n // `--depth static` is the exception, and deliberately so: it reads the\n // TypeScript program and mounts nothing, so it must not pay for — or be\n // able to be affected by — a DOM it never renders into.\n if (depth !== \"static\") installDom();\n\n const shared = {\n configPath,\n depth,\n ...(scenario ? { scenario } : {}),\n ...(values.scope ? { scope: values.scope } : {}),\n ...(values.tsconfig ? { tsconfig: values.tsconfig } : {}),\n ...(values.json ? { json: true } : {}),\n ...(values.plain ? { plain: true } : {}),\n ...(values[\"baseline-dir\"] ? { baselineDir: values[\"baseline-dir\"] } : {}),\n };\n\n if (command === \"inspect\") {\n const { runInspect } = await import(\"./commands/inspect.js\");\n return await runInspect({\n ...shared,\n ...(values.detail ? { detail: true } : {}),\n ...(values.explain ? { explain: true } : {}),\n ...(values.schemas ? { schemas: true } : {}),\n });\n }\n if (command === \"snapshot\") {\n const { runSnapshot } = await import(\"./commands/snapshot.js\");\n return await runSnapshot(shared);\n }\n const { runCheck } = await import(\"./commands/check.js\");\n return await runCheck({\n ...shared,\n ...(values.detail ? { detail: true } : {}),\n ...(values[\"allow-unresolved\"] ? { allowUnresolved: true } : {}),\n });\n } catch (error) {\n writeError(error instanceof Error ? error.message : String(error));\n if (error instanceof Error && error.stack && process.env[\"AGENT_SURFACE_DEBUG\"]) {\n writeError(error.stack);\n }\n // `2` — the command could not run, as opposed to running and finding\n // something. CI has to tell those apart: a gate that exits 1 both when the\n // surface changed and when the tool never loaded the app is a gate whose\n // green is the only signal worth anything, and whose red says nothing.\n return 2;\n }\n}\n\nasync function readVersion(): Promise<string> {\n try {\n const { readFileSync } = await import(\"node:fs\");\n const path = fileURLToPath(new URL(\"../package.json\", import.meta.url));\n return (JSON.parse(readFileSync(path, \"utf8\")) as { version: string }).version;\n } catch {\n return \"unknown\";\n }\n}\n\n/**\n * Self-execute only as a binary; importing this module (tests) must not run it.\n * `argv[1]` is compared through `realpathSync` because package managers install\n * the bin as a symlink — comparing the raw path silently never matches, and the\n * CLI exits 0 having done nothing.\n */\nfunction invokedAsBinary(): boolean {\n const entry = process.argv[1];\n if (!entry) return false;\n try {\n return fileURLToPath(import.meta.url) === realpathSync(entry);\n } catch {\n return false;\n }\n}\n\n/**\n * How long a finished command is allowed to keep running before it is treated\n * as wedged. Costs a hung run one extra second; costs a healthy run nothing,\n * because a healthy run has already exited by then.\n */\nconst GRACE_MS = 1000;\n\n/**\n * What this process's own stdin/stdout/stderr are called, depending on where\n * they were pointed: a terminal, a `|`, or a `>`. None of the three holds the\n * event loop open — a clean run exits naturally through all of them — so when\n * something *else* has wedged the command they are still in the handle table,\n * and naming them would send the reader after the one thing that is not the\n * cause. Their own leak would be the CLI's bug to fix, not the app's to hear\n * about.\n */\nconst OWN_STDIO = new Set([\"TTYWrap\", \"PipeWrap\", \"FileWrap\"]);\n\n/** Resource types still holding the loop once the command is provably wedged. */\nfunction heldHandles(): string[] {\n const active = process.getActiveResourcesInfo?.() ?? [];\n return active.filter((resource) => !OWN_STDIO.has(resource));\n}\n\n/**\n * `process.exit()` discards whatever is still buffered on a pipe, so a\n * redirected run could lose its last lines — and redirected runs are the ones\n * that matter (`--json`, CI logs). Drain both streams first, but never wait\n * indefinitely: a reader that has stopped consuming must not turn a forced exit\n * back into the hang it exists to prevent.\n */\nasync function flushOutput(): Promise<void> {\n const drained = Promise.all(\n [process.stdout, process.stderr].map(\n (stream) =>\n new Promise<void>((resolve) => {\n if (stream.writableLength === 0) resolve();\n else stream.write(\"\", () => resolve());\n }),\n ),\n );\n const deadline = new Promise<void>((resolve) => {\n setTimeout(resolve, 2000).unref();\n });\n await Promise.race([drained, deadline]);\n}\n\n/**\n * Ends the process, and says why it had to be ended when that is the case.\n *\n * The mount is an arbitrary React tree, not code written for a one-shot\n * process: a polling interval, a websocket, an animation loop or a data layer's\n * cache timer all keep Node's event loop alive long after the surface has been\n * rendered. Setting `process.exitCode` alone means such a command prints its\n * full, correct output and then appears to hang — with a successful exit code\n * already set, and nothing on screen to explain the wait (`AS-CLI-005`).\n *\n * The detector is the timer itself, not a reading of the handle table. An\n * unref'd timer does not hold the loop open, so a command with nothing left to\n * do exits naturally on `process.exitCode` and this never fires. Its firing is\n * therefore the diagnosis — this run *was* about to hang — and whatever it then\n * finds in the handle table is genuinely the cause. Reading the table eagerly\n * instead would blame the app for the CLI's own teardown: vite's dev server is\n * still closing its socket at the moment the last scenario is rendered, so\n * every healthy run would accuse its own app of leaking a `TCPServerWrap`.\n *\n * Naming the handles is the same move the package already makes for\n * capabilities: the invisible thing becomes inspectable. Exiting anyway is what\n * makes the tool usable unattended.\n */\nfunction exitWhenWedged(code: number): void {\n process.exitCode = code;\n setTimeout(() => {\n const held = heldHandles();\n if (held.length > 0) {\n const kinds = [...new Set(held)].sort().join(\", \");\n writeError(\n [\n \"\",\n \"PROCESS CLEANUP WARN\",\n `Open handles ${held.length} (${kinds})`,\n \"Impact report complete; exit code unchanged; process exit forced\",\n \"Likely cause polling, websocket, or a cache timer created during mount\",\n `Exit ${code}`,\n ].join(\"\\n\"),\n );\n }\n void flushOutput().then(() => process.exit(code));\n }, GRACE_MS).unref();\n}\n\nif (invokedAsBinary()) {\n main().then(\n (code) => exitWhenWedged(code),\n (error: unknown) => {\n writeError(error instanceof Error ? error.message : String(error));\n exitWhenWedged(1);\n },\n );\n}\n","import { JSDOM } from \"jsdom\";\n\n/**\n * A presentation surface only exists once components mount, and mounting needs\n * a DOM. Vitest gets one from its `jsdom` environment; a plain Node process has\n * to install one itself — *before* anything imports `react-dom`, which reads\n * these globals at module scope.\n *\n * Process-wide on purpose, and permanent: the app tree runs inside the\n * vite-node graph, which shares this realm's globals, and there is deliberately\n * no way to take the DOM back down — see the note on teardown below. Returning\n * nothing is the honest signature; an installer that handed back a disposer\n * doing nothing would read, at every call site, as cleanup that happens.\n */\nexport function installDom(url = \"http://localhost/\"): void {\n const globals = globalThis as Record<string, unknown>;\n if (typeof globals[\"document\"] !== \"undefined\") return;\n\n const dom = new JSDOM(\"<!doctype html><html><body></body></html>\", {\n url,\n pretendToBeVisual: true,\n });\n const { window } = dom;\n\n // Everything jsdom's window defines that this realm does not already have.\n // Skipping existing keys matters: Node's own `fetch`, `URL` and timers are\n // more capable than jsdom's shims, and clobbering them breaks app code.\n for (const key of Object.getOwnPropertyNames(window)) {\n if (key.startsWith(\"_\")) continue;\n if (key in globals) continue;\n const descriptor = Object.getOwnPropertyDescriptor(window, key);\n if (!descriptor) continue;\n Object.defineProperty(globals, key, descriptor);\n }\n\n for (const key of [\"window\", \"document\", \"navigator\"] as const) {\n if (!(key in globals)) {\n Object.defineProperty(globals, key, { value: window[key], configurable: true });\n }\n }\n}\n\n/**\n * There is deliberately no teardown, and the DOM is deliberately process-wide.\n *\n * `react-dom` captures `window`/`document` when it is first imported. Removing\n * the globals — or worse, calling `window.close()` — leaves that captured\n * reference pointing at a dead realm, so the *next* mount in the same process\n * fails in a way that looks nothing like its cause. A CLI invocation ends by\n * exiting (see `exitWhenWedged` in `bin.ts`), so there is nothing to reclaim; only\n * in-process callers (the test suite) run more than one command, and those are\n * exactly the ones this protects.\n */\n"],"mappings":";;;;;;;;;;AACA,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;;;ACH1B,SAAS,aAAa;AAcf,SAAS,WAAW,MAAM,qBAA2B;AAC1D,QAAM,UAAU;AAChB,MAAI,OAAO,QAAQ,UAAU,MAAM,YAAa;AAEhD,QAAM,MAAM,IAAI,MAAM,6CAA6C;AAAA,IACjE;AAAA,IACA,mBAAmB;AAAA,EACrB,CAAC;AACD,QAAM,EAAE,OAAO,IAAI;AAKnB,aAAW,OAAO,OAAO,oBAAoB,MAAM,GAAG;AACpD,QAAI,IAAI,WAAW,GAAG,EAAG;AACzB,QAAI,OAAO,QAAS;AACpB,UAAM,aAAa,OAAO,yBAAyB,QAAQ,GAAG;AAC9D,QAAI,CAAC,WAAY;AACjB,WAA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,CAAC;AAAA,IACL;AAAA,EACF;AACA,QAAM,WAAW,IAAI,QAAc,CAAC,YAAY;AAC9C,eAAW,SAAS,GAAI,EAAE,MAAM;AAAA,EAClC,CAAC;AACD,QAAM,QAAQ,KAAK,CAAC,SAAS,QAAQ,CAAC;AACxC;AAyBA,SAAS,eAAe,MAAoB;AAC1C,UAAQ,WAAW;AACnB,aAAW,MAAM;AACf,UAAM,OAAO,YAAY;AACzB,QAAI,KAAK,SAAS,GAAG;AACnB,YAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,EAAE,KAAK,EAAE,KAAK,IAAI;AACjD;AAAA,QACE;AAAA,UACE;AAAA,UACA;AAAA,UACA,iBAAiB,KAAK,MAAM,KAAK,KAAK;AAAA,UACtC;AAAA,UACA;AAAA,UACA,iBAAiB,IAAI;AAAA,QACvB,EAAE,KAAK,IAAI;AAAA,MACb;AAAA,IACF;AACA,SAAK,YAAY,EAAE,KAAK,MAAM,QAAQ,KAAK,IAAI,CAAC;AAAA,EAClD,GAAG,QAAQ,EAAE,MAAM;AACrB;AAEA,IAAI,gBAAgB,GAAG;AACrB,OAAK,EAAE;AAAA,IACL,CAAC,SAAS,eAAe,IAAI;AAAA,IAC7B,CAAC,UAAmB;AAClB,iBAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACjE,qBAAe,CAAC;AAAA,IAClB;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,183 @@
1
+ import {
2
+ coverageReport,
3
+ renderCheckOverviewPlain,
4
+ renderCoveragePlain,
5
+ renderDriftPlain,
6
+ renderFailuresPlain,
7
+ renderNoVerdictPlain,
8
+ scenarioBaseline
9
+ } from "./chunk-J2NN3J5N.js";
10
+ import "./chunk-DYDSJM7R.js";
11
+ import {
12
+ ALLOWLIST_FILE,
13
+ SCENARIO_MANIFEST_FILE,
14
+ UNREAD_ALLOWLIST_FILE,
15
+ annotate,
16
+ baselinePath,
17
+ coverageExitCode,
18
+ diff,
19
+ joinCoverage,
20
+ mountScenarios,
21
+ readBaseline,
22
+ readInventory,
23
+ readScenarioManifest
24
+ } from "./chunk-Q5WOLWEW.js";
25
+ import {
26
+ UsageError,
27
+ write,
28
+ writeError
29
+ } from "./chunk-QIVOZAWX.js";
30
+
31
+ // src/commands/check.ts
32
+ import { existsSync, readdirSync } from "fs";
33
+ import { relative } from "path";
34
+ async function runCheck(options) {
35
+ if (options.depth === "static") {
36
+ throw new UsageError(
37
+ "check --depth static has nothing to compare \u2014 a baseline is a projection, and at this depth nothing is mounted. Use --depth runtime for drift alone, or full for both."
38
+ );
39
+ }
40
+ const analysis = {
41
+ configPath: options.configPath,
42
+ depth: options.depth,
43
+ ...options.scenario ? { scenario: options.scenario } : {},
44
+ ...options.scope ? { scope: options.scope } : {},
45
+ ...options.tsconfig ? { tsconfig: options.tsconfig } : {},
46
+ ...options.baselineDir ? { baselineDir: options.baselineDir } : {}
47
+ };
48
+ const inventory = readInventory(analysis);
49
+ const runtime = await mountScenarios(analysis);
50
+ if (!runtime) throw new UsageError("check needs a mount, and this depth performs none");
51
+ const drifted = [];
52
+ for (const result of runtime.results) {
53
+ const path = baselinePath(runtime.baselineDir, result.scenario);
54
+ const expected = readBaseline(path);
55
+ if (expected === void 0) {
56
+ drifted.push({ scenario: result.scenario, missingBaseline: true, entries: [] });
57
+ continue;
58
+ }
59
+ const actual = scenarioBaseline(result);
60
+ const entries = annotate(diff(expected, actual), actual, expected);
61
+ if (entries.length > 0) drifted.push({ scenario: result.scenario, entries });
62
+ }
63
+ const committedScenarios = readScenarioManifest(runtime.baselineDir);
64
+ const declared = [...runtime.declaredScenarios].sort();
65
+ const scenarioManifestMismatch = committedScenarios === void 0 || JSON.stringify(committedScenarios) !== JSON.stringify(declared);
66
+ const reserved = /* @__PURE__ */ new Set([SCENARIO_MANIFEST_FILE, ALLOWLIST_FILE, UNREAD_ALLOWLIST_FILE]);
67
+ const staleBaselineFiles = (existsSync(runtime.baselineDir) ? readdirSync(runtime.baselineDir, { withFileTypes: true }) : []).filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !reserved.has(entry.name)).map((entry) => entry.name.slice(0, -5)).filter((scenario) => !runtime.declaredScenarios.includes(scenario)).sort();
68
+ const rejected = runtime.results.filter((result) => result.rejections.length > 0).map((result) => ({ scenario: result.scenario, rejections: result.rejections }));
69
+ const coverage = joinCoverage(inventory, runtime, analysis);
70
+ const coverageFailed = coverage !== void 0 && coverageExitCode(coverage, { allowUnresolved: options.allowUnresolved === true }) !== 0;
71
+ const couldNotRun = runtime.failures.length > 0;
72
+ const ok = drifted.length === 0 && !coverageFailed && !couldNotRun && rejected.length === 0 && !scenarioManifestMismatch && staleBaselineFiles.length === 0;
73
+ if (options.json) {
74
+ write(
75
+ JSON.stringify(
76
+ {
77
+ ok,
78
+ drifted,
79
+ failures: runtime.failures,
80
+ rejected,
81
+ scenarioManifest: {
82
+ expected: declared,
83
+ committed: committedScenarios ?? null,
84
+ staleBaselines: staleBaselineFiles
85
+ },
86
+ coverage: coverageReport(coverage)
87
+ },
88
+ null,
89
+ 2
90
+ )
91
+ );
92
+ return couldNotRun ? 2 : ok ? 0 : 1;
93
+ }
94
+ const overview = renderCheckOverviewPlain({
95
+ status: couldNotRun ? "ERROR" : ok ? "PASS" : "FAIL",
96
+ ...coverage ? { coverage } : {},
97
+ unresolvedAllowed: options.allowUnresolved === true,
98
+ baselineCurrent: Math.max(0, runtime.results.length - drifted.length),
99
+ baselineTotal: runtime.scenarios.length,
100
+ scenarioManifestOk: !scenarioManifestMismatch && staleBaselineFiles.length === 0,
101
+ rejected: rejected.reduce((sum, entry) => sum + entry.rejections.length, 0),
102
+ mountFailures: runtime.failures.length,
103
+ scenarios: runtime.scenarios
104
+ });
105
+ if (ok) write(overview);
106
+ else writeError(overview);
107
+ if (coverage) {
108
+ const rendered = renderCoveragePlain(coverage, {
109
+ compact: true,
110
+ ...options.detail ? { detail: true } : {}
111
+ });
112
+ if (rendered) {
113
+ if (coverageFailed) writeError(`
114
+ ${rendered}`);
115
+ else write(`
116
+ ${rendered}`);
117
+ }
118
+ }
119
+ const missing = drifted.filter((entry) => entry.missingBaseline);
120
+ const changed = drifted.filter((entry) => !entry.missingBaseline);
121
+ if (rejected.length > 0) {
122
+ writeError(
123
+ [
124
+ `${coverage ? "\n" : ""}REJECTED REGISTRATIONS \u2014 the runtime refused authored surface (${rejected.reduce((sum, entry) => sum + entry.rejections.length, 0)})`,
125
+ ...rejected.flatMap(
126
+ (entry) => entry.rejections.map(
127
+ (rejection) => ` ${entry.scenario}: ${rejection.componentType}@${rejection.instanceId} (${rejection.reason})`
128
+ )
129
+ )
130
+ ].join("\n")
131
+ );
132
+ }
133
+ if (scenarioManifestMismatch || staleBaselineFiles.length > 0) {
134
+ const committed = committedScenarios?.join(", ") ?? "missing";
135
+ writeError(
136
+ [
137
+ `${coverage || rejected.length > 0 ? "\n" : ""}SCENARIO DRIFT \u2014 committed baselines do not match config`,
138
+ ` config: ${declared.join(", ")}`,
139
+ ` manifest: ${committed}`,
140
+ ...staleBaselineFiles.length > 0 ? [` stale baselines: ${staleBaselineFiles.join(", ")}`] : [],
141
+ " run `agent-surface snapshot` and commit the manifest"
142
+ ].join("\n")
143
+ );
144
+ }
145
+ if (missing.length > 0) {
146
+ writeError(
147
+ [
148
+ `${coverage ? "\n" : ""}NO BASELINE \u2014 nothing to compare against, which is not the same as a match (${missing.length})`,
149
+ ...missing.map(
150
+ (entry) => ` ${entry.scenario}: ${relative(
151
+ process.cwd(),
152
+ baselinePath(runtime.baselineDir, entry.scenario)
153
+ )} does not exist \u2014 run \`agent-surface snapshot\` and commit it`
154
+ )
155
+ ].join("\n")
156
+ );
157
+ }
158
+ if (changed.length > 0) {
159
+ writeError(
160
+ [
161
+ `${coverage || missing.length > 0 ? "\n" : ""}DRIFT \u2014 the surface changed against its baseline (${changed.length})`,
162
+ ...changed.map((entry) => renderDriftPlain(entry.scenario, entry.entries)),
163
+ "",
164
+ `surface drift in ${changed.length} scenario${changed.length === 1 ? "" : "s"} \u2014 review the change, then \`agent-surface snapshot\` to accept it`
165
+ ].join("\n")
166
+ );
167
+ }
168
+ if (couldNotRun) {
169
+ writeError(`
170
+ ${renderFailuresPlain(runtime.failures)}`);
171
+ if (inventory) writeError(`
172
+ ${renderNoVerdictPlain(runtime.failures)}`);
173
+ return 2;
174
+ }
175
+ if (ok) {
176
+ return 0;
177
+ }
178
+ return 1;
179
+ }
180
+ export {
181
+ runCheck
182
+ };
183
+ //# sourceMappingURL=check-POE5VRSE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/check.ts"],"sourcesContent":["import { existsSync, readdirSync } from \"node:fs\";\nimport { relative } from \"node:path\";\nimport {\n UsageError,\n joinCoverage,\n mountScenarios,\n readInventory,\n type AnalysisOptions,\n type Depth,\n} from \"../analysis.js\";\nimport {\n annotate,\n baselinePath,\n diff,\n readBaseline,\n readScenarioManifest,\n SCENARIO_MANIFEST_FILE,\n type DiffEntry,\n} from \"../baseline.js\";\nimport { ALLOWLIST_FILE, coverageExitCode, UNREAD_ALLOWLIST_FILE } from \"../coverage.js\";\nimport {\n renderCoveragePlain,\n renderCheckOverviewPlain,\n renderDriftPlain,\n renderFailuresPlain,\n renderNoVerdictPlain,\n} from \"../render/plain.js\";\nimport { write, writeError } from \"../output.js\";\nimport { coverageReport, scenarioBaseline } from \"../report.js\";\n\nexport interface CheckOptions {\n configPath: string;\n depth: Depth;\n scenario?: string;\n scope?: string[];\n tsconfig?: string;\n baselineDir?: string;\n allowUnresolved?: boolean;\n json?: boolean;\n plain?: boolean;\n detail?: boolean;\n}\n\ninterface ScenarioDrift {\n scenario: string;\n missingBaseline?: boolean;\n entries: DiffEntry[];\n}\n\ninterface RejectedScenario {\n scenario: string;\n rejections: Array<{ componentType: string; instanceId: string; reason: string }>;\n}\n\n/**\n * The gate. The only command in this package that fails on a finding, which is\n * why every finding has to reach it.\n *\n * It used to fail on exactly one class — the projection drifting from its\n * baseline — and print a line telling you that capabilities no scenario mounts\n * were a different command's question. A gate that names the check it is not\n * performing is a gate with a hole in it, and in CI the hole was silent: a\n * whole unreached route sat behind a green tick.\n *\n * So it now fails on every incomplete or changed report:\n *\n * - **drift** — the surface changed against its committed baseline;\n * - **a missing baseline** — nothing to compare, which is not the same as a match;\n * - **an unreached capability** — authored, and no scenario mounts it;\n * - **an unread call site** — the catalog is incomplete, so the third check\n * above is computed over a denominator that is only a floor;\n * - **a rejected registration** — authored surface was refused;\n * - **scenario drift** — config, manifest and baseline files disagree.\n *\n * `.agent-surface/coverage-allow.json` ratchets the third; `--allow-unresolved`\n * accepts the fourth. Both are deliberate, committed decisions rather than\n * flags that quietly widen the gate.\n *\n * Output is always plain, with no rendering framework in its path at all: this\n * is a report that gets pasted into a pull request and read out of a CI log,\n * and neither of those is a terminal.\n */\nexport async function runCheck(options: CheckOptions): Promise<number> {\n if (options.depth === \"static\") {\n throw new UsageError(\n \"check --depth static has nothing to compare — a baseline is a projection, and \" +\n \"at this depth nothing is mounted. Use --depth runtime for drift alone, or full for both.\",\n );\n }\n\n const analysis: AnalysisOptions = {\n configPath: options.configPath,\n depth: options.depth,\n ...(options.scenario ? { scenario: options.scenario } : {}),\n ...(options.scope ? { scope: options.scope } : {}),\n ...(options.tsconfig ? { tsconfig: options.tsconfig } : {}),\n ...(options.baselineDir ? { baselineDir: options.baselineDir } : {}),\n };\n\n const inventory = readInventory(analysis);\n // No streaming here, unlike `inspect`. A report is read top-down and has to\n // lead with its findings, which means every finding has to exist first.\n const runtime = await mountScenarios(analysis);\n if (!runtime) throw new UsageError(\"check needs a mount, and this depth performs none\");\n\n const drifted: ScenarioDrift[] = [];\n for (const result of runtime.results) {\n const path = baselinePath(runtime.baselineDir, result.scenario);\n const expected = readBaseline(path);\n if (expected === undefined) {\n drifted.push({ scenario: result.scenario, missingBaseline: true, entries: [] });\n continue;\n }\n const actual = scenarioBaseline(result);\n const entries = annotate(diff(expected, actual), actual, expected);\n if (entries.length > 0) drifted.push({ scenario: result.scenario, entries });\n }\n\n const committedScenarios = readScenarioManifest(runtime.baselineDir);\n const declared = [...runtime.declaredScenarios].sort();\n const scenarioManifestMismatch =\n committedScenarios === undefined ||\n JSON.stringify(committedScenarios) !== JSON.stringify(declared);\n const reserved = new Set([SCENARIO_MANIFEST_FILE, ALLOWLIST_FILE, UNREAD_ALLOWLIST_FILE]);\n const staleBaselineFiles = (existsSync(runtime.baselineDir)\n ? readdirSync(runtime.baselineDir, { withFileTypes: true })\n : [])\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\") && !reserved.has(entry.name))\n .map((entry) => entry.name.slice(0, -5))\n .filter((scenario) => !runtime.declaredScenarios.includes(scenario))\n .sort();\n\n const rejected: RejectedScenario[] = runtime.results\n .filter((result) => result.rejections.length > 0)\n .map((result) => ({ scenario: result.scenario, rejections: result.rejections }));\n\n const coverage = joinCoverage(inventory, runtime, analysis);\n const coverageFailed =\n coverage !== undefined &&\n coverageExitCode(coverage, { allowUnresolved: options.allowUnresolved === true }) !== 0;\n const couldNotRun = runtime.failures.length > 0;\n const ok =\n drifted.length === 0 &&\n !coverageFailed &&\n !couldNotRun &&\n rejected.length === 0 &&\n !scenarioManifestMismatch &&\n staleBaselineFiles.length === 0;\n\n if (options.json) {\n write(\n JSON.stringify(\n {\n ok,\n drifted,\n failures: runtime.failures,\n rejected,\n scenarioManifest: {\n expected: declared,\n committed: committedScenarios ?? null,\n staleBaselines: staleBaselineFiles,\n },\n coverage: coverageReport(coverage),\n },\n null,\n 2,\n ),\n );\n return couldNotRun ? 2 : ok ? 0 : 1;\n }\n\n const overview = renderCheckOverviewPlain({\n status: couldNotRun ? \"ERROR\" : ok ? \"PASS\" : \"FAIL\",\n ...(coverage ? { coverage } : {}),\n unresolvedAllowed: options.allowUnresolved === true,\n baselineCurrent: Math.max(0, runtime.results.length - drifted.length),\n baselineTotal: runtime.scenarios.length,\n scenarioManifestOk: !scenarioManifestMismatch && staleBaselineFiles.length === 0,\n rejected: rejected.reduce((sum, entry) => sum + entry.rejections.length, 0),\n mountFailures: runtime.failures.length,\n scenarios: runtime.scenarios,\n });\n if (ok) write(overview);\n else writeError(overview);\n\n // The gap leads, because it is the finding this command could not previously\n // make at all. Drift follows, because it is the one it always could.\n if (coverage) {\n const rendered = renderCoveragePlain(coverage, {\n compact: true,\n ...(options.detail ? { detail: true } : {}),\n });\n if (rendered) {\n if (coverageFailed) writeError(`\\n${rendered}`);\n else write(`\\n${rendered}`);\n }\n }\n\n // \"No baseline\" is not drift, and filing it under a heading that says the\n // surface changed would be a claim about a comparison that never happened.\n const missing = drifted.filter((entry) => entry.missingBaseline);\n const changed = drifted.filter((entry) => !entry.missingBaseline);\n\n if (rejected.length > 0) {\n writeError(\n [\n `${coverage ? \"\\n\" : \"\"}REJECTED REGISTRATIONS — the runtime refused authored surface (${rejected.reduce((sum, entry) => sum + entry.rejections.length, 0)})`,\n ...rejected.flatMap((entry) =>\n entry.rejections.map(\n (rejection) =>\n ` ${entry.scenario}: ${rejection.componentType}@${rejection.instanceId} (${rejection.reason})`,\n ),\n ),\n ].join(\"\\n\"),\n );\n }\n\n if (scenarioManifestMismatch || staleBaselineFiles.length > 0) {\n const committed = committedScenarios?.join(\", \") ?? \"missing\";\n writeError(\n [\n `${coverage || rejected.length > 0 ? \"\\n\" : \"\"}SCENARIO DRIFT — committed baselines do not match config`,\n ` config: ${declared.join(\", \")}`,\n ` manifest: ${committed}`,\n ...(staleBaselineFiles.length > 0\n ? [` stale baselines: ${staleBaselineFiles.join(\", \")}`]\n : []),\n \" run `agent-surface snapshot` and commit the manifest\",\n ].join(\"\\n\"),\n );\n }\n\n if (missing.length > 0) {\n writeError(\n [\n `${coverage ? \"\\n\" : \"\"}NO BASELINE — nothing to compare against, which is not the same as a match (${missing.length})`,\n ...missing.map(\n (entry) =>\n ` ${entry.scenario}: ${relative(\n process.cwd(),\n baselinePath(runtime.baselineDir, entry.scenario),\n )} does not exist — run \\`agent-surface snapshot\\` and commit it`,\n ),\n ].join(\"\\n\"),\n );\n }\n\n if (changed.length > 0) {\n writeError(\n [\n `${coverage || missing.length > 0 ? \"\\n\" : \"\"}DRIFT — the surface changed against its baseline (${changed.length})`,\n ...changed.map((entry) => renderDriftPlain(entry.scenario, entry.entries)),\n \"\",\n `surface drift in ${changed.length} scenario${\n changed.length === 1 ? \"\" : \"s\"\n } — review the change, then \\`agent-surface snapshot\\` to accept it`,\n ].join(\"\\n\"),\n );\n }\n\n if (couldNotRun) {\n writeError(`\\n${renderFailuresPlain(runtime.failures)}`);\n if (inventory) writeError(`\\n${renderNoVerdictPlain(runtime.failures)}`);\n return 2;\n }\n\n if (ok) {\n return 0;\n }\n return 1;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,mBAAmB;AACxC,SAAS,gBAAgB;AAiFzB,eAAsB,SAAS,SAAwC;AACrE,MAAI,QAAQ,UAAU,UAAU;AAC9B,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AAEA,QAAM,WAA4B;AAAA,IAChC,YAAY,QAAQ;AAAA,IACpB,OAAO,QAAQ;AAAA,IACf,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;AAAA,IACzD,GAAI,QAAQ,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;AAAA,IAChD,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;AAAA,IACzD,GAAI,QAAQ,cAAc,EAAE,aAAa,QAAQ,YAAY,IAAI,CAAC;AAAA,EACpE;AAEA,QAAM,YAAY,cAAc,QAAQ;AAGxC,QAAM,UAAU,MAAM,eAAe,QAAQ;AAC7C,MAAI,CAAC,QAAS,OAAM,IAAI,WAAW,mDAAmD;AAEtF,QAAM,UAA2B,CAAC;AAClC,aAAW,UAAU,QAAQ,SAAS;AACpC,UAAM,OAAO,aAAa,QAAQ,aAAa,OAAO,QAAQ;AAC9D,UAAM,WAAW,aAAa,IAAI;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