@agent-surface/cli 0.10.0 → 0.11.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.
Files changed (40) hide show
  1. package/README.md +64 -23
  2. package/dist/bin.js +63 -41
  3. package/dist/bin.js.map +1 -1
  4. package/dist/check-BYQ34OVQ.js +122 -0
  5. package/dist/check-BYQ34OVQ.js.map +1 -0
  6. package/dist/chunk-DYDSJM7R.js +170 -0
  7. package/dist/chunk-DYDSJM7R.js.map +1 -0
  8. package/dist/{chunk-4AEQKM2X.js → chunk-GXXKZTQB.js} +261 -206
  9. package/dist/chunk-GXXKZTQB.js.map +1 -0
  10. package/dist/{chunk-FYEXHWGG.js → chunk-QIVOZAWX.js} +52 -2
  11. package/dist/chunk-QIVOZAWX.js.map +1 -0
  12. package/dist/chunk-RXX63JSL.js +298 -0
  13. package/dist/chunk-RXX63JSL.js.map +1 -0
  14. package/dist/index.d.ts +15 -1
  15. package/dist/init-LYYVXFEQ.js +141 -0
  16. package/dist/init-LYYVXFEQ.js.map +1 -0
  17. package/dist/{ink-HBPOQTRS.js → ink-P23VKP4H.js} +102 -33
  18. package/dist/ink-P23VKP4H.js.map +1 -0
  19. package/dist/inspect-3CBRKTDM.js +108 -0
  20. package/dist/inspect-3CBRKTDM.js.map +1 -0
  21. package/dist/snapshot-DJ22WCT4.js +59 -0
  22. package/dist/snapshot-DJ22WCT4.js.map +1 -0
  23. package/package.json +4 -4
  24. package/dist/capabilities-OLFYMHCL.js +0 -37
  25. package/dist/capabilities-OLFYMHCL.js.map +0 -1
  26. package/dist/check-IN4XKAND.js +0 -84
  27. package/dist/check-IN4XKAND.js.map +0 -1
  28. package/dist/chunk-4AEQKM2X.js.map +0 -1
  29. package/dist/chunk-A27Y7ALQ.js +0 -51
  30. package/dist/chunk-A27Y7ALQ.js.map +0 -1
  31. package/dist/chunk-FYEXHWGG.js.map +0 -1
  32. package/dist/chunk-ODUIFFPM.js +0 -104
  33. package/dist/chunk-ODUIFFPM.js.map +0 -1
  34. package/dist/coverage-HCHLJTDD.js +0 -133
  35. package/dist/coverage-HCHLJTDD.js.map +0 -1
  36. package/dist/ink-HBPOQTRS.js.map +0 -1
  37. package/dist/inspect-NJNB6CAS.js +0 -213
  38. package/dist/inspect-NJNB6CAS.js.map +0 -1
  39. package/dist/snapshot-JQAB73OV.js +0 -38
  40. package/dist/snapshot-JQAB73OV.js.map +0 -1
@@ -1,14 +1,174 @@
1
1
  import {
2
- formatValue
3
- } from "./chunk-ODUIFFPM.js";
2
+ UsageError,
3
+ createSurfaceRunner
4
+ } from "./chunk-QIVOZAWX.js";
5
+
6
+ // src/baseline.ts
7
+ import { mkdirSync, readFileSync, writeFileSync } from "fs";
8
+ import { dirname, join, resolve } from "path";
9
+ import { serializeSurfaceSnapshot } from "@agent-surface/testing";
10
+ var DEFAULT_BASELINE_DIR = ".agent-surface";
11
+ function baselineDirFor(configPath, configured) {
12
+ return resolve(dirname(configPath), configured ?? DEFAULT_BASELINE_DIR);
13
+ }
14
+ function baselinePath(dir, scenario) {
15
+ return join(dir, `${scenario}.json`);
16
+ }
17
+ function normalize(snapshot) {
18
+ return serializeSurfaceSnapshot(snapshot);
19
+ }
20
+ function readBaseline(path) {
21
+ try {
22
+ return JSON.parse(readFileSync(path, "utf8"));
23
+ } catch {
24
+ return void 0;
25
+ }
26
+ }
27
+ function writeBaseline(path, value) {
28
+ mkdirSync(dirname(path), { recursive: true });
29
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
30
+ `, "utf8");
31
+ }
32
+ var PATH_SEGMENT = /([^.[\]]+)|\[(\d+)\]/g;
33
+ function subjectFor(document, path) {
34
+ let node = document;
35
+ let subject;
36
+ for (const match of path.matchAll(PATH_SEGMENT)) {
37
+ if (typeof node !== "object" || node === null) return subject;
38
+ const record = node;
39
+ const candidate = record["capabilityId"] ?? record["procedureId"];
40
+ if (typeof candidate === "string") subject = candidate;
41
+ const key = match[1] ?? match[2];
42
+ if (key === void 0) return subject;
43
+ node = record[key];
44
+ }
45
+ if (typeof node === "object" && node !== null) {
46
+ const record = node;
47
+ const candidate = record["capabilityId"] ?? record["procedureId"];
48
+ if (typeof candidate === "string") subject = candidate;
49
+ }
50
+ return subject;
51
+ }
52
+ function annotate(entries, after, before) {
53
+ return entries.map((entry) => {
54
+ const subject = subjectFor(after, entry.path) ?? subjectFor(before, entry.path);
55
+ return subject ? { ...entry, subject } : entry;
56
+ });
57
+ }
58
+ function diff(before, after, path = "") {
59
+ if (Object.is(before, after)) return [];
60
+ const bothArrays = Array.isArray(before) && Array.isArray(after);
61
+ const bothObjects = !bothArrays && typeof before === "object" && typeof after === "object" && before !== null && after !== null;
62
+ if (bothArrays) {
63
+ const entries = [];
64
+ const max = Math.max(before.length, after.length);
65
+ for (let i = 0; i < max; i++) {
66
+ const at = `${path}[${i}]`;
67
+ if (i >= before.length) entries.push({ path: at, kind: "added", after: after[i] });
68
+ else if (i >= after.length) entries.push({ path: at, kind: "removed", before: before[i] });
69
+ else entries.push(...diff(before[i], after[i], at));
70
+ }
71
+ return entries;
72
+ }
73
+ if (bothObjects) {
74
+ const entries = [];
75
+ const beforeRecord = before;
76
+ const afterRecord = after;
77
+ const keys = /* @__PURE__ */ new Set([...Object.keys(beforeRecord), ...Object.keys(afterRecord)]);
78
+ for (const key of [...keys].sort()) {
79
+ const at = path ? `${path}.${key}` : key;
80
+ if (!(key in beforeRecord)) {
81
+ entries.push({ path: at, kind: "added", after: afterRecord[key] });
82
+ } else if (!(key in afterRecord)) {
83
+ entries.push({ path: at, kind: "removed", before: beforeRecord[key] });
84
+ } else {
85
+ entries.push(...diff(beforeRecord[key], afterRecord[key], at));
86
+ }
87
+ }
88
+ return entries;
89
+ }
90
+ if (JSON.stringify(before) === JSON.stringify(after)) return [];
91
+ return [{ path: path || "<root>", kind: "changed", before, after }];
92
+ }
93
+ function formatValue(value) {
94
+ if (value === void 0) return "\u2014";
95
+ const text = typeof value === "string" ? value : JSON.stringify(value);
96
+ return text.length > 120 ? `${text.slice(0, 117)}\u2026` : text;
97
+ }
98
+
99
+ // src/coverage.ts
100
+ import { existsSync, readFileSync as readFileSync2 } from "fs";
101
+ import { join as join2 } from "path";
102
+ var ALLOWLIST_FILE = "coverage-allow.json";
103
+ function allowlistPathFor(baselineDir) {
104
+ return join2(baselineDir, ALLOWLIST_FILE);
105
+ }
106
+ function readAllowlist(path) {
107
+ if (!existsSync(path)) return {};
108
+ let parsed;
109
+ try {
110
+ parsed = JSON.parse(readFileSync2(path, "utf8"));
111
+ } catch (error) {
112
+ throw new Error(
113
+ `could not parse ${path}: ${error instanceof Error ? error.message : String(error)}`
114
+ );
115
+ }
116
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
117
+ throw new Error(`${path} must be a JSON object of { "capabilityId": "reason" }`);
118
+ }
119
+ const allowlist = {};
120
+ for (const [id, reason] of Object.entries(parsed)) {
121
+ if (typeof reason !== "string" || reason.trim() === "") {
122
+ throw new Error(`${path}: "${id}" needs a non-empty reason string`);
123
+ }
124
+ allowlist[id] = reason;
125
+ }
126
+ return allowlist;
127
+ }
128
+ function buildCoverageReport(input) {
129
+ const unreached = [];
130
+ const allowed = [];
131
+ for (const id of [...input.authored].sort()) {
132
+ if (input.reachedIds.has(id)) continue;
133
+ if (id in input.allowlist) {
134
+ allowed.push(id);
135
+ continue;
136
+ }
137
+ unreached.push({ capabilityId: id, origin: input.origins.get(id) ?? { file: "?", line: 0 } });
138
+ }
139
+ const staleAllowlist = Object.keys(input.allowlist).filter((id) => input.reachedIds.has(id) || !input.authored.has(id)).sort();
140
+ const unaccounted = [...input.reachedIds].filter((id) => !input.authored.has(id)).sort();
141
+ const domainReached = unaccounted.filter((id) => id.startsWith("domain:"));
142
+ const undeclared = unaccounted.filter((id) => !id.startsWith("domain:"));
143
+ return {
144
+ authored: input.authored.size,
145
+ reached: [...input.authored].filter((id) => input.reachedIds.has(id)).length,
146
+ scenarios: input.scenarios,
147
+ ...input.scope ? { scope: input.scope } : {},
148
+ allowlistOutOfScope: input.allowlistOutOfScope ?? 0,
149
+ unreached,
150
+ undeclared,
151
+ domainReached,
152
+ unresolved: input.unresolved,
153
+ allowed,
154
+ staleAllowlist,
155
+ allowlistPath: input.allowlistPath
156
+ };
157
+ }
158
+ function coverageExitCode(report, options = {}) {
159
+ if (report.unreached.length > 0) return 1;
160
+ if (report.unresolved.length > 0 && !options.allowUnresolved) return 1;
161
+ if (report.staleAllowlist.length > 0) return 1;
162
+ return 0;
163
+ }
4
164
 
5
165
  // src/extract.ts
6
- import { existsSync } from "fs";
7
- import { dirname, isAbsolute, join, relative, resolve } from "path";
166
+ import { existsSync as existsSync2 } from "fs";
167
+ import { dirname as dirname2, isAbsolute, join as join3, relative, resolve as resolve2 } from "path";
8
168
  import ts from "typescript";
9
169
  var UNRESOLVED_ID = "<unresolved>";
10
170
  function findTsconfig(from) {
11
- return ts.findConfigFile(resolve(from), ts.sys.fileExists, "tsconfig.json");
171
+ return ts.findConfigFile(resolve2(from), ts.sys.fileExists, "tsconfig.json");
12
172
  }
13
173
  function readProgramFiles(tsconfigPath) {
14
174
  const read = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
@@ -20,7 +180,7 @@ function readProgramFiles(tsconfigPath) {
20
180
  const parsed = ts.parseJsonConfigFileContent(
21
181
  read.config,
22
182
  ts.sys,
23
- dirname(tsconfigPath)
183
+ dirname2(tsconfigPath)
24
184
  );
25
185
  if (parsed.errors.length > 0 && parsed.fileNames.length === 0) {
26
186
  throw new Error(
@@ -219,9 +379,9 @@ function visitCall(call, emit, source) {
219
379
  );
220
380
  }
221
381
  function extractCapabilities(options) {
222
- const root = resolve(options.root);
223
- const tsconfigPath = options.tsconfig ? isAbsolute(options.tsconfig) ? options.tsconfig : join(root, options.tsconfig) : findTsconfig(root);
224
- if (!tsconfigPath || !existsSync(tsconfigPath)) {
382
+ const root = resolve2(options.root);
383
+ const tsconfigPath = options.tsconfig ? isAbsolute(options.tsconfig) ? options.tsconfig : join3(root, options.tsconfig) : findTsconfig(root);
384
+ if (!tsconfigPath || !existsSync2(tsconfigPath)) {
225
385
  throw new Error(
226
386
  `no tsconfig.json found from ${root} \u2014 \`capabilities\` reads the TypeScript program, so it needs one (pass --tsconfig to point at it)`
227
387
  );
