@neuralaxis/vibedoctor 0.2.1 → 0.3.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 (57) hide show
  1. package/README.md +70 -24
  2. package/dist/adapters/biome.js +3 -2
  3. package/dist/adapters/flowDoctor.d.ts +7 -0
  4. package/dist/adapters/flowDoctor.js +195 -0
  5. package/dist/adapters/gitleaks.js +17 -3
  6. package/dist/adapters/index.d.ts +1 -0
  7. package/dist/adapters/index.js +3 -1
  8. package/dist/adapters/osvScanner.js +4 -2
  9. package/dist/adapters/ruff.js +17 -4
  10. package/dist/adapters/shared.d.ts +4 -0
  11. package/dist/cli/commands/init.js +7 -0
  12. package/dist/cli/commands/scan.d.ts +9 -1
  13. package/dist/cli/commands/scan.js +37 -3
  14. package/dist/cli/index.js +40 -11
  15. package/dist/core/agentDiagnosis.d.ts +39 -0
  16. package/dist/core/agentDiagnosis.js +96 -0
  17. package/dist/core/config.d.ts +11 -0
  18. package/dist/core/config.js +31 -2
  19. package/dist/core/engine.d.ts +8 -1
  20. package/dist/core/engine.js +73 -51
  21. package/dist/core/executable.js +14 -6
  22. package/dist/core/executionPolicy.d.ts +55 -0
  23. package/dist/core/executionPolicy.js +144 -0
  24. package/dist/core/finding.d.ts +1 -1
  25. package/dist/core/finding.js +8 -3
  26. package/dist/core/findingCorrelator.d.ts +19 -0
  27. package/dist/core/findingCorrelator.js +112 -0
  28. package/dist/core/findingNormalizer.js +1 -0
  29. package/dist/core/git.d.ts +2 -0
  30. package/dist/core/git.js +26 -1
  31. package/dist/core/managedTools.d.ts +25 -0
  32. package/dist/core/managedTools.js +186 -0
  33. package/dist/core/repoGraph.d.ts +62 -0
  34. package/dist/core/repoGraph.js +408 -0
  35. package/dist/core/riskRanker.d.ts +6 -0
  36. package/dist/core/riskRanker.js +127 -0
  37. package/dist/core/scanContext.d.ts +26 -0
  38. package/dist/core/scanContext.js +44 -0
  39. package/dist/core/scanPlanner.d.ts +1 -0
  40. package/dist/core/scanPlanner.js +18 -6
  41. package/dist/core/toolRegistry.js +12 -5
  42. package/dist/core/toolRunner.d.ts +4 -0
  43. package/dist/core/toolRunner.js +28 -3
  44. package/dist/core/toolRuntime.d.ts +40 -0
  45. package/dist/core/toolRuntime.js +417 -0
  46. package/dist/core/toolVerification.d.ts +3 -1
  47. package/dist/core/toolVerification.js +58 -3
  48. package/dist/index.d.ts +5 -0
  49. package/dist/index.js +5 -0
  50. package/dist/integration/envelope.d.ts +72 -0
  51. package/dist/integration/envelope.js +61 -0
  52. package/dist/integration/sourceFingerprint.d.ts +21 -0
  53. package/dist/integration/sourceFingerprint.js +68 -0
  54. package/dist/reporters/agent.d.ts +1 -1
  55. package/dist/reporters/agent.js +7 -0
  56. package/package.json +81 -80
  57. package/schemas/machine-envelope.v1.schema.json +92 -0
package/dist/cli/index.js CHANGED
@@ -20,6 +20,7 @@ const report_1 = require("./commands/report");
20
20
  const scan_1 = require("./commands/scan");
21
21
  const setup_1 = require("./commands/setup");
22
22
  const tool_1 = require("./commands/tool");
