@neuralaxis/vibedoctor 0.2.0 → 0.2.2

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 (80) hide show
  1. package/README.md +135 -23
  2. package/dist/adapters/biome.js +136 -21
  3. package/dist/adapters/flowDoctor.d.ts +7 -0
  4. package/dist/adapters/flowDoctor.js +195 -0
  5. package/dist/adapters/gitleaks.js +4 -2
  6. package/dist/adapters/index.d.ts +1 -0
  7. package/dist/adapters/index.js +3 -1
  8. package/dist/adapters/osvScanner.js +140 -19
  9. package/dist/adapters/presidio.js +3 -1
  10. package/dist/adapters/ruff.js +7 -3
  11. package/dist/adapters/shared.d.ts +4 -0
  12. package/dist/cli/commands/init.js +112 -50
  13. package/dist/cli/commands/privacyReview.js +3 -4
  14. package/dist/cli/commands/scan.d.ts +6 -0
  15. package/dist/cli/commands/scan.js +16 -2
  16. package/dist/cli/commands/setup.d.ts +13 -17
  17. package/dist/cli/commands/setup.js +138 -200
  18. package/dist/cli/index.js +4 -4
  19. package/dist/core/agentDiagnosis.d.ts +39 -0
  20. package/dist/core/agentDiagnosis.js +96 -0
  21. package/dist/core/capability.d.ts +92 -0
  22. package/dist/core/capability.js +122 -0
  23. package/dist/core/config.d.ts +47 -0
  24. package/dist/core/config.js +134 -3
  25. package/dist/core/credentialHeuristics.d.ts +28 -0
  26. package/dist/core/credentialHeuristics.js +179 -0
  27. package/dist/core/engine.d.ts +29 -1
  28. package/dist/core/engine.js +510 -126
  29. package/dist/core/executable.d.ts +18 -0
  30. package/dist/core/executable.js +137 -0
  31. package/dist/core/fileRole.d.ts +24 -0
  32. package/dist/core/fileRole.js +125 -0
  33. package/dist/core/finding.d.ts +125 -1
  34. package/dist/core/finding.js +70 -8
  35. package/dist/core/findingCorrelator.d.ts +19 -0
  36. package/dist/core/findingCorrelator.js +112 -0
  37. package/dist/core/findingNormalizer.d.ts +33 -0
  38. package/dist/core/findingNormalizer.js +172 -0
  39. package/dist/core/managedTools.d.ts +25 -0
  40. package/dist/core/managedTools.js +186 -0
  41. package/dist/core/projectDetector.d.ts +13 -0
  42. package/dist/core/projectDetector.js +100 -15
  43. package/dist/core/relevance.d.ts +87 -0
  44. package/dist/core/relevance.js +367 -0
  45. package/dist/core/repoGraph.d.ts +62 -0
  46. package/dist/core/repoGraph.js +408 -0
  47. package/dist/core/riskRanker.d.ts +6 -0
  48. package/dist/core/riskRanker.js +127 -0
  49. package/dist/core/scanContext.d.ts +26 -0
  50. package/dist/core/scanContext.js +44 -0
  51. package/dist/core/scanPlanner.d.ts +13 -0
  52. package/dist/core/scanPlanner.js +66 -38
  53. package/dist/core/semverLite.d.ts +27 -0
  54. package/dist/core/semverLite.js +163 -0
  55. package/dist/core/suppressions.d.ts +96 -0
  56. package/dist/core/suppressions.js +302 -0
  57. package/dist/core/toolRegistry.d.ts +58 -0
  58. package/dist/core/toolRegistry.js +254 -0
  59. package/dist/core/toolRunner.d.ts +27 -2
  60. package/dist/core/toolRunner.js +79 -93
  61. package/dist/core/toolRuntime.d.ts +40 -0
  62. package/dist/core/toolRuntime.js +417 -0
  63. package/dist/core/toolVerification.d.ts +89 -0
  64. package/dist/core/toolVerification.js +425 -0
  65. package/dist/dpdp/collectors/optionalScanners.js +120 -30
  66. package/dist/dpdp/findings.d.ts +33 -3
  67. package/dist/dpdp/findings.js +191 -4
  68. package/dist/dpdp/scan.js +2 -2
  69. package/dist/dpdp/scoring.d.ts +14 -4
  70. package/dist/dpdp/scoring.js +34 -8
  71. package/dist/dpdp/types.d.ts +19 -1
  72. package/dist/index.d.ts +5 -0
  73. package/dist/index.js +5 -0
  74. package/dist/reporters/agent.d.ts +1 -1
  75. package/dist/reporters/agent.js +7 -0
  76. package/dist/reporters/html.js +57 -13
  77. package/dist/reporters/json.js +7 -1
  78. package/dist/reporters/markdown.js +46 -4
  79. package/dist/reporters/sarif.js +54 -5
  80. package/package.json +80 -80