@@ -281,218 +441,113 @@ function unresolved(inventory) {
281
441
  return inventory.capabilities.filter((capability) => capability.resolution === "unresolved");
282
442
  }
283
443
 
284
- // src/render/plain.ts
285
- var MARK = { expose: "+", disable: "~", hide: "-" };
286
- function renderRow(row, lines) {
287
- const tags = row.tags.length > 0 ? ` [${row.tags.join(", ")}]` : "";
288
- lines.push(` ${MARK[row.outcome]} ${row.name}${tags}`);
289
- lines.push(` ${row.description}`);
290
- if (row.reason) lines.push(` reason: ${row.reason}`);
291
- if (row.policies) {
292
- if (row.policies.length === 0) {
293
- lines.push(" policies: none");
294
- } else {
295
- for (const policy of row.policies) {
296
- const vote = policy.discovery ? policy.discovery.decision === "disable" ? `disable \u2014 ${policy.discovery.reason}` : policy.discovery.decision : "no discovery hook";
297
- const phases = policy.phases.length > 0 ? policy.phases.join("/") : "\u2014";
298
- const flags = [
299
- policy.threw ? "THREW" : "",
300
- policy.confirmationEscalation ? "escalates-confirmation" : ""
301
- ].filter(Boolean).join(", ");
302
- lines.push(
303
- ` policy ${policy.name} (${policy.scope}, ${phases}): ${vote}${flags ? ` [${flags}]` : ""}`
304
- );
305
- }
306
- }
307
- if (row.availability && !row.availability.available) {
308
- lines.push(
309
- ` availability: unavailable${row.availability.reason ? ` \u2014 ${row.availability.reason}` : ""}`
444
+ // src/analysis.ts
445
+ import { dirname as dirname3 } from "path";
446
+ import { matchesScope } from "@agent-surface/core/explain";
447
+ function readInventory(options) {
448
+ if (options.depth === "runtime") return void 0;
449
+ return extractCapabilities({
450
+ root: dirname3(options.configPath),
451
+ ...options.tsconfig ? { tsconfig: options.tsconfig } : {}
452
+ });
453
+ }
454
+ async function mountScenarios(options, onEach) {
455
+ if (options.depth === "static") return void 0;
456
+ const runner = await createSurfaceRunner(options.configPath);
457
+ try {
458
+ if (options.scenario && !runner.scenarioNames.includes(options.scenario)) {
459
+ throw new UsageError(
460
+ `unknown scenario "${options.scenario}" \u2014 this config defines ` + runner.scenarioNames.map((name) => `"${name}"`).join(", ")
310
461
  );
311
462
  }
312
- }
313
- if (row.schemas) {
314
- if (row.schemas.input !== void 0) {
315
- lines.push(` input: ${JSON.stringify(row.schemas.input)}`);
316
- }
317
- if (row.schemas.output !== void 0) {
318
- lines.push(` output: ${JSON.stringify(row.schemas.output)}`);
463
+ const scenarios = options.scenario ? [options.scenario] : runner.scenarioNames;
464
+ const results = [];
465
+ const failures = [];
466
+ for (const scenario of scenarios) {
467
+ let result;
468
+ try {
469
+ result = await runner.collect({
470
+ scenario,
471
+ ...options.scope ? { scope: options.scope } : {}
472
+ });
473
+ } catch (error) {
474
+ failures.push({
475
+ scenario,
476
+ message: error instanceof Error ? error.message : String(error)
477
+ });
478
+ continue;
479
+ }
480
+ results.push(result);
481
+ await onEach?.(result);
319
482
  }
483
+ return {
484
+ scenarios,
485
+ results,
486
+ failures,
487
+ baselineDir: baselineDirFor(
488
+ options.configPath,
489
+ options.baselineDir ?? runner.config.baselineDir
490
+ )
491
+ };
492
+ } finally {
493
+ await runner.close();
320
494
  }
321
495
  }
322
- function renderCountsPlain(view) {
323
- return `${view.counts.callable} callable, ${view.counts.disabled} visible-disabled, ${view.counts.hidden} hidden` + (view.rejections.length > 0 ? `, ${view.rejections.length} registration${view.rejections.length === 1 ? "" : "s"} rejected` : "");
496
+ function componentTypeOf(capabilityId) {
497
+ const withoutPlane = capabilityId.replace(/^(view|domain):/, "");
498
+ const dot = withoutPlane.lastIndexOf(".");
499
+ return dot === -1 ? withoutPlane : withoutPlane.slice(0, dot);
324
500
  }
325
- function renderRejections(view, lines) {
326
- if (view.rejections.length === 0) return;
327
- lines.push("");
328
- lines.push(`rejected during mount (${view.rejections.length})`);
329
- for (const rejection of view.rejections) {
330
- const why = rejection.reason === "duplicate" ? "duplicate \u2014 an earlier registration holds this key" : "guard \u2014 onRegister rejected this registration";
331
- lines.push(` ! ${rejection.componentType} (${rejection.instanceId}) ${why}`);
332
- }
333
- }
334
- function renderSurfacePlain(view) {
335
- const lines = [];
336
- lines.push(
337
- `scenario ${view.scenario}${view.route ? ` route ${view.route}` : ""}${view.scope && view.scope.length > 0 ? ` scope ${view.scope.join(" ")}` : ""}`
338
- );
339
- lines.push(renderCountsPlain(view));
340
- renderRejections(view, lines);
341
- const populated = view.groups.filter((group) => group.rows.length > 0);
342
- if (populated.length === 0) {
343
- lines.push("");
344
- if (view.counts.hidden > 0) {
345
- lines.push(
346
- `Nothing is callable here \u2014 all ${view.counts.hidden} registered capabilities were hidden by policy.`
347
- );
348
- if (!view.explained) lines.push("Re-run with --explain to see which policy hid them.");
349
- } else {
350
- lines.push("Nothing is registered for this scenario \u2014 the agent has no surface here.");
351
- if (!view.explained) {
352
- lines.push("Re-run with --explain to see whether a policy hid it.");
353
- }
354
- }
355
- return lines.join("\n");
356
- }
357
- for (const group of populated) {
358
- lines.push("");
359
- lines.push(`${group.heading} (${group.rows.length})`);
360
- for (const row of group.rows) renderRow(row, lines);
361
- }
362
- return lines.join("\n");
363
- }
364
- function renderInventoryPlain(inventory) {
365
- const lines = [];
366
- const resolved = inventory.capabilities.filter((c) => c.resolution !== "unresolved");
367
- const unresolvedEntries = unresolved(inventory);
368
- const ids = authoredIds(inventory);
369
- lines.push(
370
- `${ids.size} authored (upper bound), ${resolved.length} call site${resolved.length === 1 ? "" : "s"} across ${inventory.filesAnalyzed} file${inventory.filesAnalyzed === 1 ? "" : "s"}`
371
- );
372
- lines.push("domain: not analyzed \u2014 domain capabilities come from the oRPC router (OQ-1)");
373
- if (inventory.filesOutsideRoot > 0) {
374
- lines.push(
375
- `${inventory.filesOutsideRoot} program file${inventory.filesOutsideRoot === 1 ? "" : "s"} outside the config's directory were not analyzed`
376
- );
377
- }
378
- const byId = [...resolved].sort((a, b) => a.capabilityId.localeCompare(b.capabilityId));
379
- if (byId.length > 0) {
380
- lines.push("");
381
- for (const capability of byId) {
382
- const mark = capability.resolution === "static" ? " " : "~";
383
- lines.push(` ${mark} ${capability.capabilityId}`);
384
- lines.push(` ${capability.origin.file}:${capability.origin.line} [${capability.kind}]`);
385
- if (capability.description) lines.push(` ${capability.description}`);
386
- if (capability.note) lines.push(` partial: ${capability.note}`);
501
+ function joinCoverage(inventory, runtime, options) {
502
+ if (!inventory || !runtime) return void 0;
503
+ if (runtime.failures.length > 0) return void 0;
504
+ const inScope = (capabilityId) => matchesScope(componentTypeOf(capabilityId), options.scope);
505
+ const origins = /* @__PURE__ */ new Map();
506
+ for (const capability of inventory.capabilities) {
507
+ if (!origins.has(capability.capabilityId)) {
508
+ origins.set(capability.capabilityId, capability.origin);
387
509
  }
388
510
  }
389
- if (unresolvedEntries.length > 0) {
390
- lines.push("");
391
- lines.push(`unresolved (${unresolvedEntries.length})`);
392
- for (const capability of unresolvedEntries) {
393
- lines.push(` ? ${capability.origin.file}:${capability.origin.line}`);
394
- lines.push(` ${capability.note ?? "the extractor could not read this call site"}`);
511
+ const authored = new Set([...authoredIds(inventory)].filter(inScope));
512
+ const reachedIds = /* @__PURE__ */ new Set();
513
+ for (const result of runtime.results) {
514
+ for (const capability of result.explanation.capabilities) {
515
+ reachedIds.add(capability.capabilityId);
395
516
  }
396
- lines.push("");
397
- lines.push(
398
- `${unresolvedEntries.length} call site${unresolvedEntries.length === 1 ? "" : "s"} could not be resolved \u2014 fix them, or re-run with --allow-unresolved to accept the gap`
399
- );
400
517
  }
401
- return lines.join("\n");
402
- }
403
- function renderCoveragePlain(report) {
404
- const lines = [];
405
- lines.push(
406
- `${report.authored} authored (upper bound), ${report.reached} reached across ${report.scenarios.length} scenario${report.scenarios.length === 1 ? "" : "s"} (${report.scenarios.join(", ")})`
518
+ const allowlistPath = allowlistPathFor(runtime.baselineDir);
519
+ const wholeAllowlist = readAllowlist(allowlistPath);
520
+ const allowlist = Object.fromEntries(
521
+ Object.entries(wholeAllowlist).filter(([id]) => inScope(id))
407
522
  );
408
- if (report.unreached.length > 0) {
409
- lines.push("");
410
- lines.push(`unreached (${report.unreached.length})`);
411
- for (const entry of report.unreached) {
412
- lines.push(` ${entry.capabilityId}`);
413
- lines.push(` ${entry.origin.file}:${entry.origin.line} \u2014 no scenario mounts it`);
414
- }
415
- }
416
- if (report.domainReached.length > 0) {
417
- lines.push("");
418
- lines.push(
419
- `domain (not analyzed) (${report.domainReached.length}) \u2014 reached, and outside this inventory by design`
420
- );
421
- for (const id of report.domainReached) lines.push(` ${id}`);
422
- }
423
- if (report.undeclared.length > 0) {
424
- lines.push("");
425
- lines.push(`undeclared (${report.undeclared.length})`);
426
- lines.push(" present at runtime with no static origin \u2014 a dynamic registration, or a gap here");
427
- for (const id of report.undeclared) lines.push(` ${id}`);
428
- }
429
- if (report.unresolved.length > 0) {
430
- lines.push("");
431
- lines.push(`unresolved (${report.unresolved.length})`);
432
- for (const capability of report.unresolved) {
433
- lines.push(` ? ${capability.origin.file}:${capability.origin.line}`);
434
- lines.push(` ${capability.note ?? "the extractor could not read this call site"}`);
435
- }
436
- }
437
- if (report.allowed.length > 0) {
438
- lines.push("");
439
- lines.push(
440
- `${report.allowed.length} unreached capabilit${report.allowed.length === 1 ? "y is" : "ies are"} allowlisted in ${report.allowlistPath}`
441
- );
442
- }
443
- if (report.staleAllowlist.length > 0) {
444
- lines.push("");
445
- lines.push(`stale allowlist entries (${report.staleAllowlist.length})`);
446
- lines.push(" these are reached now \u2014 delete them so the list cannot silently rot");
447
- for (const id of report.staleAllowlist) lines.push(` ${id}`);
448
- }
449
- lines.push("");
450
- const verdicts = [];
451
- if (report.unreached.length > 0) {
452
- verdicts.push(
453
- `surface coverage gap in ${report.unreached.length} capabilit${report.unreached.length === 1 ? "y" : "ies"} \u2014 add a scenario, or delete the component`
454
- );
455
- }
456
- if (report.unresolved.length > 0) {
457
- verdicts.push(
458
- `${report.unresolved.length} call site${report.unresolved.length === 1 ? "" : "s"} could not be read, so this report is incomplete \u2014 fix them, or accept the gap knowingly`
459
- );
460
- }
461
- if (report.staleAllowlist.length > 0) {
462
- verdicts.push(
463
- `${report.staleAllowlist.length} allowlist entr${report.staleAllowlist.length === 1 ? "y is" : "ies are"} stale \u2014 remove them so the list cannot silently rot`
464
- );
465
- }
466
- if (verdicts.length === 0) {
467
- verdicts.push(
468
- report.allowed.length > 0 ? "no new surface coverage gaps \u2014 the allowlist still holds the known ones" : "every authored capability is reached by a scenario"
469
- );
470
- }
471
- lines.push(...verdicts);
472
- return lines.join("\n");
473
- }
474
- function renderDiffPlain(scenario, entries) {
475
- const lines = [`${scenario}: ${entries.length} change${entries.length === 1 ? "" : "s"}`];
476
- for (const entry of entries) {
477
- const where = entry.subject ? `${entry.subject} (${entry.path})` : entry.path;
478
- if (entry.kind === "added") lines.push(` + ${where} ${formatValue(entry.after)}`);
479
- else if (entry.kind === "removed") lines.push(` - ${where} ${formatValue(entry.before)}`);
480
- else {
481
- lines.push(` ~ ${where}`);
482
- lines.push(` before: ${formatValue(entry.before)}`);
483
- lines.push(` after: ${formatValue(entry.after)}`);
484
- }
485
- }
486
- return lines.join("\n");
523
+ return buildCoverageReport({
524
+ authored,
525
+ origins,
526
+ reachedIds,
527
+ scenarios: runtime.scenarios,
528
+ ...options.scope ? { scope: options.scope } : {},
529
+ unresolved: unresolved(inventory),
530
+ allowlist,
531
+ allowlistOutOfScope: Object.keys(wholeAllowlist).length - Object.keys(allowlist).length,
532
+ allowlistPath
533
+ });
487
534
  }
488
535
 
489
536
  export {
537
+ baselinePath,
538
+ normalize,
539
+ readBaseline,
540
+ writeBaseline,
541
+ annotate,
542
+ diff,
543
+ formatValue,
544
+ coverageExitCode,
545
+ findTsconfig,
490
546
  extractCapabilities,
491
547
  authoredIds,
492
548
  unresolved,
493
- renderSurfacePlain,
494
- renderInventoryPlain,
495
- renderCoveragePlain,
496
- renderDiffPlain
549
+ readInventory,
550
+ mountScenarios,
551
+ joinCoverage
497
552
  };
498
- //# sourceMappingURL=chunk-4AEQKM2X.js.map
553
+ //# sourceMappingURL=chunk-GXXKZTQB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/baseline.ts","../src/coverage.ts","../src/extract.ts","../src/analysis.ts"],"sourcesContent":["import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { serializeSurfaceSnapshot } from \"@agent-surface/testing\";\nimport type { AgentSurfaceSnapshot } from \"@agent-surface/core\";\n\nexport const DEFAULT_BASELINE_DIR = \".agent-surface\";\n\nexport function baselineDirFor(configPath: string, configured?: string): string {\n return resolve(dirname(configPath), configured ?? DEFAULT_BASELINE_DIR);\n}\n\nexport function baselinePath(dir: string, scenario: string): string {\n return join(dir, `${scenario}.json`);\n}\n\n/**\n * The committed form. `serializeSurfaceSnapshot` is the same normalizer the\n * Vitest matcher uses: registration ids become stable placeholders and the\n * volatile fields (surfaceId, capturedAt, version) drop out, so a baseline\n * diff is a diff of *what agents can see* and nothing else.\n */\nexport function normalize(snapshot: AgentSurfaceSnapshot): unknown {\n return serializeSurfaceSnapshot(snapshot);\n}\n\nexport function readBaseline(path: string): unknown | undefined {\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n } catch {\n return undefined;\n }\n}\n\nexport function writeBaseline(path: string, value: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n}\n\nexport interface DiffEntry {\n path: string;\n kind: \"added\" | \"removed\" | \"changed\";\n before?: unknown;\n after?: unknown;\n /**\n * The capability the change belongs to. A reviewer needs to know that\n * `view:devices.table.sort` changed — `components[3].actions[1]` is the same\n * fact in a form nobody can act on.\n */\n subject?: string;\n}\n\nconst PATH_SEGMENT = /([^.[\\]]+)|\\[(\\d+)\\]/g;\n\n/** Nearest enclosing capability id for a diff path, if the path sits inside one. */\nfunction subjectFor(document: unknown, path: string): string | undefined {\n let node: unknown = document;\n let subject: string | undefined;\n for (const match of path.matchAll(PATH_SEGMENT)) {\n if (typeof node !== \"object\" || node === null) return subject;\n const record = node as Record<string, unknown>;\n const candidate = record[\"capabilityId\"] ?? record[\"procedureId\"];\n if (typeof candidate === \"string\") subject = candidate;\n const key = match[1] ?? match[2];\n if (key === undefined) return subject;\n node = record[key];\n }\n if (typeof node === \"object\" && node !== null) {\n const record = node as Record<string, unknown>;\n const candidate = record[\"capabilityId\"] ?? record[\"procedureId\"];\n if (typeof candidate === \"string\") subject = candidate;\n }\n return subject;\n}\n\n/** Labels each entry with the capability it belongs to, when there is one. */\nexport function annotate(entries: DiffEntry[], after: unknown, before: unknown): DiffEntry[] {\n return entries.map((entry) => {\n const subject = subjectFor(after, entry.path) ?? subjectFor(before, entry.path);\n return subject ? { ...entry, subject } : entry;\n });\n}\n\n/**\n * Structural diff, deliberately total: every difference is drift, including a\n * changed description. Descriptions are the provider's cached prompt prefix\n * (D28) — a silent edit re-bills every conversation, so it is exactly the kind\n * of change a reviewer should see.\n */\nexport function diff(before: unknown, after: unknown, path = \"\"): DiffEntry[] {\n if (Object.is(before, after)) return [];\n\n const bothArrays = Array.isArray(before) && Array.isArray(after);\n const bothObjects =\n !bothArrays &&\n typeof before === \"object\" &&\n typeof after === \"object\" &&\n before !== null &&\n after !== null;\n\n if (bothArrays) {\n const entries: DiffEntry[] = [];\n const max = Math.max(before.length, after.length);\n for (let i = 0; i < max; i++) {\n const at = `${path}[${i}]`;\n if (i >= before.length) entries.push({ path: at, kind: \"added\", after: after[i] });\n else if (i >= after.length) entries.push({ path: at, kind: \"removed\", before: before[i] });\n else entries.push(...diff(before[i], after[i], at));\n }\n return entries;\n }\n\n if (bothObjects) {\n const entries: DiffEntry[] = [];\n const beforeRecord = before as Record<string, unknown>;\n const afterRecord = after as Record<string, unknown>;\n const keys = new Set([...Object.keys(beforeRecord), ...Object.keys(afterRecord)]);\n for (const key of [...keys].sort()) {\n const at = path ? `${path}.${key}` : key;\n if (!(key in beforeRecord)) {\n entries.push({ path: at, kind: \"added\", after: afterRecord[key] });\n } else if (!(key in afterRecord)) {\n entries.push({ path: at, kind: \"removed\", before: beforeRecord[key] });\n } else {\n entries.push(...diff(beforeRecord[key], afterRecord[key], at));\n }\n }\n return entries;\n }\n\n if (JSON.stringify(before) === JSON.stringify(after)) return [];\n return [{ path: path || \"<root>\", kind: \"changed\", before, after }];\n}\n\nexport function formatValue(value: unknown): string {\n if (value === undefined) return \"—\";\n const text = typeof value === \"string\" ? value : JSON.stringify(value);\n return text.length > 120 ? `${text.slice(0, 117)}…` : text;\n}\n","/**\n * `coverage` — authored minus reached (`AS-COVER-004…005`, D36).\n *\n * The inventory says what the codebase authors; the scenarios say what a mount\n * surfaces. Neither half alone answers \"which authored capability does no\n * scenario reach\", because that is a set difference no command computed.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { AuthoredCapability } from \"./extract.js\";\n\nexport const ALLOWLIST_FILE = \"coverage-allow.json\";\n\n/**\n * A committed list of unreached capabilities a repository has decided not to\n * fix yet, each with a reason. Adoption has to ratchet rather than gate: a\n * codebase turning this on with 200 unreached capabilities cannot fix them in\n * one pull request, and a check that can only be adopted big-bang is a check\n * that never gets adopted.\n */\nexport type CoverageAllowlist = Record<string, string>;\n\nexport function allowlistPathFor(baselineDir: string): string {\n return join(baselineDir, ALLOWLIST_FILE);\n}\n\nexport function readAllowlist(path: string): CoverageAllowlist {\n if (!existsSync(path)) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, \"utf8\"));\n } catch (error) {\n throw new Error(\n `could not parse ${path}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(`${path} must be a JSON object of { \"capabilityId\": \"reason\" }`);\n }\n const allowlist: CoverageAllowlist = {};\n for (const [id, reason] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof reason !== \"string\" || reason.trim() === \"\") {\n throw new Error(`${path}: \"${id}\" needs a non-empty reason string`);\n }\n allowlist[id] = reason;\n }\n return allowlist;\n}\n\nexport interface UnreachedCapability {\n capabilityId: string;\n origin: { file: string; line: number };\n}\n\nexport interface CoverageReport {\n /** Distinct capability ids the inventory resolved, within any active scope. */\n authored: number;\n /** How many of them at least one scenario surfaced. */\n reached: number;\n scenarios: string[];\n /**\n * The scope every number here was computed under (`AS-CLI-007`). A scope\n * filters the catalog *and* the mount, so `10 authored` without it on screen\n * reads as a claim about the whole codebase when it is a claim about one\n * prefix of it.\n */\n scope?: string[];\n /**\n * Allowlist entries outside the active scope, which a scoped run cannot\n * judge: not unreached (nothing looked), not stale (nothing reached them).\n * Counted rather than silently dropped, so a scoped run never reads as a\n * verdict on the whole allowlist.\n */\n allowlistOutOfScope: number;\n /** Authored, surfaced by no scenario, and not allowlisted — the finding. */\n unreached: UnreachedCapability[];\n /**\n * Present at runtime with no static origin: a dynamic registration, or a gap\n * in the extractor. `view:` only — see `domainReached`.\n */\n undeclared: string[];\n /**\n * `domain:` capabilities a scenario surfaced. Held apart from `undeclared`\n * because the inventory never claimed to analyze that plane: filing them as\n * \"no static origin\" would report the design's own stated boundary as a\n * defect, which is the misleading check this whole command rejects.\n */\n domainReached: string[];\n /** Carried forward from the inventory. */\n unresolved: AuthoredCapability[];\n /** Unreached, but listed in the allowlist. */\n allowed: string[];\n /** Listed in the allowlist and reached anyway — the list has rotted. */\n staleAllowlist: string[];\n allowlistPath: string;\n}\n\nexport interface BuildCoverageInput {\n authored: Set<string>;\n /** First origin seen for each authored id, for the report. */\n origins: Map<string, { file: string; line: number }>;\n /**\n * Every capability id any scenario's *explanation* held.\n *\n * The explanation, not the snapshot. A capability a policy hid **was**\n * reached: a scenario mounted it and the policy made a deliberate decision\n * about it. Classifying those as unreached would flood the report with the\n * library's own correct behaviour — in the example app the `anonymous`\n * scenario alone would contribute eleven false gaps.\n */\n reachedIds: Set<string>;\n scenarios: string[];\n scope?: string[];\n unresolved: AuthoredCapability[];\n /**\n * Already filtered to the active scope by the caller, which owns the scope\n * predicate. Entries outside it are counted in `allowlistOutOfScope`.\n */\n allowlist: CoverageAllowlist;\n allowlistOutOfScope?: number;\n allowlistPath: string;\n}\n\nexport function buildCoverageReport(input: BuildCoverageInput): CoverageReport {\n const unreached: UnreachedCapability[] = [];\n const allowed: string[] = [];\n\n for (const id of [...input.authored].sort()) {\n if (input.reachedIds.has(id)) continue;\n if (id in input.allowlist) {\n allowed.push(id);\n continue;\n }\n unreached.push({ capabilityId: id, origin: input.origins.get(id) ?? { file: \"?\", line: 0 } });\n }\n\n // An allowlist entry that is no longer unreached fails the command, so the\n // list shrinks and cannot silently rot — the same idiom as the baselines\n // `check` already commits.\n const staleAllowlist = Object.keys(input.allowlist)\n .filter((id) => input.reachedIds.has(id) || !input.authored.has(id))\n .sort();\n\n const unaccounted = [...input.reachedIds].filter((id) => !input.authored.has(id)).sort();\n const domainReached = unaccounted.filter((id) => id.startsWith(\"domain:\"));\n const undeclared = unaccounted.filter((id) => !id.startsWith(\"domain:\"));\n\n return {\n authored: input.authored.size,\n reached: [...input.authored].filter((id) => input.reachedIds.has(id)).length,\n scenarios: input.scenarios,\n ...(input.scope ? { scope: input.scope } : {}),\n allowlistOutOfScope: input.allowlistOutOfScope ?? 0,\n unreached,\n undeclared,\n domainReached,\n unresolved: input.unresolved,\n allowed,\n staleAllowlist,\n allowlistPath: input.allowlistPath,\n };\n}\n\n/**\n * `0` clean, `1` a gap.\n *\n * `undeclared` deliberately does not fail (OQ-4): a dynamically registered\n * capability is legitimate, and from the outside it is indistinguishable from\n * an extractor that missed something. Failing on it would punish the honest\n * case to catch the other one. It is reported, loudly, and revisited when a\n * codebase does it deliberately.\n *\n * `unresolved` does fail, and `--allow-unresolved` is the only way past it\n * (`AS-COVER-003`). A partial understanding of a codebase that reports itself\n * as complete is the failure the whole static half exists to remove: `unreached`\n * is computed against the catalog, so a catalog with holes in it makes that\n * count a floor rather than an answer. Accepting the gap still prints it.\n */\nexport function coverageExitCode(\n report: CoverageReport,\n options: { allowUnresolved?: boolean } = {},\n): number {\n if (report.unreached.length > 0) return 1;\n if (report.unresolved.length > 0 && !options.allowUnresolved) return 1;\n if (report.staleAllowlist.length > 0) return 1;\n return 0;\n}\n","/**\n * The static capability inventory (`AS-COVER-001…003`, D35).\n *\n * `inspect` answers *what can an agent do on this page right now*. It cannot\n * answer *did we author something no scenario ever reaches*, because a surface\n * is a projection of what is mounted: a route no scenario visits registers\n * nothing, so there is nothing to report and nothing to diff. The denominator\n * has to come from somewhere that does not require mounting.\n *\n * It comes from here. A registration call site is far more static than the\n * surface it produces:\n *\n * ```tsx\n * useAgentComponent({\n * type: \"devices.table\", // string literal\n * actions: { sort: action({ … }) }, // capability name is a key\n * });\n * ```\n *\n * `view:devices.table.sort` is fully determined by source text. What is\n * genuinely dynamic — availability, policy outcome, binding — is the\n * *projection*, and none of it is claimed here.\n *\n * ## This creates no exposure path (directive §2.1)\n *\n * No DOM is scanned, nothing is registered, no annotation is suggested. This\n * module *reads the same reviewed registration code* a human reads and counts\n * what is already there. It lives in `@agent-surface/cli` — which no adapter\n * imports and no application ships — and must never be re-exported from\n * `@agent-surface/core`, mirroring `AS-EXPLAIN-004` (`AS-COVER-006`).\n *\n * ## Failure discipline is the substance, not a detail\n *\n * > Better a missing check than a misleading check.\n *\n * A call site this module cannot understand is **reported with its file and\n * line**, never dropped. An inventory that silently omitted the constructs it\n * failed to parse would understate the denominator, and a coverage number built\n * on it would claim completeness it never had.\n */\nimport { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport ts from \"typescript\";\n\n/** Identity could not be recovered from the call site at all. */\nexport const UNRESOLVED_ID = \"<unresolved>\";\n\nexport interface AuthoredCapability {\n /** Canonical id, instance-independent: `view:devices.table.sort`. */\n capabilityId: string;\n kind: \"observation\" | \"action\" | \"procedure\";\n /** Where a human can go and read it. */\n origin: { file: string; line: number };\n /** Literals recovered from the call site; absent when not statically known. */\n description?: string;\n effect?: string;\n /**\n * How much of this call site the extractor understood.\n *\n * `static` — identity and metadata both recovered from literals.\n * `partial` — identity resolved, some metadata dynamic. The common case: a\n * spread `instanceId`, or a description built from a template.\n * `unresolved` — identity NOT resolved. Reported, never dropped.\n */\n resolution: \"static\" | \"partial\" | \"unresolved\";\n /** Present on `partial`/`unresolved`: what defeated the extractor. */\n note?: string;\n}\n\nexport interface CapabilityInventory {\n capabilities: AuthoredCapability[];\n /** Absolute path to the tsconfig whose file list was analyzed. */\n tsconfig: string;\n /** Directory the analysis was rooted at — the surface config's own. */\n root: string;\n /** Files the program actually walked — the inventory's blast radius. */\n filesAnalyzed: number;\n /**\n * Program files skipped for living outside `root` — workspace packages the\n * app's tsconfig aliases in, typically the library's own source. Reported\n * rather than dropped silently: a boundary nobody can see is a boundary\n * nobody can check.\n */\n filesOutsideRoot: number;\n /**\n * The `domain:` plane is deliberately *not* analyzed here. Those capabilities\n * come from the oRPC router, which is already a static export (OQ-1), and\n * reporting zero of them would read as \"there are none\" rather than \"nobody\n * looked\".\n */\n domain: \"not-analyzed\";\n}\n\n/* ── locating the program ─────────────────────────────────────────────── */\n\nexport function findTsconfig(from: string): string | undefined {\n return ts.findConfigFile(resolve(from), ts.sys.fileExists, \"tsconfig.json\");\n}\n\ninterface ProgramFiles {\n fileNames: string[];\n options: ts.CompilerOptions;\n}\n\nfunction readProgramFiles(tsconfigPath: string): ProgramFiles {\n const read = ts.readConfigFile(tsconfigPath, ts.sys.readFile);\n if (read.error) {\n throw new Error(\n `could not read ${tsconfigPath}: ${ts.flattenDiagnosticMessageText(read.error.messageText, \" \")}`,\n );\n }\n const parsed = ts.parseJsonConfigFileContent(\n read.config as object,\n ts.sys,\n dirname(tsconfigPath),\n );\n if (parsed.errors.length > 0 && parsed.fileNames.length === 0) {\n throw new Error(\n `could not resolve any files from ${tsconfigPath}: ${parsed.errors\n .map((error) => ts.flattenDiagnosticMessageText(error.messageText, \" \"))\n .join(\"; \")}`,\n );\n }\n return { fileNames: parsed.fileNames, options: parsed.options };\n}\n\n/* ── small AST helpers ────────────────────────────────────────────────── */\n\nfunction calleeName(call: ts.CallExpression): string | undefined {\n if (ts.isIdentifier(call.expression)) return call.expression.text;\n if (ts.isPropertyAccessExpression(call.expression)) return call.expression.name.text;\n return undefined;\n}\n\nfunction propertyName(name: ts.PropertyName): string | undefined {\n if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text;\n return undefined;\n}\n\nfunction propertyOf(\n object: ts.ObjectLiteralExpression,\n wanted: string,\n): ts.Expression | undefined {\n for (const property of object.properties) {\n if (ts.isPropertyAssignment(property) && propertyName(property.name) === wanted) {\n return property.initializer;\n }\n }\n return undefined;\n}\n\nfunction hasSpread(object: ts.ObjectLiteralExpression): boolean {\n return object.properties.some((property) => ts.isSpreadAssignment(property));\n}\n\nfunction literalText(node: ts.Expression | undefined): string | undefined {\n if (!node) return undefined;\n if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;\n if (ts.isParenthesizedExpression(node)) return literalText(node.expression);\n // `\"one long \" + \"description split over two lines\"` is as statically known\n // as either half. Descriptions are the provider's cached prompt prefix (D28),\n // so they are long enough that authors wrap them — calling that `partial`\n // would report the codebase's most common formatting choice as a defect.\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {\n const left = literalText(node.left);\n const right = literalText(node.right);\n if (left !== undefined && right !== undefined) return left + right;\n }\n return undefined;\n}\n\n/** A short name for whatever construct defeated us, for the `note`. */\nfunction describeConstruct(node: ts.Expression): string {\n if (ts.isCallExpression(node)) {\n const callee = calleeName(node);\n return callee ? `built by ${callee}()` : \"built by a call expression\";\n }\n if (ts.isIdentifier(node)) return `a variable (${node.text}) this extractor could not follow`;\n if (ts.isConditionalExpression(node)) return \"a conditional expression\";\n if (ts.isTemplateExpression(node)) return \"a template with substitutions\";\n if (ts.isPropertyAccessExpression(node)) return \"a property access\";\n return \"a non-literal expression\";\n}\n\n/**\n * Resolves a config argument to an object literal, following **one hop** to a\n * same-module `const`.\n *\n * One hop is the whole rule. `useAgentComponent(CONFIG)` where `CONFIG` is a\n * module constant is common and cheap; `useAgentComponent(buildConfig(props))`\n * is not resolvable at any depth worth implementing. Stopping at one hop keeps\n * the limit *visible in the output* rather than buried in the implementation —\n * the deeper case is reported as `unresolved` with the construct named, which\n * is the behaviour this module exists to guarantee.\n */\nfunction objectLiteralFor(\n expression: ts.Expression,\n source: ts.SourceFile,\n): { object?: ts.ObjectLiteralExpression; note?: string } {\n if (ts.isObjectLiteralExpression(expression)) return { object: expression };\n\n if (ts.isIdentifier(expression)) {\n const target = expression.text;\n let found: ts.ObjectLiteralExpression | undefined;\n const visit = (node: ts.Node): void => {\n if (found) return;\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.name.text === target &&\n node.initializer &&\n ts.isObjectLiteralExpression(node.initializer)\n ) {\n found = node.initializer;\n return;\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n if (found) return { object: found };\n return {\n note: `the config is \\`${target}\\`, which is not a same-module object literal — the extractor follows one hop only`,\n };\n }\n\n return { note: `the config is ${describeConstruct(expression)}` };\n}\n\n/* ── the extraction itself ────────────────────────────────────────────── */\n\n/** Hooks that register one capability against the enclosing render scope. */\nconst GRANULAR_HOOKS = new Set([\"useAgentAction\", \"useAgentObservation\"]);\n\ninterface Emitter {\n push(capability: AuthoredCapability): void;\n origin(node: ts.Node): { file: string; line: number };\n}\n\nfunction capabilitiesFromGroup(\n group: ts.Expression | undefined,\n kind: \"observation\" | \"action\",\n componentType: string,\n componentPartial: string | undefined,\n emit: Emitter,\n source: ts.SourceFile,\n): void {\n if (!group) return;\n\n const resolved = objectLiteralFor(group, source);\n if (!resolved.object) {\n emit.push({\n capabilityId: `view:${componentType}.${UNRESOLVED_ID}`,\n kind,\n origin: emit.origin(group),\n resolution: \"unresolved\",\n note: `\\`${kind}s\\` on \"${componentType}\" is not an object literal: ${resolved.note}`,\n });\n return;\n }\n\n for (const property of resolved.object.properties) {\n // A spread inside the capability map can add capabilities this extractor\n // cannot name. That is an identity gap, not a metadata gap.\n if (ts.isSpreadAssignment(property)) {\n emit.push({\n capabilityId: `view:${componentType}.${UNRESOLVED_ID}`,\n kind,\n origin: emit.origin(property),\n resolution: \"unresolved\",\n note: `\\`${kind}s\\` on \"${componentType}\" spreads another object, which may contribute capabilities this inventory cannot name`,\n });\n continue;\n }\n\n const name =\n ts.isPropertyAssignment(property) || ts.isMethodDeclaration(property)\n ? propertyName(property.name)\n : ts.isShorthandPropertyAssignment(property)\n ? property.name.text\n : undefined;\n\n if (name === undefined) {\n emit.push({\n capabilityId: `view:${componentType}.${UNRESOLVED_ID}`,\n kind,\n origin: emit.origin(property),\n resolution: \"unresolved\",\n note: `a capability on \"${componentType}\" has a computed name`,\n });\n continue;\n }\n\n // Identity is recovered from the key alone; the value only carries metadata.\n const capability: AuthoredCapability = {\n capabilityId: `view:${componentType}.${name}`,\n kind,\n origin: emit.origin(property),\n resolution: \"static\",\n };\n const notes: string[] = [];\n if (componentPartial) notes.push(componentPartial);\n\n const value = ts.isPropertyAssignment(property) ? property.initializer : undefined;\n const definition =\n value && ts.isCallExpression(value) && value.arguments.length > 0\n ? value.arguments[0]\n : value;\n\n if (definition && ts.isObjectLiteralExpression(definition)) {\n const description = literalText(propertyOf(definition, \"description\"));\n if (description !== undefined) capability.description = description;\n else notes.push(\"description is not a string literal\");\n\n if (kind === \"action\") {\n const effect = literalText(propertyOf(definition, \"effect\"));\n if (effect !== undefined) capability.effect = effect;\n else notes.push(\"effect is not a string literal\");\n }\n if (hasSpread(definition)) notes.push(\"the definition spreads another object\");\n } else {\n notes.push(\n value\n ? `the definition is ${describeConstruct(value)}`\n : \"the definition is not an object literal\",\n );\n }\n\n if (notes.length > 0) {\n capability.resolution = \"partial\";\n capability.note = notes.join(\"; \");\n }\n emit.push(capability);\n }\n}\n\nfunction visitCall(call: ts.CallExpression, emit: Emitter, source: ts.SourceFile): void {\n const callee = calleeName(call);\n if (callee === undefined) return;\n\n if (GRANULAR_HOOKS.has(callee)) {\n // OQ-3: the granular hooks register through a render-scope link rather than\n // one aggregated descriptor, so the component `type` is not at this call\n // site at all. Reporting the call site as unresolved is the honest state\n // until that join key is settled — silently ignoring it would make a\n // codebase that uses them look fully covered.\n emit.push({\n capabilityId: UNRESOLVED_ID,\n kind: callee === \"useAgentAction\" ? \"action\" : \"observation\",\n origin: emit.origin(call),\n resolution: \"unresolved\",\n note: `${callee}() registers against a render-scope link, so its component type is not at this call site`,\n });\n return;\n }\n\n if (callee !== \"useAgentComponent\" && callee !== \"register\") return;\n const argument = call.arguments[0];\n if (!argument) return;\n\n const resolved = objectLiteralFor(argument, source);\n if (!resolved.object) {\n emit.push({\n capabilityId: UNRESOLVED_ID,\n kind: \"action\",\n origin: emit.origin(call),\n resolution: \"unresolved\",\n note: `${callee}() call site could not be read: ${resolved.note}`,\n });\n return;\n }\n\n const config = resolved.object;\n const type = literalText(propertyOf(config, \"type\"));\n if (type === undefined) {\n // `register` is a common method name; only treat it as ours once the call\n // actually looks like a registration. A `type` that exists but is dynamic\n // *is* ours, and is a genuine finding.\n if (callee === \"register\" && propertyOf(config, \"type\") === undefined) return;\n emit.push({\n capabilityId: UNRESOLVED_ID,\n kind: \"action\",\n origin: emit.origin(call),\n resolution: \"unresolved\",\n note: `\\`type\\` is not a string literal, so no capability id on this component can be determined`,\n });\n return;\n }\n\n // A spread at the component level is the documented common case — the\n // conditional `...(props.instance ? { instanceId } : {})`. `instanceId` is not\n // part of a capability id, so identity survives; metadata may not.\n const componentPartial = hasSpread(config)\n ? \"the component config spreads another object, so some metadata here may be dynamic\"\n : undefined;\n\n capabilitiesFromGroup(\n propertyOf(config, \"observations\"),\n \"observation\",\n type,\n componentPartial,\n emit,\n source,\n );\n capabilitiesFromGroup(\n propertyOf(config, \"actions\"),\n \"action\",\n type,\n componentPartial,\n emit,\n source,\n );\n}\n\nexport interface ExtractOptions {\n /** Directory the analysis is rooted at — normally the surface config's dir. */\n root: string;\n /** Explicit tsconfig; found upward from `root` when omitted. */\n tsconfig?: string;\n}\n\n/**\n * Reads the program and returns every capability its registration call sites\n * author. Nothing is executed: no Vite server, no jsdom, no scenarios, no mount.\n */\nexport function extractCapabilities(options: ExtractOptions): CapabilityInventory {\n const root = resolve(options.root);\n const tsconfigPath = options.tsconfig\n ? isAbsolute(options.tsconfig)\n ? options.tsconfig\n : join(root, options.tsconfig)\n : findTsconfig(root);\n\n if (!tsconfigPath || !existsSync(tsconfigPath)) {\n throw new Error(\n `no tsconfig.json found from ${root} — \\`capabilities\\` reads the TypeScript program, ` +\n \"so it needs one (pass --tsconfig to point at it)\",\n );\n }\n\n const { fileNames, options: compilerOptions } = readProgramFiles(tsconfigPath);\n const program = ts.createProgram(fileNames, compilerOptions);\n\n const capabilities: AuthoredCapability[] = [];\n let filesAnalyzed = 0;\n\n let filesOutsideRoot = 0;\n\n for (const source of program.getSourceFiles()) {\n if (source.isDeclarationFile) continue;\n if (source.fileName.includes(\"/node_modules/\")) continue;\n // A tsconfig with workspace path aliases pulls the library's *own* source\n // into the program, where `registry.register(definition)` inside\n // `useAgentComponent` reads as an unresolvable registration call site. It\n // is not one: it is the implementation every real call site goes through.\n // The inventory covers the app the surface config points at, and says so\n // rather than quietly widening or narrowing.\n if (!isInside(root, source.fileName)) {\n filesOutsideRoot += 1;\n continue;\n }\n filesAnalyzed += 1;\n\n const emit: Emitter = {\n push: (capability) => capabilities.push(capability),\n origin: (node) => ({\n file: relative(root, source.fileName),\n line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,\n }),\n };\n\n const visit = (node: ts.Node): void => {\n if (ts.isCallExpression(node)) visitCall(node, emit, source);\n ts.forEachChild(node, visit);\n };\n visit(source);\n }\n\n capabilities.sort(\n (a, b) =>\n a.capabilityId.localeCompare(b.capabilityId) ||\n a.origin.file.localeCompare(b.origin.file) ||\n a.origin.line - b.origin.line,\n );\n\n return {\n capabilities,\n tsconfig: tsconfigPath,\n root,\n filesAnalyzed,\n filesOutsideRoot,\n domain: \"not-analyzed\",\n };\n}\n\n/** True when `file` lives under `root` — the analyzed boundary. */\nfunction isInside(root: string, file: string): boolean {\n const rel = relative(root, file);\n return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n}\n\n/** Distinct capability ids the inventory resolved — the coverage denominator. */\nexport function authoredIds(inventory: CapabilityInventory): Set<string> {\n const ids = new Set<string>();\n for (const capability of inventory.capabilities) {\n if (capability.resolution === \"unresolved\") continue;\n if (capability.capabilityId.endsWith(UNRESOLVED_ID)) continue;\n ids.add(capability.capabilityId);\n }\n return ids;\n}\n\nexport function unresolved(inventory: CapabilityInventory): AuthoredCapability[] {\n return inventory.capabilities.filter((capability) => capability.resolution === \"unresolved\");\n}\n","/**\n * The two halves of the surface, and the join between them.\n *\n * A presentation surface has two sources of truth, and every command needs\n * some mix of both:\n *\n * - the **catalog** — what this codebase authors. Static: `type` is a string\n * literal, capability names are object keys, so `view:devices.table.sort` is\n * fully determined by source text ([`extract.ts`](./extract.ts)).\n * - the **projection** — what a mounted scenario actually surfaces, after\n * availability, policy and binding have had their say ([`collect.ts`](./collect.ts)).\n *\n * Splitting those across separate commands is what let a green `check` sit on\n * top of a route no scenario visits. So the split lives here, behind a `depth`\n * dial, and the commands compose the same three steps in whatever order their\n * output needs: `inspect` streams and closes with the verdict, `check` collects\n * and leads with it.\n */\nimport { dirname } from \"node:path\";\nimport { matchesScope } from \"@agent-surface/core/explain\";\nimport { baselineDirFor } from \"./baseline.js\";\nimport { UsageError, type Depth } from \"./contract.js\";\nimport type { CollectResult } from \"./collect.js\";\nimport {\n allowlistPathFor,\n buildCoverageReport,\n readAllowlist,\n type CoverageReport,\n} from \"./coverage.js\";\nimport {\n authoredIds,\n extractCapabilities,\n unresolved,\n type CapabilityInventory,\n} from \"./extract.js\";\nimport { createSurfaceRunner } from \"./load.js\";\n\nexport type { Depth } from \"./contract.js\";\nexport { UsageError } from \"./contract.js\";\n\nexport interface AnalysisOptions {\n configPath: string;\n depth: Depth;\n scenario?: string;\n scope?: string[];\n tsconfig?: string;\n baselineDir?: string;\n}\n\n/**\n * The static half. `undefined` at `--depth runtime`, which is the caller\n * saying it does not want this computed rather than it having failed.\n */\nexport function readInventory(options: AnalysisOptions): CapabilityInventory | undefined {\n if (options.depth === \"runtime\") return undefined;\n return extractCapabilities({\n root: dirname(options.configPath),\n ...(options.tsconfig ? { tsconfig: options.tsconfig } : {}),\n });\n}\n\n/** A scenario the config declares whose mount threw. Named, never swallowed. */\nexport interface ScenarioFailure {\n scenario: string;\n message: string;\n}\n\nexport interface RuntimeAnalysis {\n /** Every scenario this run set out to mount, in config order. */\n scenarios: string[];\n /** The ones that mounted. */\n results: CollectResult[];\n failures: ScenarioFailure[];\n baselineDir: string;\n}\n\n/**\n * The runtime half. `undefined` at `--depth static`.\n *\n * `onEach` is awaited as each scenario finishes, so a command can print as it\n * goes instead of after the last mount — a config with ten scenarios is a long\n * time to look at nothing.\n *\n * A scenario that throws is recorded and the run continues. Before this was\n * one command, `capabilities` was the only thing that still worked on an app\n * that would not mount; merging the commands would have thrown that away if a\n * single bad scenario could abort the run.\n */\nexport async function mountScenarios(\n options: AnalysisOptions,\n onEach?: (result: CollectResult) => void | Promise<void>,\n): Promise<RuntimeAnalysis | undefined> {\n if (options.depth === \"static\") return undefined;\n\n const runner = await createSurfaceRunner(options.configPath);\n try {\n if (options.scenario && !runner.scenarioNames.includes(options.scenario)) {\n throw new UsageError(\n `unknown scenario \"${options.scenario}\" — this config defines ` +\n runner.scenarioNames.map((name) => `\"${name}\"`).join(\", \"),\n );\n }\n const scenarios = options.scenario ? [options.scenario] : runner.scenarioNames;\n const results: CollectResult[] = [];\n const failures: ScenarioFailure[] = [];\n\n for (const scenario of scenarios) {\n let result: CollectResult;\n try {\n result = await runner.collect({\n scenario,\n ...(options.scope ? { scope: options.scope } : {}),\n });\n } catch (error) {\n failures.push({\n scenario,\n message: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n results.push(result);\n await onEach?.(result);\n }\n\n return {\n scenarios,\n results,\n failures,\n baselineDir: baselineDirFor(\n options.configPath,\n options.baselineDir ?? runner.config.baselineDir,\n ),\n };\n } finally {\n await runner.close();\n }\n}\n\n/**\n * The component type a capability id belongs to: `view:devices.table.sort` →\n * `devices.table`. Capability names are object keys and cannot contain a dot,\n * so the last one is always the boundary; component types can and do.\n */\nfunction componentTypeOf(capabilityId: string): string {\n const withoutPlane = capabilityId.replace(/^(view|domain):/, \"\");\n const dot = withoutPlane.lastIndexOf(\".\");\n return dot === -1 ? withoutPlane : withoutPlane.slice(0, dot);\n}\n\n/**\n * Authored minus reached (`AS-COVER-004…005`).\n *\n * Two ways this returns `undefined`, and neither is \"no gaps\":\n *\n * - a half was not computed, because the depth did not ask for it;\n * - **a scenario failed to mount.** That scenario reached nothing, so every\n * capability it would have surfaced would be reported as one no scenario\n * reaches. A coverage verdict computed over a partial run is precisely the\n * misleading check this package refuses to emit, so there is no verdict\n * until every scenario mounted. The renderer says which of the two it was.\n */\nexport function joinCoverage(\n inventory: CapabilityInventory | undefined,\n runtime: RuntimeAnalysis | undefined,\n options: AnalysisOptions,\n): CoverageReport | undefined {\n if (!inventory || !runtime) return undefined;\n if (runtime.failures.length > 0) return undefined;\n\n // A scope filters the mount, so it has to filter the catalog by the same\n // predicate — core's own, not a second copy of it. Without this, `--scope\n // devices` reported every `app.navigation` capability as unreached, with the\n // words \"no scenario mounts it\" over two that both scenarios mount.\n const inScope = (capabilityId: string): boolean =>\n matchesScope(componentTypeOf(capabilityId), options.scope);\n\n const origins = new Map<string, { file: string; line: number }>();\n for (const capability of inventory.capabilities) {\n if (!origins.has(capability.capabilityId)) {\n origins.set(capability.capabilityId, capability.origin);\n }\n }\n\n const authored = new Set([...authoredIds(inventory)].filter(inScope));\n const reachedIds = new Set<string>();\n for (const result of runtime.results) {\n for (const capability of result.explanation.capabilities) {\n reachedIds.add(capability.capabilityId);\n }\n }\n\n // The allowlist is a statement about the whole catalog, and a scoped run has\n // only looked at part of it. Judging an out-of-scope entry either way would\n // be wrong in both directions — it is not an unreached capability this run\n // waved through, and it is not a stale entry either, because nothing here\n // reached it.\n const allowlistPath = allowlistPathFor(runtime.baselineDir);\n const wholeAllowlist = readAllowlist(allowlistPath);\n const allowlist = Object.fromEntries(\n Object.entries(wholeAllowlist).filter(([id]) => inScope(id)),\n );\n\n return buildCoverageReport({\n authored,\n origins,\n reachedIds,\n scenarios: runtime.scenarios,\n ...(options.scope ? { scope: options.scope } : {}),\n unresolved: unresolved(inventory),\n allowlist,\n allowlistOutOfScope: Object.keys(wholeAllowlist).length - Object.keys(allowlist).length,\n allowlistPath,\n });\n}\n"],"mappings":";;;;;;AAAA,SAAS,WAAW,cAAc,qBAAqB;AACvD,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,gCAAgC;AAGlC,IAAM,uBAAuB;AAE7B,SAAS,eAAe,YAAoB,YAA6B;AAC9E,SAAO,QAAQ,QAAQ,UAAU,GAAG,cAAc,oBAAoB;AACxE;AAEO,SAAS,aAAa,KAAa,UAA0B;AAClE,SAAO,KAAK,KAAK,GAAG,QAAQ,OAAO;AACrC;AAQO,SAAS,UAAU,UAAyC;AACjE,SAAO,yBAAyB,QAAQ;AAC1C;AAEO,SAAS,aAAa,MAAmC;AAC9D,MAAI;AACF,WAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAAA,EAC9C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,cAAc,MAAc,OAAsB;AAChE,YAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAC5C,gBAAc,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,GAAM,MAAM;AACnE;AAeA,IAAM,eAAe;AAGrB,SAAS,WAAW,UAAmB,MAAkC;AACvE,MAAI,OAAgB;AACpB,MAAI;AACJ,aAAW,SAAS,KAAK,SAAS,YAAY,GAAG;AAC/C,QAAI,O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