23
+ const executionPolicy_1 = require("../core/executionPolicy");
23
24
  function getVersion() {
24
25
  try {
25
26
  // After `npm version patch` + publish, package.json is shipped (see "files").
@@ -47,19 +48,47 @@ async function main() {
47
48
  });
48
49
  program
49
50
  .command("scan")
50
- .description("Run relevant checks and print a short health report")
51
- .option("--changed", "Only report changed-file issues")
52
- .option("--quick", "Quick mode")
53
- .option("--full", "Full mode")
51
+ .description("Run the full applicable diagnosis and print a ranked health report")
52
+ .option("--changed", "Optimize for git-changed files")
53
+ .option("--quick", "Narrower opt-in profile")
54
+ .option("--full", "Alias for the default full applicable diagnosis")
54
55
  .option("--category <categories>", "Comma-separated finding categories")
55
- .option("--report <format>", "terminal|json|html|agent|agent-json", "terminal")
56
+ .option("--report <format>", "terminal|json|html|agent|agent-json|envelope", "terminal")
57
+ .option("--root <dir>", "Repository to scan (default: the current directory)")
58
+ .option("--profile <name>", "default|static|trusted. static runs only external read-only analysers: no project-local tools, tests, executable project config or network", "default")
59
+ .option("--allow-network", "Allow network-backed tools (Semgrep registry, OSV) under --profile static|trusted")
56
60
  .action(async (options) => {
57
- const result = await (0, scan_1.runScanCommand)(process.cwd(), options);
58
- process.stdout.write(result.output);
59
- // Force exit: some child processes / native tool wrappers (especially on Windows)
60
- // can leave event-loop handles open even after 'close'. Explicit exit guarantees
61
- // the CLI terminates promptly for terminals and CI after printing the report.
62
- process.exit(result.exitCode);
61
+ const root = node_path_1.default.resolve(options.root ?? process.cwd());
62
+ if (!["default", "static", "trusted"].includes(options.profile)) {
63
+ process.stderr.write(`Unknown --profile "${options.profile}". Use default, static or trusted.\n`);
64
+ process.exit(64);
65
+ }
66
+ if (!node_fs_1.default.existsSync(root) || !node_fs_1.default.statSync(root).isDirectory()) {
67
+ process.stderr.write(`--root is not a directory: ${root}\n`);
68
+ process.exit(64);
69
+ }
70
+ const profile = options.profile;
71
+ const scan = () => (0, scan_1.runScanCommand)(root, { ...options, version: getVersion() });
72
+ let result;
73
+ try {
74
+ result =
75
+ profile === "default"
76
+ ? await scan()
77
+ : await (0, executionPolicy_1.withExecutionPolicy)((0, executionPolicy_1.profilePolicy)(profile, { targetRoot: root, allowNetwork: Boolean(options.allowNetwork) }), scan);
78
+ }
79
+ catch (error) {
80
+ // In envelope mode a crash produces no envelope and a distinct exit code (70), so a
81
+ // caller never mistakes it for a completed scan whose policy gate failed (1).
82
+ if (options.report === "envelope") {
83
+ process.stderr.write(`vibedoctor: scan failed: ${error instanceof Error ? error.message : String(error)}\n`);
84
+ process.exit(70);
85
+ }
86
+ throw error;
87
+ }
88
+ // Force exit once stdout has flushed: some child processes / native tool wrappers
89
+ // (especially on Windows) can leave event-loop handles open even after 'close', and
90
+ // exiting before a large piped write drains would truncate the report.
91
+ process.stdout.write(result.output, () => process.exit(result.exitCode));
63
92
  });
64
93
  program
65
94
  .command("setup")
@@ -0,0 +1,39 @@
1
+ import type { AgentPlan, RecoveryAction, ScanCompleteness, ScanOutput, ToolStatusSummary } from "./engine";
2
+ import type { EvidenceGrade, Finding, FindingCategory, Severity, Confidence } from "./finding";
3
+ import { type FindingLocation, type RootCauseGroup } from "./findingCorrelator";
4
+ export type AgentIssue = {
5
+ id: string;
6
+ ruleId: string;
7
+ title: string;
8
+ severity: Severity;
9
+ confidence: Confidence;
10
+ evidenceGrade: EvidenceGrade;
11
+ category: FindingCategory;
12
+ locations: FindingLocation[];
13
+ impact: string;
14
+ likelyRootCause: string;
15
+ supportingEngines: string[];
16
+ recommendedRepair: string;
17
+ verificationGuidance: string;
18
+ };
19
+ export type AgentDiagnosisSummary = {
20
+ score: number;
21
+ mode: ScanOutput["mode"];
22
+ planned: number;
23
+ completed: number;
24
+ findingCount: number;
25
+ blockerCount: number;
26
+ topIssueCount: number;
27
+ };
28
+ export type AgentDiagnosis = {
29
+ completeness: ScanCompleteness;
30
+ summary: AgentDiagnosisSummary;
31
+ topIssues: AgentIssue[];
32
+ rootCauseGroups: RootCauseGroup[];
33
+ toolStatuses: ToolStatusSummary[];
34
+ recoveryActions: RecoveryAction[];
35
+ recommendedOrder: string[];
36
+ agentPlan: AgentPlan;
37
+ };
38
+ export declare function findingToAgentIssue(finding: Finding, testCommands?: string[]): AgentIssue;
39
+ export declare function buildAgentDiagnosis(scan: ScanOutput): AgentDiagnosis;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findingToAgentIssue = findingToAgentIssue;
4
+ exports.buildAgentDiagnosis = buildAgentDiagnosis;
5
+ const findingCorrelator_1 = require("./findingCorrelator");
6
+ const riskRanker_1 = require("./riskRanker");
7
+ function describeImpact(finding) {
8
+ if (finding.category === "security") {
9
+ return "Credentials or vulnerable dependencies can be exploited if this reaches a shared or deployed tree.";
10
+ }
11
+ if (finding.source === "flow-doctor") {
12
+ return "A request or error path does not match the implemented contract, so the feature can fail at runtime.";
13
+ }
14
+ if (finding.category === "correctness" || finding.category === "tests") {
15
+ return "Type, lint, or test evidence indicates the code may not behave as written.";
16
+ }
17
+ if (finding.category === "privacy") {
18
+ return "Personal data may be handled without a visible control.";
19
+ }
20
+ if (finding.category === "dead_code" || finding.category === "leftovers") {
21
+ return "Unused or leftover code increases review cost and hides real defects.";
22
+ }
23
+ return finding.message;
24
+ }
25
+ function recommendedRepair(finding) {
26
+ if (finding.remediation?.steps.length) {
27
+ return finding.remediation.steps.join(" ");
28
+ }
29
+ if (finding.agentInstruction) {
30
+ return finding.agentInstruction;
31
+ }
32
+ if (finding.fixCommand) {
33
+ return `Apply: ${finding.fixCommand}`;
34
+ }
35
+ return finding.message;
36
+ }
37
+ function verificationGuidance(finding, testCommands) {
38
+ const test = testCommands[0];
39
+ const parts = [
40
+ finding.file ? `Re-read ${finding.file}${finding.startLine ? `:${finding.startLine}` : ""} after the edit.` : undefined,
41
+ test ? `Run \`${test}\`.` : undefined,
42
+ "Run `vibedoctor scan --changed --report agent-json` and confirm this finding id is gone."
43
+ ];
44
+ return parts.filter(Boolean).join(" ");
45
+ }
46
+ function findingToAgentIssue(finding, testCommands = []) {
47
+ return {
48
+ id: finding.id,
49
+ ruleId: finding.evidence?.toolRawId ?? finding.title,
50
+ title: finding.title,
51
+ severity: finding.severity,
52
+ confidence: finding.confidence,
53
+ evidenceGrade: finding.evidenceGrade ?? "observed",
54
+ category: finding.category,
55
+ locations: [{ file: finding.file, startLine: finding.startLine, endLine: finding.endLine }],
56
+ impact: describeImpact(finding),
57
+ likelyRootCause: (0, findingCorrelator_1.inferRootCause)(finding),
58
+ supportingEngines: Array.from(new Set([finding.source, ...(finding.corroboratedBy ?? [])])),
59
+ recommendedRepair: recommendedRepair(finding),
60
+ verificationGuidance: verificationGuidance(finding, testCommands)
61
+ };
62
+ }
63
+ function buildAgentDiagnosis(scan) {
64
+ const ranked = (0, riskRanker_1.rankFindings)(scan.findings);
65
+ const groups = (0, findingCorrelator_1.correlateFindings)(ranked);
66
+ const topFindings = ranked.slice(0, 8);
67
+ const topIssues = topFindings.map((finding) => {
68
+ const group = groups.find((candidate) => candidate.findingIds.includes(finding.id));
69
+ const issue = findingToAgentIssue(finding, scan.testCommands);
70
+ if (group) {
71
+ issue.supportingEngines = group.supportingEngines;
72
+ issue.likelyRootCause = group.likelyRootCause;
73
+ issue.locations = group.locations;
74
+ }
75
+ return issue;
76
+ });
77
+ const recommendedOrder = topIssues.map((issue) => issue.id);
78
+ return {
79
+ completeness: scan.completeness,
80
+ summary: {
81
+ score: scan.score.overall,
82
+ mode: scan.mode,
83
+ planned: scan.completeness.planned,
84
+ completed: scan.completeness.completed,
85
+ findingCount: scan.findings.length,
86
+ blockerCount: scan.blockers.length,
87
+ topIssueCount: topIssues.length
88
+ },
89
+ topIssues,
90
+ rootCauseGroups: groups,
91
+ toolStatuses: scan.toolStatuses,
92
+ recoveryActions: scan.recoveryActions,
93
+ recommendedOrder,
94
+ agentPlan: scan.agentPlan
95
+ };
96
+ }
@@ -36,6 +36,14 @@ export type VibeDoctorConfig = {
36
36
  deferredTools: string[];
37
37
  /** Verify each tool resolves and runs before trusting its absence of findings. */
38
38
  verifyToolsBeforeScan: boolean;
39
+ /** Resolve/provision engines into a VibeDoctor-owned cache instead of mutating the repo. */
40
+ managedTools: {
41
+ enabled: boolean;
42
+ /** Override for ~/.cache/vibedoctor. */
43
+ cacheDir?: string;
44
+ allowNetwork: boolean;
45
+ preferProjectLocal: boolean;
46
+ };
39
47
  };
40
48
  relevance: {
41
49
  enabled: boolean;
@@ -120,6 +128,9 @@ export type VibeDoctorConfig = {
120
128
  enabled: boolean;
121
129
  };
122
130
  };
131
+ flowAnalysis: {
132
+ enabled: boolean;
133
+ };
123
134
  dpdp: {
124
135
  enabled: boolean;
125
136
  include: string[];
@@ -62,7 +62,12 @@ exports.defaultConfig = {
62
62
  onTimeout: "scoped_retry",
63
63
  scopedRetryTimeoutSeconds: 60,
64
64
  deferredTools: [],
65
- verifyToolsBeforeScan: true
65
+ verifyToolsBeforeScan: true,
66
+ managedTools: {
67
+ enabled: true,
68
+ allowNetwork: true,
69
+ preferProjectLocal: true
70
+ }
66
71
  },
67
72
  relevance: {
68
73
  enabled: true,
@@ -141,6 +146,9 @@ exports.defaultConfig = {
141
146
  enabled: true
142
147
  }
143
148
  },
149
+ flowAnalysis: {
150
+ enabled: true
151
+ },
144
152
  dpdp: {
145
153
  enabled: true,
146
154
  include: [],
@@ -284,6 +292,7 @@ function normalizeRawConfig(raw) {
284
292
  const rawPrivacy = rawChecks?.privacy;
285
293
  const rawPrivacyAi = (rawPrivacy?.ai ?? {});
286
294
  const rawPresidio = (rawPrivacy?.presidio ?? {});
295
+ const rawFlow = (rawChecks?.flowAnalysis ?? rawChecks?.flow_analysis);
287
296
  const rawDpdp = rawChecks?.dpdp;
288
297
  const rawDpdpOrg = (rawDpdp?.organization ?? rawDpdp?.organisation ?? {});
289
298
  return {
@@ -313,7 +322,8 @@ function normalizeRawConfig(raw) {
313
322
  deferredTools: normalizeStringArray(rawRuntime.deferredTools ?? rawRuntime.deferred_tools, exports.defaultConfig.runtime.deferredTools),
314
323
  verifyToolsBeforeScan: rawRuntime.verifyToolsBeforeScan ??
315
324
  rawRuntime.verify_tools_before_scan ??
316
- exports.defaultConfig.runtime.verifyToolsBeforeScan
325
+ exports.defaultConfig.runtime.verifyToolsBeforeScan,
326
+ managedTools: normalizeManagedTools(rawRuntime.managedTools ?? rawRuntime.managed_tools)
317
327
  }
318
328
  }
319
329
  : {}),
@@ -492,6 +502,11 @@ function normalizeRawConfig(raw) {
492
502
  }
493
503
  }
494
504
  : exports.defaultConfig.checks.privacy,
505
+ flowAnalysis: rawFlow
506
+ ? {
507
+ enabled: rawFlow.enabled ?? exports.defaultConfig.checks.flowAnalysis.enabled
508
+ }
509
+ : exports.defaultConfig.checks.flowAnalysis,
495
510
  dpdp: rawDpdp
496
511
  ? {
497
512
  enabled: rawDpdp.enabled ?? exports.defaultConfig.checks.dpdp.enabled,
@@ -536,6 +551,20 @@ function normalizeRawConfig(raw) {
536
551
  : {})
537
552
  };
538
553
  }
554
+ function normalizeManagedTools(raw) {
555
+ const defaults = exports.defaultConfig.runtime.managedTools;
556
+ if (!isRecord(raw)) {
557
+ return { ...defaults };
558
+ }
559
+ return {
560
+ enabled: raw.enabled ?? defaults.enabled,
561
+ cacheDir: raw.cacheDir ?? raw.cache_dir ?? defaults.cacheDir,
562
+ allowNetwork: raw.allowNetwork ?? raw.allow_network ?? defaults.allowNetwork,
563
+ preferProjectLocal: raw.preferProjectLocal ??
564
+ raw.prefer_project_local ??
565
+ defaults.preferProjectLocal
566
+ };
567
+ }
539
568
  function normalizeTriState(value, fallback) {
540
569
  if (value === true || value === "true" || value === "yes") {
541
570
  return "true";
@@ -1,3 +1,4 @@
1
+ import { type AgentDiagnosis } from "./agentDiagnosis";
1
2
  import { type AgentPolicy } from "../agentPack/policy";
2
3
  import { type Finding, type FindingCategory } from "./finding";
3
4
  import { type ScanMode } from "./scanPlanner";
@@ -8,6 +9,8 @@ import { type RelevanceReport } from "./relevance";
8
9
  import { type SuppressionReport } from "./suppressions";
9
10
  import { type ToolVerification } from "./toolVerification";
10
11
  import { type PrivacyReviewSummary } from "./privacyReview";
12
+ declare const ALL_ADAPTERS: readonly [import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter, import("../adapters/shared").ToolAdapter];
13
+ export declare function getScanAdapters(): typeof ALL_ADAPTERS;
11
14
  export type AgentPlanTarget = "generic" | "codex" | "copilot" | "claude" | "cursor";
12
15
  export type AgentPlanTask = {
13
16
  id: string;
@@ -89,6 +92,8 @@ export type ScanOutput = {
89
92
  suppressedFindings: Finding[];
90
93
  /** Tool-by-tool proof of what resolved and ran, with paths and versions. */
91
94
  verifications: ToolVerification[];
95
+ /** Agent-first diagnosis: correlated, ranked, actionable. Present on live scans. */
96
+ diagnosis?: AgentDiagnosis;
92
97
  };
93
98
  export type SafeFixResult = {
94
99
  before: ScanOutput;
@@ -129,7 +134,9 @@ export declare function createAgentPlan(scan: Pick<ScanOutput, "findings" | "sco
129
134
  policy?: AgentPolicy;
130
135
  target?: AgentPlanTarget;
131
136
  }): AgentPlan;
132
- export declare function runScan(root: string, mode?: ScanMode): Promise<ScanOutput>;
137
+ export declare function runScan(root: string, mode?: ScanMode, options?: {
138
+ runtimeOptions?: import("./toolRuntime").ToolRuntimeOptions;
139
+ }): Promise<ScanOutput>;
133
140
  export declare function retryTool(root: string, toolId: string, timeoutSeconds?: number): Promise<ToolRetryOutput>;
134
141
  export declare function filterScanByCategories(scan: ScanOutput, categories: FindingCategory[], options?: FilterScanOptions): ScanOutput;
135
142
  export declare function buildSummaryLines(scan: ScanOutput): string[];
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getScanAdapters = getScanAdapters;
3
4
  exports.withReportingDefaults = withReportingDefaults;
4
5
  exports.createAgentPlan = createAgentPlan;
5
6
  exports.runScan = runScan;
@@ -15,6 +16,10 @@ const privacyDetector_1 = require("../adapters/privacyDetector");
15
16
  const dpdp_1 = require("../adapters/dpdp");
16
17
  const customRefactor_1 = require("../adapters/customRefactor");
17
18
  const customDeadChain_1 = require("../adapters/customDeadChain");
19
+ const flowDoctor_1 = require("../adapters/flowDoctor");
20
+ const agentDiagnosis_1 = require("./agentDiagnosis");
21
+ const riskRanker_1 = require("./riskRanker");
22
+ const scanContext_1 = require("./scanContext");
18
23
  const presidio_1 = require("../adapters/presidio");
19
24
  const policy_1 = require("../agentPack/policy");
20
25
  const baseline_1 = require("./baseline");
@@ -32,6 +37,7 @@ const relevance_1 = require("./relevance");
32
37
  const suppressions_1 = require("./suppressions");
33
38
  const toolRegistry_1 = require("./toolRegistry");
34
39
  const toolVerification_1 = require("./toolVerification");
40
+ const executionPolicy_1 = require("./executionPolicy");
35
41
  const privacyReview_1 = require("./privacyReview");
36
42
  const ALL_ADAPTERS = [
37
43
  adapters_1.gitleaksAdapter,
@@ -55,20 +61,12 @@ const ALL_ADAPTERS = [
55
61
  presidio_1.presidioAdapter,
56
62
  adapters_1.telemetryDetectorAdapter,
57
63
  customLeftovers_1.customLeftoversAdapter,
58
- customRefactor_1.customRefactorAdapter
64
+ customRefactor_1.customRefactorAdapter,
65
+ flowDoctor_1.flowDoctorAdapter
59
66
  ];
60
- const categoryPriority = {
61
- security: 0,
62
- tests: 1,
63
- correctness: 2,
64
- dependencies: 3,
65
- privacy: 4,
66
- dead_code: 5,
67
- leftovers: 6,
68
- refactor_readiness: 7,
69
- maintainability: 8,
70
- efficiency: 9
71
- };
67
+ function getScanAdapters() {
68
+ return ALL_ADAPTERS;
69
+ }
72
70
  const emptyRelevanceReport = {
73
71
  enabled: false,
74
72
  perTool: [],
@@ -132,36 +130,12 @@ function withReportingDefaults(partial) {
132
130
  relevance: partial.relevance ?? emptyRelevanceReport,
133
131
  suppressions: partial.suppressions ?? emptySuppressionReport,
134
132
  suppressedFindings: partial.suppressedFindings ?? [],
135
- verifications: partial.verifications ?? []
133
+ verifications: partial.verifications ?? [],
134
+ diagnosis: partial.diagnosis
136
135
  };
137
136
  }
138
137
  function sortFindings(findings) {
139
- return [...findings].sort((left, right) => {
140
- const categoryDelta = categoryPriority[left.category] - categoryPriority[right.category];
141
- if (categoryDelta !== 0) {
142
- return categoryDelta;
143
- }
144
- const severityDelta = severityMap_1.severityRank[right.severity] - severityMap_1.severityRank[left.severity];
145
- if (severityDelta !== 0) {
146
- return severityDelta;
147
- }
148
- if (left.isNew !== right.isNew) {
149
- return left.isNew ? -1 : 1;
150
- }
151
- const fileDelta = (left.file ?? "").localeCompare(right.file ?? "");
152
- if (fileDelta !== 0) {
153
- return fileDelta;
154
- }
155
- const lineDelta = (left.startLine ?? 0) - (right.startLine ?? 0);
156
- if (lineDelta !== 0) {
157
- return lineDelta;
158
- }
159
- const titleDelta = left.title.localeCompare(right.title);
160
- if (titleDelta !== 0) {
161
- return titleDelta;
162
- }
163
- return left.id.localeCompare(right.id);
164
- });
138
+ return (0, riskRanker_1.rankFindings)(findings);
165
139
  }
166
140
  function summarizeFindings(findings) {
167
141
  const ordered = sortFindings(findings);
@@ -301,7 +275,7 @@ function buildScanOutput(options) {
301
275
  const summary = summarizeFindings(options.findings);
302
276
  const policy = options.policy ?? policy_1.defaultAgentPolicy;
303
277
  const recoveryActions = buildRecoveryActions(options.toolStatuses, options.skippedTools);
304
- return {
278
+ const output = {
305
279
  root: options.root,
306
280
  mode: options.mode,
307
281
  score: options.score,
@@ -335,6 +309,8 @@ function buildScanOutput(options) {
335
309
  suppressedFindings: options.suppressedFindings,
336
310
  verifications: options.verifications
337
311
  };
312
+ output.diagnosis = (0, agentDiagnosis_1.buildAgentDiagnosis)(output);
313
+ return output;
338
314
  }
339
315
  function firstUsefulLine(value) {
340
316
  return value
@@ -391,6 +367,21 @@ function narrowContextToFiles(ctx, files) {
391
367
  function commandText(command) {
392
368
  return [command.cmd, ...command.args].join(" ");
393
369
  }
370
+ /** A verification miss is still a result DPDP can reuse instead of launching the same missing tool again. */
371
+ function skippedForVerification(adapter, verification) {
372
+ return {
373
+ findings: [],
374
+ status: {
375
+ command: adapter.id,
376
+ stdout: "",
377
+ stderr: verification.reason,
378
+ exitCode: null,
379
+ durationMs: 0,
380
+ status: "skipped",
381
+ installHint: verification.remediation ?? adapter.installHint
382
+ }
383
+ };
384
+ }
394
385
  async function runAdapter(adapter, ctx, deadline) {
395
386
  if (adapter.runStandalone) {
396
387
  return adapter.runStandalone(ctx);
@@ -490,12 +481,12 @@ async function retryWithNarrowedScope(adapter, ctx, originalTimeoutSeconds) {
490
481
  * because the scan is about to invoke each tool anyway. `vibedoctor setup` does
491
482
  * the same work at `execute` depth, where there is no later run to rely on.
492
483
  */
493
- async function verifySelectedTools(root, adapterIds, config) {
484
+ async function verifySelectedTools(root, adapterIds, config, toolRuntime) {
494
485
  const entries = adapterIds.map(toolRegistry_1.getToolEntry).filter((entry) => Boolean(entry));
495
486
  if (!config.runtime.verifyToolsBeforeScan || entries.length === 0) {
496
487
  return new Map();
497
488
  }
498
- const verifications = await (0, toolVerification_1.verifyTools)(entries, root, "resolve");
489
+ const verifications = await (0, toolVerification_1.verifyTools)(entries, root, "resolve", toolRuntime);
499
490
  return new Map(verifications.map((verification) => [verification.id, verification]));
500
491
  }
501
492
  /** Derives the capability state for a tool that was selected and attempted. */
@@ -563,13 +554,32 @@ function reasonForCapability(id, state, run, verification, normalizationNote) {
563
554
  return { reason: "Did not run." };
564
555
  }
565
556
  }
566
- async function runScan(root, mode = "default") {
557
+ async function runScan(root, mode = "default", options) {
567
558
  const [{ config, configPath }, { policy }] = await Promise.all([(0, config_1.loadConfig)(root), (0, policy_1.loadAgentPolicy)(root)]);
568
- const project = await (0, projectDetector_1.detectProject)(root, config.paths.exclude);
559
+ // An integration execution profile outranks the target's configuration: repository settings
560
+ // cannot re-enable project-local tools, downloads, or DPDP's own Presidio/Semgrep launches.
561
+ const execution = (0, executionPolicy_1.currentPolicy)();
562
+ let runtimeOptions = options?.runtimeOptions;
563
+ if (execution.profile !== "default") {
564
+ config.runtime.managedTools.preferProjectLocal = execution.allowProjectLocalTools;
565
+ config.runtime.managedTools.allowNetwork = execution.allowNetwork;
566
+ if (!execution.allowProjectExecution) {
567
+ config.checks.dpdp.usePresidio = false;
568
+ if (!execution.allowNetwork)
569
+ config.checks.dpdp.useSemgrep = false;
570
+ }
571
+ runtimeOptions = {
572
+ ...runtimeOptions,
573
+ preferProjectLocal: execution.allowProjectLocalTools,
574
+ allowNetwork: execution.allowNetwork
575
+ };
576
+ }
577
+ const scanContext = await (0, scanContext_1.buildScanContext)(root, config, mode, runtimeOptions);
578
+ const project = scanContext.repo;
569
579
  const plan = await (0, scanPlanner_1.createScanPlan)(project, config, [...ALL_ADAPTERS], mode);
570
- const ctx = { root, project, config, scanMode: mode };
580
+ const ctx = { root, project, config, scanMode: mode, toolRuntime: scanContext.toolRuntime, scanContext };
571
581
  const selectedAdapters = ALL_ADAPTERS.filter((adapter) => plan.adapterIds.includes(adapter.id));
572
- const verifications = await verifySelectedTools(root, plan.adapterIds, config);
582
+ const verifications = await verifySelectedTools(root, plan.adapterIds, config, scanContext.toolRuntime);
573
583
  // A tool that failed verification is not launched: doing so produces a
574
584
  // confusing process error in place of the clear reason we already have.
575
585
  const runnableAdapters = selectedAdapters.filter((adapter) => {
@@ -582,7 +592,17 @@ async function runScan(root, mode = "default") {
582
592
  // findings/status instead of launching duplicate Semgrep and Presidio processes.
583
593
  const adapterResults = await Promise.all(independentAdapters.map(async (adapter) => ({ adapter, result: await runAdapter(adapter, ctx, deadline) })));
584
594
  if (runnableAdapters.some((adapter) => adapter.id === "dpdp")) {
585
- const sharedToolResults = Object.fromEntries(adapterResults.map(({ adapter, result }) => [adapter.id, result]));
595
+ const blockedShares = selectedAdapters
596
+ .filter((adapter) => adapter.id !== "dpdp" && !runnableAdapters.includes(adapter))
597
+ .map((adapter) => {
598
+ const verification = verifications.get(adapter.id);
599
+ return verification ? [adapter.id, skippedForVerification(adapter, verification)] : undefined;
600
+ })
601
+ .filter((entry) => Boolean(entry));
602
+ const sharedToolResults = Object.fromEntries([
603
+ ...adapterResults.map(({ adapter, result }) => [adapter.id, result]),
604
+ ...blockedShares
605
+ ]);
586
606
  const dpdpCtx = { ...ctx, sharedToolResults };
587
607
  adapterResults.push({ adapter: dpdp_1.dpdpAdapter, result: await runAdapter(dpdp_1.dpdpAdapter, dpdpCtx, deadline) });
588
608
  }
@@ -667,7 +687,7 @@ async function runScan(root, mode = "default") {
667
687
  remediation: excluded.state === "deferred"
668
688
  ? `Remove ${excluded.id} from runtime.deferred_tools to run it again.`
669
689
  : excluded.state === "not_selected"
670
- ? "Run `vibedoctor scan --full` to include it."
690
+ ? "Run `vibedoctor scan` for the full applicable diagnosis."
671
691
  : undefined,
672
692
  trust: "authoritative"
673
693
  });
@@ -799,7 +819,8 @@ async function retryTool(root, toolId, timeoutSeconds) {
799
819
  nextAction: "Run vibedoctor scan --full --report agent-json and request human review if the tool remains incomplete."
800
820
  };
801
821
  }
802
- const ctx = { root, project, config, scanMode: "full" };
822
+ const scanContext = await (0, scanContext_1.buildScanContext)(root, config, "full");
823
+ const ctx = { root, project, config, scanMode: "full", toolRuntime: scanContext.toolRuntime, scanContext };
803
824
  const seconds = timeoutSeconds ?? Math.max(config.runtime.defaultTimeoutSeconds, (config.runtime.toolTimeouts[toolId] ?? config.runtime.defaultTimeoutSeconds) * 2);
804
825
  const command = adapter.buildScanCommand(ctx);
805
826
  command.timeoutMs = seconds * 1000;
@@ -989,7 +1010,8 @@ async function safeFix(root) {
989
1010
  const before = await runScan(root, "default");
990
1011
  const { config } = await (0, config_1.loadConfig)(root);
991
1012
  const project = await (0, projectDetector_1.detectProject)(root, config.paths.exclude);
992
- const ctx = { root, project, config, scanMode: "default" };
1013
+ const scanContext = await (0, scanContext_1.buildScanContext)(root, config, "default");
1014
+ const ctx = { root, project, config, scanMode: "default", toolRuntime: scanContext.toolRuntime, scanContext };
993
1015
  const fixableAdapters = ALL_ADAPTERS.filter((adapter) => adapter.buildFixCommand && adapter.detect);
994
1016
  const results = [];
995
1017
  for (const adapter of fixableAdapters) {
@@ -11,6 +11,7 @@ exports.commandExists = commandExists;
11
11
  exports.describeSearchPaths = describeSearchPaths;
12
12
  const node_path_1 = __importDefault(require("node:path"));
13
13
  const node_fs_1 = require("node:fs");
14
+ const executionPolicy_1 = require("./executionPolicy");
14
15
  /**
15
16
  * Executable discovery, shared by every code path that needs to know whether a
16
17
  * tool is usable.
@@ -72,12 +73,14 @@ function getUserToolSearchPaths(env) {
72
73
  return paths;
73
74
  }
74
75
  function buildCommandEnv(cwd, overrides) {
75
- const env = { ...process.env, ...overrides };
76
+ const policy = (0, executionPolicy_1.currentPolicy)();
77
+ // Integration profiles pass a minimal environment instead of inheriting every variable.
78
+ const env = { ...(0, executionPolicy_1.policyEnv)(process.env, policy), ...overrides };
76
79
  const pathKey = getPathKey(env);
77
80
  const existingPath = env[pathKey];
78
- env[pathKey] = [...getLocalToolSearchPaths(cwd), ...getUserToolSearchPaths(env), existingPath]
79
- .filter(Boolean)
80
- .join(node_path_1.default.delimiter);
81
+ const local = policy.allowProjectLocalTools ? getLocalToolSearchPaths(cwd) : [];
82
+ const entries = [...local, ...getUserToolSearchPaths(env), ...(existingPath ?? "").split(node_path_1.default.delimiter)].filter(Boolean);
83
+ env[pathKey] = (0, executionPolicy_1.allowedPathEntries)(entries, policy).join(node_path_1.default.delimiter);
81
84
  return env;
82
85
  }
83
86
  function isExecutableFile(candidate) {
@@ -106,8 +109,13 @@ function isExecutableFile(candidate) {
106
109
  * should treat that as "not installed" and report the searched locations.
107
110
  */
108
111
  function resolveExecutable(command, cwd, env = buildCommandEnv(cwd, undefined)) {
112
+ const policy = (0, executionPolicy_1.currentPolicy)();
113
+ // Nothing inside the target may be launched when project-local tools are not allowed.
114
+ const permitted = (candidate) => policy.allowProjectLocalTools || !policy.targetRoot || !(0, executionPolicy_1.isInside)(policy.targetRoot, candidate);
109
115
  if (node_path_1.default.isAbsolute(command)) {
110
- return isExecutableFile(command) ? { path: command, requiresShell: /\.(?:cmd|bat)$/i.test(command) } : undefined;
116
+ return isExecutableFile(command) && permitted(command)
117
+ ? { path: command, requiresShell: /\.(?:cmd|bat)$/i.test(command) }
118
+ : undefined;
111
119
  }
112
120
  const pathValue = env[getPathKey(env)] ?? "";
113
121
  const directories = pathValue.split(node_path_1.default.delimiter).filter(Boolean);
@@ -120,7 +128,7 @@ function resolveExecutable(command, cwd, env = buildCommandEnv(cwd, undefined))
120
128
  for (const directory of directories) {
121
129
  for (const extension of extensions) {
122
130
  const candidate = node_path_1.default.join(directory, `${command}${extension}`);
123
- if ((0, node_fs_1.existsSync)(candidate) && isExecutableFile(candidate)) {
131
+ if ((0, node_fs_1.existsSync)(candidate) && isExecutableFile(candidate) && permitted(candidate)) {
124
132
  return { path: candidate, requiresShell: /\.(?:cmd|bat)$/i.test(candidate) };
125
133
  }
126
134
  }