@delegance/claude-autopilot 2.4.0 → 5.0.0-alpha.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.
Files changed (129) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +164 -106
  3. package/bin/_launcher.js +77 -0
  4. package/bin/claude-autopilot.js +3 -0
  5. package/bin/guardrail.js +3 -0
  6. package/package.json +15 -9
  7. package/presets/generic/guardrail.config.yaml +35 -0
  8. package/presets/generic/stack.md +40 -0
  9. package/presets/nextjs-supabase/{autopilot.config.yaml → guardrail.config.yaml} +7 -0
  10. package/scripts/autoregress.ts +27 -11
  11. package/skills/autopilot/SKILL.md +170 -0
  12. package/skills/claude-autopilot.md +80 -0
  13. package/skills/guardrail.md +39 -0
  14. package/skills/migrate/SKILL.md +83 -0
  15. package/src/adapters/council/claude.ts +41 -0
  16. package/src/adapters/council/openai.ts +40 -0
  17. package/src/adapters/council/types.ts +7 -0
  18. package/src/adapters/loader.ts +7 -7
  19. package/src/adapters/review-engine/auto.ts +2 -2
  20. package/src/adapters/review-engine/claude.ts +9 -11
  21. package/src/adapters/review-engine/codex.ts +9 -11
  22. package/src/adapters/review-engine/gemini.ts +9 -11
  23. package/src/adapters/review-engine/openai-compatible.ts +10 -12
  24. package/src/adapters/review-engine/parse-output.ts +32 -6
  25. package/src/adapters/review-engine/prompt-builder.ts +19 -0
  26. package/src/adapters/review-engine/types.ts +1 -1
  27. package/src/adapters/vcs-host/commit-status.ts +39 -0
  28. package/src/adapters/vcs-host/github.ts +2 -2
  29. package/src/cli/baseline.ts +125 -0
  30. package/src/cli/ci.ts +11 -8
  31. package/src/cli/costs.ts +80 -0
  32. package/src/cli/council.ts +96 -0
  33. package/src/cli/detector.ts +21 -5
  34. package/src/cli/explain.ts +197 -0
  35. package/src/cli/fix.ts +249 -0
  36. package/src/cli/hook.ts +72 -27
  37. package/src/cli/ignore-helper.ts +116 -0
  38. package/src/cli/index.ts +302 -28
  39. package/src/cli/init.ts +12 -12
  40. package/src/cli/lsp.ts +200 -0
  41. package/src/cli/mcp.ts +206 -0
  42. package/src/cli/pr-comment.ts +5 -5
  43. package/src/cli/pr-desc.ts +168 -0
  44. package/src/cli/pr-review-comments.ts +3 -3
  45. package/src/cli/pr.ts +76 -0
  46. package/src/cli/preflight.ts +15 -32
  47. package/src/cli/report.ts +186 -0
  48. package/src/cli/run.ts +140 -36
  49. package/src/cli/scan.ts +233 -0
  50. package/src/cli/setup.ts +121 -15
  51. package/src/cli/test-gen.ts +125 -0
  52. package/src/cli/triage.ts +137 -0
  53. package/src/cli/watch.ts +52 -31
  54. package/src/cli/worker.ts +109 -0
  55. package/src/core/cache/review-cache.ts +2 -2
  56. package/src/core/chunking/index.ts +2 -2
  57. package/src/core/config/loader.ts +24 -12
  58. package/src/core/config/preset-resolver.ts +6 -6
  59. package/src/core/config/schema.ts +121 -3
  60. package/src/core/config/types.ts +57 -2
  61. package/src/core/council/config.ts +71 -0
  62. package/src/core/council/context.ts +17 -0
  63. package/src/core/council/runner.ts +83 -0
  64. package/src/core/council/types.ts +45 -0
  65. package/src/core/detect/llm-key.ts +89 -0
  66. package/src/core/detect/workspaces.ts +103 -0
  67. package/src/core/errors.ts +4 -4
  68. package/src/core/fix/generator.ts +149 -0
  69. package/src/core/ignore/index.ts +4 -4
  70. package/src/core/mcp/concurrency.ts +16 -0
  71. package/src/core/mcp/handlers/fix-finding.ts +126 -0
  72. package/src/core/mcp/handlers/get-capabilities.ts +62 -0
  73. package/src/core/mcp/handlers/get-findings.ts +36 -0
  74. package/src/core/mcp/handlers/review-diff.ts +65 -0
  75. package/src/core/mcp/handlers/scan-files.ts +65 -0
  76. package/src/core/mcp/handlers/validate-fix.ts +41 -0
  77. package/src/core/mcp/run-store.ts +85 -0
  78. package/src/core/mcp/workspace.ts +35 -0
  79. package/src/core/persist/baseline.ts +112 -0
  80. package/src/core/persist/cost-log.ts +1 -1
  81. package/src/core/persist/findings-cache.ts +1 -1
  82. package/src/core/persist/triage.ts +112 -0
  83. package/src/core/phases/static-rules.ts +18 -5
  84. package/src/core/pipeline/review-phase.ts +65 -26
  85. package/src/core/pipeline/run.ts +42 -10
  86. package/src/core/runtime/lock.ts +2 -2
  87. package/src/core/runtime/state.ts +2 -2
  88. package/src/core/schema-alignment/detector.ts +59 -0
  89. package/src/core/schema-alignment/extractor/index.ts +24 -0
  90. package/src/core/schema-alignment/extractor/prisma.ts +21 -0
  91. package/src/core/schema-alignment/extractor/sql.ts +99 -0
  92. package/src/core/schema-alignment/llm-check.ts +91 -0
  93. package/src/core/schema-alignment/scanner.ts +107 -0
  94. package/src/core/schema-alignment/types.ts +43 -0
  95. package/src/core/shell.ts +3 -3
  96. package/src/core/static-rules/registry.ts +17 -8
  97. package/src/core/static-rules/rules/brand-tokens.ts +145 -0
  98. package/src/core/static-rules/rules/hardcoded-secrets.ts +27 -1
  99. package/src/core/static-rules/rules/insecure-redirect.ts +67 -0
  100. package/src/core/static-rules/rules/missing-auth.ts +70 -0
  101. package/src/core/static-rules/rules/schema-alignment.ts +132 -0
  102. package/src/core/static-rules/rules/sql-injection.ts +71 -0
  103. package/src/core/static-rules/rules/ssrf.ts +63 -0
  104. package/src/core/static-rules/tailwind-extractor.ts +38 -0
  105. package/src/core/test-gen/coverage-analyzer.ts +93 -0
  106. package/src/core/test-gen/framework-detector.ts +21 -0
  107. package/src/core/test-gen/test-writer.ts +33 -0
  108. package/src/core/ui/design-context-loader.ts +87 -0
  109. package/src/core/worker/client.ts +46 -0
  110. package/src/core/worker/lockfile.ts +38 -0
  111. package/src/core/worker/server.ts +81 -0
  112. package/src/formatters/junit.ts +52 -0
  113. package/src/formatters/sarif.ts +2 -2
  114. package/src/index.ts +1 -2
  115. package/tests/snapshots/baselines/src-formatters-sarif.json +4 -4
  116. package/tests/snapshots/index.json +3 -3
  117. package/tests/snapshots/src-formatters-sarif.snap.ts +1 -1
  118. package/tests/snapshots/src-snapshots-impact-selector.snap.ts +3 -3
  119. package/tests/snapshots/src-snapshots-import-scanner.snap.ts +3 -3
  120. package/tests/snapshots/src-snapshots-serializer.snap.ts +2 -2
  121. package/bin/autopilot.js +0 -20
  122. package/skills/autopilot.md +0 -157
  123. /package/presets/go/{autopilot.config.yaml → guardrail.config.yaml} +0 -0
  124. /package/presets/python-fastapi/{autopilot.config.yaml → guardrail.config.yaml} +0 -0
  125. /package/presets/rails-postgres/{autopilot.config.yaml → guardrail.config.yaml} +0 -0
  126. /package/presets/t3/{autopilot.config.yaml → guardrail.config.yaml} +0 -0
  127. /package/{src → scripts}/snapshots/impact-selector.ts +0 -0
  128. /package/{src → scripts}/snapshots/import-scanner.ts +0 -0
  129. /package/{src → scripts}/snapshots/serializer.ts +0 -0
