claude-crap 0.2.0 → 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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-crap-plugin",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for the claude-crap plugin bundle",
6
6
  "type": "module",
package/src/index.ts CHANGED
@@ -58,8 +58,10 @@ import { loadCrapConfig, CrapConfigError } from "./crap-config.js";
58
58
  import { findTestFile } from "./tools/test-harness.js";
59
59
  import { resolveWithinWorkspace } from "./workspace-guard.js";
60
60
  import { autoScan } from "./scanner/auto-scan.js";
61
+ import { bootstrapScanner } from "./scanner/bootstrap.js";
61
62
  import {
62
63
  autoScanSchema,
64
+ bootstrapScannerSchema,
63
65
  computeCrapSchema,
64
66
  computeTdrSchema,
65
67
  analyzeFileAstSchema,
@@ -213,6 +215,12 @@ async function main(): Promise<void> {
213
215
  "Auto-detect available scanners (ESLint, Semgrep, Bandit, Stryker) in the workspace, run them, and ingest findings into the SARIF store.",
214
216
  inputSchema: autoScanSchema,
215
217
  },
218
+ {
219
+ name: "bootstrap_scanner",
220
+ description:
221
+ "Detect project type, install the right scanner (ESLint for JS/TS, Bandit for Python, Semgrep for Java/C#), create minimal config, and run auto_scan to verify.",
222
+ inputSchema: bootstrapScannerSchema,
223
+ },
216
224
  ],
217
225
  }));
218
226
 
@@ -540,6 +548,36 @@ async function main(): Promise<void> {
540
548
  }
541
549
  }
542
550
 
551
+ case "bootstrap_scanner": {
552
+ logger.info({ tool: "bootstrap_scanner" }, "Tool call received");
553
+ try {
554
+ const result = await bootstrapScanner(config.pluginRoot, sarifStore, logger);
555
+ const markdown = renderBootstrapMarkdown(result);
556
+ return {
557
+ content: [
558
+ { type: "text", text: markdown },
559
+ { type: "text", text: JSON.stringify(result, null, 2) },
560
+ ],
561
+ isError: !result.success,
562
+ };
563
+ } catch (err) {
564
+ logger.error({ err }, "bootstrap_scanner failed");
565
+ return {
566
+ content: [
567
+ {
568
+ type: "text",
569
+ text: JSON.stringify(
570
+ { tool: "bootstrap_scanner", status: "error", message: (err as Error).message },
571
+ null,
572
+ 2,
573
+ ),
574
+ },
575
+ ],
576
+ isError: true,
577
+ };
578
+ }
579
+ }
580
+
543
581
  case "auto_scan": {
544
582
  logger.info({ tool: "auto_scan" }, "Tool call received");
545
583
  try {
@@ -653,6 +691,46 @@ async function main(): Promise<void> {
653
691
  });
654
692
  }
655
693
 
694
+ /**
695
+ * Render a human-readable Markdown summary of a bootstrap result.
696
+ */
697
+ function renderBootstrapMarkdown(result: import("./scanner/bootstrap.js").BootstrapResult): string {
698
+ const lines: string[] = ["## claude-crap :: bootstrap scanner\n"];
699
+
700
+ lines.push(`**Project type:** ${result.projectType}`);
701
+
702
+ if (result.alreadyConfigured) {
703
+ lines.push(`**Status:** Scanner(s) already configured: ${result.existingScanners.join(", ")}`);
704
+ lines.push("\nNo installation needed. Run `auto_scan` to ingest findings.");
705
+ return lines.join("\n");
706
+ }
707
+
708
+ lines.push("");
709
+
710
+ if (result.steps.length > 0) {
711
+ lines.push("### Steps\n");
712
+ lines.push("| Action | Status | Detail |");
713
+ lines.push("| ------ | :----: | ------ |");
714
+ for (const s of result.steps) {
715
+ const status = s.success ? "ok" : "failed";
716
+ lines.push(`| ${s.action} | ${status} | ${s.detail} |`);
717
+ }
718
+ lines.push("");
719
+ }
720
+
721
+ if (result.autoScanResult) {
722
+ const r = result.autoScanResult;
723
+ const scanners = r.results.filter((s) => s.success).map((s) => s.scanner);
724
+ lines.push(
725
+ `**Auto-scan:** ${r.totalFindings} finding(s) ingested from ${scanners.join(", ") || "no scanners"} in ${(r.totalDurationMs / 1000).toFixed(1)}s`,
726
+ );
727
+ lines.push("");
728
+ }
729
+
730
+ lines.push(`**Summary:** ${result.summary}`);
731
+ return lines.join("\n");
732
+ }
733
+
656
734
  /**
657
735
  * Render a human-readable Markdown summary of an auto-scan result.
658
736
  */
