@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
@@ -3,113 +3,96 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getLocalToolSearchPaths = getLocalToolSearchPaths;
7
- exports.buildCommandEnv = buildCommandEnv;
6
+ exports.getLocalToolSearchPaths = exports.buildCommandEnv = void 0;
8
7
  exports.commandExistsOnWindowsPath = commandExistsOnWindowsPath;
8
+ exports.quoteForWindowsShell = quoteForWindowsShell;
9
9
  exports.runCommand = runCommand;
10
10
  exports.runCommands = runCommands;
11
11
  const node_path_1 = __importDefault(require("node:path"));
12
- const node_fs_1 = require("node:fs");
13
12
  const node_child_process_1 = require("node:child_process");
14
13
  const node_child_process_2 = require("node:child_process");
15
- const LOCAL_TOOL_PATHS = [
16
- ["node_modules", ".bin"],
17
- [".venv", "Scripts"],
18
- [".venv", "bin"],
19
- ["venv", "Scripts"],
20
- ["venv", "bin"]
21
- ];
22
- function ancestorDirs(startDir) {
23
- if (!startDir) {
24
- return [];
25
- }
26
- const dirs = [];
27
- let current = node_path_1.default.resolve(startDir);
28
- while (true) {
29
- dirs.push(current);
30
- const parent = node_path_1.default.dirname(current);
31
- if (parent === current) {
32
- return dirs;
33
- }
34
- current = parent;
35
- }
36
- }
37
- function getPathKey(env) {
38
- return Object.keys(env).find((key) => key.toLowerCase() === "path") ?? "PATH";
39
- }
40
- function getLocalToolSearchPaths(cwd) {
41
- const paths = ancestorDirs(cwd).flatMap((dir) => LOCAL_TOOL_PATHS.map((segments) => node_path_1.default.join(dir, ...segments)));
42
- return Array.from(new Set(paths));
14
+ const executable_1 = require("./executable");
15
+ Object.defineProperty(exports, "buildCommandEnv", { enumerable: true, get: function () { return executable_1.buildCommandEnv; } });
16
+ Object.defineProperty(exports, "getLocalToolSearchPaths", { enumerable: true, get: function () { return executable_1.getLocalToolSearchPaths; } });
17
+ const toolRuntime_1 = require("./toolRuntime");
18
+ function commandExistsOnWindowsPath(command, cwd) {
19
+ return (0, executable_1.resolveExecutable)(command, cwd) !== undefined;
43
20
  }
44
- function getUserToolSearchPaths(env) {
45
- const paths = [];
46
- if (process.platform === "win32" && env.APPDATA) {
47
- const pythonRoot = node_path_1.default.join(env.APPDATA, "Python");
48
- try {
49
- for (const entry of (0, node_fs_1.readdirSync)(pythonRoot, { withFileTypes: true })) {
50
- if (entry.isDirectory() && /^Python\d+$/i.test(entry.name)) {
51
- paths.push(node_path_1.default.join(pythonRoot, entry.name, "Scripts"));
52
- }
53
- }
54
- }
55
- catch {
56
- // Python user packages have not been installed for this account.
21
+ function resolveLaunchTarget(command, cwd, env) {
22
+ const resolved = (0, executable_1.resolveExecutable)(command, cwd, env);
23
+ if (resolved) {
24
+ if (resolved.requiresShell) {
25
+ // cmd.exe scripts must run through the shell; quote the resolved path so
26
+ // directories with spaces (e.g. "Program Files") do not break parsing.
27
+ return {
28
+ command: resolved.path.includes(" ") ? `"${resolved.path}"` : resolved.path,
29
+ useShell: true,
30
+ resolvedPath: resolved.path
31
+ };
57
32
  }
33
+ return { command: resolved.path, useShell: false, resolvedPath: resolved.path };
58
34
  }
59
- else if (env.HOME) {
60
- paths.push(node_path_1.default.join(env.HOME, ".local", "bin"));
35
+ if (process.platform === "win32" && !node_path_1.default.isAbsolute(command)) {
36
+ // Not found via PATH/PATHEXT probing. Fall back to the shell so commands that
37
+ // are only reachable through cmd.exe mechanisms (App Execution Aliases,
38
+ // App Paths registry entries) still launch, matching the previous behavior.
39
+ return { command, useShell: true };
61
40
  }
62
- return paths;
63
- }
64
- function buildCommandEnv(cwd, overrides) {
65
- const env = { ...process.env, ...overrides };
66
- const pathKey = getPathKey(env);
67
- const existingPath = env[pathKey];
68
- env[pathKey] = [...getLocalToolSearchPaths(cwd), ...getUserToolSearchPaths(env), existingPath].filter(Boolean).join(node_path_1.default.delimiter);
69
- return env;
41
+ return { command, useShell: false };
70
42
  }
71
- function findWindowsCommandOnPath(command, env) {
72
- const pathValue = env[getPathKey(env)] ?? "";
73
- const extensions = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
74
- .split(";")
75
- .map((extension) => extension.toLowerCase());
76
- for (const directory of pathValue.split(node_path_1.default.delimiter).filter(Boolean)) {
77
- for (const extension of extensions) {
78
- const candidate = node_path_1.default.join(directory, `${command}${extension}`);
79
- if ((0, node_fs_1.existsSync)(candidate)) {
80
- return candidate;
81
- }
82
- }
83
- }
84
- return undefined;
85
- }
86
- function commandExistsOnWindowsPath(command, cwd) {
87
- return findWindowsCommandOnPath(command, buildCommandEnv(cwd, undefined)) !== undefined;
88
- }
89
- function resolveWindowsCommand(command, env) {
90
- if (process.platform !== "win32" || node_path_1.default.isAbsolute(command) || node_path_1.default.extname(command)) {
91
- return { command, useShell: false };
43
+ /**
44
+ * Quotes one argument for a cmd.exe command line.
45
+ *
46
+ * Node's `shell: true` joins the command and arguments with spaces and hands the
47
+ * result to cmd.exe verbatim (the behaviour deprecated as DEP0190), so an
48
+ * argument containing a space, a quote, or a shell metacharacter — a repository
49
+ * path under "Program Files", a glob, a rule id with a pipe — arrives split or
50
+ * partly interpreted by the shell. Arguments with nothing special in them are
51
+ * left exactly as they were, so this only changes the cases that were broken.
52
+ */
53
+ function quoteForWindowsShell(argument) {
54
+ if (argument === "") {
55
+ return '""';
92
56
  }
93
- const candidate = findWindowsCommandOnPath(command, env);
94
- if (candidate) {
95
- if (/\.(?:cmd|bat)$/i.test(candidate)) {
96
- // cmd.exe scripts must run through the shell; quote the resolved path so
97
- // directories with spaces (e.g. "Program Files") do not break parsing.
98
- return { command: candidate.includes(" ") ? `"${candidate}"` : candidate, useShell: true };
99
- }
100
- return { command: candidate, useShell: false };
57
+ if (!/[\s"&|<>^()%!]/.test(argument)) {
58
+ return argument;
101
59
  }
102
- // Not found via PATH/PATHEXT probing. Fall back to the shell so commands that
103
- // are only reachable through cmd.exe mechanisms (App Execution Aliases,
104
- // App Paths registry entries) still launch, matching the previous behavior.
105
- return { command, useShell: true };
60
+ // Double any backslashes that precede a quote or end the argument, so the
61
+ // receiving program's argv parser sees them as literal backslashes.
62
+ const escaped = argument.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1");
63
+ // Quoting stops cmd.exe interpreting &, |, <, >, ^ and parentheses, but %VAR%
64
+ // still expands inside quotes and has no in-quote escape, so each % is moved
65
+ // outside the quoted run where a caret does escape it.
66
+ return `"${escaped}"`.split("%").join('"^%"');
106
67
  }
107
68
  async function runCommand(spec, installHint) {
108
69
  const startedAt = Date.now();
109
- const env = buildCommandEnv(spec.cwd, spec.env);
110
- const resolved = resolveWindowsCommand(spec.cmd, env);
70
+ if (spec.tool) {
71
+ const runtime = spec.runtime ?? (0, toolRuntime_1.createToolRuntime)({ projectRoot: spec.cwd });
72
+ const resolvedTool = await runtime.resolve(spec.tool, { projectRoot: spec.cwd });
73
+ if (!resolvedTool.executablePath) {
74
+ const failedHard = resolvedTool.status === "checksum_mismatch" || resolvedTool.status === "failed";
75
+ return {
76
+ command: [spec.tool, ...spec.args].join(" "),
77
+ stdout: "",
78
+ stderr: resolvedTool.reason,
79
+ exitCode: null,
80
+ durationMs: Date.now() - startedAt,
81
+ status: failedHard ? "error" : "skipped",
82
+ installHint: resolvedTool.remediation ?? installHint
83
+ };
84
+ }
85
+ spec = { ...spec, cmd: resolvedTool.executablePath };
86
+ }
87
+ const env = (0, executable_1.buildCommandEnv)(spec.cwd, spec.env);
88
+ const resolved = resolveLaunchTarget(spec.cmd, spec.cwd, env);
89
+ // Build the shell command line here instead of letting spawn concatenate the
90
+ // arguments for us, which it does without any escaping.
91
+ const launch = resolved.useShell
92
+ ? { command: [resolved.command, ...spec.args.map(quoteForWindowsShell)].join(" "), args: [] }
93
+ : { command: resolved.command, args: spec.args };
111
94
  return new Promise((resolve) => {
112
- const child = (0, node_child_process_1.spawn)(resolved.command, spec.args, {
95
+ const child = (0, node_child_process_1.spawn)(launch.command, launch.args, {
113
96
  cwd: spec.cwd,
114
97
  env,
115
98
  shell: resolved.useShell,
@@ -155,7 +138,8 @@ async function runCommand(spec, installHint) {
155
138
  exitCode: null,
156
139
  durationMs: Date.now() - startedAt,
157
140
  status: /ENOENT|not recognized/i.test(error.message) ? "skipped" : "error",
158
- installHint
141
+ installHint,
142
+ resolvedPath: resolved.resolvedPath
159
143
  });
160
144
  });
161
145
  child.on("close", (exitCode) => {
@@ -175,7 +159,8 @@ async function runCommand(spec, installHint) {
175
159
  : /not recognized|not found|is not installed|no such file/i.test(stderr)
176
160
  ? "skipped"
177
161
  : "error",
178
- installHint
162
+ installHint,
163
+ resolvedPath: resolved.resolvedPath
179
164
  });
180
165
  });
181
166
  if (spec.timeoutMs) {
@@ -201,7 +186,8 @@ async function runCommand(spec, installHint) {
201
186
  exitCode: null,
202
187
  durationMs: Date.now() - startedAt,
203
188
  status: "timeout",
204
- installHint
189
+ installHint,
190
+ resolvedPath: resolved.resolvedPath
205
191
  });
206
192
  }, spec.timeoutMs);
207
193
  }
@@ -0,0 +1,40 @@
1
+ import { isManagedTool, type ManagedToolSpec } from "./managedTools";
2
+ export type ToolResolutionStatus = "resolved" | "not_found" | "checksum_mismatch" | "unsupported_platform" | "failed";
3
+ export type ToolResolutionSource = "project-local" | "managed" | "path";
4
+ export type ToolResolution = {
5
+ tool: string;
6
+ status: ToolResolutionStatus;
7
+ source?: ToolResolutionSource;
8
+ version?: string;
9
+ executablePath?: string;
10
+ cachePath?: string;
11
+ reusedCache: boolean;
12
+ reason: string;
13
+ remediation?: string;
14
+ };
15
+ export type ToolRuntimeOptions = {
16
+ cacheDir?: string;
17
+ projectRoot?: string;
18
+ enabled?: boolean;
19
+ allowNetwork?: boolean;
20
+ preferProjectLocal?: boolean;
21
+ allowPathFallback?: boolean;
22
+ /** Test/advanced: replace the catalog for a tool. */
23
+ catalog?: Record<string, ManagedToolSpec>;
24
+ /** Test: copy this local file instead of downloading. */
25
+ localArtifacts?: Record<string, string>;
26
+ fetchArtifact?: (url: string, destFile: string) => Promise<void>;
27
+ };
28
+ export type ToolRuntime = {
29
+ readonly cacheDir: string;
30
+ resolve(tool: string, options?: {
31
+ projectRoot?: string;
32
+ }): Promise<ToolResolution>;
33
+ };
34
+ export declare const DOWNLOAD_TIMEOUT_MS = 45000;
35
+ export declare const MAX_DOWNLOAD_BYTES: number;
36
+ export declare function defaultToolCacheDir(): string;
37
+ export declare function createToolRuntime(options?: ToolRuntimeOptions): ToolRuntime;
38
+ export declare function isProjectLocalPath(candidate: string, projectRoot: string | undefined): boolean;
39
+ export declare function sha256File(filePath: string): Promise<string>;
40
+ export { isManagedTool };
@@ -0,0 +1,417 @@
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.isManagedTool = exports.MAX_DOWNLOAD_BYTES = exports.DOWNLOAD_TIMEOUT_MS = void 0;
7
+ exports.defaultToolCacheDir = defaultToolCacheDir;
8
+ exports.createToolRuntime = createToolRuntime;
9
+ exports.isProjectLocalPath = isProjectLocalPath;
10
+ exports.sha256File = sha256File;
11
+ const node_crypto_1 = require("node:crypto");
12
+ const node_child_process_1 = require("node:child_process");
13
+ const node_fs_1 = require("node:fs");
14
+ const node_https_1 = __importDefault(require("node:https"));
15
+ const node_os_1 = __importDefault(require("node:os"));
16
+ const node_path_1 = __importDefault(require("node:path"));
17
+ const executable_1 = require("./executable");
18
+ const managedTools_1 = require("./managedTools");
19
+ Object.defineProperty(exports, "isManagedTool", { enumerable: true, get: function () { return managedTools_1.isManagedTool; } });
20
+ exports.DOWNLOAD_TIMEOUT_MS = 45_000;
21
+ exports.MAX_DOWNLOAD_BYTES = 80 * 1024 * 1024;
22
+ const MANIFEST_NAME = "manifest.json";
23
+ function defaultToolCacheDir() {
24
+ if (process.env.VIBEDOCTOR_TOOL_CACHE) {
25
+ return process.env.VIBEDOCTOR_TOOL_CACHE;
26
+ }
27
+ return node_path_1.default.join(node_os_1.default.homedir(), ".cache", "vibedoctor");
28
+ }
29
+ function envAllowsNetwork() {
30
+ const value = process.env.VIBEDOCTOR_ALLOW_NETWORK;
31
+ if (value === "0" || value === "false") {
32
+ return false;
33
+ }
34
+ return true;
35
+ }
36
+ function createToolRuntime(options = {}) {
37
+ const cacheDir = options.cacheDir ?? defaultToolCacheDir();
38
+ const managedEnabled = options.enabled ?? true;
39
+ const allowNetwork = (options.allowNetwork ?? true) && envAllowsNetwork();
40
+ const preferProjectLocal = options.preferProjectLocal ?? true;
41
+ const allowPathFallback = options.allowPathFallback ?? true;
42
+ const catalog = options.catalog;
43
+ const localArtifacts = options.localArtifacts ?? {};
44
+ const fetchArtifact = options.fetchArtifact ?? downloadFile;
45
+ async function resolve(tool, resolveOptions = {}) {
46
+ const projectRoot = resolveOptions.projectRoot ?? options.projectRoot;
47
+ const spec = catalog?.[tool] ?? (0, managedTools_1.getManagedTool)(tool);
48
+ if (preferProjectLocal && projectRoot) {
49
+ const local = findProjectLocal(tool, projectRoot);
50
+ if (local) {
51
+ return {
52
+ tool,
53
+ status: "resolved",
54
+ source: "project-local",
55
+ version: spec?.version,
56
+ executablePath: local,
57
+ reusedCache: false,
58
+ reason: `Using project-local ${tool} at ${local}.`
59
+ };
60
+ }
61
+ }
62
+ if (spec && managedEnabled) {
63
+ const managed = await resolveManaged(spec);
64
+ if (managed.status === "resolved" || managed.status === "checksum_mismatch") {
65
+ return managed;
66
+ }
67
+ if (managed.status === "unsupported_platform") {
68
+ const fromPath = allowPathFallback
69
+ ? projectRoot
70
+ ? (0, executable_1.resolveExecutable)(tool, projectRoot)
71
+ : (0, executable_1.resolveExecutable)(tool)
72
+ : undefined;
73
+ if (fromPath) {
74
+ return {
75
+ tool,
76
+ status: "resolved",
77
+ source: "path",
78
+ executablePath: fromPath.path,
79
+ reusedCache: false,
80
+ reason: `No managed ${tool} artifact for this platform; using PATH at ${fromPath.path}.`
81
+ };
82
+ }
83
+ return managed;
84
+ }
85
+ const fromPath = allowPathFallback
86
+ ? projectRoot
87
+ ? (0, executable_1.resolveExecutable)(tool, projectRoot)
88
+ : (0, executable_1.resolveExecutable)(tool)
89
+ : undefined;
90
+ if (fromPath && !isProjectLocalPath(fromPath.path, projectRoot)) {
91
+ return {
92
+ tool,
93
+ status: "resolved",
94
+ source: "path",
95
+ version: spec.version,
96
+ executablePath: fromPath.path,
97
+ reusedCache: false,
98
+ reason: `Managed ${tool} was not available (${managed.reason}); using PATH at ${fromPath.path}.`
99
+ };
100
+ }
101
+ return managed;
102
+ }
103
+ const fromPath = projectRoot ? (0, executable_1.resolveExecutable)(tool, projectRoot) : (0, executable_1.resolveExecutable)(tool);
104
+ if (fromPath) {
105
+ return {
106
+ tool,
107
+ status: "resolved",
108
+ source: isProjectLocalPath(fromPath.path, projectRoot) ? "project-local" : "path",
109
+ executablePath: fromPath.path,
110
+ reusedCache: false,
111
+ reason: `Resolved ${tool} at ${fromPath.path}.`
112
+ };
113
+ }
114
+ return {
115
+ tool,
116
+ status: "not_found",
117
+ reusedCache: false,
118
+ reason: spec
119
+ ? `Managed ${tool} is disabled and ${tool} was not found on PATH.`
120
+ : `${tool} is not a managed engine and was not found on PATH.`,
121
+ remediation: `Install ${tool} or add a managed-tool entry for it.`
122
+ };
123
+ }
124
+ async function resolveManaged(spec) {
125
+ const platform = (0, managedTools_1.currentPlatformKey)();
126
+ const artifact = (0, managedTools_1.artifactFor)(spec, platform);
127
+ if (!artifact) {
128
+ return {
129
+ tool: spec.id,
130
+ status: "unsupported_platform",
131
+ version: spec.version,
132
+ reusedCache: false,
133
+ reason: `No managed ${spec.id} ${spec.version} artifact for platform ${platform}.`,
134
+ remediation: `Install ${spec.id} yourself, or run on a supported platform (win32-x64, darwin-arm64, linux-x64, …).`
135
+ };
136
+ }
137
+ const toolDir = node_path_1.default.join(cacheDir, "tools", spec.id, spec.version);
138
+ const binaryPath = node_path_1.default.join(toolDir, artifact.binary);
139
+ const cached = await readValidCache(spec, artifact, toolDir, binaryPath);
140
+ if (cached) {
141
+ return cached;
142
+ }
143
+ try {
144
+ await node_fs_1.promises.mkdir(toolDir, { recursive: true });
145
+ const staged = await stageArtifact(spec, artifact, toolDir);
146
+ const digest = await sha256File(staged.archivePath);
147
+ if (digest !== artifact.sha256.toLowerCase()) {
148
+ await rmQuiet(staged.archivePath);
149
+ return {
150
+ tool: spec.id,
151
+ status: "checksum_mismatch",
152
+ version: spec.version,
153
+ cachePath: toolDir,
154
+ reusedCache: false,
155
+ reason: `Checksum mismatch for managed ${spec.id} ${spec.version}: expected ${artifact.sha256}, got ${digest}. The file was not installed.`,
156
+ remediation: `Delete ${toolDir} and rerun the scan. If this persists, the download is corrupt or the catalog checksum is wrong.`
157
+ };
158
+ }
159
+ const executablePath = await materializeBinary(staged, artifact, toolDir, binaryPath);
160
+ await writeManifest(toolDir, {
161
+ tool: spec.id,
162
+ version: spec.version,
163
+ platform,
164
+ sha256: artifact.sha256,
165
+ binary: artifact.binary,
166
+ binarySha256: await sha256File(executablePath),
167
+ provisionedAt: new Date().toISOString()
168
+ });
169
+ if (staged.cleanup) {
170
+ await rmQuiet(staged.archivePath);
171
+ }
172
+ return {
173
+ tool: spec.id,
174
+ status: "resolved",
175
+ source: "managed",
176
+ version: spec.version,
177
+ executablePath,
178
+ cachePath: toolDir,
179
+ reusedCache: false,
180
+ reason: `Provisioned managed ${spec.id} ${spec.version} at ${executablePath}.`
181
+ };
182
+ }
183
+ catch (error) {
184
+ const message = error instanceof Error ? error.message : String(error);
185
+ return {
186
+ tool: spec.id,
187
+ status: /checksum/i.test(message) ? "checksum_mismatch" : "failed",
188
+ version: spec.version,
189
+ cachePath: toolDir,
190
+ reusedCache: false,
191
+ reason: `Could not provision managed ${spec.id} ${spec.version}: ${message}`,
192
+ remediation: allowNetwork
193
+ ? `Check network access to the artifact URL, or install ${spec.id} on PATH.`
194
+ : `Network is disabled. Provide a cached copy under ${toolDir} or a test artifact, or install ${spec.id} on PATH.`
195
+ };
196
+ }
197
+ }
198
+ async function readValidCache(spec, artifact, toolDir, binaryPath) {
199
+ try {
200
+ await node_fs_1.promises.access(binaryPath);
201
+ const manifest = await readManifest(toolDir);
202
+ if (!manifest || manifest.sha256.toLowerCase() !== artifact.sha256.toLowerCase()) {
203
+ return undefined;
204
+ }
205
+ if (manifest.binarySha256) {
206
+ const digest = await sha256File(binaryPath);
207
+ if (digest !== manifest.binarySha256.toLowerCase()) {
208
+ return undefined;
209
+ }
210
+ }
211
+ return {
212
+ tool: spec.id,
213
+ status: "resolved",
214
+ source: "managed",
215
+ version: spec.version,
216
+ executablePath: binaryPath,
217
+ cachePath: toolDir,
218
+ reusedCache: true,
219
+ reason: `Reused managed ${spec.id} ${spec.version} at ${binaryPath}.`
220
+ };
221
+ }
222
+ catch {
223
+ return undefined;
224
+ }
225
+ }
226
+ async function stageArtifact(spec, artifact, toolDir) {
227
+ const local = localArtifacts[spec.id];
228
+ if (local) {
229
+ const dest = node_path_1.default.join(toolDir, node_path_1.default.basename(local));
230
+ await node_fs_1.promises.copyFile(local, dest);
231
+ return { archivePath: dest, cleanup: artifact.archive !== "none" };
232
+ }
233
+ if (!allowNetwork) {
234
+ throw new Error(`Network is disabled and ${spec.id} ${spec.version} is not in the VibeDoctor cache (${toolDir}).`);
235
+ }
236
+ const fileName = node_path_1.default.basename(new URL(artifact.url).pathname) || `${spec.id}.bin`;
237
+ const dest = node_path_1.default.join(toolDir, fileName);
238
+ await fetchArtifact(artifact.url, dest);
239
+ return { archivePath: dest, cleanup: artifact.archive !== "none" };
240
+ }
241
+ return { cacheDir, resolve };
242
+ }
243
+ function findProjectLocal(tool, projectRoot) {
244
+ const resolved = (0, executable_1.resolveExecutable)(tool, projectRoot);
245
+ if (!resolved) {
246
+ return undefined;
247
+ }
248
+ return isProjectLocalPath(resolved.path, projectRoot) ? resolved.path : undefined;
249
+ }
250
+ function isProjectLocalPath(candidate, projectRoot) {
251
+ if (!projectRoot) {
252
+ return false;
253
+ }
254
+ const relative = node_path_1.default.relative(projectRoot, candidate);
255
+ if (!relative || relative.startsWith("..") || node_path_1.default.isAbsolute(relative)) {
256
+ return false;
257
+ }
258
+ return /(^|[/\\])(node_modules|\.venv|venv)([/\\]|$)/i.test(relative);
259
+ }
260
+ async function materializeBinary(staged, artifact, toolDir, binaryPath) {
261
+ if (artifact.archive === "none") {
262
+ if (node_path_1.default.resolve(staged.archivePath) !== node_path_1.default.resolve(binaryPath)) {
263
+ await node_fs_1.promises.copyFile(staged.archivePath, binaryPath);
264
+ }
265
+ if (process.platform !== "win32") {
266
+ await node_fs_1.promises.chmod(binaryPath, 0o755);
267
+ }
268
+ return binaryPath;
269
+ }
270
+ await extractArchive(staged.archivePath, toolDir, artifact.archive);
271
+ const found = await findExtractedBinary(toolDir, artifact.binary);
272
+ if (!found) {
273
+ throw new Error(`Archive extracted but ${artifact.binary} was not found in ${toolDir}.`);
274
+ }
275
+ if (node_path_1.default.resolve(found) !== node_path_1.default.resolve(binaryPath)) {
276
+ await node_fs_1.promises.copyFile(found, binaryPath);
277
+ }
278
+ if (process.platform !== "win32") {
279
+ await node_fs_1.promises.chmod(binaryPath, 0o755);
280
+ }
281
+ return binaryPath;
282
+ }
283
+ async function extractArchive(archivePath, destDir, kind) {
284
+ const args = kind === "tar.gz" ? ["-xzf", archivePath, "-C", destDir] : ["-xf", archivePath, "-C", destDir];
285
+ await new Promise((resolve, reject) => {
286
+ (0, node_child_process_1.execFile)("tar", args, { windowsHide: true }, (error, _stdout, stderr) => {
287
+ if (error) {
288
+ reject(new Error(stderr || error.message));
289
+ return;
290
+ }
291
+ resolve();
292
+ });
293
+ });
294
+ }
295
+ async function findExtractedBinary(dir, binary) {
296
+ const direct = node_path_1.default.join(dir, binary);
297
+ try {
298
+ await node_fs_1.promises.access(direct);
299
+ return direct;
300
+ }
301
+ catch {
302
+ // Search one level down — some archives wrap the binary in a folder.
303
+ }
304
+ const entries = await node_fs_1.promises.readdir(dir, { withFileTypes: true });
305
+ for (const entry of entries) {
306
+ if (entry.isDirectory()) {
307
+ const nested = node_path_1.default.join(dir, entry.name, binary);
308
+ try {
309
+ await node_fs_1.promises.access(nested);
310
+ return nested;
311
+ }
312
+ catch {
313
+ // keep looking
314
+ }
315
+ }
316
+ if (entry.isFile() && entry.name === binary) {
317
+ return node_path_1.default.join(dir, entry.name);
318
+ }
319
+ }
320
+ return undefined;
321
+ }
322
+ async function readManifest(toolDir) {
323
+ try {
324
+ return JSON.parse(await node_fs_1.promises.readFile(node_path_1.default.join(toolDir, MANIFEST_NAME), "utf8"));
325
+ }
326
+ catch {
327
+ return undefined;
328
+ }
329
+ }
330
+ async function writeManifest(toolDir, manifest) {
331
+ await node_fs_1.promises.writeFile(node_path_1.default.join(toolDir, MANIFEST_NAME), `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
332
+ }
333
+ async function sha256File(filePath) {
334
+ const hash = (0, node_crypto_1.createHash)("sha256");
335
+ const handle = await node_fs_1.promises.open(filePath, "r");
336
+ try {
337
+ const stream = handle.createReadStream();
338
+ for await (const chunk of stream) {
339
+ hash.update(chunk);
340
+ }
341
+ }
342
+ finally {
343
+ await handle.close();
344
+ }
345
+ return hash.digest("hex");
346
+ }
347
+ async function downloadFile(url, destFile) {
348
+ await node_fs_1.promises.mkdir(node_path_1.default.dirname(destFile), { recursive: true });
349
+ await new Promise((resolve, reject) => {
350
+ let settled = false;
351
+ const fail = (error) => {
352
+ if (settled) {
353
+ return;
354
+ }
355
+ settled = true;
356
+ reject(error);
357
+ };
358
+ const succeed = () => {
359
+ if (settled) {
360
+ return;
361
+ }
362
+ settled = true;
363
+ resolve();
364
+ };
365
+ const follow = (target, remaining) => {
366
+ if (!target.startsWith("https://")) {
367
+ fail(new Error(`Refusing non-HTTPS download: ${target}`));
368
+ return;
369
+ }
370
+ const request = node_https_1.default.get(target, { timeout: exports.DOWNLOAD_TIMEOUT_MS }, (response) => {
371
+ const status = response.statusCode ?? 0;
372
+ if (status >= 300 && status < 400 && response.headers.location && remaining > 0) {
373
+ response.resume();
374
+ follow(new URL(response.headers.location, target).toString(), remaining - 1);
375
+ return;
376
+ }
377
+ if (status !== 200) {
378
+ response.resume();
379
+ fail(new Error(`Download failed (${status}) for ${target}`));
380
+ return;
381
+ }
382
+ const out = (0, node_fs_1.createWriteStream)(destFile);
383
+ let received = 0;
384
+ response.on("data", (chunk) => {
385
+ received += chunk.length;
386
+ if (received > exports.MAX_DOWNLOAD_BYTES) {
387
+ request.destroy();
388
+ out.destroy();
389
+ fail(new Error(`Download exceeded ${exports.MAX_DOWNLOAD_BYTES} bytes for ${target}`));
390
+ }
391
+ });
392
+ response.setTimeout(exports.DOWNLOAD_TIMEOUT_MS, () => {
393
+ request.destroy();
394
+ out.destroy();
395
+ fail(new Error(`Download timed out after ${exports.DOWNLOAD_TIMEOUT_MS}ms`));
396
+ });
397
+ response.pipe(out);
398
+ out.on("finish", () => out.close((error) => (error ? fail(error) : succeed())));
399
+ out.on("error", fail);
400
+ });
401
+ request.setTimeout(exports.DOWNLOAD_TIMEOUT_MS, () => {
402
+ request.destroy();
403
+ fail(new Error(`Download timed out after ${exports.DOWNLOAD_TIMEOUT_MS}ms`));
404
+ });
405
+ request.on("error", fail);
406
+ };
407
+ follow(url, 5);
408
+ });
409
+ }
410
+ async function rmQuiet(target) {
411
+ try {
412
+ await node_fs_1.promises.rm(target, { force: true });
413
+ }
414
+ catch {
415
+ // best effort
416
+ }
417
+ }