@@ -0,0 +1,96 @@
1
+ // src/cli/council.ts
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { loadConfig } from '../core/config/loader.ts';
5
+ import { parseCouncilConfig } from '../core/council/config.ts';
6
+ import { runCouncil } from '../core/council/runner.ts';
7
+ import { makeClaudeCouncilAdapter } from '../adapters/council/claude.ts';
8
+ import { makeOpenAICouncilAdapter } from '../adapters/council/openai.ts';
9
+ import type { CouncilAdapter } from '../adapters/council/types.ts';
10
+ import type { CouncilModelEntry } from '../core/council/types.ts';
11
+ import { GuardrailError } from '../core/errors.ts';
12
+
13
+ function makeAdapter(entry: CouncilModelEntry): CouncilAdapter {
14
+ switch (entry.adapter) {
15
+ case 'claude': return makeClaudeCouncilAdapter(entry.model, entry.label);
16
+ case 'openai': return makeOpenAICouncilAdapter(entry.model, entry.label);
17
+ }
18
+ }
19
+
20
+ export async function runCouncilCmd(opts: {
21
+ prompt?: string;
22
+ contextFile?: string;
23
+ configPath?: string;
24
+ dryRun?: boolean;
25
+ noSynthesize?: boolean;
26
+ }): Promise<number> {
27
+ const cwd = process.cwd();
28
+ const configPath = opts.configPath ?? path.join(cwd, 'guardrail.config.yaml');
29
+
30
+ let config;
31
+ try {
32
+ config = await loadConfig(configPath);
33
+ } catch (err) {
34
+ console.error(err instanceof GuardrailError ? err.message : String(err));
35
+ return 1;
36
+ }
37
+
38
+ if (!config.council) {
39
+ console.error('[council] No "council" section in guardrail.config.yaml — add council.models and council.synthesizer');
40
+ return 1;
41
+ }
42
+
43
+ let councilConfig;
44
+ try {
45
+ councilConfig = parseCouncilConfig(config.council as Record<string, unknown>);
46
+ } catch (err) {
47
+ console.error(err instanceof GuardrailError ? err.message : String(err));
48
+ return 1;
49
+ }
50
+
51
+ if (opts.dryRun) {
52
+ process.stdout.write(JSON.stringify({ schema_version: 1, status: 'dry_run', config: councilConfig }, null, 2) + '\n');
53
+ return 0;
54
+ }
55
+
56
+ if (!opts.prompt) {
57
+ console.error('[council] --prompt is required');
58
+ return 1;
59
+ }
60
+ if (!opts.contextFile) {
61
+ console.error('[council] --context-file is required');
62
+ return 1;
63
+ }
64
+
65
+ let contextDoc: string;
66
+ try {
67
+ contextDoc = fs.readFileSync(opts.contextFile, 'utf8');
68
+ } catch {
69
+ console.error(`[council] Cannot read context file: ${opts.contextFile}`);
70
+ return 1;
71
+ }
72
+
73
+ const adapters = councilConfig.models.map(makeAdapter);
74
+ const synthesizer = opts.noSynthesize
75
+ ? { label: 'none', consult: async () => '' } as CouncilAdapter
76
+ : makeAdapter(councilConfig.synthesizer);
77
+
78
+ const result = await runCouncil(
79
+ councilConfig,
80
+ adapters,
81
+ synthesizer,
82
+ opts.prompt,
83
+ contextDoc,
84
+ );
85
+
86
+ // When no-synthesize, clear the empty synthesis object
87
+ if (opts.noSynthesize && result.synthesis?.text === '') {
88
+ delete (result as unknown as Record<string, unknown>)['synthesis'];
89
+ }
90
+
91
+ process.stdout.write(JSON.stringify(result, null, 2) + '\n');
92
+
93
+ if (result.status === 'failed') return 2;
94
+ if (result.status === 'partial') return 1;
95
+ return 0;
96
+ }
@@ -34,6 +34,21 @@ function nodeTestCommand(cwd: string): string {
34
34
  return cmd;
35
35
  }