@@ -22,6 +22,7 @@
22
22
  import type { Logger } from "pino";
23
23
  import { detectScanners, type ScannerDetection } from "./detector.js";
24
24
  import { runScanner, type ScannerRunResult } from "./runner.js";
25
+ import { bootstrapScanner } from "./bootstrap.js";
25
26
  import { adaptScannerOutput, type KnownScanner } from "../adapters/index.js";
26
27
  import type { SarifStore } from "../sarif/sarif-store.js";
27
28
 
@@ -106,6 +107,20 @@ export async function autoScan(
106
107
  );
107
108
 
108
109
  if (available.length === 0) {
110
+ // No scanners configured — try to bootstrap one automatically.
111
+ logger.info("auto-scan: no scanners found, attempting bootstrap");
112
+ try {
113
+ const bootstrapResult = await bootstrapScanner(workspaceRoot, sarifStore, logger);
114
+ if (bootstrapResult.autoScanResult) {
115
+ return bootstrapResult.autoScanResult;
116
+ }
117
+ } catch (err) {
118
+ logger.warn(
119
+ { err: (err as Error).message },
120
+ "auto-scan: bootstrap failed — continuing with empty results",
121
+ );
122
+ }
123
+
109
124
  return {
110
125
  detected,
111
126
  results: [],
@@ -0,0 +1,435 @@
1
+ /**
2
+ * Bootstrap a scanner for projects that don't have one configured.
3
+ *
4
+ * Detects the project type from workspace signals (package.json,
5
+ * tsconfig.json, pyproject.toml, pom.xml, *.csproj, etc.), installs
6
+ * the appropriate scanner, creates a minimal config file, and runs
7
+ * `autoScan()` to verify and ingest findings immediately.
8
+ *
9
+ * Coverage maps to the five languages the tree-sitter engine supports:
10
+ *
11
+ * - JavaScript / TypeScript → ESLint (npm install + flat config)
12
+ * - Python → Bandit (install instructions only — virtualenv boundary)
13
+ * - Java → Semgrep (install instructions)
14
+ * - C# → Semgrep (install instructions)
15
+ * - Unknown → Semgrep (polyglot fallback)
16
+ *
17
+ * For JS/TS projects the tool runs `npm install --save-dev` and writes
18
+ * an `eslint.config.mjs`. For all other languages it returns manual
19
+ * install instructions rather than executing package managers whose
20
+ * environment assumptions may not hold.
21
+ *
22
+ * @module scanner/bootstrap
23
+ */
24
+
25
+ import { existsSync, writeFileSync, readdirSync } from "node:fs";
26
+ import { join } from "node:path";
27
+ import { execFile } from "node:child_process";
28
+ import type { Logger } from "pino";
29
+ import type { KnownScanner } from "../adapters/common.js";
30
+ import { adaptScannerOutput } from "../adapters/index.js";
31
+ import { detectScanners } from "./detector.js";
32
+ import { runScanner } from "./runner.js";
33
+ import type { AutoScanResult, ScannerResult } from "./auto-scan.js";
34
+ import type { SarifStore } from "../sarif/sarif-store.js";
35
+
36
+ // ── Types ──────────────────────────────────────────────────────────
37
+
38
+ /**
39
+ * Detected project type, aligned with tree-sitter supported languages.
40
+ */
41
+ export type ProjectType =
42
+ | "javascript"
43
+ | "typescript"
44
+ | "python"
45
+ | "java"
46
+ | "csharp"
47
+ | "unknown";
48
+
49
+ /**
50
+ * A single step in the bootstrap process.
51
+ */
52
+ export interface BootstrapStep {
53
+ /** What was attempted (e.g. "install eslint", "create eslint.config.mjs"). */
54
+ action: string;
55
+ /** Whether the step completed successfully. */
56
+ success: boolean;
57
+ /** Human-readable detail (command output, error message, or instruction). */
58
+ detail: string;
59
+ }
60
+
61
+ /**
62
+ * Complete result of a bootstrap_scanner invocation.
63
+ */
64
+ export interface BootstrapResult {
65
+ /** Detected project type based on workspace signals. */
66
+ projectType: ProjectType;
67
+ /** Whether a scanner was already configured (detected by detector.ts). */
68
+ alreadyConfigured: boolean;
69
+ /** Which scanners were already available, if any. */
70
+ existingScanners: string[];
71
+ /** Steps executed (or instructions returned) during bootstrap. */
72
+ steps: BootstrapStep[];
73
+ /** The auto-scan result after installation (null if skipped). */
74
+ autoScanResult: AutoScanResult | null;
75
+ /** Whether the overall bootstrap succeeded. */
76
+ success: boolean;
77
+ /** Summary message suitable for display. */
78
+ summary: string;
79
+ }
80
+
81
+ // ── Project type detection ─────────────────────────────────────────
82
+
83
+ /**
84
+ * Detect the project type from workspace signals.
85
+ *
86
+ * Checks in priority order: TypeScript, JavaScript, Python, Java,
87
+ * C#, then unknown. TypeScript wins over plain JavaScript because
88
+ * `tsconfig.json` implies a superset.
89
+ */
90
+ export function detectProjectType(workspaceRoot: string): ProjectType {
91
+ const has = (file: string) => existsSync(join(workspaceRoot, file));
92
+
93
+ // JS/TS detection — package.json is the anchor
94
+ if (has("package.json")) {
95
+ if (has("tsconfig.json")) return "typescript";
96
+ return "javascript";
97
+ }
98
+
99
+ // Python detection
100
+ if (has("pyproject.toml") || has("setup.py") || has("requirements.txt")) {
101
+ return "python";
102
+ }
103
+
104
+ // Java detection
105
+ if (has("pom.xml") || has("build.gradle") || has("build.gradle.kts")) {
106
+ return "java";
107
+ }
108
+
109
+ // C# detection
110
+ if (has("Directory.Build.props")) return "csharp";
111
+ try {
112
+ const entries = readdirSync(workspaceRoot);
113
+ if (entries.some((e) => e.endsWith(".csproj") || e.endsWith(".sln"))) {
114
+ return "csharp";
115
+ }
116
+ } catch {
117
+ // readdirSync can fail on permissions — fall through
118
+ }
119
+
120
+ return "unknown";
121
+ }
122
+
123
+ // ── ESLint config generation ───────────────────────────────────────
124
+
125
+ /**
126
+ * Generate a minimal ESLint flat config (ESLint 9+).
127
+ *
128
+ * @param isTypeScript Include typescript-eslint when true.
129
+ * @returns The config file content as a string.
130
+ */
131
+ export function generateEslintConfig(isTypeScript: boolean): string {
132
+ if (isTypeScript) {
133
+ return `import js from "@eslint/js";
134
+ import tseslint from "typescript-eslint";
135
+
136
+ export default tseslint.config(
137
+ js.configs.recommended,
138
+ ...tseslint.configs.recommended,
139
+ {
140
+ ignores: ["dist/", "node_modules/", "coverage/"],
141
+ },
142
+ );
143
+ `;
144
+ }
145
+
146
+ return `import js from "@eslint/js";
147
+
148
+ export default [
149
+ js.configs.recommended,
150
+ {
151
+ ignores: ["dist/", "node_modules/", "coverage/"],
152
+ },
153
+ ];
154
+ `;
155
+ }
156
+
157
+ // ── Installation helpers ───────────────────────────────────────────
158
+
159
+ /**
160
+ * Run `npm install --save-dev` for the given packages.
161
+ */
162
+ function npmInstall(
163
+ workspaceRoot: string,
164
+ packages: string[],
165
+ ): Promise<BootstrapStep> {
166
+ return new Promise((resolve) => {
167
+ execFile(
168
+ "npm",
169
+ ["install", "--save-dev", ...packages],
170
+ {
171
+ cwd: workspaceRoot,
172
+ timeout: 120_000,
173
+ env: { ...process.env, FORCE_COLOR: "0" },
174
+ },
175
+ (err, stdout, stderr) => {
176
+ if (err) {
177
+ resolve({
178
+ action: `npm install --save-dev ${packages.join(" ")}`,
179
+ success: false,
180
+ detail: stderr || (err as Error).message,
181
+ });
182
+ return;
183
+ }
184
+ resolve({
185
+ action: `npm install --save-dev ${packages.join(" ")}`,
186
+ success: true,
187
+ detail: `installed ${packages.join(", ")}`,
188
+ });
189
+ },
190
+ );
191
+ });
192
+ }
193
+
194
+ /**
195
+ * Write the ESLint config file to the workspace root.
196
+ * Returns failure if the file already exists.
197
+ */
198
+ function writeEslintConfigFile(
199
+ workspaceRoot: string,
200
+ isTypeScript: boolean,
201
+ ): BootstrapStep {
202
+ const configPath = join(workspaceRoot, "eslint.config.mjs");
203
+ if (existsSync(configPath)) {
204
+ return {
205
+ action: "create eslint.config.mjs",
206
+ success: true,
207
+ detail: "eslint.config.mjs already exists — skipped",
208
+ };
209
+ }
210
+
211
+ try {
212
+ writeFileSync(configPath, generateEslintConfig(isTypeScript), "utf-8");
213
+ return {
214
+ action: "create eslint.config.mjs",
215
+ success: true,
216
+ detail: `created eslint.config.mjs (${isTypeScript ? "TypeScript" : "JavaScript"} template)`,
217
+ };
218
+ } catch (err) {
219
+ return {
220
+ action: "create eslint.config.mjs",
221
+ success: false,
222
+ detail: (err as Error).message,
223
+ };
224
+ }
225
+ }
226
+
227
+ // ── Scanner-to-language mapping ────────────────────────────────────
228
+
229
+ /**
230
+ * Map project type → recommended scanner and install instructions.
231
+ */
232
+ interface ScannerRecommendation {
233
+ scanner: KnownScanner;
234
+ canAutoInstall: boolean;
235
+ installInstructions: string;
236
+ }
237
+
238
+ function getRecommendation(projectType: ProjectType): ScannerRecommendation {
239
+ switch (projectType) {
240
+ case "javascript":
241
+ case "typescript":
242
+ return {
243
+ scanner: "eslint",
244
+ canAutoInstall: true,
245
+ installInstructions: "npm install --save-dev eslint @eslint/js",
246
+ };
247
+ case "python":
248
+ return {
249
+ scanner: "bandit",
250
+ canAutoInstall: false,
251
+ installInstructions:
252
+ "pip install bandit (or: pipx install bandit, poetry add --group dev bandit)",
253
+ };
254
+ case "java":
255
+ case "csharp":
256
+ return {
257
+ scanner: "semgrep",
258
+ canAutoInstall: false,
259
+ installInstructions:
260
+ "brew install semgrep (or: pip install semgrep, pipx install semgrep)",
261
+ };
262
+ case "unknown":
263
+ return {
264
+ scanner: "semgrep",
265
+ canAutoInstall: false,
266
+ installInstructions:
267
+ "brew install semgrep (or: pip install semgrep, pipx install semgrep)",
268
+ };
269
+ }
270
+ }
271
+
272
+ // ── Main orchestrator ──────────────────────────────────────────────
273
+
274
+ /**
275
+ * Bootstrap a scanner for the current workspace.
276
+ *
277
+ * 1. Check if a scanner is already configured (short-circuit if so)
278
+ * 2. Detect the project type
279
+ * 3. Install the recommended scanner (or return instructions)
280
+ * 4. Run auto_scan to verify and ingest findings
281
+ *
282
+ * @param workspaceRoot Absolute path to the project root.
283
+ * @param sarifStore Live SARIF store for auto-scan ingestion.
284
+ * @param logger Pino logger for progress reporting.
285
+ */
286
+ export async function bootstrapScanner(
287
+ workspaceRoot: string,
288
+ sarifStore: SarifStore,
289
+ logger: Logger,
290
+ ): Promise<BootstrapResult> {
291
+ // 1. Check existing scanners
292
+ const detections = await detectScanners(workspaceRoot);
293
+ const available = detections.filter((d) => d.available);
294
+
295
+ if (available.length > 0) {
296
+ const existingScanners = available.map((d) => d.scanner);
297
+ logger.info(
298
+ { existingScanners },
299
+ "bootstrap: scanner(s) already configured — skipping",
300
+ );
301
+ return {
302
+ projectType: detectProjectType(workspaceRoot),
303
+ alreadyConfigured: true,
304
+ existingScanners,
305
+ steps: [],
306
+ autoScanResult: null,
307
+ success: true,
308
+ summary: `Scanner(s) already configured: ${existingScanners.join(", ")}. Run auto_scan to ingest findings.`,
309
+ };
310
+ }
311
+
312
+ // 2. Detect project type
313
+ const projectType = detectProjectType(workspaceRoot);
314
+ const recommendation = getRecommendation(projectType);
315
+ const steps: BootstrapStep[] = [];
316
+
317
+ logger.info(
318
+ { projectType, scanner: recommendation.scanner },
319
+ "bootstrap: detected project type",
320
+ );
321
+
322
+ // 3. Install scanner
323
+ if (recommendation.canAutoInstall) {
324
+ // JS/TS: auto-install ESLint
325
+ const isTypeScript = projectType === "typescript";
326
+ const packages = isTypeScript
327
+ ? ["eslint", "@eslint/js", "typescript-eslint"]
328
+ : ["eslint", "@eslint/js"];
329
+
330
+ const installStep = await npmInstall(workspaceRoot, packages);
331
+ steps.push(installStep);
332
+
333
+ if (installStep.success) {
334
+ const configStep = writeEslintConfigFile(workspaceRoot, isTypeScript);
335
+ steps.push(configStep);
336
+ }
337
+ } else {
338
+ // Python / Java / C# / Unknown: return instructions
339
+ steps.push({
340
+ action: `suggest ${recommendation.scanner} install`,
341
+ success: true,
342
+ detail: recommendation.installInstructions,
343
+ });
344
+ }
345
+
346
+ // 4. Run scanner directly if installation succeeded (inline scan
347
+ // to avoid circular dependency — autoScan calls bootstrapScanner)
348
+ const installSucceeded = steps.every((s) => s.success);
349
+ let autoScanResult: AutoScanResult | null = null;
350
+
351
+ if (installSucceeded && recommendation.canAutoInstall) {
352
+ try {
353
+ const scanStart = Date.now();
354
+ const postDetections = await detectScanners(workspaceRoot);
355
+ const postAvailable = postDetections.filter((d) => d.available);
356
+ const scanResults: ScannerResult[] = [];
357
+ let scanFindings = 0;
358
+
359
+ const settled = await Promise.allSettled(
360
+ postAvailable.map((d) => runScanner(d.scanner, workspaceRoot)),
361
+ );
362
+
363
+ for (let i = 0; i < postAvailable.length; i++) {
364
+ const det = postAvailable[i]!;
365
+ const res = settled[i]!;
366
+
367
+ if (res.status === "rejected" || !res.value.success) {
368
+ scanResults.push({
369
+ scanner: det.scanner,
370
+ success: false,
371
+ findingsIngested: 0,
372
+ durationMs: res.status === "fulfilled" ? res.value.durationMs : 0,
373
+ error: res.status === "rejected"
374
+ ? String(res.reason)
375
+ : res.value.error ?? "unknown error",
376
+ });
377
+ continue;
378
+ }
379
+
380
+ const runResult = res.value;
381
+ let parsed: unknown;
382
+ try { parsed = JSON.parse(runResult.rawOutput); } catch { parsed = runResult.rawOutput; }
383
+ const adapted = adaptScannerOutput(runResult.scanner, parsed);
384
+ const stats = sarifStore.ingestRun(adapted.document, adapted.sourceTool);
385
+ scanFindings += stats.accepted;
386
+
387
+ scanResults.push({
388
+ scanner: runResult.scanner,
389
+ success: true,
390
+ findingsIngested: stats.accepted,
391
+ durationMs: runResult.durationMs,
392
+ });
393
+ }
394
+
395
+ if (scanFindings > 0) await sarifStore.persist();
396
+
397
+ autoScanResult = {
398
+ detected: postDetections,
399
+ results: scanResults,
400
+ totalFindings: scanFindings,
401
+ totalDurationMs: Date.now() - scanStart,
402
+ };
403
+ } catch (err) {
404
+ logger.warn(
405
+ { err: (err as Error).message },
406
+ "bootstrap: scan after install failed",
407
+ );
408
+ }
409
+ }
410
+
411
+ // 5. Build result
412
+ const findings = autoScanResult?.totalFindings ?? 0;
413
+ const scannerInstalled = recommendation.canAutoInstall && installSucceeded;
414
+
415
+ let summary: string;
416
+ if (scannerInstalled && autoScanResult) {
417
+ summary = `Installed ${recommendation.scanner} for ${projectType} project. Auto-scan found ${findings} finding(s).`;
418
+ } else if (scannerInstalled) {
419
+ summary = `Installed ${recommendation.scanner} for ${projectType} project. Auto-scan did not run.`;
420
+ } else if (!recommendation.canAutoInstall) {
421
+ summary = `Detected ${projectType} project. Install ${recommendation.scanner} manually: ${recommendation.installInstructions}`;
422
+ } else {
423
+ summary = `Failed to install ${recommendation.scanner}. Check the error details in the steps.`;
424
+ }
425
+
426
+ return {
427
+ projectType,
428
+ alreadyConfigured: false,
429
+ existingScanners: [],
430
+ steps,
431
+ autoScanResult,
432
+ success: installSucceeded,
433
+ summary,
434
+ };
435
+ }
@@ -20,3 +20,11 @@
20
20
  export { detectScanners, type ScannerDetection } from "./detector.js";
21
21
  export { runScanner, type ScannerRunResult } from "./runner.js";
22
22
  export { autoScan, type AutoScanResult, type ScannerResult } from "./auto-scan.js";
23
+ export {
24
+ bootstrapScanner,
25
+ detectProjectType,
26
+ generateEslintConfig,
27
+ type BootstrapResult,
28
+ type BootstrapStep,
29
+ type ProjectType,
30
+ } from "./bootstrap.js";
@@ -203,6 +203,20 @@ export const ingestScannerOutputSchema = {
203
203
  * Schema for the `auto_scan` tool. Auto-detects available scanners
204
204
  * in the workspace, runs them, and ingests findings into the SARIF store.
205
205
  */
206
+ /**
207
+ * Schema for the `bootstrap_scanner` tool. Detects project type,
208
+ * installs the appropriate scanner, creates config files, and runs
209
+ * auto_scan to verify.
210
+ */
211
+ export const bootstrapScannerSchema = {
212
+ type: "object",
213
+ description:
214
+ "Detect the project type (JavaScript, TypeScript, Python, Java, C#), install the appropriate scanner (ESLint for JS/TS, Bandit for Python, Semgrep for Java/C#), create a minimal config file, and run auto_scan to verify. Skips installation if a scanner is already configured. Use this when auto_scan finds no scanners and quality grades are vacuously A.",
215
+ properties: {},
216
+ required: [],
217
+ additionalProperties: false,
218
+ } as const;
219
+
206
220
  export const autoScanSchema = {
207
221
  type: "object",
208
222
  description:
@@ -232,7 +232,7 @@ describe("MCP server integration", { skip: !serverBuilt }, () => {
232
232
  assert.ok(child && !child.killed, "server child should be running");
233
233
  });
234
234
 
235
- it("exposes all eight tools via tools/list", async () => {
235
+ it("exposes all nine tools via tools/list", async () => {
236
236
  const response = await client!.request<{ result?: { tools?: Array<{ name: string }> } }>(
237
237
  "tools/list",
238
238
  );
@@ -240,6 +240,7 @@ describe("MCP server integration", { skip: !serverBuilt }, () => {
240
240
  assert.deepEqual(names, [
241
241
  "analyze_file_ast",
242
242
  "auto_scan",
243
+ "bootstrap_scanner",
243
244
  "compute_crap",
244
245
  "compute_tdr",
245
246
  "ingest_sarif",