@neuralaxis/vibedoctor 0.2.0 → 0.2.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.
Files changed (52) hide show
  1. package/README.md +86 -0
  2. package/dist/adapters/biome.js +135 -21
  3. package/dist/adapters/osvScanner.js +136 -17
  4. package/dist/adapters/presidio.js +3 -1
  5. package/dist/cli/commands/init.js +105 -50
  6. package/dist/cli/commands/privacyReview.js +3 -4
  7. package/dist/cli/commands/setup.d.ts +13 -17
  8. package/dist/cli/commands/setup.js +138 -200
  9. package/dist/core/capability.d.ts +92 -0
  10. package/dist/core/capability.js +122 -0
  11. package/dist/core/config.d.ts +36 -0
  12. package/dist/core/config.js +105 -3
  13. package/dist/core/credentialHeuristics.d.ts +28 -0
  14. package/dist/core/credentialHeuristics.js +179 -0
  15. package/dist/core/engine.d.ts +21 -0
  16. package/dist/core/engine.js +466 -85
  17. package/dist/core/executable.d.ts +18 -0
  18. package/dist/core/executable.js +137 -0
  19. package/dist/core/fileRole.d.ts +24 -0
  20. package/dist/core/fileRole.js +125 -0
  21. package/dist/core/finding.d.ts +124 -0
  22. package/dist/core/finding.js +62 -5
  23. package/dist/core/findingNormalizer.d.ts +33 -0
  24. package/dist/core/findingNormalizer.js +171 -0
  25. package/dist/core/projectDetector.d.ts +13 -0
  26. package/dist/core/projectDetector.js +100 -15
  27. package/dist/core/relevance.d.ts +87 -0
  28. package/dist/core/relevance.js +367 -0
  29. package/dist/core/scanPlanner.d.ts +12 -0
  30. package/dist/core/scanPlanner.js +61 -37
  31. package/dist/core/semverLite.d.ts +27 -0
  32. package/dist/core/semverLite.js +163 -0
  33. package/dist/core/suppressions.d.ts +96 -0
  34. package/dist/core/suppressions.js +302 -0
  35. package/dist/core/toolRegistry.d.ts +58 -0
  36. package/dist/core/toolRegistry.js +247 -0
  37. package/dist/core/toolRunner.d.ts +23 -2
  38. package/dist/core/toolRunner.js +61 -93
  39. package/dist/core/toolVerification.d.ts +87 -0
  40. package/dist/core/toolVerification.js +370 -0
  41. package/dist/dpdp/collectors/optionalScanners.js +120 -30
  42. package/dist/dpdp/findings.d.ts +33 -3
  43. package/dist/dpdp/findings.js +191 -4
  44. package/dist/dpdp/scan.js +2 -2
  45. package/dist/dpdp/scoring.d.ts +14 -4
  46. package/dist/dpdp/scoring.js +34 -8
  47. package/dist/dpdp/types.d.ts +19 -1
  48. package/dist/reporters/html.js +57 -13
  49. package/dist/reporters/json.js +7 -1
  50. package/dist/reporters/markdown.js +46 -4
  51. package/dist/reporters/sarif.js +54 -5
  52. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withReportingDefaults = withReportingDefaults;
3
4
  exports.createAgentPlan = createAgentPlan;
4
5
  exports.runScan = runScan;
5
6
  exports.retryTool = retryTool;
@@ -24,6 +25,13 @@ const scanPlanner_1 = require("./scanPlanner");
24
25
  const scoring_1 = require("./scoring");
25
26
  const toolRunner_1 = require("./toolRunner");
26
27
  const severityMap_1 = require("../rules/severityMap");
28
+ const capability_1 = require("./capability");
29
+ const fileRole_1 = require("./fileRole");
30
+ const findingNormalizer_1 = require("./findingNormalizer");
31
+ const relevance_1 = require("./relevance");
32
+ const suppressions_1 = require("./suppressions");
33
+ const toolRegistry_1 = require("./toolRegistry");
34
+ const toolVerification_1 = require("./toolVerification");
27
35
  const privacyReview_1 = require("./privacyReview");
