@neuralaxis/vibedoctor 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,23 +4,25 @@
4
4
  <img src="website/public/logo-lockup.png" alt="VibeDoctor, a NeuralAxis product" width="360" />
5
5
  </p>
6
6
 
7
- **A local health check for code you did not write line by line.**
7
+ **A health check for AI-written code. Your AI says it's done. Is it?**
8
8
  **Give VibeDoctor a repository. It figures out what applies, runs the diagnosis, and tells you or your coding agent what to fix first.**
9
9
 
10
- VibeDoctor scans JavaScript, TypeScript, Python, and mixed repositories for code-health, security, privacy, testing, and maintainability problems. It combines engine output into one ranked report, one normalized finding format, and a fix-next plan that humans and coding agents can use without interpreting a wall of unrelated logs.
10
+ Website: **[vibedoctor.in](https://vibedoctor.in/)** · [What it checks](https://vibedoctor.in/checks/) · [DPDP readiness scan](https://vibedoctor.in/dpdp/)
11
+
12
+ VibeDoctor scans vibe-coded JavaScript, TypeScript, Python, and mixed repositories for leaked keys, broken API routes, swallowed errors, vulnerable packages, personal data in logs and LLM prompts, and the usual code-health, testing, and maintainability problems. Works with Cursor, Claude Code, Codex, and GitHub Copilot. It combines engine output into one ranked report, one normalized finding format, and a fix-next plan that humans and coding agents can use without interpreting a wall of unrelated logs.
11
13
 
12
14
  ```bash
13
- npx @neuralaxis/vibedoctor scan
15
+ npx @neuralaxis/vibedoctor scan --full
14
16
  ```
15
17
 
16
18
  That is the default path: full applicable diagnosis, local by default. Missing or failed scanners are reported as incomplete evidence, never silently counted as a clean result.
17
19
 
18
- The public product site lives in [`website/`](website/README.md) and deploys from GitHub Pages.
20
+ The public product site, [vibedoctor.in](https://vibedoctor.in/), lives in [`website/`](website/README.md) and deploys from GitHub Pages.
19
21
 
20
22
  ## Start here
21
23
 
22
24
  ```bash
23
- npx @neuralaxis/vibedoctor scan
25
+ npx @neuralaxis/vibedoctor scan --full
24
26
  ```
25
27
 
26
28
  That is enough for a first diagnosis. VibeDoctor detects the repository, runs the capabilities that apply, correlates overlapping evidence, and ranks what to fix first.
@@ -28,7 +30,7 @@ That is enough for a first diagnosis. VibeDoctor detects the repository, runs th
28
30
  For an AI coding agent:
29
31
 
30
32
  ```bash
31
- npx @neuralaxis/vibedoctor scan --report agent-json
33
+ npx @neuralaxis/vibedoctor scan --full --report agent-json
32
34
  ```
33
35
 
34
36
  Optional narrower runs:
@@ -37,7 +39,6 @@ Optional narrower runs:
37
39
  | --- | --- |
38
40
  | Fast profile | `npx @neuralaxis/vibedoctor scan --quick` |
39
41
  | Git-changed files | `npx @neuralaxis/vibedoctor scan --changed` |
40
- | Explicit full alias | `npx @neuralaxis/vibedoctor scan --full` |
41
42
  | Agent repair plan file | `npx @neuralaxis/vibedoctor agent-plan --format markdown` |
42
43
  | India DPDP technical readiness | `npx @neuralaxis/vibedoctor dpdp scan --full` |
43
44
 
@@ -169,6 +170,8 @@ CLI exit codes let people, agents, and CI distinguish health failures from missi
169
170
  | `0` | The scan completed and configured gates passed. |
170
171
  | `1` | One or more configured health gates failed. |
171
172
  | `2` | Required checks were incomplete. |
173
+ | `64` | Invalid `scan` options (unknown `--profile`, `--root` not a directory). |
174
+ | `70` | `--report envelope` only: the scan crashed before completing, so no envelope was written. |
172
175
 
173
176
  Skipped scanners are never treated as clean results. Privacy findings affect the privacy category score by default, but do not lower the overall score or fail CI unless you opt into privacy gates.
174
177
 
@@ -243,6 +246,17 @@ vibedoctor mcp
243
246
 
244
247
  It exposes structured operations for changed and full scans, report retrieval, finding explanations, safe fixes, repair plans, verification, privacy review, and DPDP technical readiness. Generated agent configs include MCP wiring where the target supports it.
245
248
 
249
+ The stdio transport uses newline-delimited JSON, as required by MCP. Existing clients using VibeDoctor's earlier `Content-Length` framing are still supported.
250
+
251
+ For container-based MCP introspection (including Glama), build the repository's Dockerfile and run it with stdin attached:
252
+
253
+ ```sh
254
+ docker build -t vibedoctor-mcp .
255
+ docker run --rm -i vibedoctor-mcp
256
+ ```
257
+
258
+ The container runs as a non-root user in an empty `/workspace`. To scan a project, mount that project at `/workspace` with permissions appropriate to the operations you intend to use. Optional external scanners are not bundled; scan coverage reports any unavailable engines.
259
+
246
260
  ## Privacy Review
247
261
 
248
262
  Privacy Review is deterministic-first and advisory by default. Evidence stored in reports is masked or classified instead of preserving raw PII.
@@ -374,8 +388,8 @@ Human-review-only DPDP items do not fail CI. Configure `checks.dpdp.fail_on_seve
374
388
  | --- | --- |
375
389
  | Initialize configuration | `vibedoctor init` |
376
390
  | Plan or apply scanner setup | `vibedoctor setup` / `vibedoctor setup --apply` |
377
- | Full applicable diagnosis | `vibedoctor scan` |
378
- | Quick, changed, or explicit full | `vibedoctor scan --quick` / `--changed` / `--full` |
391
+ | Full applicable diagnosis (default) | `vibedoctor scan --full` |
392
+ | Narrower quick or changed-files run | `vibedoctor scan --quick` / `--changed` |
379
393
  | Scan selected categories | `vibedoctor scan --category dead_code,leftovers` |
380
394
  | Render a fresh full report | `vibedoctor report --json`, `--html`, `--markdown`, `--sarif`, or `--agent` |
381
395
  | Apply supported safe fixes | `vibedoctor fix --safe` |
@@ -386,7 +400,25 @@ Human-review-only DPDP items do not fail CI. Configure `checks.dpdp.fail_on_seve
386
400
  | Generate an agent plan | `vibedoctor agent-plan --format markdown` |
387
401
  | Start MCP | `vibedoctor mcp` |
388
402
 
389
- `scan --report` supports `terminal`, `json`, `html`, `agent`, and `agent-json`. The separate `report` command performs a fresh full scan and can also render Markdown or SARIF to standard output.
403
+ `scan --report` supports `terminal`, `json`, `html`, `agent`, `agent-json`, and `envelope`. The separate `report` command performs a fresh full scan and can also render Markdown or SARIF to standard output.
404
+
405
+ ### Scanning code you do not fully trust
406
+
407
+ By default VibeDoctor behaves as it always has: project-local tools (for example `node_modules/.bin/tsc`) are preferred, and test runners can execute the project's tests. When you scan a repository you did not write (CI bots, other tools, downloaded code), choose an explicit profile:
408
+
409
+ ```bash
410
+ vibedoctor scan --root ./some-repo --profile static --report envelope
411
+ ```
412
+
413
+ | Profile | What runs |
414
+ | --- | --- |
415
+ | `default` | Everything applicable, as before. |
416
+ | `static` | Only analysers that read files and run from outside the repository. No project-local executables, no project tests or scripts, no tools that load executable project config (vitest, jest, knip, coverage.py, Presidio), no network (Semgrep registry, OSV), a minimal child environment, and no Windows `cmd.exe` fallback. Excluded tools appear in the capability matrix with the reason. |
417
+ | `trusted` | The project's own tools and tests may run; network stays off unless `--allow-network`. |
418
+
419
+ `--allow-network` re-enables network-backed tools under `static` or `trusted`. The repository's `vibedoctor.yml` cannot re-enable a tool the profile excludes. Reports are still written to `.vibedoctor/` in every profile.
420
+
421
+ `--report envelope` prints one versioned JSON document for integrations. It contains the unchanged `--report json` report plus the producer version, run identity, profile, a content fingerprint of the scanned files, git state, the configuration fingerprint, a stable fingerprint per finding, and the gate outcome. See [docs/machine-envelope.md](docs/machine-envelope.md) and [schemas/machine-envelope.v1.schema.json](schemas/machine-envelope.v1.schema.json).
390
422
 
391
423
  ## Network and data behavior
392
424
 
@@ -394,7 +426,7 @@ Core scanning and report generation run locally and do not require a hosted Vibe
394
426
 
395
427
  ## Development
396
428
 
397
- Requirements: Node.js 18 or newer and npm 10.x.
429
+ Requirements: Node.js 20.19 or newer and npm 10.x.
398
430
 
399
431
  ```bash
400
432
  npm test
@@ -406,7 +438,7 @@ npm pack --dry-run
406
438
  Useful local commands:
407
439
 
408
440
  ```bash
409
- npm run dev -- scan --quick
441
+ npm run dev -- scan --full
410
442
  npm run dev -- agent init --targets all
411
443
  npm run dev -- agent plugin --targets all --force
412
444
  ```
@@ -426,3 +458,17 @@ npm run dev -- agent plugin --targets all --force
426
458
  ## License
427
459
 
428
460
  VibeDoctor is licensed under GPL-3.0-or-later.
461
+
462
+ ### Homepage arcade
463
+
464
+ The homepage includes a small **DO NOT PRESS** button that opens SHIP IT!, a
465
+ 15-second bug-catching game. It needs no login, backend, or extra dependencies.
466
+ Golden bugs earn three points; a personal best is stored locally when available.
467
+ Sound is off by default. Keyboard controls, reduced motion, and pausing while the
468
+ tab is hidden are supported. The result screen offers replay, a friend challenge,
469
+ and the real scan command. The arcade is implemented in
470
+ `website/src/components/ShipItArcade.astro`; the homepage imports it below the hero.
471
+
472
+ Validate website changes with `npm run check`, `npm run test:arcade`, and
473
+ `npm run build` in `website/`. The arcade test exercises game logic with a
474
+ deterministic clock and minimal DOM; it does not replace browser layout checks.
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.gitleaksAdapter = void 0;
4
4
  const finding_1 = require("../core/finding");
5
+ const executionPolicy_1 = require("../core/executionPolicy");
5
6
  function parseGitleaks(stdout) {
6
7
  const trimmed = stdout.trim();
7
8
  return trimmed ? JSON.parse(trimmed) : [];
@@ -16,7 +17,18 @@ exports.gitleaksAdapter = {
16
17
  return {
17
18
  tool: "gitleaks",
18
19
  cmd: "gitleaks",
19
- args: ["detect", "--no-banner", "--redact", "--report-format", "json", "--report-path", "-"],
20
+ // The static profile scans files only (--no-git), so the target's git configuration is
21
+ // never consulted by gitleaks' internal `git log -p`.
22
+ args: [
23
+ "detect",
24
+ ...((0, executionPolicy_1.currentPolicy)().profile === "static" ? ["--no-git"] : []),
25
+ "--no-banner",
26
+ "--redact",
27
+ "--report-format",
28
+ "json",
29
+ "--report-path",
30
+ "-"
31
+ ],
20
32
  cwd: ctx.root,
21
33
  timeoutMs: 60_000,
22
34
  runtime: ctx.toolRuntime
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ruffAdapter = void 0;
4
4
  const finding_1 = require("../core/finding");
5
5
  const shared_1 = require("./shared");
6
+ const executionPolicy_1 = require("../core/executionPolicy");
6
7
  function parseRuffOutput(stdout) {
7
8
  const trimmed = stdout.trim();
8
9
  if (!trimmed) {
@@ -31,7 +32,15 @@ exports.ruffAdapter = {
31
32
  return {
32
33
  tool: "ruff",
33
34
  cmd: "ruff",
34
- args: ["check", ...targets, "--output-format", "json", ...excludePatterns],
35
+ // Explicit profiles leave the scanned repository unchanged: no .ruff_cache is written.
36
+ args: [
37
+ "check",
38
+ ...targets,
39
+ "--output-format",
40
+ "json",
41
+ ...excludePatterns,
42
+ ...((0, executionPolicy_1.currentPolicy)().profile === "default" ? [] : ["--no-cache"])
43
+ ],
35
44
  cwd: ctx.root,
36
45
  timeoutMs: 60_000,
37
46
  runtime: ctx.toolRuntime
@@ -16,5 +16,7 @@ export declare function runScanCommand(root: string, options: {
16
16
  quick?: boolean;
17
17
  full?: boolean;
18
18
  category?: string;
19
- report?: "terminal" | "json" | "html" | "agent" | "agent-json";
19
+ report?: "terminal" | "json" | "html" | "agent" | "agent-json" | "envelope";
20
+ /** Producer version recorded in the machine envelope. */
21
+ version?: string;
20
22
  }): Promise<ScanCommandResult>;
@@ -12,6 +12,9 @@ const html_1 = require("../../reporters/html");
12
12
  const agent_1 = require("../../reporters/agent");
13
13
  const shared_1 = require("./shared");
14
14
  const gates_1 = require("../../dpdp/gates");
15
+ const executionPolicy_1 = require("../../core/executionPolicy");
16
+ const envelope_1 = require("../../integration/envelope");
17
+ const sourceFingerprint_1 = require("../../integration/sourceFingerprint");
15
18
  function shouldCountForFailure(isNew, config) {
16
19
  return config.baseline.failOnlyOnNewIssues ? isNew : true;
17
20
  }
@@ -87,13 +90,30 @@ function resolveScanMode(options) {
87
90
  }
88
91
  async function runScanCommand(root, options) {
89
92
  const mode = resolveScanMode(options);
90
- const scan = await (0, engine_1.runScan)(root, mode);
91
93
  const categories = (0, finding_1.parseFindingCategoryList)(options.category);
94
+ const startedAt = new Date();
95
+ // Fingerprint the snapshot before tools run, so the envelope names exactly what was scanned.
96
+ const source = options.report === "envelope" ? await (0, sourceFingerprint_1.sourceFingerprint)(root) : null;
97
+ const scan = await (0, engine_1.runScan)(root, mode);
92
98
  const filteredScan = categories ? (0, engine_2.filterScanByCategories)(scan, categories) : scan;
93
99
  const { config } = await (0, shared_1.getConfig)(root);
94
100
  await (0, shared_1.ensureOutputArtifacts)(root, config, filteredScan);
95
101
  const exitCode = determineExitCode(filteredScan, config);
96
102
  switch (options.report) {
103
+ case "envelope": {
104
+ const envelope = await (0, envelope_1.buildMachineEnvelope)({
105
+ scan: filteredScan,
106
+ config,
107
+ policy: (0, executionPolicy_1.currentPolicy)(),
108
+ version: options.version ?? "unknown",
109
+ startedAt,
110
+ finishedAt: new Date(),
111
+ exitCode,
112
+ categories: categories ?? null,
113
+ source: source
114
+ });
115
+ return { output: `${JSON.stringify(envelope)}\n`, exitCode };
116
+ }
97
117
  case "json":
98
118
  return { output: (0, json_1.renderJsonReport)(filteredScan), exitCode };
99
119
  case "html":
@@ -276,7 +276,7 @@ function renderPlan({ plan, include, installResults = [], postInstall }) {
276
276
  lines.push(" - Manually install lizard or semgrep (shown above with one-line hints) for deeper complexity + rule-based checks");
277
277
  lines.push(" - Add jscpd (npm) if you want duplication heatmaps for large refactors");
278
278
  lines.push("");
279
- lines.push("Tip: Re-run `vibedoctor scan --quick` (or `scan --full`) after changes to see updated health + findings.");
279
+ lines.push("Tip: Re-run `vibedoctor scan --full` (or `scan --quick` for a narrower pass) after changes to see updated health + findings.");
280
280
  }
281
281
  return `${lines.join("\n")}\n`;
282
282
  }
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").
@@ -52,14 +53,42 @@ async function main() {
52
53
  .option("--quick", "Narrower opt-in profile")
53
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")
@@ -37,6 +37,7 @@ const relevance_1 = require("./relevance");
37
37
  const suppressions_1 = require("./suppressions");
38
38
  const toolRegistry_1 = require("./toolRegistry");
39
39
  const toolVerification_1 = require("./toolVerification");
40
+ const executionPolicy_1 = require("./executionPolicy");
40
41
  const privacyReview_1 = require("./privacyReview");
41
42
  const ALL_ADAPTERS = [
42
43
  adapters_1.gitleaksAdapter,
@@ -555,7 +556,25 @@ function reasonForCapability(id, state, run, verification, normalizationNote) {
555
556
  }
556
557
  async function runScan(root, mode = "default", options) {
557
558
  const [{ config, configPath }, { policy }] = await Promise.all([(0, config_1.loadConfig)(root), (0, policy_1.loadAgentPolicy)(root)]);
558
- const scanContext = await (0, scanContext_1.buildScanContext)(root, config, mode, options?.runtimeOptions);
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);
559
578
  const project = scanContext.repo;
560
579
  const plan = await (0, scanPlanner_1.createScanPlan)(project, config, [...ALL_ADAPTERS], mode);
561
580
  const ctx = { root, project, config, scanMode: mode, toolRuntime: scanContext.toolRuntime, scanContext };
@@ -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
  }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Execution policy for one scan.
3
+ *
4
+ * The default policy reproduces VibeDoctor's long-standing behaviour exactly (project-local
5
+ * tools first, project tests may run, the Windows shell fallback). Callers that scan code they
6
+ * do not fully trust (CI bots, other tools, repositories downloaded from elsewhere) can opt in
7
+ * to an explicit profile with `scan --profile`:
8
+ *
9
+ * - `static`: only analysers that read files and run from outside the target. No project-local
10
+ * executables, no project scripts/tests, no tools that load executable project configuration,
11
+ * no network, and a minimal environment for child processes.
12
+ * - `trusted`: the caller explicitly accepts running the project's own tools and tests, with a
13
+ * minimal environment and network off unless allowed.
14
+ *
15
+ * Reports are still written to the usual `.vibedoctor/` folder in every profile.
16
+ *
17
+ * The policy travels with the async call chain (AsyncLocalStorage), so it applies only to the
18
+ * scan that asked for it and no adapter has to thread it through.
19
+ */
20
+ export type ExecutionProfile = "default" | "static" | "trusted";
21
+ export type ExecutionPolicy = {
22
+ profile: ExecutionProfile;
23
+ /** Absolute repository root being diagnosed; nothing inside it may be executed in `static`. */
24
+ targetRoot?: string;
25
+ /** Optional scratch directory for child-process temp files (TEMP/TMP/TMPDIR). */
26
+ tempRoot?: string;
27
+ allowProjectLocalTools: boolean;
28
+ allowProjectExecution: boolean;
29
+ allowShellFallback: boolean;
30
+ allowNetwork: boolean;
31
+ /** When set, child processes receive only these variables (plus PATH/TEMP handling). */
32
+ envAllowlist?: string[];
33
+ /** Upper bound on captured stdout/stderr per child process. */
34
+ maxOutputBytes?: number;
35
+ };
36
+ export declare const DEFAULT_POLICY: ExecutionPolicy;
37
+ export declare function profilePolicy(profile: ExecutionProfile, options?: {
38
+ targetRoot: string;
39
+ tempRoot?: string;
40
+ allowNetwork?: boolean;
41
+ }): ExecutionPolicy;
42
+ export declare function currentPolicy(): ExecutionPolicy;
43
+ export declare function withExecutionPolicy<T>(policy: ExecutionPolicy, run: () => Promise<T>): Promise<T>;
44
+ /** Why a tool must not run under the current policy, or undefined when it may. */
45
+ export declare function policyExclusion(toolId: string, policy?: ExecutionPolicy): string | undefined;
46
+ export declare function isInside(parent: string, child: string): boolean;
47
+ /**
48
+ * PATH entries a child may search. Relative entries (such as ".") and anything inside the
49
+ * target are removed when project-local tools are not allowed.
50
+ */
51
+ export declare function allowedPathEntries(entries: string[], policy?: ExecutionPolicy): string[];
52
+ /** Environment passed to children under the policy (the full environment by default). */
53
+ export declare function policyEnv(base: NodeJS.ProcessEnv, policy?: ExecutionPolicy): NodeJS.ProcessEnv;
54
+ /** Git settings that could run commands from repository configuration are switched off. */
55
+ export declare function gitSafetyEnv(policy?: ExecutionPolicy): NodeJS.ProcessEnv;
@@ -0,0 +1,144 @@
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.DEFAULT_POLICY = void 0;
7
+ exports.profilePolicy = profilePolicy;
8
+ exports.currentPolicy = currentPolicy;
9
+ exports.withExecutionPolicy = withExecutionPolicy;
10
+ exports.policyExclusion = policyExclusion;
11
+ exports.isInside = isInside;
12
+ exports.allowedPathEntries = allowedPathEntries;
13
+ exports.policyEnv = policyEnv;
14
+ exports.gitSafetyEnv = gitSafetyEnv;
15
+ const node_async_hooks_1 = require("node:async_hooks");
16
+ const node_path_1 = __importDefault(require("node:path"));
17
+ exports.DEFAULT_POLICY = {
18
+ profile: "default",
19
+ allowProjectLocalTools: true,
20
+ allowProjectExecution: true,
21
+ allowShellFallback: true,
22
+ allowNetwork: true
23
+ };
24
+ const ENV_ALLOWLIST = [
25
+ "PATH",
26
+ "Path",
27
+ "PATHEXT",
28
+ "SystemRoot",
29
+ "SYSTEMROOT",
30
+ "windir",
31
+ "ComSpec",
32
+ "HOME",
33
+ "USERPROFILE",
34
+ "APPDATA",
35
+ "LOCALAPPDATA",
36
+ "HOMEDRIVE",
37
+ "HOMEPATH",
38
+ "LANG",
39
+ "LC_ALL",
40
+ "TZ",
41
+ "NUMBER_OF_PROCESSORS",
42
+ "PROCESSOR_ARCHITECTURE",
43
+ "VIBEDOCTOR_TOOL_CACHE"
44
+ ];
45
+ /**
46
+ * Tools excluded from a profile, with the reason surfaced in the capability matrix.
47
+ * Each entry was checked against the adapter: a flag named "static" is not evidence.
48
+ */
49
+ const STATIC_EXCLUSIONS = {
50
+ vitest: "Runs the project's tests and loads its vitest config (project code execution).",
51
+ jest: "Runs the project's tests and loads its jest config (project code execution).",
52
+ knip: "Loads JS/TS project config and plugin configs, which execute project code.",
53
+ "coverage.py": "coverage.py loads .coveragerc plugins, which are Python code.",
54
+ presidio: "Runs a Python interpreter that may resolve to the project's environment and download models.",
55
+ semgrep: "Uses `--config auto`, which downloads rules from the network.",
56
+ "osv-scanner": "Queries the OSV vulnerability API over the network."
57
+ };
58
+ const TRUSTED_EXCLUSIONS = {
59
+ semgrep: STATIC_EXCLUSIONS.semgrep,
60
+ "osv-scanner": STATIC_EXCLUSIONS["osv-scanner"]
61
+ };
62
+ function profilePolicy(profile, options = { targetRoot: process.cwd() }) {
63
+ if (profile === "default")
64
+ return { ...exports.DEFAULT_POLICY, targetRoot: node_path_1.default.resolve(options.targetRoot) };
65
+ const base = {
66
+ profile,
67
+ targetRoot: node_path_1.default.resolve(options.targetRoot),
68
+ tempRoot: options.tempRoot ? node_path_1.default.resolve(options.tempRoot) : undefined,
69
+ allowNetwork: options.allowNetwork ?? false,
70
+ allowShellFallback: false,
71
+ envAllowlist: ENV_ALLOWLIST,
72
+ maxOutputBytes: 64 * 1024 * 1024
73
+ };
74
+ return profile === "static"
75
+ ? { ...base, allowProjectLocalTools: false, allowProjectExecution: false }
76
+ : { ...base, allowProjectLocalTools: true, allowProjectExecution: true };
77
+ }
78
+ const store = new node_async_hooks_1.AsyncLocalStorage();
79
+ function currentPolicy() {
80
+ return store.getStore() ?? exports.DEFAULT_POLICY;
81
+ }
82
+ function withExecutionPolicy(policy, run) {
83
+ return store.run(policy, run);
84
+ }
85
+ /** Why a tool must not run under the current policy, or undefined when it may. */
86
+ function policyExclusion(toolId, policy = currentPolicy()) {
87
+ if (policy.profile === "static") {
88
+ const reason = STATIC_EXCLUSIONS[toolId];
89
+ if (reason && !(policy.allowNetwork && (toolId === "semgrep" || toolId === "osv-scanner")))
90
+ return `Excluded by the static profile: ${reason}`;
91
+ }
92
+ if (policy.profile === "trusted" && !policy.allowNetwork && TRUSTED_EXCLUSIONS[toolId])
93
+ return `Excluded because network is off: ${TRUSTED_EXCLUSIONS[toolId]}`;
94
+ return undefined;
95
+ }
96
+ function isInside(parent, child) {
97
+ const relative = node_path_1.default.relative(node_path_1.default.resolve(parent), node_path_1.default.resolve(child));
98
+ return relative === "" || (!relative.startsWith("..") && !node_path_1.default.isAbsolute(relative));
99
+ }
100
+ /**
101
+ * PATH entries a child may search. Relative entries (such as ".") and anything inside the
102
+ * target are removed when project-local tools are not allowed.
103
+ */
104
+ function allowedPathEntries(entries, policy = currentPolicy()) {
105
+ if (policy.allowProjectLocalTools || !policy.targetRoot)
106
+ return entries;
107
+ return entries.filter((entry) => node_path_1.default.isAbsolute(entry) && !isInside(policy.targetRoot, entry));
108
+ }
109
+ /** Environment passed to children under the policy (the full environment by default). */
110
+ function policyEnv(base, policy = currentPolicy()) {
111
+ if (!policy.envAllowlist)
112
+ return base;
113
+ const env = {};
114
+ for (const key of policy.envAllowlist)
115
+ if (base[key] !== undefined)
116
+ env[key] = base[key];
117
+ if (policy.tempRoot) {
118
+ // Tools that write scratch files (deptry, jscpd) write them where the caller chose.
119
+ const temp = policy.tempRoot;
120
+ env.TEMP = temp;
121
+ env.TMP = temp;
122
+ env.TMPDIR = temp;
123
+ }
124
+ if (!policy.allowNetwork)
125
+ env.VIBEDOCTOR_ALLOW_NETWORK = "0";
126
+ return env;
127
+ }
128
+ /** Git settings that could run commands from repository configuration are switched off. */
129
+ function gitSafetyEnv(policy = currentPolicy()) {
130
+ if (policy.profile === "default")
131
+ return {};
132
+ const overrides = [
133
+ ["core.fsmonitor", "false"],
134
+ ["core.hooksPath", process.platform === "win32" ? "NUL" : "/dev/null"],
135
+ ["diff.external", ""],
136
+ ["core.pager", "cat"]
137
+ ];
138
+ const env = { GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_COUNT: String(overrides.length) };
139
+ overrides.forEach(([key, value], index) => {
140
+ env[`GIT_CONFIG_KEY_${index}`] = key;
141
+ env[`GIT_CONFIG_VALUE_${index}`] = value;
142
+ });
143
+ return env;
144
+ }
@@ -1,3 +1,5 @@
1
1
  export declare function isGitRepo(root: string): Promise<boolean>;
2
2
  export declare function getChangedFiles(root: string): Promise<string[]>;
3
+ /** HEAD commit of the repository, or null when the root is not a git work tree. */
4
+ export declare function getHeadCommit(root: string): Promise<string | null>;
3
5
  export declare function isWorkingTreeDirty(root: string): Promise<boolean>;
package/dist/core/git.js CHANGED
@@ -2,12 +2,24 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isGitRepo = isGitRepo;
4
4
  exports.getChangedFiles = getChangedFiles;
5
+ exports.getHeadCommit = getHeadCommit;
5
6
  exports.isWorkingTreeDirty = isWorkingTreeDirty;
6
7
  const node_child_process_1 = require("node:child_process");
7
8
  const node_util_1 = require("node:util");
9
+ const executable_1 = require("./executable");
10
+ const executionPolicy_1 = require("./executionPolicy");
8
11
  const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
9
12
  async function runGit(root, args) {
10
- return execFileAsync("git", args, { cwd: root, windowsHide: true });
13
+ const policy = (0, executionPolicy_1.currentPolicy)();
14
+ if (policy.profile === "default")
15
+ return execFileAsync("git", args, { cwd: root, windowsHide: true });
16
+ // Integration profiles launch git by absolute path from outside the target, with repository
17
+ // settings that could run commands (fsmonitor, hooks, external diff) switched off.
18
+ const env = { ...(0, executable_1.buildCommandEnv)(undefined, undefined), ...(0, executionPolicy_1.gitSafetyEnv)(policy) };
19
+ const git = (0, executable_1.resolveExecutable)("git", undefined, env);
20
+ if (!git)
21
+ throw new Error("git is not available outside the target repository");
22
+ return execFileAsync(git.path, args, { cwd: root, windowsHide: true, env });
11
23
  }
12
24
  async function isGitRepo(root) {
13
25
  try {
@@ -53,6 +65,19 @@ async function getChangedFiles(root) {
53
65
  return [];
54
66
  }
55
67
  }
68
+ /** HEAD commit of the repository, or null when the root is not a git work tree. */
69
+ async function getHeadCommit(root) {
70
+ if (!(await isGitRepo(root))) {
71
+ return null;
72
+ }
73
+ try {
74
+ const { stdout } = await runGit(root, ["rev-parse", "HEAD"]);
75
+ return stdout.trim() || null;
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
56
81
  async function isWorkingTreeDirty(root) {
57
82
  if (!(await isGitRepo(root))) {
58
83
  return false;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.QUICK_ADAPTER_IDS = void 0;
4
4
  exports.createScanPlan = createScanPlan;
5
+ const executionPolicy_1 = require("./executionPolicy");
5
6
  exports.QUICK_ADAPTER_IDS = new Set([
6
7
  "ruff",
7
8
  "biome",
@@ -46,6 +47,13 @@ async function createScanPlan(project, config, adapters, mode) {
46
47
  const excluded = [];
47
48
  const deferred = new Set(config.runtime.deferredTools);
48
49
  for (const adapter of adapters) {
50
+ // The caller's execution profile outranks repository configuration: a target's
51
+ // vibedoctor.yml cannot re-enable a tool the profile excludes.
52
+ const excludedByPolicy = (0, executionPolicy_1.policyExclusion)(adapter.id);
53
+ if (excludedByPolicy) {
54
+ excluded.push({ id: adapter.id, state: "disabled", reason: excludedByPolicy });
55
+ continue;
56
+ }
49
57
  const disabled = disabledReason(adapter, config);
50
58
  if (disabled) {
51
59
  excluded.push({ id: adapter.id, state: "disabled", reason: `Turned off in config: ${disabled}.` });
@@ -15,6 +15,7 @@ const executable_1 = require("./executable");
15
15
  Object.defineProperty(exports, "buildCommandEnv", { enumerable: true, get: function () { return executable_1.buildCommandEnv; } });
16
16
  Object.defineProperty(exports, "getLocalToolSearchPaths", { enumerable: true, get: function () { return executable_1.getLocalToolSearchPaths; } });
17
17
  const toolRuntime_1 = require("./toolRuntime");
18
+ const executionPolicy_1 = require("./executionPolicy");
18
19
  function commandExistsOnWindowsPath(command, cwd) {
19
20
  return (0, executable_1.resolveExecutable)(command, cwd) !== undefined;
20
21
  }
@@ -32,7 +33,9 @@ function resolveLaunchTarget(command, cwd, env) {
32
33
  }
33
34
  return { command: resolved.path, useShell: false, resolvedPath: resolved.path };
34
35
  }
35
- if (process.platform === "win32" && !node_path_1.default.isAbsolute(command)) {
36
+ // Integration profiles never fall back to cmd.exe: its lookup searches the working directory,
37
+ // which is the target repository.
38
+ if (process.platform === "win32" && !node_path_1.default.isAbsolute(command) && (0, executionPolicy_1.currentPolicy)().allowShellFallback) {
36
39
  // Not found via PATH/PATHEXT probing. Fall back to the shell so commands that
37
40
  // are only reachable through cmd.exe mechanisms (App Execution Aliases,
38
41
  // App Paths registry entries) still launch, matching the previous behavior.
@@ -91,6 +94,8 @@ async function runCommand(spec, installHint) {
91
94
  const launch = resolved.useShell
92
95
  ? { command: [resolved.command, ...spec.args.map(quoteForWindowsShell)].join(" "), args: [] }
93
96
  : { command: resolved.command, args: spec.args };
97
+ // Integration profiles bound captured output so a runaway tool cannot exhaust memory.
98
+ const maxBytes = (0, executionPolicy_1.currentPolicy)().maxOutputBytes ?? Number.POSITIVE_INFINITY;
94
99
  return new Promise((resolve) => {
95
100
  const child = (0, node_child_process_1.spawn)(launch.command, launch.args, {
96
101
  cwd: spec.cwd,
@@ -103,10 +108,12 @@ async function runCommand(spec, installHint) {
103
108
  let settled = false;
104
109
  let timeoutHandle;
105
110
  child.stdout.on("data", (chunk) => {
106
- stdout += chunk.toString();
111
+ if (stdout.length < maxBytes)
112
+ stdout += chunk.toString();
107
113
  });
108
114
  child.stderr.on("data", (chunk) => {
109
- stderr += chunk.toString();
115
+ if (stderr.length < maxBytes)
116
+ stderr += chunk.toString();
110
117
  });
111
118
  function cleanup() {
112
119
  try {
@@ -0,0 +1,72 @@
1
+ import type { VibeDoctorConfig } from "../core/config";
2
+ import type { ScanOutput } from "../core/engine";
3
+ import type { ExecutionPolicy } from "../core/executionPolicy";
4
+ import { type Finding } from "../core/finding";
5
+ import type { SourceFingerprint } from "./sourceFingerprint";
6
+ /**
7
+ * Versioned machine envelope (`scan --report envelope`).
8
+ *
9
+ * It wraps the unchanged `--report json` document with what an integrating tool needs to trust
10
+ * and reuse a result: producer version, run identity and timing, the execution profile, the
11
+ * exact source snapshot, the configuration fingerprint, a stable fingerprint per finding, and
12
+ * the policy-gate outcome kept separate from completeness. Contract: docs/machine-envelope.md
13
+ * and schemas/machine-envelope.v1.schema.json. Additive changes keep the major version.
14
+ */
15
+ export declare const ENVELOPE_SCHEMA = "vibedoctor.machine-envelope";
16
+ export declare const ENVELOPE_VERSION = "1.0.0";
17
+ type JsonReport = Record<string, unknown> & {
18
+ findings: Finding[];
19
+ };
20
+ export type MachineEnvelope = {
21
+ schema: typeof ENVELOPE_SCHEMA;
22
+ schemaVersion: string;
23
+ producer: {
24
+ name: string;
25
+ version: string;
26
+ };
27
+ run: {
28
+ id: string;
29
+ startedAt: string;
30
+ finishedAt: string;
31
+ mode: string;
32
+ profile: ExecutionPolicy["profile"];
33
+ network: boolean;
34
+ categories: string[] | null;
35
+ };
36
+ repository: {
37
+ root: string;
38
+ source: SourceFingerprint;
39
+ git: {
40
+ head: string | null;
41
+ dirty: boolean | null;
42
+ changedFiles: number | null;
43
+ };
44
+ };
45
+ config: {
46
+ path: string | null;
47
+ fingerprint: string;
48
+ };
49
+ /** Whether the scan ran to completion; a crash never produces an envelope. */
50
+ execution: {
51
+ status: "completed";
52
+ };
53
+ /** Policy gate, independent of completeness: 0 pass, 1 finding/score gate, 2 incomplete. */
54
+ gate: {
55
+ exitCode: number;
56
+ status: "pass" | "fail" | "incomplete";
57
+ };
58
+ /** The `--report json` document; findings additionally carry `fingerprint`. */
59
+ report: JsonReport;
60
+ };
61
+ export declare function buildMachineEnvelope(input: {
62
+ scan: ScanOutput;
63
+ config: VibeDoctorConfig;
64
+ policy: ExecutionPolicy;
65
+ version: string;
66
+ startedAt: Date;
67
+ finishedAt: Date;
68
+ exitCode: number;
69
+ categories: string[] | null;
70
+ source: SourceFingerprint;
71
+ }): Promise<MachineEnvelope>;
72
+ export {};
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ENVELOPE_VERSION = exports.ENVELOPE_SCHEMA = void 0;
4
+ exports.buildMachineEnvelope = buildMachineEnvelope;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const finding_1 = require("../core/finding");
7
+ const git_1 = require("../core/git");
8
+ const json_1 = require("../reporters/json");
9
+ /**
10
+ * Versioned machine envelope (`scan --report envelope`).
11
+ *
12
+ * It wraps the unchanged `--report json` document with what an integrating tool needs to trust
13
+ * and reuse a result: producer version, run identity and timing, the execution profile, the
14
+ * exact source snapshot, the configuration fingerprint, a stable fingerprint per finding, and
15
+ * the policy-gate outcome kept separate from completeness. Contract: docs/machine-envelope.md
16
+ * and schemas/machine-envelope.v1.schema.json. Additive changes keep the major version.
17
+ */
18
+ exports.ENVELOPE_SCHEMA = "vibedoctor.machine-envelope";
19
+ exports.ENVELOPE_VERSION = "1.0.0";
20
+ const withFingerprint = (findings) => Array.isArray(findings)
21
+ ? findings.map((f) => ({ ...f, fingerprint: (0, finding_1.fingerprintFinding)(f) }))
22
+ : findings;
23
+ async function buildMachineEnvelope(input) {
24
+ const { scan, config, policy } = input;
25
+ const report = JSON.parse((0, json_1.renderJsonReport)(scan));
26
+ for (const key of ["findings", "topFindings", "privacyFindings", "dpdpFindings", "suppressedFindings"])
27
+ if (key in report)
28
+ report[key] = withFingerprint(report[key]);
29
+ const git = (await (0, git_1.isGitRepo)(scan.root))
30
+ ? {
31
+ head: await (0, git_1.getHeadCommit)(scan.root),
32
+ dirty: await (0, git_1.isWorkingTreeDirty)(scan.root),
33
+ changedFiles: (await (0, git_1.getChangedFiles)(scan.root)).length
34
+ }
35
+ : { head: null, dirty: null, changedFiles: null };
36
+ return {
37
+ schema: exports.ENVELOPE_SCHEMA,
38
+ schemaVersion: exports.ENVELOPE_VERSION,
39
+ producer: { name: "@neuralaxis/vibedoctor", version: input.version },
40
+ run: {
41
+ id: (0, node_crypto_1.randomUUID)(),
42
+ startedAt: input.startedAt.toISOString(),
43
+ finishedAt: input.finishedAt.toISOString(),
44
+ mode: scan.mode,
45
+ profile: policy.profile,
46
+ network: policy.allowNetwork,
47
+ categories: input.categories
48
+ },
49
+ repository: { root: scan.root, source: input.source, git },
50
+ config: {
51
+ path: scan.configPath ?? null,
52
+ fingerprint: (0, node_crypto_1.createHash)("sha256").update(JSON.stringify(config)).digest("hex")
53
+ },
54
+ execution: { status: "completed" },
55
+ gate: {
56
+ exitCode: input.exitCode,
57
+ status: input.exitCode === 0 ? "pass" : input.exitCode === 2 ? "incomplete" : "fail"
58
+ },
59
+ report
60
+ };
61
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `sha256-tree-v1`: identifies the exact file contents a scan saw, including uncommitted edits
3
+ * (a commit hash alone does not). Documented in docs/machine-envelope.md so other tools can
4
+ * recompute it independently:
5
+ *
6
+ * for every regular file under the root, skipping the directories in SKIPPED_DIRECTORIES and
7
+ * symbolic links, take the POSIX path relative to the root and sha256(content) in hex;
8
+ * sort by path (code-unit order); hash the concatenation of `${path}\0${hash}\n`.
9
+ *
10
+ * At most MAX_FILES files are hashed; beyond that `truncated` is true and the value covers
11
+ * only the first MAX_FILES paths in sorted order.
12
+ */
13
+ export declare const SKIPPED_DIRECTORIES: Set<string>;
14
+ export declare const MAX_FILES = 50000;
15
+ export type SourceFingerprint = {
16
+ algorithm: "sha256-tree-v1";
17
+ value: string;
18
+ files: number;
19
+ truncated: boolean;
20
+ };
21
+ export declare function sourceFingerprint(root: string): Promise<SourceFingerprint>;
@@ -0,0 +1,68 @@
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.MAX_FILES = exports.SKIPPED_DIRECTORIES = void 0;
7
+ exports.sourceFingerprint = sourceFingerprint;
8
+ const node_crypto_1 = require("node:crypto");
9
+ const node_fs_1 = require("node:fs");
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ /**
12
+ * `sha256-tree-v1`: identifies the exact file contents a scan saw, including uncommitted edits
13
+ * (a commit hash alone does not). Documented in docs/machine-envelope.md so other tools can
14
+ * recompute it independently:
15
+ *
16
+ * for every regular file under the root, skipping the directories in SKIPPED_DIRECTORIES and
17
+ * symbolic links, take the POSIX path relative to the root and sha256(content) in hex;
18
+ * sort by path (code-unit order); hash the concatenation of `${path}\0${hash}\n`.
19
+ *
20
+ * At most MAX_FILES files are hashed; beyond that `truncated` is true and the value covers
21
+ * only the first MAX_FILES paths in sorted order.
22
+ */
23
+ exports.SKIPPED_DIRECTORIES = new Set([
24
+ ".git",
25
+ ".vibedoctor",
26
+ "node_modules",
27
+ ".venv",
28
+ "venv",
29
+ "__pycache__",
30
+ ".world",
31
+ // Tool caches are scratch output, not source; skipping them keeps identity stable when a
32
+ // scanner (for example ruff in the default profile) writes its cache into the repository.
33
+ ".ruff_cache",
34
+ ".mypy_cache",
35
+ ".pytest_cache"
36
+ ]);
37
+ exports.MAX_FILES = 50_000;
38
+ async function sourceFingerprint(root) {
39
+ const files = [];
40
+ let truncated = false;
41
+ async function walk(dir) {
42
+ const entries = await node_fs_1.promises.readdir(dir, { withFileTypes: true });
43
+ for (const entry of entries) {
44
+ if (entry.isSymbolicLink())
45
+ continue;
46
+ const absolute = node_path_1.default.join(dir, entry.name);
47
+ if (entry.isDirectory()) {
48
+ if (!exports.SKIPPED_DIRECTORIES.has(entry.name))
49
+ await walk(absolute);
50
+ }
51
+ else if (entry.isFile()) {
52
+ files.push(node_path_1.default.relative(root, absolute).split(node_path_1.default.sep).join("/"));
53
+ }
54
+ }
55
+ }
56
+ await walk(root);
57
+ files.sort();
58
+ if (files.length > exports.MAX_FILES) {
59
+ truncated = true;
60
+ files.length = exports.MAX_FILES;
61
+ }
62
+ const tree = (0, node_crypto_1.createHash)("sha256");
63
+ for (const file of files) {
64
+ const content = await node_fs_1.promises.readFile(node_path_1.default.join(root, file));
65
+ tree.update(`${file}\0${(0, node_crypto_1.createHash)("sha256").update(content).digest("hex")}\n`);
66
+ }
67
+ return { algorithm: "sha256-tree-v1", value: tree.digest("hex"), files: files.length, truncated };
68
+ }
@@ -2,18 +2,19 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.runMcpServer = runMcpServer;
4
4
  const tools_1 = require("./tools");
5
- function writeMessage(payload) {
5
+ const { version } = require("../../package.json");
6
+ function writeMessage(payload, framing) {
6
7
  const body = JSON.stringify(payload);
7
- process.stdout.write(`Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`);
8
+ process.stdout.write(framing === "newline" ? `${body}\n` : `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`);
8
9
  }
9
- function writeResult(id, result) {
10
+ function writeResult(id, result, framing) {
10
11
  writeMessage({
11
12
  jsonrpc: "2.0",
12
13
  id,
13
14
  result
14
- });
15
+ }, framing);
15
16
  }
16
- function writeError(id, code, message) {
17
+ function writeError(id, code, message, framing) {
17
18
  writeMessage({
18
19
  jsonrpc: "2.0",
19
20
  id,
@@ -21,12 +22,25 @@ function writeError(id, code, message) {
21
22
  code,
22
23
  message
23
24
  }
24
- });
25
+ }, framing);
25
26
  }
26
27
  function parseMessages(buffer) {
27
28
  const messages = [];
28
29
  let cursor = buffer;
29
30
  while (cursor.length > 0) {
31
+ // Standard MCP stdio uses one JSON message per line. Preserve the original
32
+ // header framing for clients that already use VibeDoctor's legacy transport.
33
+ const prefix = cursor.subarray(0, Math.min(cursor.length, 15)).toString("ascii").toLowerCase();
34
+ if (!"content-length:".startsWith(prefix) && !prefix.startsWith("content-length:")) {
35
+ const lineEnd = cursor.indexOf("\n");
36
+ if (lineEnd === -1)
37
+ break;
38
+ const body = cursor.subarray(0, lineEnd).toString("utf8").trim();
39
+ cursor = cursor.subarray(lineEnd + 1);
40
+ if (body)
41
+ messages.push({ body, framing: "newline" });
42
+ continue;
43
+ }
30
44
  const headerEnd = cursor.indexOf("\r\n\r\n");
31
45
  if (headerEnd === -1) {
32
46
  break;
@@ -42,16 +56,16 @@ function parseMessages(buffer) {
42
56
  if (cursor.length < bodyEnd) {
43
57
  break;
44
58
  }
45
- messages.push(JSON.parse(cursor.subarray(bodyStart, bodyEnd).toString("utf8")));
59
+ messages.push({ body: cursor.subarray(bodyStart, bodyEnd).toString("utf8"), framing: "content-length" });
46
60
  cursor = cursor.subarray(bodyEnd);
47
61
  }
48
62
  return { messages, remaining: cursor };
49
63
  }
50
- async function handleRequest(root, request) {
64
+ async function handleRequest(root, request, framing) {
51
65
  const id = request.id ?? null;
52
66
  if (!request.method) {
53
67
  if (request.id !== undefined) {
54
- writeError(id, -32600, "Invalid request");
68
+ writeError(id, -32600, "Invalid request", framing);
55
69
  }
56
70
  return;
57
71
  }
@@ -62,17 +76,17 @@ async function handleRequest(root, request) {
62
76
  protocolVersion: "2024-11-05",
63
77
  serverInfo: {
64
78
  name: "vibedoctor",
65
- version: "0.1.0"
79
+ version
66
80
  },
67
81
  capabilities: {
68
82
  tools: {}
69
83
  }
70
- });
84
+ }, framing);
71
85
  return;
72
86
  case "notifications/initialized":
73
87
  return;
74
88
  case "ping":
75
- writeResult(id, {});
89
+ writeResult(id, {}, framing);
76
90
  return;
77
91
  case "tools/list":
78
92
  writeResult(id, {
@@ -81,17 +95,17 @@ async function handleRequest(root, request) {
81
95
  description: tool.description,
82
96
  inputSchema: tool.inputSchema
83
97
  }))
84
- });
98
+ }, framing);
85
99
  return;
86
100
  case "tools/call": {
87
101
  const toolName = request.params?.name;
88
102
  if (typeof toolName !== "string") {
89
- writeError(id, -32602, "Tool name is required");
103
+ writeError(id, -32602, "Tool name is required", framing);
90
104
  return;
91
105
  }
92
106
  const tool = tools_1.mcpTools.find((candidate) => candidate.name === toolName);
93
107
  if (!tool) {
94
- writeError(id, -32601, `Unknown tool: ${toolName}`);
108
+ writeError(id, -32601, `Unknown tool: ${toolName}`, framing);
95
109
  return;
96
110
  }
97
111
  const args = request.params?.arguments;
@@ -104,38 +118,46 @@ async function handleRequest(root, request) {
104
118
  }
105
119
  ],
106
120
  structuredContent: result
107
- });
121
+ }, framing);
108
122
  return;
109
123
  }
110
124
  default:
111
- writeError(id, -32601, `Unsupported method: ${request.method}`);
125
+ if (request.id !== undefined)
126
+ writeError(id, -32601, `Unsupported method: ${request.method}`, framing);
112
127
  }
113
128
  }
114
129
  catch (error) {
115
130
  const message = error instanceof Error ? error.message : String(error);
116
- writeError(id, -32000, message);
131
+ writeError(id, -32000, message, framing);
117
132
  }
118
133
  }
119
134
  async function runMcpServer(root) {
120
135
  let buffer = Buffer.alloc(0);
121
- process.stdin.on("data", async (chunk) => {
136
+ for await (const chunk of process.stdin) {
122
137
  try {
123
138
  buffer = Buffer.concat([buffer, chunk]);
124
139
  const parsed = parseMessages(buffer);
125
140
  buffer = parsed.remaining;
126
- for (const message of parsed.messages) {
127
- await handleRequest(root, message);
141
+ for (const { body, framing } of parsed.messages) {
142
+ let request;
143
+ try {
144
+ request = JSON.parse(body);
145
+ }
146
+ catch {
147
+ writeError(null, -32700, "Invalid JSON", framing);
148
+ continue;
149
+ }
150
+ if (typeof request !== "object" || request === null || Array.isArray(request)) {
151
+ writeError(null, -32600, "Invalid request", framing);
152
+ continue;
153
+ }
154
+ await handleRequest(root, request, framing);
128
155
  }
129
156
  }
130
157
  catch (error) {
131
158
  const message = error instanceof Error ? error.message : String(error);
132
- writeError(null, -32700, message);
159
+ writeError(null, -32700, message, "newline");
133
160
  buffer = Buffer.alloc(0);
134
161
  }
135
- });
136
- process.stdin.resume();
137
- await new Promise((resolve) => {
138
- process.stdin.on("end", () => resolve());
139
- process.stdin.on("close", () => resolve());
140
- });
162
+ }
141
163
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neuralaxis/vibedoctor",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
4
4
  "description": "Health diagnosis and fix planning for JS, TS, Python, and mixed repositories.",
5
5
  "type": "commonjs",
6
6
  "publishConfig": {
@@ -19,12 +19,13 @@
19
19
  },
20
20
  "files": [
21
21
  "dist",
22
+ "schemas",
22
23
  "README.md",
23
24
  "LICENSE",
24
25
  "package.json"
25
26
  ],
26
27
  "engines": {
27
- "node": ">=18"
28
+ "node": ">=20"
28
29
  },
29
30
  "packageManager": "npm@10.8.2",
30
31
  "keywords": [
@@ -32,7 +33,14 @@
32
33
  "cli",
33
34
  "static-analysis",
34
35
  "technical-debt",
35
- "agent-tools"
36
+ "agent-tools",
37
+ "vibe-coding",
38
+ "ai-generated-code",
39
+ "security",
40
+ "secrets",
41
+ "privacy",
42
+ "dpdp",
43
+ "mcp"
36
44
  ],
37
45
  "scripts": {
38
46
  "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
@@ -51,25 +59,25 @@
51
59
  "type": "git",
52
60
  "url": "git+https://github.com/neural-axis/VibeDoctor.git"
53
61
  },
54
- "homepage": "https://github.com/neural-axis/VibeDoctor#readme",
62
+ "homepage": "https://vibedoctor.in",
55
63
  "bugs": {
56
64
  "url": "https://github.com/neural-axis/VibeDoctor/issues"
57
65
  },
58
66
  "dependencies": {
59
67
  "commander": "^14.0.0",
60
- "minimatch": "^10.0.1",
68
+ "minimatch": "^11.0.9",
61
69
  "yaml": "^2.8.1"
62
70
  },
63
71
  "devDependencies": {
64
72
  "@biomejs/biome": "^2.5.0",
65
73
  "@types/node": "^24.0.1",
66
- "@vitest/coverage-v8": "^3.2.6",
74
+ "@vitest/coverage-v8": "^4.1.12",
67
75
  "jscpd": "^5.0.9",
68
- "knip": "^6.16.1",
76
+ "knip": "^6.48.0",
69
77
  "tsx": "^4.20.3",
70
78
  "typescript": "^5.8.3",
71
- "vite": "^7.3.5",
72
- "vitest": "^3.2.6"
79
+ "vite": "^7.3.8",
80
+ "vitest": "^4.1.12"
73
81
  },
74
82
  "overrides": {
75
83
  "esbuild": "0.28.1"
@@ -0,0 +1,92 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/neuralaxis/vibedoctor/schemas/machine-envelope.v1.schema.json",
4
+ "title": "VibeDoctor machine envelope v1",
5
+ "description": "Output of `vibedoctor scan --report envelope`. See docs/machine-envelope.md. Additive fields keep the major version.",
6
+ "type": "object",
7
+ "required": ["schema", "schemaVersion", "producer", "run", "repository", "config", "execution", "gate", "report"],
8
+ "properties": {
9
+ "schema": { "const": "vibedoctor.machine-envelope" },
10
+ "schemaVersion": { "type": "string", "pattern": "^1\\.\\d+\\.\\d+$" },
11
+ "producer": {
12
+ "type": "object",
13
+ "required": ["name", "version"],
14
+ "properties": { "name": { "type": "string" }, "version": { "type": "string" } }
15
+ },
16
+ "run": {
17
+ "type": "object",
18
+ "required": ["id", "startedAt", "finishedAt", "mode", "profile", "network", "categories"],
19
+ "properties": {
20
+ "id": { "type": "string" },
21
+ "startedAt": { "type": "string", "format": "date-time" },
22
+ "finishedAt": { "type": "string", "format": "date-time" },
23
+ "mode": { "type": "string" },
24
+ "profile": { "enum": ["default", "static", "trusted"] },
25
+ "network": { "type": "boolean" },
26
+ "categories": { "type": ["array", "null"], "items": { "type": "string" } }
27
+ }
28
+ },
29
+ "repository": {
30
+ "type": "object",
31
+ "required": ["root", "source", "git"],
32
+ "properties": {
33
+ "root": { "type": "string" },
34
+ "source": {
35
+ "type": "object",
36
+ "required": ["algorithm", "value", "files", "truncated"],
37
+ "properties": {
38
+ "algorithm": { "const": "sha256-tree-v1" },
39
+ "value": { "type": "string", "pattern": "^[0-9a-f]{64}$" },
40
+ "files": { "type": "integer", "minimum": 0 },
41
+ "truncated": { "type": "boolean" }
42
+ }
43
+ },
44
+ "git": {
45
+ "type": "object",
46
+ "required": ["head", "dirty", "changedFiles"],
47
+ "properties": {
48
+ "head": { "type": ["string", "null"] },
49
+ "dirty": { "type": ["boolean", "null"] },
50
+ "changedFiles": { "type": ["integer", "null"] }
51
+ }
52
+ }
53
+ }
54
+ },
55
+ "config": {
56
+ "type": "object",
57
+ "required": ["path", "fingerprint"],
58
+ "properties": {
59
+ "path": { "type": ["string", "null"] },
60
+ "fingerprint": { "type": "string", "pattern": "^[0-9a-f]{64}$" }
61
+ }
62
+ },
63
+ "execution": {
64
+ "type": "object",
65
+ "required": ["status"],
66
+ "properties": { "status": { "const": "completed" } }
67
+ },
68
+ "gate": {
69
+ "type": "object",
70
+ "required": ["exitCode", "status"],
71
+ "properties": {
72
+ "exitCode": { "enum": [0, 1, 2] },
73
+ "status": { "enum": ["pass", "fail", "incomplete"] }
74
+ }
75
+ },
76
+ "report": {
77
+ "type": "object",
78
+ "description": "The `scan --report json` document. Findings additionally carry `fingerprint`.",
79
+ "required": ["score", "completeness", "findings", "capabilityMatrix"],
80
+ "properties": {
81
+ "findings": {
82
+ "type": "array",
83
+ "items": {
84
+ "type": "object",
85
+ "required": ["id", "source", "category", "severity", "title", "fingerprint"],
86
+ "properties": { "fingerprint": { "type": "string" } }
87
+ }
88
+ }
89
+ }
90
+ }
91
+ }
92
+ }