@delegance/claude-autopilot 2.5.0 → 5.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +63 -0
- package/README.md +169 -106
- package/bin/_launcher.js +77 -0
- package/bin/claude-autopilot.js +3 -0
- package/bin/guardrail.js +3 -0
- package/package.json +23 -9
- package/presets/generic/guardrail.config.yaml +35 -0
- package/presets/generic/stack.md +40 -0
- package/presets/nextjs-supabase/{autopilot.config.yaml → guardrail.config.yaml} +7 -0
- package/scripts/autoregress.ts +27 -11
- package/skills/autopilot/SKILL.md +170 -0
- package/skills/claude-autopilot.md +80 -0
- package/skills/guardrail.md +39 -0
- package/skills/migrate/SKILL.md +83 -0
- package/src/adapters/council/claude.ts +41 -0
- package/src/adapters/council/openai.ts +40 -0
- package/src/adapters/council/types.ts +7 -0
- package/src/adapters/loader.ts +7 -7
- package/src/adapters/review-engine/auto.ts +2 -2
- package/src/adapters/review-engine/claude.ts +9 -11
- package/src/adapters/review-engine/codex.ts +9 -11
- package/src/adapters/review-engine/gemini.ts +9 -11
- package/src/adapters/review-engine/openai-compatible.ts +10 -12
- package/src/adapters/review-engine/parse-output.ts +32 -6
- package/src/adapters/review-engine/prompt-builder.ts +19 -0
- package/src/adapters/review-engine/types.ts +1 -1
- package/src/adapters/vcs-host/commit-status.ts +39 -0
- package/src/adapters/vcs-host/github.ts +2 -2
- package/src/cli/baseline.ts +125 -0
- package/src/cli/ci.ts +11 -8
- package/src/cli/costs.ts +2 -2
- package/src/cli/council.ts +96 -0
- package/src/cli/detector.ts +21 -5
- package/src/cli/explain.ts +197 -0
- package/src/cli/fix.ts +173 -111
- package/src/cli/hook.ts +72 -27
- package/src/cli/ignore-helper.ts +116 -0
- package/src/cli/index.ts +355 -31
- package/src/cli/init.ts +12 -12
- package/src/cli/lsp.ts +200 -0
- package/src/cli/mcp.ts +206 -0
- package/src/cli/pr-comment.ts +5 -5
- package/src/cli/pr-desc.ts +168 -0
- package/src/cli/pr-review-comments.ts +3 -3
- package/src/cli/pr.ts +76 -0
- package/src/cli/preflight.ts +109 -32
- package/src/cli/report.ts +186 -0
- package/src/cli/run.ts +140 -36
- package/src/cli/scan.ts +233 -0
- package/src/cli/setup.ts +121 -15
- package/src/cli/test-gen.ts +125 -0
- package/src/cli/triage.ts +137 -0
- package/src/cli/watch.ts +52 -31
- package/src/cli/worker.ts +109 -0
- package/src/core/cache/review-cache.ts +2 -2
- package/src/core/chunking/index.ts +2 -2
- package/src/core/config/loader.ts +10 -10
- package/src/core/config/preset-resolver.ts +6 -6
- package/src/core/config/schema.ts +103 -2
- package/src/core/config/types.ts +57 -2
- package/src/core/council/config.ts +71 -0
- package/src/core/council/context.ts +17 -0
- package/src/core/council/runner.ts +83 -0
- package/src/core/council/types.ts +45 -0
- package/src/core/detect/llm-key.ts +89 -0
- package/src/core/detect/workspaces.ts +103 -0
- package/src/core/errors.ts +4 -4
- package/src/core/fix/generator.ts +149 -0
- package/src/core/ignore/index.ts +4 -4
- package/src/core/mcp/concurrency.ts +16 -0
- package/src/core/mcp/handlers/fix-finding.ts +126 -0
- package/src/core/mcp/handlers/get-capabilities.ts +62 -0
- package/src/core/mcp/handlers/get-findings.ts +36 -0
- package/src/core/mcp/handlers/review-diff.ts +65 -0
- package/src/core/mcp/handlers/scan-files.ts +65 -0
- package/src/core/mcp/handlers/validate-fix.ts +41 -0
- package/src/core/mcp/run-store.ts +85 -0
- package/src/core/mcp/workspace.ts +35 -0
- package/src/core/persist/baseline.ts +112 -0
- package/src/core/persist/cost-log.ts +1 -1
- package/src/core/persist/findings-cache.ts +1 -1
- package/src/core/persist/triage.ts +112 -0
- package/src/core/phases/static-rules.ts +18 -5
- package/src/core/pipeline/review-phase.ts +65 -26
- package/src/core/pipeline/run.ts +42 -10
- package/src/core/runtime/lock.ts +2 -2
- package/src/core/runtime/state.ts +2 -2
- package/src/core/schema-alignment/detector.ts +59 -0
- package/src/core/schema-alignment/extractor/index.ts +24 -0
- package/src/core/schema-alignment/extractor/prisma.ts +21 -0
- package/src/core/schema-alignment/extractor/sql.ts +99 -0
- package/src/core/schema-alignment/llm-check.ts +91 -0
- package/src/core/schema-alignment/scanner.ts +107 -0
- package/src/core/schema-alignment/types.ts +43 -0
- package/src/core/shell.ts +3 -3
- package/src/core/static-rules/registry.ts +17 -8
- package/src/core/static-rules/rules/brand-tokens.ts +145 -0
- package/src/core/static-rules/rules/hardcoded-secrets.ts +27 -1
- package/src/core/static-rules/rules/insecure-redirect.ts +67 -0
- package/src/core/static-rules/rules/missing-auth.ts +70 -0
- package/src/core/static-rules/rules/schema-alignment.ts +132 -0
- package/src/core/static-rules/rules/sql-injection.ts +71 -0
- package/src/core/static-rules/rules/ssrf.ts +63 -0
- package/src/core/static-rules/tailwind-extractor.ts +38 -0
- package/src/core/test-gen/coverage-analyzer.ts +93 -0
- package/src/core/test-gen/framework-detector.ts +21 -0
- package/src/core/test-gen/test-writer.ts +33 -0
- package/src/core/ui/design-context-loader.ts +87 -0
- package/src/core/worker/client.ts +46 -0
- package/src/core/worker/lockfile.ts +38 -0
- package/src/core/worker/server.ts +81 -0
- package/src/formatters/junit.ts +52 -0
- package/src/formatters/sarif.ts +2 -2
- package/src/index.ts +1 -2
- package/tests/snapshots/baselines/src-formatters-sarif.json +4 -4
- package/tests/snapshots/index.json +3 -3
- package/tests/snapshots/src-formatters-sarif.snap.ts +1 -1
- package/tests/snapshots/src-snapshots-impact-selector.snap.ts +3 -3
- package/tests/snapshots/src-snapshots-import-scanner.snap.ts +3 -3
- package/tests/snapshots/src-snapshots-serializer.snap.ts +2 -2
- package/bin/autopilot.js +0 -20
- package/skills/autopilot.md +0 -157
- /package/presets/go/{autopilot.config.yaml → guardrail.config.yaml} +0 -0
- /package/presets/python-fastapi/{autopilot.config.yaml → guardrail.config.yaml} +0 -0
- /package/presets/rails-postgres/{autopilot.config.yaml → guardrail.config.yaml} +0 -0
- /package/presets/t3/{autopilot.config.yaml → guardrail.config.yaml} +0 -0
- /package/{src → scripts}/snapshots/impact-selector.ts +0 -0
- /package/{src → scripts}/snapshots/import-scanner.ts +0 -0
- /package/{src → scripts}/snapshots/serializer.ts +0 -0
package/src/cli/run.ts
CHANGED
|
@@ -25,23 +25,37 @@ import { loadRulesFromConfig } from '../core/static-rules/registry.ts';
|
|
|
25
25
|
import { resolvePreset } from '../core/config/preset-resolver.ts';
|
|
26
26
|
import { mergeConfigs } from '../core/config/preset-resolver.ts';
|
|
27
27
|
import { loadAdapter } from '../adapters/loader.ts';
|
|
28
|
-
import {
|
|
28
|
+
import { runGuardrail } from '../core/pipeline/run.ts';
|
|
29
29
|
import { resolveGitTouchedFiles } from '../core/git/touched-files.ts';
|
|
30
30
|
import type { RunInput } from '../core/pipeline/run.ts';
|
|
31
31
|
import type { ReviewEngine } from '../adapters/review-engine/types.ts';
|
|
32
|
-
import type {
|
|
32
|
+
import type { GuardrailConfig } from '../core/config/types.ts';
|
|
33
33
|
import { fileURLToPath } from 'node:url';
|
|
34
34
|
import { toSarif } from '../formatters/sarif.ts';
|
|
35
|
+
import { toJUnit } from '../formatters/junit.ts';
|
|
36
|
+
import { loadTriage, filterTriaged } from '../core/persist/triage.ts';
|
|
35
37
|
import { emitAnnotations } from '../formatters/github-annotations.ts';
|
|
36
38
|
import { detectStack } from '../core/detect/stack.ts';
|
|
37
39
|
import { detectProtectedPaths } from '../core/detect/protected-paths.ts';
|
|
38
40
|
import { detectGitContext } from '../core/detect/git-context.ts';
|
|
41
|
+
import { detectWorkspaces, mapFilesToWorkspaces } from '../core/detect/workspaces.ts';
|
|
39
42
|
import { detectProject } from './detector.ts';
|
|
40
43
|
import { detectPrNumber, formatComment, postPrComment } from './pr-comment.ts';
|
|
41
44
|
import { postReviewComments } from './pr-review-comments.ts';
|
|
42
45
|
import { loadIgnoreRules, parseConfigIgnore, applyIgnoreRules } from '../core/ignore/index.ts';
|
|
46
|
+
import { detectLLMKey, LLM_KEY_HINTS } from '../core/detect/llm-key.ts';
|
|
43
47
|
import { loadCachedFindings, saveCachedFindings, filterNewFindings } from '../core/persist/findings-cache.ts';
|
|
48
|
+
import { loadBaseline, filterBaselined } from '../core/persist/baseline.ts';
|
|
44
49
|
import { appendCostLog } from '../core/persist/cost-log.ts';
|
|
50
|
+
import { postCommitStatus, resolveCommitSha } from '../adapters/vcs-host/commit-status.ts';
|
|
51
|
+
|
|
52
|
+
function computeExitCode(findings: { severity: string }[], failOn: string): number {
|
|
53
|
+
if (failOn === 'none') return 0;
|
|
54
|
+
const fail = failOn === 'warning' ? ['critical', 'warning']
|
|
55
|
+
: failOn === 'note' ? ['critical', 'warning', 'note']
|
|
56
|
+
: ['critical'];
|
|
57
|
+
return findings.some(f => fail.includes(f.severity)) ? 1 : 0;
|
|
58
|
+
}
|
|
45
59
|
|
|
46
60
|
function readToolVersion(): string {
|
|
47
61
|
const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '../../package.json');
|
|
@@ -70,10 +84,13 @@ export interface RunCommandOptions {
|
|
|
70
84
|
dryRun?: boolean; // skip review, print what would run
|
|
71
85
|
diff?: boolean; // use diff strategy (send git hunks instead of full files)
|
|
72
86
|
delta?: boolean; // only report findings not present in last run's baseline
|
|
87
|
+
newOnly?: boolean; // only report findings not in committed .guardrail-baseline.json
|
|
88
|
+
failOn?: 'critical' | 'warning' | 'note' | 'none'; // severity threshold for exit 1
|
|
73
89
|
inlineComments?: boolean; // post per-line review comments on the PR diff
|
|
74
|
-
format?: 'text' | 'sarif';
|
|
90
|
+
format?: 'text' | 'sarif' | 'junit';
|
|
75
91
|
outputPath?: string;
|
|
76
92
|
postComments?: boolean; // post/update summary comment on the open PR
|
|
93
|
+
skipReview?: boolean; // skip tests and review phases (static rules only)
|
|
77
94
|
}
|
|
78
95
|
|
|
79
96
|
/**
|
|
@@ -82,27 +99,26 @@ export interface RunCommandOptions {
|
|
|
82
99
|
*/
|
|
83
100
|
export async function runCommand(options: RunCommandOptions = {}): Promise<number> {
|
|
84
101
|
const cwd = options.cwd ?? process.cwd();
|
|
85
|
-
const configPath = options.configPath ?? path.join(cwd, '
|
|
102
|
+
const configPath = options.configPath ?? path.join(cwd, 'guardrail.config.yaml');
|
|
86
103
|
|
|
104
|
+
// Load + merge config (graceful zero-config fallback)
|
|
105
|
+
let config: GuardrailConfig;
|
|
87
106
|
if (!fs.existsSync(configPath)) {
|
|
88
|
-
console.
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
107
|
+
console.log(fmt('dim', `[run] No guardrail.config.yaml found — using defaults. Run \`npx guardrail setup\` to configure.`));
|
|
108
|
+
config = { configVersion: 1, reviewEngine: { adapter: 'auto' }, testCommand: null };
|
|
109
|
+
} else {
|
|
110
|
+
try {
|
|
111
|
+
const userConfig = await loadConfig(configPath);
|
|
112
|
+
if (userConfig.preset) {
|
|
113
|
+
const preset = await resolvePreset(userConfig.preset);
|
|
114
|
+
config = mergeConfigs(preset.config, userConfig);
|
|
115
|
+
} else {
|
|
116
|
+
config = userConfig;
|
|
117
|
+
}
|
|
118
|
+
} catch (err) {
|
|
119
|
+
console.error(fmt('red', `[run] Config error: ${err instanceof Error ? err.message : String(err)}`));
|
|
120
|
+
return 1;
|
|
102
121
|
}
|
|
103
|
-
} catch (err) {
|
|
104
|
-
console.error(fmt('red', `[run] Config error: ${err instanceof Error ? err.message : String(err)}`));
|
|
105
|
-
return 1;
|
|
106
122
|
}
|
|
107
123
|
|
|
108
124
|
// Fill in missing config fields from auto-detection (track what was auto-detected for logging)
|
|
@@ -124,6 +140,13 @@ export async function runCommand(options: RunCommandOptions = {}): Promise<numbe
|
|
|
124
140
|
config = { ...config, testCommand: detected };
|
|
125
141
|
autoDetected.push(`test: ${detected}`);
|
|
126
142
|
}
|
|
143
|
+
|
|
144
|
+
// Monorepo workspace detection
|
|
145
|
+
const workspaces = detectWorkspaces(cwd);
|
|
146
|
+
if (workspaces && workspaces.length > 0) {
|
|
147
|
+
autoDetected.push(`workspaces: ${workspaces.length} (${workspaces.map(w => w.name).slice(0, 3).join(', ')}${workspaces.length > 3 ? ` +${workspaces.length - 3} more` : ''})`);
|
|
148
|
+
}
|
|
149
|
+
|
|
127
150
|
const gitCtx = detectGitContext(cwd);
|
|
128
151
|
|
|
129
152
|
// Resolve touched files
|
|
@@ -134,7 +157,7 @@ export async function runCommand(options: RunCommandOptions = {}): Promise<numbe
|
|
|
134
157
|
return 0;
|
|
135
158
|
}
|
|
136
159
|
|
|
137
|
-
console.log(`\n${fmt('bold', '[
|
|
160
|
+
console.log(`\n${fmt('bold', '[guardrail run]')} ${fmt('dim', configPath)}`);
|
|
138
161
|
console.log(`${fmt('dim', ` ${touchedFiles.length} changed file(s):`)} ${touchedFiles.slice(0, 5).join(', ')}${touchedFiles.length > 5 ? ` … +${touchedFiles.length - 5} more` : ''}`);
|
|
139
162
|
if (gitCtx.summary) {
|
|
140
163
|
console.log(fmt('dim', ` ${gitCtx.summary}`));
|
|
@@ -152,10 +175,13 @@ export async function runCommand(options: RunCommandOptions = {}): Promise<numbe
|
|
|
152
175
|
let reviewEngine: ReviewEngine | undefined;
|
|
153
176
|
if (config.reviewEngine) {
|
|
154
177
|
const ref = typeof config.reviewEngine === 'string' ? config.reviewEngine : config.reviewEngine.adapter;
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
178
|
+
if (!detectLLMKey().hasKey && ['auto', 'claude', 'gemini', 'codex', 'openai-compatible'].includes(ref)) {
|
|
179
|
+
console.log(fmt('yellow', '\n [run] No LLM API key — set one of:'));
|
|
180
|
+
for (const { name, url, note } of LLM_KEY_HINTS) {
|
|
181
|
+
const suffix = note ? ` (${note})` : '';
|
|
182
|
+
console.log(fmt('dim', ` ${name.padEnd(18)} ${url}${suffix}`));
|
|
183
|
+
}
|
|
184
|
+
console.log('');
|
|
159
185
|
} else {
|
|
160
186
|
try {
|
|
161
187
|
reviewEngine = await loadAdapter<ReviewEngine>({
|
|
@@ -179,6 +205,18 @@ export async function runCommand(options: RunCommandOptions = {}): Promise<numbe
|
|
|
179
205
|
config = { ...config, reviewStrategy: 'diff' };
|
|
180
206
|
}
|
|
181
207
|
|
|
208
|
+
// Pre-run cost estimate
|
|
209
|
+
if (config.cost?.estimateBeforeRun) {
|
|
210
|
+
const totalChars = touchedFiles.reduce((sum, f) => {
|
|
211
|
+
try { return sum + fs.statSync(f).size; } catch { return sum; }
|
|
212
|
+
}, 0);
|
|
213
|
+
const estTokens = Math.round(totalChars / 4);
|
|
214
|
+
const estCost = estTokens / 1_000_000 * 3.0; // rough: $3/M tokens (Sonnet)
|
|
215
|
+
const cap = config.cost?.maxPerRun;
|
|
216
|
+
console.log(fmt('dim', ` [run] estimated: ~${estTokens.toLocaleString()} tokens, ~$${estCost.toFixed(4)}`
|
|
217
|
+
+ (cap ? ` (cap: $${cap})` : '')));
|
|
218
|
+
}
|
|
219
|
+
|
|
182
220
|
// Execute pipeline
|
|
183
221
|
const input: RunInput = {
|
|
184
222
|
touchedFiles,
|
|
@@ -188,12 +226,19 @@ export async function runCommand(options: RunCommandOptions = {}): Promise<numbe
|
|
|
188
226
|
cwd,
|
|
189
227
|
gitSummary: gitCtx.summary ?? undefined,
|
|
190
228
|
base: options.base,
|
|
229
|
+
skipReview: options.skipReview,
|
|
191
230
|
};
|
|
192
231
|
|
|
232
|
+
// Post pending commit status (best-effort — never fatal)
|
|
233
|
+
const commitSha = resolveCommitSha(cwd);
|
|
234
|
+
if (commitSha) {
|
|
235
|
+
postCommitStatus({ sha: commitSha, state: 'pending', description: `Reviewing ${touchedFiles.length} file(s)…`, cwd });
|
|
236
|
+
}
|
|
237
|
+
|
|
193
238
|
console.log('');
|
|
194
|
-
const result = await
|
|
239
|
+
const result = await runGuardrail(input);
|
|
195
240
|
|
|
196
|
-
// Apply .
|
|
241
|
+
// Apply .guardrail-ignore + config ignore: rules
|
|
197
242
|
const ignoreRules = [...loadIgnoreRules(cwd), ...parseConfigIgnore(config.ignore)];
|
|
198
243
|
if (ignoreRules.length > 0) {
|
|
199
244
|
const before = result.allFindings.length;
|
|
@@ -203,11 +248,11 @@ export async function runCommand(options: RunCommandOptions = {}): Promise<numbe
|
|
|
203
248
|
}
|
|
204
249
|
const suppressed = before - result.allFindings.length;
|
|
205
250
|
if (suppressed > 0) {
|
|
206
|
-
console.log(fmt('dim', ` [run] ${suppressed} finding${suppressed !== 1 ? 's' : ''} suppressed by .
|
|
251
|
+
console.log(fmt('dim', ` [run] ${suppressed} finding${suppressed !== 1 ? 's' : ''} suppressed by .guardrail-ignore`));
|
|
207
252
|
}
|
|
208
253
|
}
|
|
209
254
|
|
|
210
|
-
// Delta mode: filter to only new findings vs last run's
|
|
255
|
+
// Delta mode: filter to only new findings vs last run's cache, then persist
|
|
211
256
|
if (options.delta) {
|
|
212
257
|
const cached = loadCachedFindings(cwd);
|
|
213
258
|
const before = result.allFindings.length;
|
|
@@ -220,7 +265,41 @@ export async function runCommand(options: RunCommandOptions = {}): Promise<numbe
|
|
|
220
265
|
console.log(fmt('dim', ` [run] ${existing} pre-existing finding${existing !== 1 ? 's' : ''} hidden (--delta mode)`));
|
|
221
266
|
}
|
|
222
267
|
}
|
|
223
|
-
|
|
268
|
+
|
|
269
|
+
// --new-only / policy.newOnly: filter against committed .guardrail-baseline.json
|
|
270
|
+
const policy = config.policy ?? {};
|
|
271
|
+
const newOnly = options.newOnly ?? policy.newOnly ?? false;
|
|
272
|
+
if (newOnly) {
|
|
273
|
+
const baseline = loadBaseline(cwd, policy.baselinePath);
|
|
274
|
+
if (baseline) {
|
|
275
|
+
const { newFindings, baselinedCount } = filterBaselined(result.allFindings, baseline);
|
|
276
|
+
result.allFindings = newFindings;
|
|
277
|
+
for (const phase of result.phases) {
|
|
278
|
+
phase.findings = filterBaselined(phase.findings, baseline).newFindings;
|
|
279
|
+
}
|
|
280
|
+
if (baselinedCount > 0) {
|
|
281
|
+
console.log(fmt('dim', ` [run] ${baselinedCount} baselined finding${baselinedCount !== 1 ? 's' : ''} suppressed (--new-only)`));
|
|
282
|
+
}
|
|
283
|
+
} else {
|
|
284
|
+
console.log(fmt('yellow', ' [run] --new-only: no .guardrail-baseline.json found — showing all findings'));
|
|
285
|
+
console.log(fmt('dim', ' Run `guardrail baseline create` after first scan to pin the baseline'));
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Triage filter: suppress accepted-risk / false-positive findings
|
|
290
|
+
const triageStore = loadTriage(cwd);
|
|
291
|
+
if (triageStore.entries.length > 0) {
|
|
292
|
+
const { active, triageCount } = filterTriaged(result.allFindings, triageStore);
|
|
293
|
+
if (triageCount > 0) {
|
|
294
|
+
result.allFindings = active;
|
|
295
|
+
for (const phase of result.phases) {
|
|
296
|
+
phase.findings = filterTriaged(phase.findings, triageStore).active;
|
|
297
|
+
}
|
|
298
|
+
console.log(fmt('dim', ` [run] ${triageCount} triaged finding${triageCount !== 1 ? 's' : ''} suppressed (accepted-risk / false-positive)`));
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// Always persist the unfiltered findings as the run cache
|
|
224
303
|
saveCachedFindings(cwd, result.allFindings);
|
|
225
304
|
|
|
226
305
|
// Append to per-run cost log
|
|
@@ -245,6 +324,14 @@ export async function runCommand(options: RunCommandOptions = {}): Promise<numbe
|
|
|
245
324
|
console.log(fmt('dim', `[run] SARIF written to ${options.outputPath}`));
|
|
246
325
|
}
|
|
247
326
|
|
|
327
|
+
// Write JUnit XML output if requested
|
|
328
|
+
if (options.format === 'junit' && options.outputPath) {
|
|
329
|
+
const junit = toJUnit(result);
|
|
330
|
+
fs.mkdirSync(path.dirname(path.resolve(options.outputPath)), { recursive: true });
|
|
331
|
+
fs.writeFileSync(options.outputPath, junit, 'utf8');
|
|
332
|
+
console.log(fmt('dim', `[run] JUnit XML written to ${options.outputPath}`));
|
|
333
|
+
}
|
|
334
|
+
|
|
248
335
|
// Post inline PR review comments if requested
|
|
249
336
|
if (options.inlineComments) {
|
|
250
337
|
const pr = detectPrNumber(cwd);
|
|
@@ -304,16 +391,33 @@ export async function runCommand(options: RunCommandOptions = {}): Promise<numbe
|
|
|
304
391
|
console.log(`\n ${fmt('dim', `${result.durationMs}ms total`)}`);
|
|
305
392
|
}
|
|
306
393
|
|
|
307
|
-
//
|
|
394
|
+
// Post final commit status
|
|
395
|
+
if (commitSha) {
|
|
396
|
+
const critical = result.allFindings.filter(f => f.severity === 'critical').length;
|
|
397
|
+
const warnings = result.allFindings.filter(f => f.severity === 'warning').length;
|
|
398
|
+
const state = result.status === 'fail' ? 'failure' : 'success';
|
|
399
|
+
const desc = result.status === 'pass'
|
|
400
|
+
? 'All checks passed'
|
|
401
|
+
: result.status === 'warn'
|
|
402
|
+
? `Passed with ${warnings} warning${warnings !== 1 ? 's' : ''}`
|
|
403
|
+
: `${critical} critical finding${critical !== 1 ? 's' : ''}`;
|
|
404
|
+
postCommitStatus({ sha: commitSha, state, description: desc, cwd });
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// Final verdict — apply policy.failOn threshold
|
|
408
|
+
const failOn = options.failOn ?? policy.failOn ?? 'critical';
|
|
409
|
+
const exitCode = computeExitCode(result.allFindings, failOn);
|
|
410
|
+
|
|
308
411
|
console.log('');
|
|
309
|
-
if (result.status
|
|
412
|
+
if (exitCode === 0 && result.status !== 'pass') {
|
|
413
|
+
const reason = failOn === 'none' ? ' (policy: fail-on=none)' : ` (policy: fail-on=${failOn})`;
|
|
414
|
+
console.log(fmt('yellow', `[run] ! Passed with findings${reason}\n`));
|
|
415
|
+
} else if (result.status === 'pass') {
|
|
310
416
|
console.log(fmt('green', '[run] ✓ All phases passed\n'));
|
|
311
|
-
return 0;
|
|
312
417
|
} else if (result.status === 'warn') {
|
|
313
418
|
console.log(fmt('yellow', '[run] ! Passed with warnings\n'));
|
|
314
|
-
return 0;
|
|
315
419
|
} else {
|
|
316
420
|
console.log(fmt('red', '[run] ✗ Pipeline failed — see findings above\n'));
|
|
317
|
-
return 1;
|
|
318
421
|
}
|
|
422
|
+
return exitCode;
|
|
319
423
|
}
|
package/src/cli/scan.ts
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import * as path from 'node:path';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import { loadConfig } from '../core/config/loader.ts';
|
|
4
|
+
import { loadAdapter } from '../adapters/loader.ts';
|
|
5
|
+
import type { ReviewEngine } from '../adapters/review-engine/types.ts';
|
|
6
|
+
import { runReviewPhase } from '../core/pipeline/review-phase.ts';
|
|
7
|
+
import { detectStack } from '../core/detect/stack.ts';
|
|
8
|
+
import { loadIgnoreRules, parseConfigIgnore, applyIgnoreRules } from '../core/ignore/index.ts';
|
|
9
|
+
import { saveCachedFindings } from '../core/persist/findings-cache.ts';
|
|
10
|
+
import type { GuardrailConfig } from '../core/config/types.ts';
|
|
11
|
+
import { detectLLMKey, LLM_KEY_HINTS } from '../core/detect/llm-key.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
|
+
const IGNORED_DIRS = new Set([
|
|
20
|
+
'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', 'coverage',
|
|
21
|
+
'.guardrail-cache', '.autopilot', '__pycache__', '.venv', 'vendor',
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
const CODE_EXTS = new Set([
|
|
25
|
+
'.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',
|
|
26
|
+
'.py', '.go', '.rb', '.rs', '.java', '.kt', '.swift',
|
|
27
|
+
'.c', '.cpp', '.h', '.cs', '.php',
|
|
28
|
+
'.sql', '.sh', '.bash', '.yaml', '.yml', '.json', '.toml',
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
function collectFiles(target: string, cwd: string): string[] {
|
|
32
|
+
const abs = path.isAbsolute(target) ? target : path.resolve(cwd, target);
|
|
33
|
+
if (!fs.existsSync(abs)) return [];
|
|
34
|
+
|
|
35
|
+
const stat = fs.statSync(abs);
|
|
36
|
+
if (stat.isFile()) return [abs];
|
|
37
|
+
|
|
38
|
+
const results: string[] = [];
|
|
39
|
+
function walk(dir: string) {
|
|
40
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
41
|
+
if (IGNORED_DIRS.has(entry.name)) continue;
|
|
42
|
+
const full = path.join(dir, entry.name);
|
|
43
|
+
if (entry.isDirectory()) {
|
|
44
|
+
walk(full);
|
|
45
|
+
} else if (entry.isFile() && CODE_EXTS.has(path.extname(entry.name))) {
|
|
46
|
+
results.push(full);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
walk(abs);
|
|
51
|
+
return results;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function collectAllFiles(cwd: string): string[] {
|
|
55
|
+
return collectFiles(cwd, cwd);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface ScanCommandOptions {
|
|
59
|
+
cwd?: string;
|
|
60
|
+
configPath?: string;
|
|
61
|
+
targets?: string[]; // explicit paths/dirs to scan
|
|
62
|
+
all?: boolean; // scan entire codebase
|
|
63
|
+
ask?: string; // targeted question to inject into review prompt
|
|
64
|
+
focus?: 'security' | 'logic' | 'performance' | 'brand' | 'all';
|
|
65
|
+
dryRun?: boolean;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function runScan(options: ScanCommandOptions = {}): Promise<number> {
|
|
69
|
+
const cwd = options.cwd ?? process.cwd();
|
|
70
|
+
const configPath = options.configPath ?? path.join(cwd, 'guardrail.config.yaml');
|
|
71
|
+
|
|
72
|
+
let config: GuardrailConfig = { configVersion: 1 };
|
|
73
|
+
if (fs.existsSync(configPath)) {
|
|
74
|
+
const loaded = await loadConfig(configPath);
|
|
75
|
+
if (loaded) config = loaded;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Collect files
|
|
79
|
+
let files: string[];
|
|
80
|
+
if (options.all) {
|
|
81
|
+
files = collectAllFiles(cwd);
|
|
82
|
+
} else if (options.targets && options.targets.length > 0) {
|
|
83
|
+
files = options.targets.flatMap(t => collectFiles(t, cwd));
|
|
84
|
+
} else {
|
|
85
|
+
console.error(fmt('red', '[scan] Specify a path, --all, or use `guardrail run` for git-changed files'));
|
|
86
|
+
console.error(fmt('dim', ' Examples:'));
|
|
87
|
+
console.error(fmt('dim', ' guardrail scan src/auth/'));
|
|
88
|
+
console.error(fmt('dim', ' guardrail scan --all'));
|
|
89
|
+
console.error(fmt('dim', ' guardrail scan --ask "is there SQL injection?" src/db/'));
|
|
90
|
+
return 1;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Deduplicate
|
|
94
|
+
files = [...new Set(files)];
|
|
95
|
+
|
|
96
|
+
if (files.length === 0) {
|
|
97
|
+
console.log(fmt('yellow', '[scan] No code files found at the specified path(s)'));
|
|
98
|
+
return 0;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (options.dryRun) {
|
|
102
|
+
console.log(fmt('bold', `[scan] Would scan ${files.length} file(s):`));
|
|
103
|
+
for (const f of files) console.log(fmt('dim', ` ${path.relative(cwd, f)}`));
|
|
104
|
+
return 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Auto-detect stack if not in config
|
|
108
|
+
if (!config.stack) {
|
|
109
|
+
config = { ...config, stack: detectStack(cwd) ?? undefined };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Build review engine
|
|
113
|
+
if (!detectLLMKey().hasKey) {
|
|
114
|
+
console.error(fmt('red', '[scan] No LLM API key — set one of:'));
|
|
115
|
+
for (const { name, url, note } of LLM_KEY_HINTS) {
|
|
116
|
+
const suffix = note ? ` (${note})` : '';
|
|
117
|
+
console.error(fmt('dim', ` ${name.padEnd(18)} ${url}${suffix}`));
|
|
118
|
+
}
|
|
119
|
+
return 1;
|
|
120
|
+
}
|
|
121
|
+
const engineRef = typeof config.reviewEngine === 'string' ? config.reviewEngine
|
|
122
|
+
: (config.reviewEngine?.adapter ?? 'auto');
|
|
123
|
+
let engine: ReviewEngine;
|
|
124
|
+
try {
|
|
125
|
+
engine = await loadAdapter<ReviewEngine>({
|
|
126
|
+
point: 'review-engine',
|
|
127
|
+
ref: engineRef,
|
|
128
|
+
options: typeof config.reviewEngine === 'object' ? config.reviewEngine.options as Record<string, unknown> : undefined,
|
|
129
|
+
});
|
|
130
|
+
} catch (err) {
|
|
131
|
+
console.error(fmt('red', `[scan] Could not load review engine: ${err instanceof Error ? err.message : String(err)}`));
|
|
132
|
+
return 1;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const focusLabel = options.focus && options.focus !== 'all' ? options.focus : null;
|
|
136
|
+
const relFiles = files.map(f => path.relative(cwd, f));
|
|
137
|
+
|
|
138
|
+
console.log('');
|
|
139
|
+
const scopeDesc = options.all ? 'entire codebase' : relFiles.slice(0, 3).join(', ') + (relFiles.length > 3 ? ` +${relFiles.length - 3} more` : '');
|
|
140
|
+
console.log(fmt('bold', `[guardrail scan]`) + fmt('dim', ` ${files.length} file(s) — ${scopeDesc}`));
|
|
141
|
+
if (options.ask) console.log(fmt('dim', ` question: ${options.ask}`));
|
|
142
|
+
if (focusLabel) console.log(fmt('dim', ` focus: ${focusLabel}`));
|
|
143
|
+
console.log('');
|
|
144
|
+
|
|
145
|
+
// Build a focused git summary / prompt context
|
|
146
|
+
const focusHint = buildFocusHint(options.ask, focusLabel);
|
|
147
|
+
|
|
148
|
+
const result = await runReviewPhase({
|
|
149
|
+
touchedFiles: relFiles,
|
|
150
|
+
engine,
|
|
151
|
+
config,
|
|
152
|
+
cwd,
|
|
153
|
+
gitSummary: focusHint,
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
// Apply ignore rules
|
|
157
|
+
const ignoreRules = [...loadIgnoreRules(cwd), ...parseConfigIgnore(config.ignore)];
|
|
158
|
+
const findings = applyIgnoreRules(result.findings, ignoreRules);
|
|
159
|
+
|
|
160
|
+
// Print results
|
|
161
|
+
if (findings.length === 0 && options.ask && result.rawOutputs && result.rawOutputs.length > 0) {
|
|
162
|
+
// --ask returned prose rather than structured findings — surface raw response
|
|
163
|
+
console.log(fmt('cyan', `Answer:`));
|
|
164
|
+
for (const raw of result.rawOutputs) {
|
|
165
|
+
// Strip markdown fences and the ## Findings / ## Review Summary headers if present
|
|
166
|
+
const cleaned = raw.replace(/^##\s+Review Summary\s*\n/gm, '').replace(/^##\s+Findings\s*\n/gm, '').trim();
|
|
167
|
+
console.log(cleaned);
|
|
168
|
+
}
|
|
169
|
+
console.log('');
|
|
170
|
+
} else if (findings.length === 0) {
|
|
171
|
+
console.log(fmt('green', '✓ No findings'));
|
|
172
|
+
} else {
|
|
173
|
+
const critical = findings.filter(f => f.severity === 'critical');
|
|
174
|
+
const warnings = findings.filter(f => f.severity === 'warning');
|
|
175
|
+
const notes = findings.filter(f => f.severity === 'note');
|
|
176
|
+
|
|
177
|
+
if (critical.length > 0) {
|
|
178
|
+
console.log(fmt('red', `🚨 ${critical.length} critical`));
|
|
179
|
+
for (const f of critical) {
|
|
180
|
+
const loc = f.file && f.file !== '<unspecified>' ? fmt('dim', `${f.file}${f.line ? `:${f.line}` : ''}`) + ' ' : '';
|
|
181
|
+
console.log(` ${loc}${f.message}`);
|
|
182
|
+
if (f.suggestion) console.log(fmt('dim', ` → ${f.suggestion}`));
|
|
183
|
+
}
|
|
184
|
+
console.log('');
|
|
185
|
+
}
|
|
186
|
+
if (warnings.length > 0) {
|
|
187
|
+
console.log(fmt('yellow', `⚠ ${warnings.length} warning${warnings.length !== 1 ? 's' : ''}`));
|
|
188
|
+
for (const f of warnings) {
|
|
189
|
+
const loc = f.file && f.file !== '<unspecified>' ? fmt('dim', `${f.file}${f.line ? `:${f.line}` : ''}`) + ' ' : '';
|
|
190
|
+
console.log(` ${loc}${f.message}`);
|
|
191
|
+
if (f.suggestion) console.log(fmt('dim', ` → ${f.suggestion}`));
|
|
192
|
+
}
|
|
193
|
+
console.log('');
|
|
194
|
+
}
|
|
195
|
+
if (notes.length > 0) {
|
|
196
|
+
console.log(fmt('dim', `ℹ ${notes.length} note${notes.length !== 1 ? 's' : ''}`));
|
|
197
|
+
for (const f of notes) {
|
|
198
|
+
const loc = f.file && f.file !== '<unspecified>' ? `${f.file}${f.line ? `:${f.line}` : ''} ` : '';
|
|
199
|
+
console.log(fmt('dim', ` ${loc}${f.message}`));
|
|
200
|
+
}
|
|
201
|
+
console.log('');
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Persist findings so `guardrail fix` can read them
|
|
206
|
+
saveCachedFindings(cwd, findings);
|
|
207
|
+
|
|
208
|
+
if (result.costUSD !== undefined) {
|
|
209
|
+
console.log(fmt('dim', ` $${result.costUSD.toFixed(4)} · ${result.durationMs}ms`));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const fixable = findings.filter(f => f.severity === 'critical' || f.severity === 'warning');
|
|
213
|
+
if (fixable.length > 0) {
|
|
214
|
+
console.log(fmt('dim', ` → run \`guardrail fix\` to auto-fix ${fixable.length} finding${fixable.length !== 1 ? 's' : ''}`));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return findings.some(f => f.severity === 'critical') ? 1 : 0;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function buildFocusHint(ask: string | undefined, focus: string | null): string {
|
|
221
|
+
const parts: string[] = [];
|
|
222
|
+
if (ask) {
|
|
223
|
+
parts.push(
|
|
224
|
+
`TARGETED QUESTION (required): The reviewer specifically wants to know: "${ask}". ` +
|
|
225
|
+
`You MUST answer this question using the structured findings format. ` +
|
|
226
|
+
`Even if no issues are found, output at least one ### [NOTE] finding that directly answers the question.`,
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
if (focus === 'security') parts.push('Focus: security vulnerabilities, auth issues, injection risks, data exposure');
|
|
230
|
+
if (focus === 'logic') parts.push('Focus: logic bugs, incorrect behavior, edge cases, null handling, async errors');
|
|
231
|
+
if (focus === 'performance') parts.push('Focus: performance issues, N+1 queries, blocking I/O, memory leaks');
|
|
232
|
+
return parts.join(' | ');
|
|
233
|
+
}
|