36
36
 
37
+ // Detects Supabase signals beyond package.json deps — env vars, config files, or client
38
+ // usage. Required because many Next.js projects reference Supabase via the CLI/SSR tooling
39
+ // before installing the JS client.
40
+ function hasSupabaseSignals(cwd: string, deps: Record<string, string>): boolean {
41
+ if ('@supabase/supabase-js' in deps) return true;
42
+ if ('@supabase/ssr' in deps) return true;
43
+ if ('@supabase/auth-helpers-nextjs' in deps) return true;
44
+ if (fs.existsSync(path.join(cwd, 'supabase', 'config.toml'))) return true;
45
+ for (const envFile of ['.env', '.env.local', '.env.development']) {
46
+ const p = path.join(cwd, envFile);
47
+ if (fs.existsSync(p) && fileContains(p, 'SUPABASE_')) return true;
48
+ }
49
+ return false;
50
+ }
51
+
37
52
  export function detectProject(cwd: string): DetectionResult {
38
53
  if (fs.existsSync(path.join(cwd, 'go.mod'))) {
39
54
  return { preset: 'go', testCommand: 'go test ./...', confidence: 'high', evidence: 'found go.mod' };
@@ -63,14 +78,15 @@ export function detectProject(cwd: string): DetectionResult {
63
78
  if ('@trpc/server' in deps) {
64
79
  return { preset: 't3', testCommand: testCmd, confidence: 'high', evidence: 'found @trpc/server in package.json' };
65
80
  }
66
- if ('next' in deps && '@supabase/supabase-js' in deps) {
67
- return { preset: 'nextjs-supabase', testCommand: testCmd, confidence: 'high', evidence: 'found next + @supabase/supabase-js in package.json' };
81
+ if ('next' in deps && hasSupabaseSignals(cwd, deps)) {
82
+ return { preset: 'nextjs-supabase', testCommand: testCmd, confidence: 'high', evidence: 'found next + supabase signals (deps/env/config)' };
68
83
  }
69
84
  if ('next' in deps) {
70
- return { preset: 'nextjs-supabase', testCommand: testCmd, confidence: 'low', evidence: 'found next in package.json (no supabase detected)' };
85
+ // Plain Next.js fall through to generic rather than mislabel as nextjs-supabase.
86
+ return { preset: 'generic', testCommand: testCmd, confidence: 'low', evidence: 'found next in package.json but no Supabase signals — using generic preset (pass --preset nextjs-supabase if you do use Supabase)' };
71
87
  }
72
- return { preset: 'nextjs-supabase', testCommand: testCmd, confidence: 'low', evidence: 'found package.json (no strong framework signals)' };
88
+ return { preset: 'generic', testCommand: testCmd, confidence: 'low', evidence: 'found package.json (no strong framework signals) — using generic preset' };
73
89
  }
74
90
 
75
- return { preset: 'nextjs-supabase', testCommand: 'npm test', confidence: 'low', evidence: 'no project signals found — using default preset' };
91
+ return { preset: 'generic', testCommand: 'npm test', confidence: 'low', evidence: 'no project signals found — using generic preset' };
76
92
  }
@@ -0,0 +1,197 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { loadCachedFindings } from '../core/persist/findings-cache.ts';
4
+ import { loadConfig } from '../core/config/loader.ts';
5
+ import { loadAdapter } from '../adapters/loader.ts';
6
+ import type { Finding } from '../core/findings/types.ts';
7
+ import type { ReviewEngine } from '../adapters/review-engine/types.ts';
8
+
9
+ const C = {
10
+ reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m',
11
+ green: '\x1b[32m', yellow: '\x1b[33m', red: '\x1b[31m', cyan: '\x1b[36m',
12
+ };
13
+ const fmt = (c: keyof typeof C, t: string) => `${C[c]}${t}${C.reset}`;
14
+
15
+ const CONTEXT_LINES = 30;
16
+
17
+ const SECTION_ORDER = ['Root Cause', 'Risk', 'How to Fix', 'Example', 'When to Suppress'] as const;
18
+ type SectionName = typeof SECTION_ORDER[number];
19
+
20
+ export interface ExplainCommandOptions {
21
+ cwd?: string;
22
+ configPath?: string;
23
+ target?: string; // "file:line" or finding index (1-based) or finding id
24
+ index?: number; // 1-based index into cached findings
25
+ }
26
+
27
+ function pickFinding(findings: Finding[], target: string): Finding | null {
28
+ // Try "file:line" format
29
+ const colonIdx = target.lastIndexOf(':');
30
+ if (colonIdx > 0) {
31
+ const file = target.slice(0, colonIdx);
32
+ const line = parseInt(target.slice(colonIdx + 1), 10);
33
+ if (!isNaN(line)) {
34
+ const match = findings.find(f => f.file.endsWith(file) && f.line === line);
35
+ if (match) return match;
36
+ }
37
+ }
38
+ // Try numeric index (1-based)
39
+ const n = parseInt(target, 10);
40
+ if (!isNaN(n) && n >= 1 && n <= findings.length) return findings[n - 1]!;
41
+ // Try finding id prefix
42
+ const byId = findings.find(f => f.id.startsWith(target));
43
+ if (byId) return byId;
44
+ return null;
45
+ }
46
+
47
+ /** Parse LLM output into named sections by ## headers. */
48
+ function parseSections(text: string): Map<string, string> {
49
+ const map = new Map<string, string>();
50
+ const parts = text.split(/^##\s+/m);
51
+ for (const part of parts) {
52
+ const newline = part.indexOf('\n');
53
+ if (newline < 0) continue;
54
+ const header = part.slice(0, newline).trim();
55
+ const body = part.slice(newline + 1).trim();
56
+ if (header && body) map.set(header, body);
57
+ }
58
+ return map;
59
+ }
60
+
61
+ function printSection(label: SectionName, body: string): void {
62
+ const icon: Record<SectionName, string> = {
63
+ 'Root Cause': '🔍',
64
+ 'Risk': '⚠️ ',
65
+ 'How to Fix': '🔧',
66
+ 'Example': '📝',
67
+ 'When to Suppress': '✅',
68
+ };
69
+ console.log(`\n${fmt('bold', `${icon[label]} ${label}`)}`);
70
+ console.log(fmt('dim', '─'.repeat(50)));
71
+ console.log(body);
72
+ }
73
+
74
+ export async function runExplain(options: ExplainCommandOptions = {}): Promise<number> {
75
+ const cwd = options.cwd ?? process.cwd();
76
+ const configPath = options.configPath ?? path.join(cwd, 'guardrail.config.yaml');
77
+
78
+ const findings = loadCachedFindings(cwd);
79
+ if (findings.length === 0) {
80
+ console.log(fmt('yellow', '[explain] No cached findings — run `guardrail run` or `guardrail scan` first.'));
81
+ return 0;
82
+ }
83
+
84
+ let finding: Finding | null = null;
85
+
86
+ if (options.target) {
87
+ finding = pickFinding(findings, options.target);
88
+ if (!finding) {
89
+ console.error(fmt('red', `[explain] No finding matching "${options.target}"`));
90
+ console.error(fmt('dim', ' Use file:line, finding index (1–' + findings.length + '), or rule id'));
91
+ return 1;
92
+ }
93
+ } else {
94
+ // No target — list findings and prompt
95
+ console.log(`\n${fmt('bold', '[guardrail explain]')} ${findings.length} cached finding${findings.length !== 1 ? 's' : ''}:\n`);
96
+ findings.forEach((f, i) => {
97
+ const sev = f.severity === 'critical' ? fmt('red', 'CRIT') : f.severity === 'warning' ? fmt('yellow', 'WARN') : fmt('dim', 'NOTE');
98
+ const loc = f.file !== '<unspecified>' ? fmt('dim', ` ${f.file}${f.line ? `:${f.line}` : ''}`) : '';
99
+ console.log(` ${String(i + 1).padStart(2)}. [${sev}]${loc} ${f.message.slice(0, 70)}`);
100
+ });
101
+ console.log(fmt('dim', '\n Run: guardrail explain <index|file:line|rule-id>\n'));
102
+ return 0;
103
+ }
104
+
105
+ // Load engine
106
+ let engine;
107
+ try {
108
+ const config = fs.existsSync(configPath) ? await loadConfig(configPath) : { configVersion: 1 as const };
109
+ const ref = typeof config.reviewEngine === 'string' ? config.reviewEngine
110
+ : (config.reviewEngine?.adapter ?? 'auto');
111
+ engine = await loadAdapter({ point: 'review-engine', ref,
112
+ options: typeof config.reviewEngine === 'object' ? config.reviewEngine.options : undefined });
113
+ } catch (err) {
114
+ console.error(fmt('red', `[explain] Could not load review engine: ${err instanceof Error ? err.message : String(err)}`));
115
+ return 1;
116
+ }
117
+
118
+ // Read file context
119
+ let codeContext = '';
120
+ if (finding.file && finding.file !== '<unspecified>' && finding.file !== '<pipeline>' && finding.line) {
121
+ const absPath = path.resolve(cwd, finding.file);
122
+ if (fs.existsSync(absPath)) {
123
+ const lines = fs.readFileSync(absPath, 'utf8').split('\n');
124
+ const lineIdx = finding.line - 1;
125
+ const start = Math.max(0, lineIdx - CONTEXT_LINES);
126
+ const end = Math.min(lines.length - 1, lineIdx + CONTEXT_LINES);
127
+ const numbered = lines.slice(start, end + 1).map((l, i) => {
128
+ const n = start + i + 1;
129
+ return `${n === finding!.line ? '>>>' : ' '} ${String(n).padStart(4)}: ${l}`;
130
+ }).join('\n');
131
+ codeContext = `\n\nRelevant code from ${finding.file} (>>> marks the finding):\n\`\`\`\n${numbered}\n\`\`\``;
132
+ }
133
+ }
134
+
135
+ const prompt = [
136
+ `I need a structured explanation of this code finding:`,
137
+ ``,
138
+ `Rule: ${finding.id}`,
139
+ `Severity: ${finding.severity.toUpperCase()}`,
140
+ `File: ${finding.file}${finding.line ? `:${finding.line}` : ''}`,
141
+ `Message: ${finding.message}`,
142
+ finding.suggestion ? `Suggestion: ${finding.suggestion}` : '',
143
+ codeContext,
144
+ ``,
145
+ `Respond using EXACTLY these five section headers (no other headers):`,
146
+ ``,
147
+ `## Root Cause`,
148
+ `[technical explanation of why this problem exists]`,
149
+ ``,
150
+ `## Risk`,
151
+ `[real-world impact, exploitability, and severity rationale]`,
152
+ ``,
153
+ `## How to Fix`,
154
+ `[concrete, code-level remediation steps]`,
155
+ ``,
156
+ `## Example`,
157
+ `[before/after code snippet showing the fix, in a fenced code block]`,
158
+ ``,
159
+ `## When to Suppress`,
160
+ `[legitimate cases where this finding can be safely ignored]`,
161
+ ].filter(s => s !== undefined && s !== null).join('\n');
162
+
163
+ const sev = finding.severity === 'critical' ? fmt('red', 'CRITICAL')
164
+ : finding.severity === 'warning' ? fmt('yellow', 'WARNING') : fmt('dim', 'NOTE');
165
+
166
+ console.log(`\n${fmt('bold', '[guardrail explain]')}`);
167
+ console.log(` [${sev}] ${fmt('dim', `${finding.file}${finding.line ? `:${finding.line}` : ''}`)} — ${finding.message}`);
168
+ if (finding.suggestion) console.log(` ${fmt('dim', `→ ${finding.suggestion}`)}`);
169
+ console.log('');
170
+
171
+ try {
172
+ const output = await (engine as unknown as ReviewEngine).review({ content: prompt, kind: 'file-batch' });
173
+ const text = output.rawOutput.trim();
174
+ const sections = parseSections(text);
175
+
176
+ let printed = false;
177
+ for (const label of SECTION_ORDER) {
178
+ const body = sections.get(label);
179
+ if (body) {
180
+ printSection(label, body);
181
+ printed = true;
182
+ }
183
+ }
184
+
185
+ if (!printed) {
186
+ // LLM didn't follow the structure — print raw
187
+ console.log(text);
188
+ }
189
+
190
+ console.log('');
191
+ } catch (err) {
192
+ console.error(fmt('red', `[explain] LLM error: ${err instanceof Error ? err.message : String(err)}`));
193
+ return 1;
194
+ }
195
+
196
+ return 0;
197
+ }
package/src/cli/fix.ts ADDED
@@ -0,0 +1,249 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import * as readline from 'node:readline';
4
+ import { execSync } from 'node:child_process';
5
+ import { loadCachedFindings } from '../core/persist/findings-cache.ts';
6
+ import { loadConfig } from '../core/config/loader.ts';
7
+ import { loadAdapter } from '../adapters/loader.ts';
8
+ import type { ReviewEngine } from '../adapters/review-engine/types.ts';
9
+ import type { Finding } from '../core/findings/types.ts';
10
+ import type { GuardrailConfig } from '../core/config/types.ts';
11
+ import { generateFix, buildUnifiedDiff, type GenerateResult } from '../core/fix/generator.ts';
12
+
13
+ const C = {
14
+ reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m',
15
+ green: '\x1b[32m', yellow: '\x1b[33m', red: '\x1b[31m', cyan: '\x1b[36m',
16
+ };
17
+ const fmt = (c: keyof typeof C, t: string) => `${C[c]}${t}${C.reset}`;
18
+
19
+ export interface FixCommandOptions {
20
+ cwd?: string;
21
+ configPath?: string;
22
+ severity?: 'critical' | 'warning' | 'all';
23
+ dryRun?: boolean;
24
+ yes?: boolean; // skip per-fix confirmation prompts
25
+ noVerify?: boolean; // skip test verification after applying fix
26
+ }
27
+
28
+ interface FixResult {
29
+ file: string;
30
+ line: number;
31
+ findingMessage: string;
32
+ status: 'fixed' | 'skipped' | 'rejected' | 'failed';
33
+ reason?: string;
34
+ }
35
+
36
+ async function confirmFix(diff: string, finding: Finding): Promise<'yes' | 'no' | 'quit'> {
37
+ console.log('');
38
+ console.log(diff);
39
+ console.log('');
40
+
41
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
42
+ return new Promise(resolve => {
43
+ rl.question(fmt('bold', ' Apply this fix? [y]es / [n]o / [q]uit '), answer => {
44
+ rl.close();
45
+ const a = answer.trim().toLowerCase();
46
+ if (a === 'q') resolve('quit');
47
+ else if (a === 'y' || a === '') resolve('yes');
48
+ else resolve('no');
49
+ });
50
+ });
51
+ }
52
+
53
+ export async function runFix(options: FixCommandOptions = {}): Promise<number> {
54
+ const cwd = options.cwd ?? process.cwd();
55
+ const configPath = options.configPath ?? path.join(cwd, 'guardrail.config.yaml');
56
+ const severityFilter = options.severity ?? 'critical';
57
+
58
+ const findings = loadCachedFindings(cwd);
59
+ if (findings.length === 0) {
60
+ console.log(fmt('yellow', '[fix] No cached findings — run `guardrail scan <path>` or `guardrail run` first.'));
61
+ return 0;
62
+ }
63
+
64
+ const fixable = findings.filter(f => {
65
+ if (!f.line || !f.file || f.file === '<unspecified>' || f.file === '<pipeline>') return false;
66
+ if (severityFilter === 'all') return true;
67
+ if (severityFilter === 'critical') return f.severity === 'critical';
68
+ return f.severity === 'critical' || f.severity === 'warning';
69
+ });
70
+
71
+ if (fixable.length === 0) {
72
+ console.log(fmt('yellow', `[fix] No fixable findings (severity=${severityFilter}, need file+line).`));
73
+ return 0;
74
+ }
75
+
76
+ const modeNote = options.dryRun ? ' (dry run)' : options.yes ? '' : ' (interactive — use --yes to skip prompts)';
77
+ console.log(`\n${fmt('bold', '[guardrail fix]')} ${fixable.length} finding${fixable.length !== 1 ? 's' : ''} to attempt${modeNote}\n`);
78
+
79
+ // Print upfront summary of all fixable findings before prompting
80
+ for (const f of fixable) {
81
+ const sev = f.severity === 'critical' ? fmt('red', 'CRITICAL') : fmt('yellow', 'WARNING ');
82
+ const loc = fmt('dim', `${f.file}:${f.line}`);
83
+ console.log(` [${sev}] ${loc} ${f.message}`);
84
+ if (f.suggestion) console.log(fmt('dim', ` → ${f.suggestion}`));
85
+ }
86
+ console.log('');
87
+
88
+ // Dry-run: listing the findings is sufficient — no LLM needed
89
+ if (options.dryRun) {
90
+ console.log(fmt('yellow', `[fix] Dry run — ${fixable.length} finding${fixable.length !== 1 ? 's' : ''} listed above, no files modified.\n`));
91
+ return 0;
92
+ }
93
+
94
+ // Load config + review engine (config optional — defaults to auto adapter)
95
+ let engine: ReviewEngine;
96
+ let loadedConfig: GuardrailConfig | null = null;
97
+ try {
98
+ loadedConfig = fs.existsSync(configPath) ? await loadConfig(configPath) : null;
99
+ const ref = loadedConfig
100
+ ? (typeof loadedConfig.reviewEngine === 'string' ? loadedConfig.reviewEngine : (loadedConfig.reviewEngine?.adapter ?? 'auto'))
101
+ : 'auto';
102
+ engine = await loadAdapter<ReviewEngine>({
103
+ point: 'review-engine',
104
+ ref,
105
+ options: loadedConfig && typeof loadedConfig.reviewEngine === 'object' ? loadedConfig.reviewEngine.options : undefined,
106
+ });
107
+ } catch (err) {
108
+ console.error(fmt('red', `[fix] Could not load review engine: ${err instanceof Error ? err.message : String(err)}`));
109
+ return 1;
110
+ }
111
+
112
+ const testCommand = loadedConfig?.testCommand ?? null;
113
+ const shouldVerify = !options.noVerify && !!testCommand;
114
+ if (shouldVerify) {
115
+ console.log(fmt('dim', `[fix] Verified mode — running "${testCommand}" after each fix\n`));
116
+ }
117
+
118
+ const results: FixResult[] = [];
119
+ let quit = false;
120
+
121
+ for (const finding of fixable) {
122
+ if (quit) {
123
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'skipped', reason: 'user quit' });
124
+ continue;
125
+ }
126
+
127
+ const sev = finding.severity === 'critical' ? fmt('red', 'CRITICAL') : fmt('yellow', 'WARNING');
128
+ console.log(`\n [${sev}] ${fmt('dim', `${finding.file}:${finding.line}`)} ${finding.message}`);
129
+
130
+ const result = await generateFix(finding, engine, cwd);
131
+
132
+ if (result.status === 'cannot_fix') {
133
+ console.log(fmt('dim', ` → skipped: ${result.reason}`));
134
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'skipped', reason: result.reason });
135
+ continue;
136
+ }
137
+
138
+ if (result.status === 'rejected') {
139
+ console.log(fmt('yellow', ` → rejected: ${result.reason}`));
140
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'rejected', reason: result.reason });
141
+ continue;
142
+ }
143
+
144
+ if (result.status === 'error') {
145
+ console.log(fmt('red', ` → error: ${result.reason}`));
146
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'failed', reason: result.reason });
147
+ continue;
148
+ }
149
+
150
+ // Show diff
151
+ const diff = buildUnifiedDiff(result.originalLines!, result.replacementLines!, finding.file, result.startLine!);
152
+
153
+ if (options.dryRun) {
154
+ console.log('');
155
+ console.log(diff);
156
+ console.log(fmt('dim', ' (dry run — not applied)'));
157
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'skipped', reason: 'dry run' });
158
+ continue;
159
+ }
160
+
161
+ // Interactive confirmation (unless --yes)
162
+ if (!options.yes) {
163
+ const answer = await confirmFix(diff, finding);
164
+ if (answer === 'quit') {
165
+ quit = true;
166
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'skipped', reason: 'user quit' });
167
+ continue;
168
+ }
169
+ if (answer === 'no') {
170
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'skipped', reason: 'user declined' });
171
+ continue;
172
+ }
173
+ } else {
174
+ // --yes mode: still print the diff so there's a record
175
+ console.log('');
176
+ console.log(diff);
177
+ }
178
+
179
+ // Apply fix atomically
180
+ try {
181
+ const absPath = path.resolve(cwd, finding.file);
182
+ const originalContent = fs.readFileSync(absPath, 'utf8');
183
+ const allLines = originalContent.split('\n');
184
+ const newLines = [
185
+ ...allLines.slice(0, result.startLine! - 1),
186
+ ...result.replacementLines!,
187
+ ...allLines.slice(result.endLine!),
188
+ ];
189
+ const tmp = absPath + '.guardrail.tmp';
190
+ fs.writeFileSync(tmp, newLines.join('\n'), 'utf8');
191
+ fs.renameSync(tmp, absPath);
192
+
193
+ if (shouldVerify) {
194
+ // Verified mode — same shell invocation pattern as phases/tests.ts
195
+ console.log(fmt('dim', ` ↻ verifying…`));
196
+ const passed = runTestCommand(testCommand!, cwd);
197
+ if (passed) {
198
+ console.log(fmt('green', ` ✓ applied + tests pass`));
199
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'fixed' });
200
+ } else {
201
+ fs.writeFileSync(absPath, originalContent, 'utf8');
202
+ console.log(fmt('yellow', ` ⚠ reverted — tests failed after fix`));
203
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'rejected', reason: 'tests failed after fix — reverted' });
204
+ }
205
+ } else {
206
+ console.log(fmt('green', ` ✓ applied`));
207
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'fixed' });
208
+ }
209
+ } catch (err) {
210
+ console.log(fmt('red', ` ✗ write failed: ${err instanceof Error ? err.message : String(err)}`));
211
+ results.push({ file: finding.file, line: finding.line!, findingMessage: finding.message, status: 'failed', reason: String(err) });
212
+ }
213
+ }
214
+
215
+ const fixed = results.filter(r => r.status === 'fixed').length;
216
+ const rejected = results.filter(r => r.status === 'rejected').length;
217
+ const failed = results.filter(r => r.status === 'failed').length;
218
+ const skipped = results.filter(r => r.status === 'skipped').length;
219
+
220
+ console.log('');
221
+ if (options.dryRun) {
222
+ console.log(fmt('yellow', `[fix] Dry run complete — ${fixable.length} finding${fixable.length !== 1 ? 's' : ''} previewed, no files modified.\n`));
223
+ } else {
224
+ const parts = [
225
+ fixed > 0 ? fmt('green', `${fixed} fixed`) : null,
226
+ rejected > 0 ? fmt('yellow', `${rejected} rejected`) : null,
227
+ failed > 0 ? fmt('red', `${failed} failed`) : null,
228
+ skipped > 0 ? fmt('dim', `${skipped} skipped`) : null,
229
+ ].filter(Boolean).join(fmt('dim', ' · '));
230
+ console.log(`[fix] ${parts}\n`);
231
+ }
232
+
233
+ return failed > 0 ? 1 : 0;
234
+ }
235
+
236
+ function runTestCommand(cmd: string, cwd: string): boolean {
237
+ try {
238
+ execSync(cmd, {
239
+ cwd,
240
+ stdio: 'ignore',
241
+ timeout: 120000,
242
+ shell: process.env.SHELL ?? '/bin/sh',
243
+ });
244
+ return true;
245
+ } catch {
246
+ return false;
247
+ }
248
+ }
249
+