@@ -6,12 +6,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.detectProject = detectProject;
7
7
  const node_fs_1 = require("node:fs");
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
- const node_child_process_1 = require("node:child_process");
10
- const node_util_1 = require("node:util");
11
9
  const git_1 = require("./git");
12
10
  const paths_1 = require("./paths");
13
- const toolRunner_1 = require("./toolRunner");
14
- const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
11
+ const executable_1 = require("./executable");
12
+ const toolRegistry_1 = require("./toolRegistry");
15
13
  const KNOWN_CONFIG_FILES = [
16
14
  "package.json",
17
15
  "tsconfig.json",
@@ -37,15 +35,14 @@ const KNOWN_CONFIG_FILES = [
37
35
  ];
38
36
  const KNOWN_LOCKFILES = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lockb", "uv.lock", "poetry.lock", "pdm.lock"];
39
37
  const KNOWN_TOOLS = ["ruff", "biome", "knip", "vulture", "gitleaks", "osv-scanner", "semgrep", "tsc", "pyright", "eslint", "jest", "vitest", "coverage"];
38
+ /**
39
+ * Availability uses the same resolution the scanner uses to launch tools.
40
+ * Shelling out to `where`/`which` answered a subtly different question — it
41
+ * ignored the local `node_modules/.bin` and virtualenv directories the scanner
42
+ * adds to PATH — so a tool could be "unavailable" here and run fine in a scan.
43
+ */
40
44
  async function commandExists(command, root) {
41
- const locator = process.platform === "win32" ? "where" : "which";
42
- try {
43
- await execFileAsync(locator, [command], { cwd: root, env: (0, toolRunner_1.buildCommandEnv)(root, undefined), windowsHide: true });
44
- return true;
45
- }
46
- catch {
47
- return false;
48
- }
45
+ return (0, executable_1.commandExists)(command, root);
49
46
  }
50
47
  function packageScriptCommand(packageManager, name) {
51
48
  if (packageManager === "pnpm") {
@@ -103,7 +100,89 @@ async function readPackageMetadata(root, packageManager) {
103
100
  if (pkg.workspaces) {
104
101
  frameworkHints.push("monorepo");
105
102
  }
106
- return { testCommands, frameworkHints };
103
+ return {
104
+ testCommands,
105
+ frameworkHints,
106
+ declaredDependencies: {
107
+ runtime: Object.keys(pkg.dependencies ?? {}),
108
+ dev: Object.keys(pkg.devDependencies ?? {}),
109
+ optional: Object.keys({ ...(pkg.optionalDependencies ?? {}), ...(pkg.peerDependencies ?? {}) })
110
+ }
111
+ };
112
+ }
113
+ /**
114
+ * Reads Python dependency declarations. Covers the shapes projects actually use:
115
+ * PEP 621 `project.dependencies`, PEP 735 `dependency-groups`, Poetry's groups,
116
+ * and plain requirements files.
117
+ */
118
+ async function readPythonDependencies(root, projectFiles) {
119
+ const runtime = new Set();
120
+ const dev = new Set();
121
+ function addSpec(target, spec) {
122
+ // Strip version constraints, extras, and markers to leave the package name.
123
+ const name = spec
124
+ .trim()
125
+ .replace(/^-[er]\s+/, "")
126
+ .split(/[\s;]/)[0]
127
+ .split(/[<>=!~[]/)[0]
128
+ .trim();
129
+ if (name && !name.startsWith("#") && !name.startsWith("-")) {
130
+ target.add(name.toLowerCase());
131
+ }
132
+ }
133
+ const pyproject = node_path_1.default.join(root, "pyproject.toml");
134
+ if (await (0, paths_1.pathExists)(pyproject)) {
135
+ const content = await node_fs_1.promises.readFile(pyproject, "utf8");
136
+ // A dependency-aware TOML parse is more than this needs: dependency arrays
137
+ // are flat lists of strings, and misreading one only costs scope precision.
138
+ for (const match of content.matchAll(/^\s*(dependencies|optional-dependencies|dev-dependencies)\s*=\s*\[([^\]]*)\]/gms)) {
139
+ const target = match[1] === "dependencies" ? runtime : dev;
140
+ for (const spec of match[2].split(",")) {
141
+ const quoted = /["']([^"']+)["']/.exec(spec);
142
+ if (quoted) {
143
+ addSpec(target, quoted[1]);
144
+ }
145
+ }
146
+ }
147
+ for (const match of content.matchAll(/^\s*\[(?:tool\.poetry\.group\.[\w-]+\.dependencies|dependency-groups)\]/gm)) {
148
+ // Group tables list one package per line after the header.
149
+ const start = match.index + match[0].length;
150
+ const block = content.slice(start).split(/^\s*\[/m)[0];
151
+ for (const line of block.split(/\r?\n/)) {
152
+ const entry = /^\s*([A-Za-z0-9_.-]+)\s*=/.exec(line);
153
+ if (entry) {
154
+ addSpec(dev, entry[1]);
155
+ }
156
+ }
157
+ }
158
+ }
159
+ for (const file of projectFiles.filter((candidate) => /(^|\/)requirements[\w.-]*\.txt$/i.test(candidate))) {
160
+ const target = /dev|test|lint|ci/i.test(file) ? dev : runtime;
161
+ try {
162
+ const content = await node_fs_1.promises.readFile(node_path_1.default.join(root, file), "utf8");
163
+ for (const line of content.split(/\r?\n/)) {
164
+ addSpec(target, line);
165
+ }
166
+ }
167
+ catch {
168
+ // Unreadable requirements file: scope stays unknown for its packages.
169
+ }
170
+ }
171
+ if (runtime.size === 0 && dev.size === 0) {
172
+ return undefined;
173
+ }
174
+ return { runtime: Array.from(runtime), dev: Array.from(dev), optional: [] };
175
+ }
176
+ function mergeDeclaredDependencies(...sources) {
177
+ const present = sources.filter((source) => Boolean(source));
178
+ if (present.length === 0) {
179
+ return undefined;
180
+ }
181
+ return {
182
+ runtime: Array.from(new Set(present.flatMap((source) => source.runtime))),
183
+ dev: Array.from(new Set(present.flatMap((source) => source.dev))),
184
+ optional: Array.from(new Set(present.flatMap((source) => source.optional)))
185
+ };
107
186
  }
108
187
  function isFrameworkEntryFile(file) {
109
188
  return (/^(?:src\/)?app\/(?:.+\/)?(?:page|layout|route|loading|error|global-error|not-found|default|template)\.(ts|tsx|js|jsx)$/.test(file) ||
@@ -161,7 +240,12 @@ async function detectProject(root, excludePatterns) {
161
240
  detectionFiles.some((file) => /(^|\/)tests?\//.test(file) && file.endsWith(".py"))) {
162
241
  packageMetadata.testCommands.push(pythonTestCommand(packageManagers));
163
242
  }
164
- const toolPairs = await Promise.all(KNOWN_TOOLS.map(async (tool) => [tool, await commandExists(tool, root)]));
243
+ // Probe every executable the registry knows about, not a hand-maintained
244
+ // subset. Tools missing from that subset always looked unavailable, so setup
245
+ // reinstalled them on every run and the scan could never confirm them.
246
+ const probeTargets = Array.from(new Set([...KNOWN_TOOLS, ...(0, toolRegistry_1.registryExecutables)()]));
247
+ const toolPairs = await Promise.all(probeTargets.map(async (tool) => [tool, await commandExists(tool, root)]));
248
+ const pythonDependencies = await readPythonDependencies(root, detectionFiles);
165
249
  const entryFiles = detectionFiles.filter((file) => /(^|\/)(main|index|app|server|cli)\.(ts|tsx|js|jsx|py)$/.test(file) || isFrameworkEntryFile(file) || file.endsWith("package.json"));
166
250
  return {
167
251
  root,
@@ -177,6 +261,7 @@ async function detectProject(root, excludePatterns) {
177
261
  toolsAvailable: Object.fromEntries(toolPairs),
178
262
  frameworkHints: Array.from(frameworkHints).sort(),
179
263
  entryFiles,
180
- projectFiles
264
+ projectFiles,
265
+ declaredDependencies: mergeDeclaredDependencies(packageMetadata.declaredDependencies, pythonDependencies)
181
266
  };
182
267
  }
@@ -0,0 +1,87 @@
1
+ import type { Confidence, EvidenceGrade, Finding } from "./finding";
2
+ /**
3
+ * Turns raw tool output into a report worth reading.
4
+ *
5
+ * Every scanner ships its own idea of what to report, and none of them know what
6
+ * else ran. The result was a report where a type-checker's 857 pre-existing
7
+ * findings, a dead-code detector's 12,060 low-confidence guesses, and three real
8
+ * secrets all arrived as one flat list — so the real items were unreachable.
9
+ *
10
+ * The controls here are uniform across tools rather than patched into each
11
+ * adapter: a confidence floor, awareness of what kind of file a finding sits in,
12
+ * validation of claims that a value is a credential, ranking that puts new and
13
+ * changed-code findings first, and a cap. Nothing is dropped silently: every
14
+ * filter records what it withheld and why, and that reaches the report.
15
+ */
16
+ export type RelevanceToolPolicy = {
17
+ minConfidence?: Confidence;
18
+ minEvidenceGrade?: EvidenceGrade;
19
+ /** 0 means no cap. */
20
+ maxFindings?: number;
21
+ /** Only surface findings another tool also reported. */
22
+ requireCorroboration?: boolean;
23
+ };
24
+ export type RelevanceConfig = {
25
+ enabled: boolean;
26
+ minConfidence: Confidence;
27
+ maxFindingsPerTool: number;
28
+ maxFindingsTotal: number;
29
+ /** What to do with findings in tests, fixtures, generated, and vendored files. */
30
+ syntheticFilePolicy: "keep" | "downgrade" | "drop";
31
+ /** Check that findings claiming to be credentials look like credentials. */
32
+ validateSecrets: boolean;
33
+ perTool: Record<string, RelevanceToolPolicy>;
34
+ };
35
+ export declare const defaultRelevanceConfig: RelevanceConfig;
36
+ /** Reasons a finding did not reach the report. Each one is disclosed, never silent. */
37
+ export type WithholdReason = "below_confidence_floor" | "below_evidence_floor" | "synthetic_file" | "not_corroborated" | "over_tool_cap" | "over_total_cap";
38
+ export type WithheldGroup = {
39
+ reason: WithholdReason;
40
+ count: number;
41
+ detail: string;
42
+ /** How to see the withheld findings if they are wanted. */
43
+ remediation: string;
44
+ };
45
+ export type ToolRelevance = {
46
+ tool: string;
47
+ reported: number;
48
+ surfaced: number;
49
+ withheld: WithheldGroup[];
50
+ /** Findings whose severity or confidence was adjusted rather than removed. */
51
+ adjusted: number;
52
+ };
53
+ export type RelevanceReport = {
54
+ enabled: boolean;
55
+ perTool: ToolRelevance[];
56
+ totalReported: number;
57
+ totalSurfaced: number;
58
+ /** Human-readable notes for the report footer. */
59
+ notes: string[];
60
+ /**
61
+ * Set when these totals describe a wider set of findings than the report they
62
+ * appear in (a category-filtered view), so the counts are not read as if they
63
+ * applied to the filtered slice.
64
+ */
65
+ scopeNote?: string;
66
+ };
67
+ /**
68
+ * Ranks a finding by how much it deserves a reader's attention. Severity leads,
69
+ * but a new finding in code the author just touched outranks an older, nominally
70
+ * more severe one they cannot act on right now.
71
+ */
72
+ export declare function computePriority(finding: Finding): number;
73
+ export type ApplyRelevanceOptions = {
74
+ root: string;
75
+ config: RelevanceConfig;
76
+ };
77
+ export type ApplyRelevanceResult = {
78
+ findings: Finding[];
79
+ report: RelevanceReport;
80
+ };
81
+ /**
82
+ * Applies relevance controls to the deduped finding set. Runs after dedupe so
83
+ * corroboration between tools is already recorded, and after the baseline so
84
+ * new-versus-existing can drive ranking.
85
+ */
86
+ export declare function applyRelevance(findings: Finding[], options: ApplyRelevanceOptions): Promise<ApplyRelevanceResult>;
87
+ export declare function renderRelevanceLines(report: RelevanceReport): string[];
@@ -0,0 +1,367 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.defaultRelevanceConfig = void 0;
7
+ exports.computePriority = computePriority;
8
+ exports.applyRelevance = applyRelevance;
9
+ exports.renderRelevanceLines = renderRelevanceLines;
10
+ const node_fs_1 = require("node:fs");
11
+ const node_path_1 = __importDefault(require("node:path"));
12
+ const credentialHeuristics_1 = require("./credentialHeuristics");
13
+ const fileRole_1 = require("./fileRole");
14
+ exports.defaultRelevanceConfig = {
15
+ enabled: true,
16
+ minConfidence: "low",
17
+ maxFindingsPerTool: 200,
18
+ maxFindingsTotal: 1000,
19
+ syntheticFilePolicy: "downgrade",
20
+ validateSecrets: true,
21
+ perTool: {
22
+ // Whole-repository dead-code guessing produces far more candidates than
23
+ // anyone can triage, and its own confidence percentage is the best available
24
+ // ranking signal. Report the defensible subset and say how many were held.
25
+ vulture: { minConfidence: "medium", maxFindings: 50 },
26
+ // Type-checkers report accumulated debt in full. The ranking below puts new
27
+ // and changed-file findings first; the cap keeps the tail out of the report.
28
+ pyright: { maxFindings: 150 },
29
+ tsc: { maxFindings: 150 },
30
+ // Duplication and complexity are advisory, and the top offenders are the
31
+ // only actionable ones.
32
+ jscpd: { maxFindings: 50 },
33
+ lizard: { maxFindings: 50 },
34
+ radon: { maxFindings: 50 }
35
+ }
36
+ };
37
+ const confidenceRank = { low: 0, medium: 1, high: 2 };
38
+ const severityRank = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
39
+ const evidenceGradeRank = { unproven: 0, heuristic: 1, observed: 2, verified: 3 };
40
+ const severityOrder = ["info", "low", "medium", "high", "critical"];
41
+ function downgradeSeverity(severity, steps = 1) {
42
+ return severityOrder[Math.max(0, severityRank[severity] - steps)];
43
+ }
44
+ class ToolLedger {
45
+ reported = 0;
46
+ adjusted = 0;
47
+ withheld = new Map();
48
+ record({ reason, detail, remediation }) {
49
+ const key = `${reason}:${detail}`;
50
+ const existing = this.withheld.get(key);
51
+ if (existing) {
52
+ existing.count += 1;
53
+ return;
54
+ }
55
+ this.withheld.set(key, { reason, count: 1, detail, remediation });
56
+ }
57
+ toResult(tool, surfaced) {
58
+ return {
59
+ tool,
60
+ reported: this.reported,
61
+ surfaced,
62
+ adjusted: this.adjusted,
63
+ withheld: Array.from(this.withheld.values()).sort((left, right) => right.count - left.count)
64
+ };
65
+ }
66
+ }
67
+ /**
68
+ * Ranks a finding by how much it deserves a reader's attention. Severity leads,
69
+ * but a new finding in code the author just touched outranks an older, nominally
70
+ * more severe one they cannot act on right now.
71
+ */
72
+ function computePriority(finding) {
73
+ let priority = severityRank[finding.severity] * 10;
74
+ priority += confidenceRank[finding.confidence] * 3;
75
+ priority += evidenceGradeRank[finding.evidenceGrade ?? "observed"] * 3;
76
+ if (finding.isNew) {
77
+ priority += 8;
78
+ }
79
+ if (finding.inChangedFile) {
80
+ priority += 6;
81
+ }
82
+ if (finding.baselineState === "resurfaced") {
83
+ priority += 5;
84
+ }
85
+ priority += Math.min(3, finding.corroboratedBy?.length ?? 0) * 4;
86
+ if (finding.fileRole && (0, fileRole_1.isSyntheticRole)(finding.fileRole)) {
87
+ priority -= 8;
88
+ }
89
+ if (finding.evidence?.reviewState === "false_positive") {
90
+ priority -= 20;
91
+ }
92
+ if (finding.isAutofixable && finding.safeToAutofix) {
93
+ priority += 2;
94
+ }
95
+ return priority;
96
+ }
97
+ function createLineReader(root) {
98
+ const cache = new Map();
99
+ return async (file, line) => {
100
+ if (!cache.has(file)) {
101
+ try {
102
+ cache.set(file, (await node_fs_1.promises.readFile(node_path_1.default.join(root, file), "utf8")).split(/\r?\n/));
103
+ }
104
+ catch {
105
+ cache.set(file, undefined);
106
+ }
107
+ }
108
+ return cache.get(file)?.[line - 1];
109
+ };
110
+ }
111
+ function isSecretClaim(finding) {
112
+ return (finding.tags.includes("secret") ||
113
+ finding.source === "gitleaks" ||
114
+ /secret|credential|api[- _]?key|token|password/i.test(finding.title));
115
+ }
116
+ /**
117
+ * Re-examines findings that claim to have found a credential. Scanners redact
118
+ * their own output, so the source line the finding points at is the only place
119
+ * the matched value can still be evaluated.
120
+ */
121
+ async function validateSecretClaim(finding, readLine) {
122
+ if (!finding.file || finding.startLine === undefined) {
123
+ return finding;
124
+ }
125
+ const line = await readLine(finding.file, finding.startLine);
126
+ const candidate = (0, credentialHeuristics_1.extractAssignedValue)(line);
127
+ const assessment = (0, credentialHeuristics_1.assessCredential)(candidate);
128
+ if (assessment.verdict === "credential" || assessment.verdict === "unknown") {
129
+ return assessment.verdict === "credential"
130
+ ? {
131
+ ...finding,
132
+ evidenceGrade: "verified",
133
+ evidence: {
134
+ ...finding.evidence,
135
+ rationale: assessment.reason,
136
+ confidenceScore: Number(assessment.entropy.toFixed(2))
137
+ }
138
+ }
139
+ : finding;
140
+ }
141
+ const isPlaceholder = assessment.verdict === "placeholder";
142
+ return {
143
+ ...finding,
144
+ // Still reported, because a scanner match is a fact worth showing — but not
145
+ // at a severity that implies a live credential is in the repository.
146
+ severity: isPlaceholder ? "info" : downgradeSeverity(finding.severity, 2),
147
+ confidence: "low",
148
+ evidenceGrade: "heuristic",
149
+ title: isPlaceholder ? `${finding.title} (placeholder value)` : `${finding.title} (likely not a credential)`,
150
+ message: `${finding.message} Contextual check: ${assessment.reason}`,
151
+ tags: Array.from(new Set([...finding.tags, "likely-false-positive"])),
152
+ evidence: {
153
+ ...finding.evidence,
154
+ reviewState: "false_positive",
155
+ rationale: assessment.reason,
156
+ maskedValue: (0, credentialHeuristics_1.maskValue)(candidate),
157
+ confidenceScore: Number(assessment.entropy.toFixed(2))
158
+ },
159
+ remediation: {
160
+ kind: "human_review",
161
+ steps: [
162
+ "Confirm the matched value is not a credential.",
163
+ `Add an acknowledgement for rule "${finding.title}" in .vibedoctor/suppressions.yml to stop reporting it.`
164
+ ],
165
+ requiredEvidence: "Confirmation that the value is an identifier rather than a credential."
166
+ }
167
+ };
168
+ }
169
+ function syntheticNote(role) {
170
+ switch (role) {
171
+ case "fixture":
172
+ return "test fixture";
173
+ case "test":
174
+ return "test file";
175
+ case "generated":
176
+ return "generated file";
177
+ case "vendor":
178
+ return "vendored dependency";
179
+ default:
180
+ return role;
181
+ }
182
+ }
183
+ /**
184
+ * Applies relevance controls to the deduped finding set. Runs after dedupe so
185
+ * corroboration between tools is already recorded, and after the baseline so
186
+ * new-versus-existing can drive ranking.
187
+ */
188
+ async function applyRelevance(findings, options) {
189
+ const { config } = options;
190
+ const ledgers = new Map();
191
+ function ledgerFor(tool) {
192
+ const existing = ledgers.get(tool);
193
+ if (existing) {
194
+ return existing;
195
+ }
196
+ const created = new ToolLedger();
197
+ ledgers.set(tool, created);
198
+ return created;
199
+ }
200
+ for (const finding of findings) {
201
+ ledgerFor(finding.source).reported += 1;
202
+ }
203
+ if (!config.enabled) {
204
+ const ranked = findings.map((finding) => ({ ...finding, priority: computePriority(finding) }));
205
+ return {
206
+ findings: ranked,
207
+ report: {
208
+ enabled: false,
209
+ perTool: Array.from(ledgers.entries()).map(([tool, ledger]) => ledger.toResult(tool, ranked.filter((finding) => finding.source === tool).length)),
210
+ totalReported: findings.length,
211
+ totalSurfaced: ranked.length,
212
+ notes: ["Relevance filtering is disabled; every finding every tool reported is included."]
213
+ }
214
+ };
215
+ }
216
+ const readLine = createLineReader(options.root);
217
+ const kept = [];
218
+ for (const original of findings) {
219
+ const policy = config.perTool[original.source] ?? {};
220
+ const ledger = ledgerFor(original.source);
221
+ let finding = original;
222
+ if (config.validateSecrets && isSecretClaim(finding)) {
223
+ const validated = await validateSecretClaim(finding, readLine);
224
+ if (validated !== finding) {
225
+ ledger.adjusted += 1;
226
+ finding = validated;
227
+ }
228
+ }
229
+ const role = finding.fileRole ?? "unknown";
230
+ if ((0, fileRole_1.isSyntheticRole)(role)) {
231
+ if (config.syntheticFilePolicy === "drop") {
232
+ ledger.record({
233
+ reason: "synthetic_file",
234
+ detail: `in a ${syntheticNote(role)}`,
235
+ remediation: "Set relevance.synthetic_file_policy: downgrade in vibedoctor.yml to include these."
236
+ });
237
+ continue;
238
+ }
239
+ if (config.syntheticFilePolicy === "downgrade") {
240
+ finding = {
241
+ ...finding,
242
+ severity: downgradeSeverity(finding.severity),
243
+ tags: Array.from(new Set([...finding.tags, `role:${role}`]))
244
+ };
245
+ ledger.adjusted += 1;
246
+ }
247
+ }
248
+ const floor = policy.minConfidence ?? config.minConfidence;
249
+ if (confidenceRank[finding.confidence] < confidenceRank[floor]) {
250
+ ledger.record({
251
+ reason: "below_confidence_floor",
252
+ detail: `${finding.confidence} confidence, below the ${floor} floor for ${finding.source}`,
253
+ remediation: `Lower relevance.per_tool.${finding.source}.min_confidence in vibedoctor.yml to see these.`
254
+ });
255
+ continue;
256
+ }
257
+ if (policy.minEvidenceGrade) {
258
+ const grade = finding.evidenceGrade ?? "observed";
259
+ if (evidenceGradeRank[grade] < evidenceGradeRank[policy.minEvidenceGrade]) {
260
+ ledger.record({
261
+ reason: "below_evidence_floor",
262
+ detail: `${grade} evidence, below the ${policy.minEvidenceGrade} floor for ${finding.source}`,
263
+ remediation: `Lower relevance.per_tool.${finding.source}.min_evidence_grade in vibedoctor.yml to see these.`
264
+ });
265
+ continue;
266
+ }
267
+ }
268
+ if (policy.requireCorroboration && (finding.corroboratedBy?.length ?? 0) === 0) {
269
+ ledger.record({
270
+ reason: "not_corroborated",
271
+ detail: `only ${finding.source} reported it, and ${finding.source} findings require corroboration`,
272
+ remediation: `Set relevance.per_tool.${finding.source}.require_corroboration: false in vibedoctor.yml to see these.`
273
+ });
274
+ continue;
275
+ }
276
+ kept.push({ ...finding, priority: computePriority(finding) });
277
+ }
278
+ // Cap per tool, keeping the highest-ranked. A cap is a reading-order decision,
279
+ // so what falls outside it is reported as a count rather than dropped quietly.
280
+ const byTool = new Map();
281
+ for (const finding of kept) {
282
+ const bucket = byTool.get(finding.source) ?? [];
283
+ bucket.push(finding);
284
+ byTool.set(finding.source, bucket);
285
+ }
286
+ const capped = [];
287
+ for (const [tool, bucket] of byTool) {
288
+ const limit = config.perTool[tool]?.maxFindings ?? config.maxFindingsPerTool;
289
+ bucket.sort((left, right) => (right.priority ?? 0) - (left.priority ?? 0));
290
+ if (limit > 0 && bucket.length > limit) {
291
+ const ledger = ledgerFor(tool);
292
+ for (let index = limit; index < bucket.length; index += 1) {
293
+ ledger.record({
294
+ reason: "over_tool_cap",
295
+ detail: `beyond the ${limit}-finding cap for ${tool}, ranked by severity, novelty, and evidence`,
296
+ remediation: `Raise relevance.per_tool.${tool}.max_findings in vibedoctor.yml, or run \`vibedoctor scan --category <category>\` to see the full set.`
297
+ });
298
+ }
299
+ capped.push(...bucket.slice(0, limit));
300
+ continue;
301
+ }
302
+ capped.push(...bucket);
303
+ }
304
+ capped.sort((left, right) => (right.priority ?? 0) - (left.priority ?? 0));
305
+ let surfaced = capped;
306
+ if (config.maxFindingsTotal > 0 && capped.length > config.maxFindingsTotal) {
307
+ for (const finding of capped.slice(config.maxFindingsTotal)) {
308
+ ledgerFor(finding.source).record({
309
+ reason: "over_total_cap",
310
+ detail: `beyond the ${config.maxFindingsTotal}-finding report cap`,
311
+ remediation: "Raise relevance.max_findings_total in vibedoctor.yml, or filter with `vibedoctor scan --category`."
312
+ });
313
+ }
314
+ surfaced = capped.slice(0, config.maxFindingsTotal);
315
+ }
316
+ const perTool = Array.from(ledgers.entries())
317
+ .map(([tool, ledger]) => ledger.toResult(tool, surfaced.filter((finding) => finding.source === tool).length))
318
+ .sort((left, right) => left.tool.localeCompare(right.tool));
319
+ return {
320
+ findings: surfaced,
321
+ report: {
322
+ enabled: true,
323
+ perTool,
324
+ totalReported: findings.length,
325
+ totalSurfaced: surfaced.length,
326
+ notes: buildRelevanceNotes(perTool)
327
+ }
328
+ };
329
+ }
330
+ function buildRelevanceNotes(perTool) {
331
+ const notes = [];
332
+ for (const tool of perTool) {
333
+ const withheldTotal = tool.withheld.reduce((sum, group) => sum + group.count, 0);
334
+ if (withheldTotal === 0) {
335
+ continue;
336
+ }
337
+ const breakdown = tool.withheld.map((group) => `${group.count} ${group.detail}`).join("; ");
338
+ notes.push(`${tool.tool}: showing ${tool.surfaced} of ${tool.reported} — withheld ${breakdown}.`);
339
+ }
340
+ return notes;
341
+ }
342
+ function renderRelevanceLines(report) {
343
+ if (!report.enabled) {
344
+ return ["Relevance filtering: disabled (all findings shown)."];
345
+ }
346
+ const withheld = report.totalReported - report.totalSurfaced;
347
+ if (withheld === 0 && report.perTool.every((tool) => tool.adjusted === 0)) {
348
+ return [];
349
+ }
350
+ const lines = [`Relevance: showing ${report.totalSurfaced} of ${report.totalReported} findings.`];
351
+ if (report.scopeNote) {
352
+ lines.push(`- ${report.scopeNote}`);
353
+ }
354
+ lines.push(...report.notes.map((note) => `- ${note}`));
355
+ const adjusted = report.perTool.filter((tool) => tool.adjusted > 0);
356
+ if (adjusted.length > 0) {
357
+ lines.push(`- Adjusted (severity or confidence changed after contextual checks): ${adjusted
358
+ .map((tool) => `${tool.tool} ${tool.adjusted}`)
359
+ .join(", ")}.`);
360
+ }
361
+ const remediations = Array.from(new Set(report.perTool.flatMap((tool) => tool.withheld.map((group) => group.remediation))));
362
+ if (remediations.length > 0) {
363
+ lines.push("To see withheld findings:");
364
+ lines.push(...remediations.map((remediation) => `- ${remediation}`));
365
+ }
366
+ return lines;
367
+ }
@@ -0,0 +1,62 @@
1
+ import type { FileIndex } from "./scanContext";
2
+ export type HttpCall = {
3
+ file: string;
4
+ line: number;
5
+ method: string;
6
+ /** False when fetch() had no visible method — do not guess GET. */
7
+ methodExplicit: boolean;
8
+ path: string;
9
+ dynamic: boolean;
10
+ absolute: boolean;
11
+ };
12
+ export type RouteDef = {
13
+ file: string;
14
+ line: number;
15
+ method: string;
16
+ path: string;
17
+ /** Simple identifier used as the handler, when one is visible. */
18
+ handler?: string;
19
+ /** True when the handler is `controllers.create` or similar — not statically bound. */
20
+ handlerMember?: boolean;
21
+ handlerFile?: string;
22
+ handlerLine?: number;
23
+ handlerExternal?: boolean;
24
+ };
25
+ export type ImportEdge = {
26
+ from: string;
27
+ specifier: string;
28
+ names: string[];
29
+ external: boolean;
30
+ };
31
+ export type SymbolDef = {
32
+ file: string;
33
+ name: string;
34
+ kind: "function" | "class" | "route" | "handler";
35
+ line: number;
36
+ exported: boolean;
37
+ };
38
+ export type CallSite = {
39
+ file: string;
40
+ callee: string;
41
+ line: number;
42
+ };
43
+ export type ErrorPath = {
44
+ file: string;
45
+ line: number;
46
+ kind: "empty_handler" | "success_after_failure";
47
+ detail: string;
48
+ };
49
+ export type RepoGraph = {
50
+ files: string[];
51
+ imports: ImportEdge[];
52
+ symbols: SymbolDef[];
53
+ calls: CallSite[];
54
+ httpCalls: HttpCall[];
55
+ routes: RouteDef[];
56
+ errorPaths: ErrorPath[];
57
+ };
58
+ export declare function normalizeRoutePath(raw: string): string;
59
+ export declare function pathsCompatible(left: string, right: string): boolean;
60
+ export declare function linkRepoGraph(graph: RepoGraph): RepoGraph;
61
+ export declare function buildRepoGraph(root: string, files: FileIndex | readonly string[]): Promise<RepoGraph>;
62
+ export declare function routeMatchesCall(call: HttpCall, route: RouteDef): boolean;