28
36
  const ALL_ADAPTERS = [
29
37
  adapters_1.gitleaksAdapter,
@@ -61,6 +69,72 @@ const categoryPriority = {
61
69
  maintainability: 8,
62
70
  efficiency: 9
63
71
  };
72
+ const emptyRelevanceReport = {
73
+ enabled: false,
74
+ perTool: [],
75
+ totalReported: 0,
76
+ totalSurfaced: 0,
77
+ notes: []
78
+ };
79
+ const emptySuppressionReport = {
80
+ file: "",
81
+ active: [],
82
+ expired: [],
83
+ invalid: [],
84
+ permanent: [],
85
+ hits: {},
86
+ expiredHits: {},
87
+ unused: [],
88
+ resurfaced: 0
89
+ };
90
+ const emptyCapabilityMatrix = (0, capability_1.buildCapabilityMatrix)([], []);
91
+ /**
92
+ * Fills in the reporting fields a scan produces, for callers that reconstruct a
93
+ * `ScanOutput` from something other than a live scan — a cached report written by
94
+ * an older version, or a test fixture. The defaults describe an unknown scan
95
+ * rather than a clean one: an empty matrix claims no coverage.
96
+ */
97
+ function withReportingDefaults(partial) {
98
+ return {
99
+ root: partial.root ?? process.cwd(),
100
+ mode: partial.mode ?? "default",
101
+ score: partial.score ?? (0, scoring_1.buildScore)(partial.findings),
102
+ findings: partial.findings,
103
+ topFindings: partial.topFindings ?? [],
104
+ blockers: partial.blockers ?? [],
105
+ fixNext: partial.fixNext ?? [],
106
+ privacyFindings: partial.privacyFindings ?? [],
107
+ privacyReview: partial.privacyReview,
108
+ leftovers: partial.leftovers ?? [],
109
+ deadCodeCandidates: partial.deadCodeCandidates ?? [],
110
+ refactorCandidates: partial.refactorCandidates ?? [],
111
+ toolStatuses: partial.toolStatuses ?? [],
112
+ skippedTools: partial.skippedTools ?? [],
113
+ completeness: partial.completeness ?? {
114
+ status: "partial",
115
+ comparable: false,
116
+ planned: 0,
117
+ completed: 0,
118
+ incompleteTools: [],
119
+ requiredIncompleteTools: [],
120
+ reason: "This result was reconstructed without capability information, so coverage is unknown."
121
+ },
122
+ recoveryActions: partial.recoveryActions ?? [],
123
+ testCommands: partial.testCommands ?? [],
124
+ agentPlan: partial.agentPlan ??
125
+ createAgentPlan({
126
+ findings: partial.findings,
127
+ score: partial.score ?? (0, scoring_1.buildScore)(partial.findings),
128
+ skippedTools: partial.skippedTools ?? []
129
+ }),
130
+ configPath: partial.configPath,
131
+ capabilityMatrix: partial.capabilityMatrix ?? emptyCapabilityMatrix,
132
+ relevance: partial.relevance ?? emptyRelevanceReport,
133
+ suppressions: partial.suppressions ?? emptySuppressionReport,
134
+ suppressedFindings: partial.suppressedFindings ?? [],
135
+ verifications: partial.verifications ?? []
136
+ };
137
+ }
64
138
  function sortFindings(findings) {
65
139
  return [...findings].sort((left, right) => {
66
140
  const categoryDelta = categoryPriority[left.category] - categoryPriority[right.category];
@@ -254,7 +328,12 @@ function buildScanOutput(options) {
254
328
  recoveryActions,
255
329
  testCommands: options.testCommands
256
330
  }, { policy, target: options.target }),
257
- configPath: options.configPath
331
+ configPath: options.configPath,
332
+ capabilityMatrix: options.capabilityMatrix,
333
+ relevance: options.relevance,
334
+ suppressions: options.suppressions,
335
+ suppressedFindings: options.suppressedFindings,
336
+ verifications: options.verifications
258
337
  };
259
338
  }
260
339
  function firstUsefulLine(value) {
@@ -298,41 +377,191 @@ function forgiveKnownToolQuirks(toolId, result, findingsCount = 0) {
298
377
  }
299
378
  return undefined;
300
379
  }
301
- async function runAdapter(adapter, ctx) {
380
+ /**
381
+ * Narrows a context to a subset of files. A tool that cannot finish the whole
382
+ * repository within its budget can still cover the code being changed, and
383
+ * partial coverage that says so is worth more than no coverage at all.
384
+ */
385
+ function narrowContextToFiles(ctx, files) {
386
+ return {
387
+ ...ctx,
388
+ project: { ...ctx.project, projectFiles: files }
389
+ };
390
+ }
391
+ function commandText(command) {
392
+ return [command.cmd, ...command.args].join(" ");
393
+ }
394
+ async function runAdapter(adapter, ctx, deadline) {
302
395
  if (adapter.runStandalone) {
303
396
  return adapter.runStandalone(ctx);
304
397
  }
305
- if (adapter.buildScanCommand && adapter.parseResult) {
306
- const command = adapter.buildScanCommand(ctx);
307
- const timeoutSeconds = ctx.config.runtime.toolTimeouts[adapter.id] ?? ctx.config.runtime.defaultTimeoutSeconds;
308
- command.timeoutMs = timeoutSeconds * 1000;
309
- const status = await (0, toolRunner_1.runCommand)(command, adapter.installHint);
310
- if (status.status === "skipped") {
311
- return { findings: [], status };
312
- }
313
- // Guard against brittle parser (unvalidated JSON, format drift in tsc etc.).
314
- // Standalone adapters already have partial internal try/catch; this covers the command+parseResult path.
315
- let parsed = [];
316
- try {
317
- parsed = adapter.parseResult(status, ctx) ?? [];
318
- }
319
- catch {
320
- parsed = [];
321
- }
322
- return { findings: parsed, status };
398
+ if (!adapter.buildScanCommand || !adapter.parseResult) {
399
+ return {
400
+ findings: [],
401
+ status: {
402
+ command: adapter.id,
403
+ stdout: "",
404
+ stderr: "Adapter has no scan command",
405
+ exitCode: null,
406
+ durationMs: 0,
407
+ status: "skipped",
408
+ installHint: adapter.installHint
409
+ }
410
+ };
323
411
  }
324
- return {
325
- findings: [],
326
- status: {
327
- command: adapter.id,
328
- stdout: "",
329
- stderr: "Adapter has no scan command",
330
- exitCode: null,
331
- durationMs: 0,
332
- status: "skipped",
333
- installHint: adapter.installHint
412
+ const { runtime } = ctx.config;
413
+ const configuredSeconds = runtime.toolTimeouts[adapter.id] ?? runtime.defaultTimeoutSeconds;
414
+ // A wall-clock ceiling for the whole scan has to bound each tool too, or the
415
+ // slowest tool decides how long the scan takes regardless of the budget.
416
+ const budgetSeconds = deadline ? Math.max(1, Math.round((deadline - Date.now()) / 1000)) : configuredSeconds;
417
+ const timeoutSeconds = Math.min(configuredSeconds, budgetSeconds);
418
+ const command = adapter.buildScanCommand(ctx);
419
+ command.timeoutMs = timeoutSeconds * 1000;
420
+ let status = await (0, toolRunner_1.runCommand)(command, adapter.installHint);
421
+ if (status.status === "timeout" && runtime.onTimeout === "scoped_retry") {
422
+ const scoped = await retryWithNarrowedScope(adapter, ctx, timeoutSeconds);
423
+ if (scoped) {
424
+ status = scoped;
334
425
  }
426
+ }
427
+ if (status.status === "skipped") {
428
+ return { findings: [], status, timeoutSeconds };
429
+ }
430
+ // Guard against brittle parsers (unvalidated JSON, format drift in tsc etc.).
431
+ // A parse failure is reported rather than swallowed: a tool that ran but whose
432
+ // output could not be read has not actually checked anything.
433
+ try {
434
+ return { findings: adapter.parseResult(status, ctx) ?? [], status, timeoutSeconds };
435
+ }
436
+ catch (error) {
437
+ return {
438
+ findings: [],
439
+ status,
440
+ parseError: `Could not parse ${adapter.id} output: ${error instanceof Error ? error.message : String(error)}`,
441
+ timeoutSeconds
442
+ };
443
+ }
444
+ }
445
+ /**
446
+ * Reruns a timed-out tool over the changed files only. Skipped when narrowing
447
+ * produces the same command line, since a tool that ignores the target list
448
+ * would simply time out again.
449
+ */
450
+ async function retryWithNarrowedScope(adapter, ctx, originalTimeoutSeconds) {
451
+ const changed = ctx.project.changedFiles.filter((file) => ctx.project.projectFiles.includes(file));
452
+ if (changed.length === 0 || !adapter.buildScanCommand) {
453
+ return undefined;
454
+ }
455
+ const original = commandText(adapter.buildScanCommand(ctx));
456
+ const narrowedCtx = narrowContextToFiles(ctx, changed);
457
+ const narrowed = adapter.buildScanCommand(narrowedCtx);
458
+ if (commandText(narrowed) === original) {
459
+ return undefined;
460
+ }
461
+ narrowed.timeoutMs = Math.max(1, ctx.config.runtime.scopedRetryTimeoutSeconds) * 1000;
462
+ const result = await (0, toolRunner_1.runCommand)(narrowed, adapter.installHint);
463
+ const coverage = {
464
+ scope: "scoped",
465
+ detail: `Timed out after ${originalTimeoutSeconds}s over the full repository; rescanned ${changed.length} changed file(s) instead.`,
466
+ targetsRequested: ctx.project.projectFiles.length,
467
+ targetsScanned: changed.length
335
468
  };
469
+ return result.status === "timeout"
470
+ ? // Even the narrowed run did not finish. Report the original timeout rather
471
+ // than a second one, and say the fallback was attempted.
472
+ {
473
+ ...result,
474
+ coverage: {
475
+ scope: "none",
476
+ detail: `Timed out after ${originalTimeoutSeconds}s, and a scoped retry over ${changed.length} changed file(s) also timed out.`,
477
+ targetsRequested: ctx.project.projectFiles.length,
478
+ targetsScanned: 0
479
+ }
480
+ }
481
+ : { ...result, coverage };
482
+ }
483
+ /**
484
+ * Resolves each selected tool before the scan trusts it.
485
+ *
486
+ * Without this, a missing tool only revealed itself as an ENOENT mid-scan —
487
+ * indistinguishable from a tool that ran and found nothing, and with no record of
488
+ * which binary was even looked for. This runs at `resolve` depth: it locates the
489
+ * executable and checks runtime compatibility without spawning a probe per tool,
490
+ * because the scan is about to invoke each tool anyway. `vibedoctor setup` does
491
+ * the same work at `execute` depth, where there is no later run to rely on.
492
+ */
493
+ async function verifySelectedTools(root, adapterIds, config) {
494
+ const entries = adapterIds.map(toolRegistry_1.getToolEntry).filter((entry) => Boolean(entry));
495
+ if (!config.runtime.verifyToolsBeforeScan || entries.length === 0) {
496
+ return new Map();
497
+ }
498
+ const verifications = await (0, toolVerification_1.verifyTools)(entries, root, "resolve");
499
+ return new Map(verifications.map((verification) => [verification.id, verification]));
500
+ }
501
+ /** Derives the capability state for a tool that was selected and attempted. */
502
+ function stateForRun(id, run, verification, findingsCount) {
503
+ if (verification && (0, toolVerification_1.isVerificationBlocking)(verification)) {
504
+ return verification.state === "incompatible_runtime" ? "runtime_incompatible" : "not_installed";
505
+ }
506
+ const status = run.status;
507
+ if (!status) {
508
+ // Built-in checks report no process status; reaching here means they ran.
509
+ return "completed";
510
+ }
511
+ if (status.status === "skipped") {
512
+ return "not_installed";
513
+ }
514
+ if (status.status === "timeout") {
515
+ return status.coverage?.scope === "scoped" ? "partial" : "timed_out";
516
+ }
517
+ if (run.parseError) {
518
+ return "failed";
519
+ }
520
+ if (status.status === "error") {
521
+ return forgiveKnownToolQuirks(id, status, findingsCount) ? "completed" : "failed";
522
+ }
523
+ return status.coverage && status.coverage.scope !== "full" ? "partial" : "completed";
524
+ }
525
+ function reasonForCapability(id, state, run, verification, normalizationNote) {
526
+ if (verification && (0, toolVerification_1.isVerificationBlocking)(verification)) {
527
+ return { reason: verification.reason, remediation: verification.remediation };
528
+ }
529
+ switch (state) {
530
+ case "completed": {
531
+ const where = verification?.resolvedPath ?? run.status?.resolvedPath;
532
+ const version = verification?.version ? ` ${verification.version}` : "";
533
+ const base = where ? `Ran${version} at ${where}.` : `Completed${version}.`;
534
+ return { reason: normalizationNote ? `${base} ${normalizationNote}` : base };
535
+ }
536
+ case "partial":
537
+ return {
538
+ reason: run.status?.coverage?.detail ?? "Covered only part of the requested scope.",
539
+ remediation: `Raise runtime.tool_timeouts.${id} in vibedoctor.yml, or run \`vibedoctor tool retry ${id}\` with a longer budget.`
540
+ };
541
+ case "timed_out":
542
+ return {
543
+ reason: run.status?.coverage?.detail ??
544
+ `Exceeded its ${run.timeoutSeconds ?? "configured"}s budget and was stopped, so this check did not run.`,
545
+ remediation: `Raise runtime.tool_timeouts.${id} in vibedoctor.yml, scan fewer paths, or run \`vibedoctor scan --changed\` for a diff-scoped run.`
546
+ };
547
+ case "failed":
548
+ return {
549
+ reason: run.parseError ?? summarizeToolStatus(run.status).message ?? "Failed while running.",
550
+ remediation: `Run \`vibedoctor tool retry ${id}\` to see the full output.`
551
+ };
552
+ case "not_installed":
553
+ return {
554
+ reason: `${id} is not installed or could not be found on PATH, so this check did not run.`,
555
+ remediation: run.status?.installHint ?? ((0, toolRegistry_1.getToolEntry)(id) ? (0, toolRegistry_1.installHintFor)((0, toolRegistry_1.getToolEntry)(id)) : `Install ${id}.`)
556
+ };
557
+ case "runtime_incompatible":
558
+ return {
559
+ reason: `${id} cannot run under the active runtime.`,
560
+ remediation: `Upgrade the runtime or add ${id} to runtime.deferred_tools to defer it deliberately.`
561
+ };
562
+ default:
563
+ return { reason: "Did not run." };
564
+ }
336
565
  }
337
566
  async function runScan(root, mode = "default") {
338
567
  const [{ config, configPath }, { policy }] = await Promise.all([(0, config_1.loadConfig)(root), (0, policy_1.loadAgentPolicy)(root)]);
@@ -340,64 +569,109 @@ async function runScan(root, mode = "default") {
340
569
  const plan = await (0, scanPlanner_1.createScanPlan)(project, config, [...ALL_ADAPTERS], mode);
341
570
  const ctx = { root, project, config, scanMode: mode };
342
571
  const selectedAdapters = ALL_ADAPTERS.filter((adapter) => plan.adapterIds.includes(adapter.id));
343
- const independentAdapters = selectedAdapters.filter((adapter) => adapter.id !== "dpdp");
572
+ const verifications = await verifySelectedTools(root, plan.adapterIds, config);
573
+ // A tool that failed verification is not launched: doing so produces a
574
+ // confusing process error in place of the clear reason we already have.
575
+ const runnableAdapters = selectedAdapters.filter((adapter) => {
576
+ const verification = verifications.get(adapter.id);
577
+ return !verification || !(0, toolVerification_1.isVerificationBlocking)(verification);
578
+ });
579
+ const deadline = config.runtime.totalBudgetSeconds > 0 ? Date.now() + config.runtime.totalBudgetSeconds * 1000 : undefined;
580
+ const independentAdapters = runnableAdapters.filter((adapter) => adapter.id !== "dpdp");
344
581
  // Run independent adapters once. DPDP follows so it can reuse optional scanner
345
582
  // findings/status instead of launching duplicate Semgrep and Presidio processes.
346
- const adapterResults = await Promise.all(independentAdapters.map(async (adapter) => ({ adapter, result: await runAdapter(adapter, ctx) })));
347
- if (selectedAdapters.some((adapter) => adapter.id === "dpdp")) {
583
+ const adapterResults = await Promise.all(independentAdapters.map(async (adapter) => ({ adapter, result: await runAdapter(adapter, ctx, deadline) })));
584
+ if (runnableAdapters.some((adapter) => adapter.id === "dpdp")) {
348
585
  const sharedToolResults = Object.fromEntries(adapterResults.map(({ adapter, result }) => [adapter.id, result]));
349
586
  const dpdpCtx = { ...ctx, sharedToolResults };
350
- adapterResults.push({ adapter: dpdp_1.dpdpAdapter, result: await runAdapter(dpdp_1.dpdpAdapter, dpdpCtx) });
587
+ adapterResults.push({ adapter: dpdp_1.dpdpAdapter, result: await runAdapter(dpdp_1.dpdpAdapter, dpdpCtx, deadline) });
351
588
  }
589
+ const classifyFile = (0, fileRole_1.createFileRoleClassifier)(config.relevance.fileRoles);
352
590
  const findings = [];
353
- const toolStatuses = [];
354
- const skippedTools = [];
591
+ const capabilities = [];
592
+ const normalizationIssues = [];
355
593
  for (const { adapter, result } of adapterResults) {
356
- findings.push(...result.findings);
357
- if (!result.status) {
358
- continue;
359
- }
360
- if (result.status.status === "skipped") {
361
- skippedTools.push({
362
- id: adapter.id,
363
- status: "skipped",
364
- installHint: result.status.installHint ?? adapter.installHint
365
- });
594
+ // Normalize per tool so location loss and enum drift are attributed to the
595
+ // tool that caused them rather than averaged across the whole scan.
596
+ const normalized = await (0, findingNormalizer_1.normalizeFindings)(result.findings, {
597
+ root,
598
+ tool: adapter.id,
599
+ classifyFile,
600
+ changedFiles: project.changedFiles
601
+ });
602
+ normalizationIssues.push(...normalized.issues);
603
+ findings.push(...normalized.findings);
604
+ const verification = verifications.get(adapter.id);
605
+ const state = stateForRun(adapter.id, result, verification, normalized.findings.length);
606
+ const { reason, remediation } = reasonForCapability(adapter.id, state, result, verification, (0, findingNormalizer_1.describeNormalizationIssues)(normalized.issues));
607
+ capabilities.push({
608
+ id: adapter.id,
609
+ category: adapter.category,
610
+ state,
611
+ planned: true,
612
+ applicable: true,
613
+ discovered: verification ? verification.state === "verified" : result.status?.status !== "skipped",
614
+ executed: Boolean(result.status) || state === "completed",
615
+ resolvedPath: verification?.resolvedPath ?? result.status?.resolvedPath ?? verification?.interpreterPath,
616
+ version: verification?.version,
617
+ command: result.status?.command,
618
+ durationMs: result.status?.durationMs,
619
+ timeoutSeconds: result.timeoutSeconds,
620
+ coverage: result.status?.coverage,
621
+ findingsReported: normalized.findings.length,
622
+ // Filled in once relevance and suppressions have run.
623
+ findingsSurfaced: normalized.findings.length,
624
+ reason,
625
+ remediation,
626
+ trust: "authoritative"
627
+ });
628
+ }
629
+ // Tools that failed verification never launched, so record them from the
630
+ // verification result alone.
631
+ for (const adapter of selectedAdapters) {
632
+ if (runnableAdapters.includes(adapter)) {
366
633
  continue;
367
634
  }
368
- const forgiven = forgiveKnownToolQuirks(adapter.id, result.status, result.findings.length);
369
- const summarized = summarizeToolStatus(result.status);
370
- toolStatuses.push({
635
+ const verification = verifications.get(adapter.id);
636
+ const state = verification.state === "incompatible_runtime" ? "runtime_incompatible" : "not_installed";
637
+ capabilities.push({
371
638
  id: adapter.id,
372
- status: forgiven?.status ?? result.status.status,
373
- ...summarized,
374
- ...(forgiven ? { message: forgiven.message } : {})
639
+ category: adapter.category,
640
+ state,
641
+ planned: true,
642
+ applicable: true,
643
+ discovered: verification.state !== "not_found",
644
+ executed: false,
645
+ resolvedPath: verification.resolvedPath ?? verification.interpreterPath,
646
+ version: verification.version,
647
+ findingsReported: 0,
648
+ findingsSurfaced: 0,
649
+ reason: verification.reason,
650
+ remediation: verification.remediation,
651
+ trust: "absent"
652
+ });
653
+ }
654
+ for (const excluded of plan.excluded) {
655
+ const adapter = ALL_ADAPTERS.find((candidate) => candidate.id === excluded.id);
656
+ capabilities.push({
657
+ id: excluded.id,
658
+ category: adapter?.category ?? "maintainability",
659
+ state: excluded.state,
660
+ planned: false,
661
+ applicable: excluded.state !== "not_applicable",
662
+ discovered: false,
663
+ executed: false,
664
+ findingsReported: 0,
665
+ findingsSurfaced: 0,
666
+ reason: excluded.reason,
667
+ remediation: excluded.state === "deferred"
668
+ ? `Remove ${excluded.id} from runtime.deferred_tools to run it again.`
669
+ : excluded.state === "not_selected"
670
+ ? "Run `vibedoctor scan --full` to include it."
671
+ : undefined,
672
+ trust: "authoritative"
375
673
  });
376
674
  }
377
- const incompleteTools = Array.from(new Set([
378
- ...skippedTools.map((tool) => tool.id),
379
- ...toolStatuses.filter((tool) => tool.status === "error" || tool.status === "timeout").map((tool) => tool.id)
380
- ])).sort();
381
- // Skipped tools can include checks that were never selected as adapters
382
- // (built-in checks, mode-filtered tools); count them in the denominator so
383
- // "completed" never underflows.
384
- const plannedIds = new Set([...selectedAdapters.map((adapter) => adapter.id), ...incompleteTools]);
385
- const requiredIncompleteTools = incompleteTools.filter((id) => config.runtime.requiredTools.includes(id));
386
- const completeness = {
387
- status: incompleteTools.length === 0
388
- ? "complete"
389
- : requiredIncompleteTools.length > 0 || config.runtime.failOnIncompleteScan
390
- ? "invalid"
391
- : "partial",
392
- comparable: incompleteTools.length === 0,
393
- planned: plannedIds.size,
394
- completed: plannedIds.size - incompleteTools.length,
395
- incompleteTools,
396
- requiredIncompleteTools,
397
- reason: incompleteTools.length > 0
398
- ? `${incompleteTools.length} of ${plannedIds.size} planned checks did not complete.`
399
- : undefined
400
- };
401
675
  let deadChainFindings = [];
402
676
  if (config.checks.deadCode.enabled) {
403
677
  const rawDead = await (0, customDeadChain_1.detectDeadChains)(project, findings, config);
@@ -407,13 +681,46 @@ async function runScan(root, mode = "default") {
407
681
  deadChainFindings = rawDead.filter((f) => rank[f.confidence] >= minRank);
408
682
  }
409
683
  let allFindings = (0, finding_1.dedupeFindings)([...findings, ...deadChainFindings]);
684
+ // Baseline first, so novelty is known before ranking; then acknowledgements,
685
+ // which may reclassify a finding as resurfaced; then relevance, which ranks and
686
+ // caps what is left.
410
687
  if (config.baseline.enabled) {
411
688
  const baseline = await (0, baseline_1.loadBaseline)(root, config.baseline.file);
412
689
  allFindings = (0, finding_1.applyBaseline)(allFindings, new Set(baseline.findings.map((entry) => entry.fingerprint)));
413
690
  }
691
+ const suppressionsResult = config.suppressions.enabled
692
+ ? (0, suppressions_1.applySuppressions)(allFindings, await (0, suppressions_1.loadSuppressions)(root, config.suppressions.file), {
693
+ requireExpiry: config.suppressions.requireExpiry
694
+ })
695
+ : { findings: allFindings, suppressed: [], report: { ...emptySuppressionReport, file: config.suppressions.file } };
696
+ const relevanceResult = await (0, relevance_1.applyRelevance)(suppressionsResult.findings, {
697
+ root,
698
+ config: config.relevance
699
+ });
700
+ allFindings = relevanceResult.findings;
414
701
  const privacyReview = await (0, privacyReview_1.loadPrivacyReview)(root, config.output.privacyReview);
415
702
  allFindings = (0, privacyReview_1.mergePrivacyReviewIntoFindings)(allFindings, privacyReview);
416
703
  allFindings = sortFindings(allFindings);
704
+ // Record what actually reached the report per tool, so "installed" and
705
+ // "completed" and "reported something you can read" stay separate facts.
706
+ const surfacedBySource = new Map();
707
+ for (const finding of allFindings) {
708
+ surfacedBySource.set(finding.source, (surfacedBySource.get(finding.source) ?? 0) + 1);
709
+ }
710
+ for (const capability of capabilities) {
711
+ capability.findingsSurfaced = surfacedBySource.get(capability.id) ?? 0;
712
+ capability.trust =
713
+ capability.state === "completed" ||
714
+ capability.state === "not_applicable" ||
715
+ capability.state === "disabled" ||
716
+ capability.state === "not_selected"
717
+ ? "authoritative"
718
+ : capability.state === "partial"
719
+ ? "partial"
720
+ : "absent";
721
+ }
722
+ const capabilityMatrix = (0, capability_1.buildCapabilityMatrix)(capabilities, config.runtime.requiredTools);
723
+ const { toolStatuses, skippedTools, completeness } = deriveLegacyStatuses(capabilityMatrix, config);
417
724
  const score = (0, scoring_1.buildScore)(allFindings);
418
725
  return buildScanOutput({
419
726
  root,
@@ -426,9 +733,57 @@ async function runScan(root, mode = "default") {
426
733
  testCommands: project.testCommands,
427
734
  policy,
428
735
  configPath,
429
- privacyReview: privacyReview?.summary
736
+ privacyReview: privacyReview?.summary,
737
+ capabilityMatrix,
738
+ relevance: relevanceResult.report,
739
+ suppressions: suppressionsResult.report,
740
+ suppressedFindings: suppressionsResult.suppressed,
741
+ verifications: Array.from(verifications.values())
430
742
  });
431
743
  }
744
+ /**
745
+ * Projects the capability matrix onto the older `toolStatuses` / `skippedTools` /
746
+ * `completeness` shapes, which the reporters, agent plan, and MCP tools consume.
747
+ * The matrix is the source of truth; these are views of it.
748
+ */
749
+ function deriveLegacyStatuses(matrix, config) {
750
+ const toolStatuses = [];
751
+ const skippedTools = [];
752
+ for (const tool of matrix.tools) {
753
+ if (tool.state === "not_installed" || tool.state === "runtime_incompatible" || tool.state === "deferred") {
754
+ skippedTools.push({ id: tool.id, status: "skipped", installHint: tool.remediation });
755
+ continue;
756
+ }
757
+ if (tool.state === "not_applicable" || tool.state === "disabled" || tool.state === "not_selected") {
758
+ continue;
759
+ }
760
+ toolStatuses.push({
761
+ id: tool.id,
762
+ status: tool.state === "timed_out" ? "timeout" : tool.state === "failed" ? "error" : "ok",
763
+ message: tool.state === "completed" ? undefined : tool.reason,
764
+ command: tool.command
765
+ });
766
+ }
767
+ const gaps = matrix.tools.filter(capability_1.isCoverageGap).map((tool) => tool.id);
768
+ const planned = matrix.tools.filter((tool) => tool.planned).length;
769
+ return {
770
+ toolStatuses,
771
+ skippedTools,
772
+ completeness: {
773
+ status: gaps.length === 0
774
+ ? "complete"
775
+ : matrix.requiredGaps.length > 0 || config.runtime.failOnIncompleteScan
776
+ ? "invalid"
777
+ : "partial",
778
+ comparable: gaps.length === 0,
779
+ planned,
780
+ completed: Math.max(0, planned - gaps.length),
781
+ incompleteTools: gaps,
782
+ requiredIncompleteTools: matrix.requiredGaps,
783
+ reason: gaps.length > 0 ? `${gaps.length} of ${planned} planned checks did not fully complete.` : undefined
784
+ }
785
+ };
786
+ }
432
787
  async function retryTool(root, toolId, timeoutSeconds) {
433
788
  const { config } = await (0, config_1.loadConfig)(root);
434
789
  const project = await (0, projectDetector_1.detectProject)(root, config.paths.exclude);
@@ -495,6 +850,9 @@ function buildRecoveryActions(toolStatuses, skippedTools = []) {
495
850
  }));
496
851
  return [...failed, ...skipped];
497
852
  }
853
+ function categoryScopeNote(categories) {
854
+ return `Counted across the whole scan, not only the ${categories.join(", ")} findings shown here.`;
855
+ }
498
856
  function filterScanByCategories(scan, categories, options = {}) {
499
857
  const findings = sortFindings(scan.findings.filter((finding) => categories.includes(finding.category)));
500
858
  const score = (0, scoring_1.buildScore)(findings);
@@ -510,7 +868,24 @@ function filterScanByCategories(scan, categories, options = {}) {
510
868
  policy: options.policy,
511
869
  target: options.target ?? scan.agentPlan.target,
512
870
  configPath: scan.configPath,
513
- privacyReview: scan.privacyReview
871
+ privacyReview: scan.privacyReview,
872
+ // The matrix describes the scan, not the filtered view, so it carries over
873
+ // unchanged apart from the surfaced counts, which now reflect the filter.
874
+ capabilityMatrix: {
875
+ ...scan.capabilityMatrix,
876
+ tools: scan.capabilityMatrix.tools.map((tool) => ({
877
+ ...tool,
878
+ findingsSurfaced: findings.filter((finding) => finding.source === tool.id).length
879
+ }))
880
+ },
881
+ // Filtering and acknowledgement counts were computed over the whole scan and
882
+ // cannot be re-attributed here (a withheld finding is no longer around to be
883
+ // categorised), so they are carried over and labelled as scan-wide rather
884
+ // than presented as totals for the categories on screen.
885
+ relevance: { ...scan.relevance, scopeNote: categoryScopeNote(categories) },
886
+ suppressions: { ...scan.suppressions, scopeNote: categoryScopeNote(categories) },
887
+ suppressedFindings: scan.suppressedFindings.filter((finding) => categories.includes(finding.category)),
888
+ verifications: scan.verifications
514
889
  });
515
890
  }
516
891
  function buildSummaryLines(scan) {
@@ -559,14 +934,20 @@ function buildSummaryLines(scan) {
559
934
  lines.push("", "DEAD CHAINS");
560
935
  scan.deadCodeCandidates.forEach((finding, index) => lines.push(`${index + 1}. ${finding.message}`));
561
936
  }
562
- if (scan.skippedTools.length > 0) {
563
- lines.push("", "SKIPPED TOOLS");
564
- scan.skippedTools.forEach((tool, index) => lines.push(`${index + 1}. ${tool.id}${tool.installHint ? ` — ${tool.installHint}` : ""}`));
937
+ // One table replaces the old "skipped tools" and "errored tools" lists. Those
938
+ // could not distinguish a tool that was never applicable from one that timed
939
+ // out mid-scan, and said nothing about how much of the repository was covered.
940
+ const matrixLines = (0, capability_1.renderCapabilityMatrixLines)(scan.capabilityMatrix);
941
+ if (matrixLines.length > 0) {
942
+ lines.push("", "TOOL COVERAGE", ...matrixLines);
943
+ }
944
+ const relevanceLines = (0, relevance_1.renderRelevanceLines)(scan.relevance);
945
+ if (relevanceLines.length > 0) {
946
+ lines.push("", "REPORT FILTERING", ...relevanceLines);
565
947
  }
566
- const erroredTools = scan.toolStatuses.filter((tool) => tool.status === "error" || tool.status === "timeout");
567
- if (erroredTools.length > 0) {
568
- lines.push("", "ERRORED TOOLS");
569
- erroredTools.forEach((tool, index) => lines.push(`${index + 1}. ${tool.id}${tool.message ? ` — ${tool.message}` : ` — ${tool.status}`}`));
948
+ const suppressionLines = (0, suppressions_1.renderSuppressionLines)(scan.suppressions);
949
+ if (suppressionLines.length > 0) {
950
+ lines.push("", "ACKNOWLEDGED", ...suppressionLines);
570
951
  }
571
952
  if (scan.recoveryActions.length > 0) {
572
953
  lines.push("", "RECOVER BEFORE EDITING");
@@ -0,0 +1,18 @@
1
+ export declare function getPathKey(env: NodeJS.ProcessEnv): string;
2
+ export declare function getLocalToolSearchPaths(cwd: string | undefined): string[];
3
+ export declare function buildCommandEnv(cwd: string | undefined, overrides: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv;
4
+ export type ResolvedExecutable = {
5
+ /** Absolute path to the file that will actually be launched. */
6
+ path: string;
7
+ /** True when the resolved file must be launched through a shell (.cmd/.bat). */
8
+ requiresShell: boolean;
9
+ };
10
+ /**
11
+ * Resolves a command name to a concrete file, searching the same augmented PATH
12
+ * the scanner uses. Returns undefined when nothing on PATH matches — callers
13
+ * should treat that as "not installed" and report the searched locations.
14
+ */
15
+ export declare function resolveExecutable(command: string, cwd?: string, env?: NodeJS.ProcessEnv): ResolvedExecutable | undefined;
16
+ export declare function commandExists(command: string, cwd?: string): boolean;
17
+ /** The directories searched, so a "not found" report can say where we looked. */
18
+ export declare function describeSearchPaths(cwd?: string): string[];