praxis-sec 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/assets/praxis-architecture.svg +304 -0
  2. package/assets/praxis-logo.svg +38 -0
  3. package/cli/agents/abom-generator.js +1 -1
  4. package/cli/agents/agent-attestation-agent.js +10 -1
  5. package/cli/agents/agent-config-scanner.js +1 -1
  6. package/cli/agents/ai-infra-inventory-agent.js +482 -482
  7. package/cli/agents/base-agent.js +1 -1
  8. package/cli/agents/endpoint-agent-abuse-agent.js +1 -1
  9. package/cli/agents/html-reporter.js +10 -10
  10. package/cli/agents/index.js +2 -2
  11. package/cli/agents/injection-tester.js +8 -1
  12. package/cli/agents/mcp-security-agent.js +600 -594
  13. package/cli/agents/memory-poisoning-agent.js +1 -1
  14. package/cli/agents/model-file-scanner.js +1 -1
  15. package/cli/agents/orchestrator.js +375 -355
  16. package/cli/agents/prompt-injection-prober.js +228 -228
  17. package/cli/bin/praxis.js +7 -3
  18. package/cli/commands/agent-fix.js +1091 -1245
  19. package/cli/commands/audit.js +1232 -1216
  20. package/cli/commands/baseline.js +3 -2
  21. package/cli/commands/benchmark.js +1 -1
  22. package/cli/commands/ci.js +50 -25
  23. package/cli/commands/deps.js +11 -5
  24. package/cli/commands/diff.js +2 -1
  25. package/cli/commands/env-audit.js +1 -1
  26. package/cli/commands/fix.js +1 -1
  27. package/cli/commands/legal.js +2 -1
  28. package/cli/commands/mcp.js +3 -2
  29. package/cli/commands/openclaw.js +3 -6
  30. package/cli/commands/red-team.js +351 -350
  31. package/cli/commands/remediate.js +1 -1
  32. package/cli/commands/rotate.js +1 -1
  33. package/cli/commands/rules.js +1 -1
  34. package/cli/commands/scan-standard.js +3 -6
  35. package/cli/commands/scan.js +554 -554
  36. package/cli/commands/score.js +1 -1
  37. package/cli/commands/undo.js +22 -77
  38. package/cli/commands/vibe-check.js +3 -2
  39. package/cli/commands/watch.js +6 -5
  40. package/cli/core/fix-plan.js +274 -0
  41. package/cli/core/fs.js +27 -0
  42. package/cli/core/git-clone.js +8 -6
  43. package/cli/core/glob.js +56 -0
  44. package/cli/core/output/html-theme.js +158 -158
  45. package/cli/core/output/json.js +56 -48
  46. package/cli/core/output/sarif.js +2 -2
  47. package/cli/core/paths.js +91 -0
  48. package/cli/core/web/jobs.js +2 -2
  49. package/cli/core/web/server.js +19 -8
  50. package/cli/data/threatpacks/latest.json +41 -41
  51. package/cli/integrations/github-action.js +136 -0
  52. package/cli/utils/cache-manager.js +2 -1
  53. package/cli/utils/plugin-loader.js +15 -95
  54. package/cli/utils/rule-import.js +227 -227
  55. package/cli/utils/rule-registry.js +425 -425
  56. package/cli/utils/scan-fingerprint.js +1 -1
  57. package/cli/utils/score-history.js +118 -118
  58. package/docs/USAGE.md +16 -9
  59. package/docs/design/WEB-UI.md +4 -5
  60. package/package.json +81 -71
@@ -1,1216 +1,1232 @@
1
- /**
2
- * Audit Command — Full Security Audit
3
- * =====================================
4
- *
5
- * One command to run everything: secrets, agents, deps, score, and
6
- * generate a comprehensive report with a prioritized remediation plan.
7
- *
8
- * USAGE:
9
- * npx praxis-sec audit [path] Full audit with HTML report
10
- * npx praxis-sec audit . --json JSON output
11
- * npx praxis-sec audit . --html report.html Custom report path
12
- * npx praxis-sec audit . --no-deps Skip dependency audit
13
- */
14
-
15
- import fs from 'fs';
16
- import path from 'path';
17
- import { renderFindingsSARIF } from '../core/output/sarif.js';
18
- import chalk from 'chalk';
19
- import ora from 'ora';
20
- import fg from 'fast-glob';
21
- import { buildOrchestrator, buildOrchestratorAsync } from '../agents/index.js';
22
- import { LegalRiskAgent } from '../agents/legal-risk-agent.js';
23
- import { ScoringEngine } from '../agents/scoring-engine.js';
24
- import { PolicyEngine } from '../agents/policy-engine.js';
25
- import { HTMLReporter } from '../agents/html-reporter.js';
26
- import { SBOMGenerator } from '../agents/sbom-generator.js';
27
- import { autoDetectProvider } from '../providers/llm-provider.js';
28
- import { runDepsAudit } from './deps.js';
29
- import {
30
- SECRET_PATTERNS,
31
- SECURITY_PATTERNS,
32
- SKIP_DIRS,
33
- SKIP_EXTENSIONS,
34
- SKIP_FILENAMES,
35
- MAX_FILE_SIZE,
36
- loadGitignorePatterns
37
- } from '../utils/patterns.js';
38
- import { isHighEntropyMatch, getConfidence } from '../utils/entropy.js';
39
- import { printBanner } from '../utils/output.js';
40
- import { CacheManager } from '../utils/cache-manager.js';
41
- import { filterBaseline } from './baseline.js';
42
- import { SecurityMemory } from '../utils/security-memory.js';
43
- import { ScanPlaybook } from '../utils/scan-playbook.js';
44
- import { generatePDF, generatePrintHTML, isChromeAvailable } from '../utils/pdf-generator.js';
45
- import { SecretsVerifier } from '../utils/secrets-verifier.js';
46
- import { applyInlineAnnotations } from './autofix.js';
47
- import { buildScanFingerprint } from '../utils/scan-fingerprint.js';
48
- import { isGitUrl, cloneGitRepo } from '../core/git-clone.js';
49
-
50
- // =============================================================================
51
- // CONSTANTS
52
- // =============================================================================
53
-
54
- const ALL_PATTERNS = [...SECRET_PATTERNS, ...SECURITY_PATTERNS];
55
-
56
- const SEV_ORDER = ['critical', 'high', 'medium', 'low'];
57
-
58
- const CATEGORY_LABELS = {
59
- secrets: 'Secrets',
60
- injection: 'Code Vulnerabilities',
61
- deps: 'Dependencies',
62
- auth: 'Auth & Access Control',
63
- config: 'Configuration',
64
- 'supply-chain': 'Supply Chain',
65
- api: 'API Security',
66
- llm: 'AI/LLM Security',
67
- legal: 'Legal Risk',
68
- };
69
-
70
- const EFFORT_MAP = {
71
- secrets: 'low',
72
- config: 'low',
73
- deps: 'medium',
74
- injection: 'medium',
75
- auth: 'medium',
76
- 'supply-chain': 'medium',
77
- api: 'medium',
78
- llm: 'high',
79
- legal: 'low',
80
- };
81
-
82
- // =============================================================================
83
- // MAIN COMMAND
84
- // =============================================================================
85
-
86
- export async function auditCommand(targetPath = '.', options = {}) {
87
- const machineOutput = options.json || options.sarif || options.csv || options.md;
88
- let gitClone = null;
89
- let effectivePath = targetPath;
90
-
91
- // ── Remote Git Repository Support ─────────────────────────────────────────
92
- if (isGitUrl(targetPath)) {
93
- if (!machineOutput) printBanner();
94
- const gitSpinner = machineOutput ? null : ora({ text: chalk.cyan(`Cloning remote Git repository: ${targetPath}...`), color: 'cyan' }).start();
95
- try {
96
- gitClone = cloneGitRepo(targetPath, {
97
- branch: options.branch,
98
- depth: options.depth,
99
- gitToken: options.gitToken,
100
- submodules: options.submodules,
101
- gitHistory: options.gitHistory,
102
- });
103
- effectivePath = gitClone.tempDir;
104
- if (gitSpinner) gitSpinner.succeed(chalk.green(`Cloned ${gitClone.repoName} (${gitClone.displayUrl}) to temporary workspace`));
105
- } catch (err) {
106
- if (gitSpinner) gitSpinner.fail(chalk.red(err.message));
107
- else console.error(chalk.red(err.message));
108
- process.exitCode = 1;
109
- return;
110
- }
111
- }
112
-
113
- try {
114
- const absolutePath = path.resolve(effectivePath);
115
-
116
- if (!fs.existsSync(absolutePath)) {
117
- console.error(chalk.red(` Path does not exist: ${absolutePath}`));
118
- process.exitCode = 1;
119
- return;
120
- }
121
-
122
- if (!machineOutput && !gitClone) {
123
- printBanner();
124
- }
125
-
126
- // ── Cache Layer ──────────────────────────────────────────────────────────
127
- // --deep forces a fresh scan so taint analysis covers every finding,
128
- // not just the ones from files changed since the last cached run.
129
- const useCache = options.cache !== false && !options.deep;
130
- const cache = new CacheManager(absolutePath);
131
- let cacheData = useCache ? cache.load() : null;
132
- let cacheDiff = null;
133
- let allFiles = [];
134
-
135
- // ── Phase 1: Secret Scan ──────────────────────────────────────────────────
136
- const secretSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 1/4] Scanning for secrets...'), color: 'cyan' }).start();
137
- let secretFindings = [];
138
- let filesScanned = 0;
139
-
140
- try {
141
- allFiles = await findFiles(absolutePath);
142
- filesScanned = allFiles.length;
143
-
144
- // Determine which files need scanning (incremental if cache exists)
145
- let filesToScan = allFiles;
146
- let cachedSecretFindings = [];
147
-
148
- if (cacheData) {
149
- cacheDiff = cache.diff(allFiles);
150
- filesToScan = cacheDiff.changedFiles;
151
- // Reuse cached findings for unchanged files (secrets only)
152
- cachedSecretFindings = cacheDiff.cachedFindings.filter(
153
- f => f.category === 'secrets' || f.category === 'secret'
154
- );
155
- }
156
-
157
- for (const file of filesToScan) {
158
- const fileResults = scanFileForSecrets(file);
159
- for (const f of fileResults) {
160
- secretFindings.push({
161
- file,
162
- line: f.line,
163
- column: f.column,
164
- severity: f.severity,
165
- category: f.category || 'secrets',
166
- rule: f.patternName,
167
- title: f.patternName.replace(/_/g, ' '),
168
- description: f.description,
169
- matched: f.matched,
170
- confidence: f.confidence,
171
- fix: file.match(/\.env(\..*)?$/)
172
- ? `Ensure .env is in .gitignore and use a secrets manager for production`
173
- : `Move to environment variable or secrets manager`,
174
- });
175
- }
176
- }
177
-
178
- // Downgrade .env findings if the file is gitignored (properly managed)
179
- const gitignoreContent = (() => {
180
- try { return fs.readFileSync(path.join(absolutePath, '.gitignore'), 'utf-8'); } catch { return ''; }
181
- })();
182
- const envIsGitignored = gitignoreContent.split('\n')
183
- .map(l => l.trim())
184
- .some(l => /^\.env(\s|$)/.test(l) || l === '*.env' || l === '.env*' || l === '.env.local' || l === '.env.production');
185
-
186
- if (envIsGitignored) {
187
- for (const f of secretFindings) {
188
- if (f.file.match(/\.env(\..*)?$/) && !f.file.includes('node_modules')) {
189
- f.severity = 'low';
190
- f.confidence = 'low';
191
- f.fix = 'Already gitignored — ensure secrets manager is used for production deploys';
192
- }
193
- }
194
- }
195
-
196
- // Downgrade secrets in test files (intentional test fixtures)
197
- const TEST_PATH = /(?:__tests__|\.test\.|\.spec\.|\/test\/|\/tests\/|\/fixtures?\/)/i;
198
- for (const f of secretFindings) {
199
- if (TEST_PATH.test(f.file)) {
200
- f.confidence = 'low';
201
- }
202
- }
203
-
204
- // Merge with cached findings for unchanged files
205
- secretFindings = [...secretFindings, ...cachedSecretFindings];
206
-
207
- const cacheNote = cacheDiff && cacheDiff.changedFiles.length < allFiles.length
208
- ? ` (${cacheDiff.changedFiles.length} changed, ${cacheDiff.unchangedCount} cached)`
209
- : '';
210
-
211
- if (secretSpinner) secretSpinner.succeed(
212
- secretFindings.length === 0
213
- ? chalk.green(`[Phase 1/4] Secrets: clean${cacheNote}`)
214
- : chalk.red(`[Phase 1/4] Secrets: ${secretFindings.length} found${cacheNote}`)
215
- );
216
- } catch (err) {
217
- if (secretSpinner) secretSpinner.fail(chalk.red(`[Phase 1/4] Secret scan failed: ${err.message}`));
218
- }
219
-
220
- // ── Phase 2: Agent Scan ───────────────────────────────────────────────────
221
- const orchestrator = await buildOrchestratorAsync(absolutePath, { quiet: true });
222
-
223
- // --hermes-only: filter to llm + supply-chain category agents only
224
- if (options.hermesOnly && orchestrator.agents) {
225
- const hermesCategories = new Set(['llm', 'supply-chain']);
226
- orchestrator.agents = orchestrator.agents.filter(a =>
227
- hermesCategories.has(a.category) || hermesCategories.has(a.constructor?.category)
228
- );
229
- }
230
-
231
- const registeredAgentCount = orchestrator.agents?.length || 15;
232
- const agentSpinner = machineOutput ? null : ora({ text: chalk.white(`[Phase 2/4] Running ${registeredAgentCount} security agents...`), color: 'cyan' }).start();
233
- let agentFindings = [];
234
- let recon = null;
235
- let agentResults = [];
236
-
237
- try {
238
- // Suppress individual agent spinners by using quiet mode
239
- // Pass changedFiles for incremental scanning if cache is valid
240
- const orchestratorOpts = { quiet: true };
241
- if (options.deep) orchestratorOpts.deep = true;
242
- if (options.local) orchestratorOpts.local = true;
243
- if (options.model) orchestratorOpts.model = options.model;
244
- if (options.provider) orchestratorOpts.provider = options.provider;
245
- if (options.baseUrl) orchestratorOpts.baseUrl = options.baseUrl;
246
- if (options.budget) orchestratorOpts.budget = options.budget;
247
- if (options.verbose) orchestratorOpts.verbose = true;
248
- if (cacheDiff && cacheDiff.changedFiles.length < allFiles.length) {
249
- orchestratorOpts.changedFiles = cacheDiff.changedFiles;
250
- }
251
- const results = await orchestrator.runAll(absolutePath, orchestratorOpts); // praxis-ignore — orchestrator result, not LLM output triggering actions
252
- recon = results.recon;
253
- agentFindings = results.findings;
254
- agentResults = results.agentResults;
255
-
256
- const totalAgentFindings = agentFindings.length;
257
- const agentCount = agentResults.filter(a => a.success).length;
258
- if (agentSpinner) agentSpinner.succeed(
259
- totalAgentFindings === 0
260
- ? chalk.green(`[Phase 2/4] ${agentCount} agents: clean`)
261
- : chalk.yellow(`[Phase 2/4] ${agentCount} agents: ${totalAgentFindings} finding(s)`)
262
- );
263
- } catch (err) {
264
- if (agentSpinner) agentSpinner.fail(chalk.red(`[Phase 2/4] Agent scan failed: ${err.message}`));
265
- }
266
-
267
- // ── Phase 3: Dependency Audit ─────────────────────────────────────────────
268
- let depVulns = [];
269
- if (options.deps !== false) {
270
- const depSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 3/4] Auditing dependencies...'), color: 'cyan' }).start();
271
- try {
272
- const depResult = await runDepsAudit(absolutePath);
273
- depVulns = depResult.vulns || [];
274
- if (depSpinner) depSpinner.succeed(
275
- depVulns.length === 0
276
- ? chalk.green('[Phase 3/4] Dependencies: clean')
277
- : chalk.red(`[Phase 3/4] Dependencies: ${depVulns.length} CVE(s)`)
278
- );
279
- } catch {
280
- if (depSpinner) depSpinner.succeed(chalk.gray('[Phase 3/4] Dependencies: skipped (no manifest)'));
281
- }
282
- } else if (!machineOutput) {
283
- console.log(chalk.gray(' [Phase 3/4] Dependencies: skipped (--no-deps)'));
284
- }
285
-
286
- // ── Phase 3b: Legal Risk Scan (opt-in) ───────────────────────────────────
287
- let legalFindings = [];
288
- if (options.includeLegal) {
289
- const legalSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 3b] Legal risk scan…'), color: 'cyan' }).start();
290
- try {
291
- const legalAgent = new LegalRiskAgent();
292
- legalFindings = await legalAgent.analyze({ rootPath: absolutePath, files: allFiles });
293
- if (legalSpinner) legalSpinner.succeed(
294
- legalFindings.length === 0
295
- ? chalk.green('[Phase 3b] Legal: clean')
296
- : chalk.yellow(`[Phase 3b] Legal: ${legalFindings.length} finding(s)`)
297
- );
298
- } catch {
299
- if (legalSpinner) legalSpinner.succeed(chalk.gray('[Phase 3b] Legal: skipped'));
300
- }
301
- }
302
-
303
- // ── Phase 4: Merge, Score, and Build Plan ─────────────────────────────────
304
- const scoreSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 4/4] Computing security score...'), color: 'cyan' }).start();
305
-
306
- // Merge secret findings + agent findings + legal findings, deduplicate
307
- const allFindings = deduplicateFindings([...secretFindings, ...agentFindings, ...legalFindings]);
308
-
309
- // Apply policy
310
- const policy = PolicyEngine.load(absolutePath);
311
- let filteredFindings = policy.applyPolicy(allFindings);
312
-
313
- // Apply baseline filter (only show new findings)
314
- if (options.baseline) {
315
- const beforeCount = filteredFindings.length;
316
- filteredFindings = filterBaseline(filteredFindings, absolutePath);
317
- if (!machineOutput && beforeCount !== filteredFindings.length) {
318
- console.log(chalk.gray(` Baseline: ${beforeCount - filteredFindings.length} known finding(s) filtered, ${filteredFindings.length} new`));
319
- }
320
- }
321
-
322
- // ── Scan Playbook — update with latest recon + findings ─────────────────
323
- try {
324
- const playbook = new ScanPlaybook(absolutePath);
325
- const suppressedRules = new SecurityMemory(absolutePath).list().map(e => e.rule).filter(Boolean);
326
- playbook.update(recon, { score: scoreResult.score, grade: scoreResult.grade?.letter || scoreResult.grade, totalFindings: filteredFindings.length }, filteredFindings, suppressedRules);
327
- } catch { /* non-fatal */ }
328
-
329
- // ── Security Memory Filter ──────────────────────────────────────────────
330
- // Auto-learn false positives from deep analysis results, then suppress
331
- // any finding that memory recognises from a previous scan.
332
- const secMemory = new SecurityMemory(absolutePath);
333
- if (options.deep) {
334
- // After deep analysis ran, learn any new false positives
335
- const newFPs = secMemory.learnFromAnalysis(filteredFindings);
336
- if (newFPs > 0 && !machineOutput) {
337
- console.log(chalk.gray(` Memory: ${newFPs} new false positive(s) learned and will be suppressed in future scans`));
338
- }
339
- }
340
- const { kept: memFiltered, suppressedCount: memSuppressed } = secMemory.filter(filteredFindings);
341
- filteredFindings = memFiltered;
342
- if (memSuppressed > 0 && !machineOutput) {
343
- console.log(chalk.gray(` Memory: ${memSuppressed} previously-confirmed false positive(s) suppressed`));
344
- }
345
-
346
- // Count suppressions (praxis-ignore comments)
347
- const suppressions = countSuppressions(allFiles);
348
-
349
- // Score
350
- const scoringEngine = new ScoringEngine();
351
- const scoreResult = scoringEngine.compute(filteredFindings, depVulns);
352
- // Round score to 1 decimal place to avoid floating-point noise (e.g., 63.300000000000004)
353
- scoreResult.score = Math.round(scoreResult.score * 10) / 10;
354
- scoringEngine.saveToHistory(absolutePath, scoreResult, suppressions);
355
-
356
- const gradeColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
357
- if (scoreSpinner) scoreSpinner.succeed(
358
- chalk.white('[Phase 4/4] Score: ') + gradeColor(`${scoreResult.score}/100 ${scoreResult.grade.letter}`)
359
- );
360
-
361
- // ── AI Classification (optional, with LLM cache) ───────────────────────
362
- if (options.ai !== false && !options.noAi) {
363
- const provider = autoDetectProvider(absolutePath, {
364
- provider: options.provider,
365
- baseUrl: options.baseUrl,
366
- model: options.model,
367
- think: options.think || false,
368
- });
369
- if (provider && filteredFindings.length > 0 && filteredFindings.length <= 50) {
370
- const aiSpinner = machineOutput ? null : ora({ text: `Classifying with ${provider.name}...`, color: 'cyan' }).start();
371
- try {
372
- // Check LLM cache for existing classifications
373
- const llmCache = cache.loadLLMClassifications();
374
- const uncachedFindings = [];
375
- let cachedCount = 0;
376
-
377
- for (const finding of filteredFindings) {
378
- const key = cache.getLLMCacheKey(finding);
379
- const cached = llmCache[key];
380
- if (cached) {
381
- finding.aiClassification = cached.classification;
382
- finding.aiReason = cached.reason;
383
- finding.aiFix = cached.fix;
384
- cachedCount++;
385
- } else {
386
- uncachedFindings.push(finding);
387
- }
388
- }
389
-
390
- // Only send uncached findings to LLM
391
- if (uncachedFindings.length > 0) {
392
- const classifications = await provider.classify(uncachedFindings);
393
- const newCacheEntries = {};
394
- for (const cl of classifications) {
395
- const finding = filteredFindings.find(f => `${f.file}:${f.line}` === cl.id);
396
- if (finding) {
397
- finding.aiClassification = cl.classification;
398
- finding.aiReason = cl.reason;
399
- finding.aiFix = cl.fix;
400
- const key = cache.getLLMCacheKey(finding);
401
- newCacheEntries[key] = {
402
- classification: cl.classification,
403
- reason: cl.reason,
404
- fix: cl.fix,
405
- cachedAt: new Date().toISOString(),
406
- };
407
- }
408
- }
409
- cache.saveLLMClassifications(newCacheEntries);
410
- }
411
-
412
- const cacheNote = cachedCount > 0 ? `, ${cachedCount} cached` : '';
413
- if (aiSpinner) aiSpinner.succeed(chalk.green(`AI classification complete (${provider.name}${cacheNote})`));
414
- } catch (err) {
415
- if (aiSpinner) aiSpinner.fail(chalk.yellow(`AI classification failed: ${err.message}`));
416
- }
417
- }
418
- }
419
-
420
- // ── Secrets Verification (optional, --verify flag) ─────────────────────
421
- if (options.verify) {
422
- const verifySpinner = machineOutput ? null : ora({ text: 'Verifying leaked secrets against provider APIs...', color: 'cyan' }).start();
423
- try {
424
- const verifier = new SecretsVerifier();
425
- const verifyResults = await verifier.verify(filteredFindings);
426
- const activeCount = verifyResults.filter(r => r.result.active === true).length;
427
- const inactiveCount = verifyResults.filter(r => r.result.active === false).length;
428
- if (verifySpinner) {
429
- verifySpinner.succeed(chalk.green(
430
- `Secrets verified: ${activeCount} active, ${inactiveCount} inactive, ${verifyResults.length - activeCount - inactiveCount} unknown`
431
- ));
432
- }
433
- // Show active secrets warning
434
- if (activeCount > 0 && !machineOutput) {
435
- console.log(chalk.red.bold(' ⚠ ACTIVE SECRETS DETECTED — rotate immediately:'));
436
- for (const r of verifyResults.filter(r => r.result.active === true)) {
437
- const rel = path.relative(absolutePath, r.finding.file).replace(/\\/g, '/');
438
- console.log(chalk.red(` ${r.result.provider}: ${rel}:${r.finding.line} — ${r.result.info}`));
439
- }
440
- }
441
- } catch (err) {
442
- if (verifySpinner) verifySpinner.fail(chalk.yellow(`Secrets verification failed: ${err.message}`));
443
- }
444
- }
445
-
446
- // ── Save Cache ──────────────────────────────────────────────────────────
447
- if (useCache) {
448
- try {
449
- // Merge agent findings back for cache (secret + agent findings from changed files)
450
- // plus cached findings from unchanged files
451
- const cachedAgentFindings = cacheData && cacheDiff
452
- ? cacheDiff.cachedFindings.filter(f => f.category !== 'secrets' && f.category !== 'secret')
453
- : [];
454
- const allFindingsForCache = [...secretFindings, ...agentFindings, ...cachedAgentFindings];
455
- cache.save(allFiles, deduplicateFindings(allFindingsForCache), recon, scoreResult);
456
- } catch {
457
- // Silent — caching should never break a scan
458
- }
459
- }
460
-
461
- // ── Build Remediation Plan ────────────────────────────────────────────────
462
- const remediationPlan = buildRemediationPlan(filteredFindings, depVulns, absolutePath);
463
-
464
- // Skip all output and file generation for inner agentic re-scans
465
- if (options._agenticInner) {
466
- return { score: scoreResult.score, findings: filteredFindings };
467
- }
468
-
469
- // ── Output ────────────────────────────────────────────────────────────────
470
- if (!machineOutput) console.log();
471
-
472
- if (options.csv) {
473
- outputCSV(filteredFindings, depVulns, scoreResult, absolutePath);
474
- } else if (options.md) {
475
- outputMarkdown(scoreResult, filteredFindings, depVulns, remediationPlan, absolutePath);
476
- } else if (options.json) {
477
- outputJSON(scoreResult, filteredFindings, depVulns, recon, agentResults, remediationPlan, suppressions, options.compare ? scoringEngine.loadHistory(absolutePath) : null, filesScanned);
478
- } else if (options.sarif) {
479
- outputSARIF(filteredFindings, absolutePath);
480
- } else {
481
- printReport(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, filesScanned);
482
- }
483
-
484
- // ── HTML Report — always on for human output, or when --html is explicit ──
485
- const explicitHtml = typeof options.html === 'string' || options.html === true;
486
- if (explicitHtml || (!options.json && !options.sarif && !options.csv && !options.md)) {
487
- const htmlPath = typeof options.html === 'string' ? options.html : 'praxis-report.html';
488
- const reporter = new HTMLReporter();
489
- reporter.generateToFile(scoreResult, filteredFindings, recon, absolutePath, htmlPath, agentResults, filesScanned);
490
-
491
- // If --html-dir or --suite specified, also generate granular multi-page report suite
492
- if (options.htmlDir || options['html-dir'] || options.suite) {
493
- const suiteDir = typeof (options.htmlDir || options['html-dir'] || options.suite) === 'string'
494
- ? (options.htmlDir || options['html-dir'] || options.suite)
495
- : 'report';
496
- reporter.generateReportSuite(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, suiteDir, agentResults, filesScanned);
497
- }
498
-
499
- // Keep stdout pure JSON/SARIF when combined with machine output
500
- const note = machineOutput ? console.error : console.log;
501
- note();
502
- note(chalk.cyan(` Full report: ${chalk.white.bold(htmlPath)}`));
503
- note(chalk.gray(` Dashboard: `) + chalk.cyan(''));
504
-
505
- // PDF export
506
- if (options.pdf) {
507
- const pdfPath = typeof options.pdf === 'string' ? options.pdf : 'praxis-report.pdf';
508
- const result = generatePDF(path.resolve(htmlPath), path.resolve(pdfPath));
509
- if (result) {
510
- note(chalk.cyan(` PDF report: ${chalk.white.bold(pdfPath)}`));
511
- } else {
512
- // Fallback: print-optimized HTML
513
- const fallbackPath = pdfPath.replace(/\.pdf$/, '.print.html');
514
- generatePrintHTML(path.resolve(htmlPath), path.resolve(fallbackPath));
515
- note(chalk.yellow(` Chrome not found — saved print-optimized HTML: ${fallbackPath}`));
516
- note(chalk.gray(' Open in a browser and Print → Save as PDF'));
517
- }
518
- }
519
- }
520
-
521
- if (!machineOutput && !options.csv && !options.md) {
522
- // ── Policy Violations ──────────────────────────────────────────────────
523
- const violations = policy.evaluate(scoreResult, filteredFindings, {
524
- agentResults,
525
- depsRun: options.deps !== false,
526
- secretsRun: true,
527
- depVulns,
528
- });
529
- if (violations.length > 0) {
530
- console.log();
531
- console.log(chalk.red.bold(' Policy Violations:'));
532
- for (const v of violations.slice(0, 5)) {
533
- console.log(chalk.red(` ✗ ${v.message}`));
534
- }
535
- }
536
-
537
- // ── Trend ───────────────────────────────────────────────────────────────
538
- const trend = scoringEngine.getTrend(absolutePath, scoreResult.score);
539
- if (trend) {
540
- const arrow = trend.diff > 0 ? chalk.green('↑') : trend.diff < 0 ? chalk.red('↓') : chalk.gray('→');
541
- const roundedDiff = Math.round(trend.diff * 10) / 10;
542
- const diffLabel = roundedDiff === 0 ? chalk.gray('no change') : chalk.white(`${roundedDiff > 0 ? '+' : ''}${roundedDiff}`);
543
- console.log(chalk.gray(` Trend: ${trend.previousScore} → ${trend.currentScore} ${arrow} (`) + diffLabel + chalk.gray(')'));
544
- }
545
-
546
- // ── Detailed Comparison ────────────────────────────────────────────────
547
- if (options.compare) {
548
- printComparison(scoringEngine, absolutePath, scoreResult);
549
- }
550
-
551
- console.log();
552
- console.log(chalk.cyan('═'.repeat(60)));
553
- console.log();
554
- }
555
-
556
- // ── Agentic Loop (--agentic) ────────────────────────────────────────────
557
- // Scan → annotate fixes → re-scan cycle until score >= target or maxIter.
558
- // NOTE: process.exit() is deferred until after the loop so all iterations
559
- // can run. The inner re-scans use _agenticInner: true to skip process.exit.
560
- if (options.agentic && !options._agenticInner) {
561
- const maxIter = typeof options.agentic === 'number' ? options.agentic : 3;
562
- const targetScore = options.agenticTarget ?? 75;
563
- let iteration = 1;
564
- let currentScore = scoreResult.score;
565
- let currentFindings = filteredFindings;
566
-
567
- if (!machineOutput) {
568
- console.log();
569
- console.log(chalk.cyan.bold(` Agentic mode: scan→fix→verify loop (max ${maxIter} iterations, target score: ${targetScore})`));
570
- }
571
-
572
- while (currentScore < targetScore && iteration <= maxIter) {
573
- if (!machineOutput) {
574
- console.log(chalk.cyan(`\n ─── Agentic iteration ${iteration}/${maxIter} (current score: ${currentScore}) ───`));
575
- }
576
-
577
- const actionable = currentFindings.filter(f => f.fix && f.severity !== 'low');
578
- if (actionable.length === 0) {
579
- if (!machineOutput) console.log(chalk.gray(' No auto-fixable findings — stopping agentic loop.'));
580
- break;
581
- }
582
-
583
- // Delegate annotation to autofix module (handles comment style, idempotency, NEVER_EDIT list)
584
- const fixCount = applyInlineAnnotations(actionable);
585
- if (!machineOutput) {
586
- console.log(chalk.yellow(` Annotated ${fixCount} finding(s). Re-scanning...`));
587
- }
588
- if (fixCount === 0) break;
589
-
590
- // Re-scan without recursing into the agentic loop or calling process.exit
591
- const innerResult = await runAuditInner(targetPath, {
592
- ...options,
593
- agentic: false,
594
- _agenticInner: true,
595
- json: false,
596
- sarif: false,
597
- csv: false,
598
- md: false,
599
- html: false,
600
- pdf: false,
601
- quiet: true,
602
- });
603
-
604
- const prevScore = currentScore;
605
- currentScore = innerResult?.score ?? currentScore;
606
- currentFindings = innerResult?.findings ?? currentFindings;
607
-
608
- if (!machineOutput) {
609
- const diff = currentScore - prevScore;
610
- const arrow = diff > 0 ? chalk.green(`↑ +${diff.toFixed(1)}`) : diff < 0 ? chalk.red(`↓ ${diff.toFixed(1)}`) : chalk.gray('→ 0');
611
- console.log(chalk.cyan(` Re-scan score: ${currentScore} ${arrow}`));
612
- }
613
-
614
- iteration++;
615
- }
616
-
617
- if (!machineOutput) {
618
- if (currentScore >= targetScore) {
619
- console.log(chalk.green.bold(`\n Agentic loop complete — target score ${targetScore} reached (${currentScore}).`));
620
- } else {
621
- console.log(chalk.yellow(`\n Agentic loop stopped after ${iteration - 1} iteration(s). Final score: ${currentScore}`));
622
- }
623
- }
624
- }
625
-
626
- // ── Exit code logic ─────────────────────────────────────────────────────
627
- // Only gate the exit code when --fail-below is explicitly requested;
628
- // a plain scan reports findings and exits 0 (CI gating belongs to `scan ci`).
629
- // Use process.exitCode (natural event-loop drain) instead of process.exit()
630
- // so in-flight libuv handles (plugin dynamic imports, etc.) close cleanly.
631
- if (options.failBelow !== undefined) {
632
- let threshold = 75;
633
- if (options.failBelow === 'baseline') {
634
- // Read baseline score from .praxis/hermes-baseline.json
635
- const baselinePath = path.join(absolutePath, '.praxis', 'hermes-baseline.json');
636
- try {
637
- const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf-8'));
638
- threshold = baseline.score || 0;
639
- if (!machineOutput) {
640
- console.log(chalk.gray(` Baseline threshold: ${threshold}/100 (from ${baselinePath})`));
641
- }
642
- } catch {
643
- if (!machineOutput) {
644
- console.log(chalk.yellow(` Warning: could not read baseline — using score 0 as threshold`));
645
- }
646
- threshold = 0;
647
- }
648
- } else {
649
- const parsed = parseInt(options.failBelow, 10);
650
- threshold = Number.isNaN(parsed) ? 75 : parsed;
651
- }
652
- process.exitCode = scoreResult.score >= threshold ? 0 : 1;
653
- }
654
- } finally {
655
- if (gitClone) {
656
- if (!options.keepClone) {
657
- gitClone.cleanup();
658
- } else if (!machineOutput) {
659
- console.log(chalk.gray(`\n Cloned repository retained at: ${gitClone.tempDir}`));
660
- }
661
- }
662
- }
663
- }
664
-
665
- /**
666
- * Run a lightweight inner audit that returns { score, findings } without
667
- * calling process.exit(). Used exclusively by the --agentic loop.
668
- */
669
- async function runAuditInner(targetPath, options) {
670
- try {
671
- return await auditCommand(targetPath, options);
672
- } catch {
673
- return null;
674
- }
675
- }
676
-
677
- // =============================================================================
678
- // REMEDIATION PLAN BUILDER
679
- // =============================================================================
680
-
681
- function buildRemediationPlan(findings, depVulns, rootPath) {
682
- const plan = [];
683
- let priority = 1;
684
-
685
- // Exclude low-confidence findings (test files, docs, comments) from remediation plan
686
- const actionable = findings.filter(f => f.confidence !== 'low');
687
-
688
- // Priority order: secrets first, then by severity
689
- const secretFindings = actionable.filter(f => f.category === 'secrets' || f.category === 'secret');
690
- const otherFindings = actionable.filter(f => f.category !== 'secrets' && f.category !== 'secret');
691
-
692
- // Group and sort
693
- for (const sev of SEV_ORDER) {
694
- // Secrets at this severity — group .env findings by file
695
- const sevSecrets = secretFindings.filter(s => s.severity === sev);
696
- const envGroups = new Map();
697
- const nonEnvSecrets = [];
698
-
699
- for (const f of sevSecrets) {
700
- const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
701
- if (f.file.match(/\.env(\..*)?$/)) {
702
- if (!envGroups.has(relFile)) envGroups.set(relFile, []);
703
- envGroups.get(relFile).push(f);
704
- } else {
705
- nonEnvSecrets.push(f);
706
- }
707
- }
708
-
709
- // One plan item per .env file
710
- for (const [relFile, envFindings] of envGroups) {
711
- const names = envFindings.map(f => f.title || f.rule).join(', ');
712
- plan.push({
713
- priority: priority++,
714
- severity: sev,
715
- category: 'secrets',
716
- categoryLabel: 'SECRETS',
717
- title: `${envFindings.length} secret${envFindings.length > 1 ? 's' : ''} in ${relFile} (${names})`,
718
- file: relFile,
719
- action: envFindings[0].fix || 'Ensure .env is in .gitignore and use a secrets manager for production',
720
- effort: 'low',
721
- });
722
- }
723
-
724
- // Individual items for non-.env secrets
725
- for (const f of nonEnvSecrets) {
726
- plan.push({
727
- priority: priority++,
728
- severity: sev,
729
- category: 'secrets',
730
- categoryLabel: 'SECRETS',
731
- title: f.title || f.rule,
732
- file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
733
- action: f.aiFix || f.fix || f.description,
734
- effort: 'low',
735
- });
736
- }
737
-
738
- // Other findings at this severity
739
- for (const f of otherFindings.filter(s => s.severity === sev)) {
740
- plan.push({
741
- priority: priority++,
742
- severity: sev,
743
- category: f.category,
744
- categoryLabel: (CATEGORY_LABELS[f.category] || f.category).toUpperCase(),
745
- title: f.title || f.rule,
746
- file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
747
- action: f.aiFix || f.fix || f.description,
748
- effort: EFFORT_MAP[f.category] || 'medium',
749
- });
750
- }
751
-
752
- // Dep vulns at this severity
753
- for (const d of depVulns.filter(v => v.severity === sev || (sev === 'medium' && v.severity === 'moderate'))) {
754
- plan.push({
755
- priority: priority++,
756
- severity: sev,
757
- category: 'deps',
758
- categoryLabel: 'DEPENDENCIES',
759
- title: `Vulnerable: ${d.package || d.id}`,
760
- file: 'package.json',
761
- action: d.description ? `${d.description.slice(0, 80)}` : 'Update to patched version',
762
- effort: 'medium',
763
- });
764
- }
765
- }
766
-
767
- return plan;
768
- }
769
-
770
- // =============================================================================
771
- // CONSOLE OUTPUT
772
- // =============================================================================
773
-
774
- function printReport(scoreResult, findings, depVulns, recon, plan, rootPath, filesScanned) {
775
- const GRADE_COLOR = { A: chalk.green.bold, B: chalk.cyan.bold, C: chalk.yellow.bold, D: chalk.red, F: chalk.red.bold };
776
- const SEV_ICON = { critical: '🔴', high: '🟠', medium: '🟡', low: '🔵' };
777
- const SEV_LABEL = { critical: 'CRITICAL — fix immediately', high: 'HIGH — fix before deploy', medium: 'MEDIUM — fix soon', low: 'LOW — review when possible' };
778
-
779
- // ── Score ─────────────────────────────────────────────────────────────────
780
- const gradeColor = GRADE_COLOR[scoreResult.grade.letter] || chalk.white;
781
- const scoreColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
782
-
783
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
784
- console.log(
785
- chalk.white.bold(' Security Score: ') +
786
- scoreColor(`${scoreResult.score}/100 `) +
787
- gradeColor(scoreResult.grade.letter) +
788
- chalk.gray(` — ${scoreResult.grade.label}`)
789
- );
790
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
791
- console.log();
792
-
793
- // ── Category Breakdown ────────────────────────────────────────────────────
794
- console.log(chalk.white.bold(' Category Breakdown'));
795
- console.log(chalk.gray(' ' + '─'.repeat(56)));
796
-
797
- for (const [key, cat] of Object.entries(scoreResult.categories)) {
798
- const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
799
- const icon = count === 0 ? chalk.green('✔') : chalk.red('✘');
800
- const status = count === 0 ? chalk.green('clean') : chalk.red(`${count} issue(s)`);
801
- const deduction = cat.deduction > 0 ? chalk.red(`-${Math.round(cat.deduction * 10) / 10} pts`) : chalk.gray('+0');
802
- console.log(` ${icon} ${chalk.white(cat.label.padEnd(22))} ${status.padEnd(25)} ${deduction}`);
803
- }
804
-
805
- // Deps row — only print if not already included in scoreResult.categories
806
- const hasDepsCategory = Object.values(scoreResult.categories).some(c => c.label?.toLowerCase().includes('depend'));
807
- if (!hasDepsCategory) {
808
- const depIcon = depVulns.length === 0 ? chalk.green('✔') : chalk.red('✘');
809
- const depStatus = depVulns.length === 0 ? chalk.green('clean') : chalk.red(`${depVulns.length} CVE(s)`);
810
- console.log(` ${depIcon} ${chalk.white('Dependencies'.padEnd(22))} ${depStatus}`);
811
- }
812
-
813
- console.log(chalk.gray(`\n Files scanned: ${filesScanned} | Findings: ${findings.length} | CVEs: ${depVulns.length}`));
814
-
815
- // ── Remediation Plan ──────────────────────────────────────────────────────
816
- if (plan.length > 0) {
817
- console.log();
818
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
819
- console.log(chalk.cyan.bold(' Remediation Plan'));
820
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
821
-
822
- let currentSev = null;
823
- let shown = 0;
824
- const maxItems = 30;
825
-
826
- for (const item of plan) {
827
- if (shown >= maxItems) {
828
- console.log(chalk.gray(`\n ... and ${plan.length - maxItems} more items in the full report`));
829
- break;
830
- }
831
-
832
- if (item.severity !== currentSev) {
833
- currentSev = item.severity;
834
- console.log();
835
- console.log(chalk.white.bold(` ${SEV_ICON[currentSev] || '⚪'} ${SEV_LABEL[currentSev] || currentSev.toUpperCase()}`));
836
- console.log(chalk.gray(' ' + '─'.repeat(56)));
837
- }
838
-
839
- console.log(
840
- chalk.white(` ${String(item.priority).padStart(2)}.`) +
841
- chalk.gray(` [${item.categoryLabel}] `) +
842
- chalk.white(item.title)
843
- );
844
- console.log(
845
- chalk.gray(` ${item.file}`) +
846
- chalk.gray(' → ') +
847
- chalk.green((item.action || '').slice(0, 70))
848
- );
849
- shown++;
850
- }
851
- } else {
852
- console.log();
853
- console.log(chalk.green.bold(' All clear — safe to ship!'));
854
- }
855
-
856
- // ── Attack Surface ────────────────────────────────────────────────────────
857
- if (recon) {
858
- console.log();
859
- console.log(chalk.gray(' Attack Surface:'));
860
- if (recon.frameworks?.length) console.log(chalk.gray(` Frameworks: ${recon.frameworks.join(', ')}`));
861
- if (recon.databases?.length) console.log(chalk.gray(` Databases: ${recon.databases.join(', ')}`));
862
- if (recon.authPatterns?.length) console.log(chalk.gray(` Auth: ${recon.authPatterns.join(', ')}`));
863
- if (recon.apiRoutes?.length) console.log(chalk.gray(` API Routes: ${recon.apiRoutes.length} discovered`));
864
- }
865
- }
866
-
867
- // =============================================================================
868
- // JSON OUTPUT
869
- // =============================================================================
870
-
871
- function outputJSON(scoreResult, findings, depVulns, recon, agentResults, remediationPlan, suppressions, history, filesScanned = null) {
872
- const output = {
873
- score: scoreResult.score,
874
- grade: scoreResult.grade.letter,
875
- gradeLabel: scoreResult.grade.label,
876
- totalFindings: findings.length,
877
- totalDepVulns: depVulns.length,
878
- categories: Object.fromEntries(
879
- Object.entries(scoreResult.categories).map(([k, v]) => [k, {
880
- label: v.label,
881
- findingCount: Object.values(v.counts).reduce((a, b) => a + b, 0),
882
- deduction: v.deduction,
883
- counts: v.counts,
884
- }])
885
- ),
886
- findings: findings.map(f => {
887
- const normFile = String(f.file || '')
888
- .replace(/\\/g, '/')
889
- .replace(/^[a-zA-Z]:\/+/, '')
890
- .replace(/^.*\/Praxis\/showcase-target\//, 'showcase-target/')
891
- .replace(/^.*\/Praxis\//, '');
892
- return {
893
- file: normFile, line: f.line, severity: f.severity, category: f.category,
894
- rule: f.rule, title: f.title, description: f.description, fix: f.fix,
895
- cwe: f.cwe, owasp: f.owasp,
896
- ...(f.eaa ? { eaa: f.eaa } : {}),
897
- ...(f.confidence ? { confidence: f.confidence } : {}),
898
- ...(f.standards ? { standards: f.standards } : {}),
899
- ...(f.deepAnalysis ? { deepAnalysis: f.deepAnalysis } : {}),
900
- ...(f.aiClassification ? {
901
- aiClassification: f.aiClassification,
902
- ...(f.aiReason ? { aiReason: f.aiReason } : {}),
903
- ...(f.aiFix ? { aiFix: f.aiFix } : {}),
904
- } : {}),
905
- };
906
- }),
907
- depVulns: depVulns.map(d => ({
908
- severity: d.severity, package: d.package || d.id, description: d.description,
909
- })),
910
- remediationPlan,
911
- recon,
912
- agents: agentResults,
913
- // Provenance: which tool, runtime and vendored data produced these numbers (P-IMP-053).
914
- fingerprint: buildScanFingerprint({ filesScanned }),
915
- };
916
- if (scoreResult.compliance) output.compliance = scoreResult.compliance;
917
- if (scoreResult.standardsSummary) output.standardsSummary = scoreResult.standardsSummary;
918
- if (scoreResult.agenticSummary) output.agenticSummary = scoreResult.agenticSummary;
919
- if (suppressions) output.suppressions = suppressions;
920
- if (history && history.length >= 2) {
921
- const prev = history[history.length - 2];
922
- output.comparison = {
923
- previousScore: prev.score,
924
- previousGrade: prev.grade,
925
- previousDate: prev.timestamp,
926
- diff: scoreResult.score - prev.score,
927
- categoryComparison: Object.fromEntries(
928
- Object.entries(scoreResult.categories).map(([k, v]) => {
929
- const prevCat = prev.categoryScores?.[k];
930
- return [k, {
931
- label: v.label,
932
- current: -v.deduction,
933
- previous: prevCat ? -prevCat.deduction : 0,
934
- delta: prevCat ? prevCat.deduction - v.deduction : 0,
935
- }];
936
- })
937
- ),
938
- };
939
- }
940
- console.log(JSON.stringify(output, null, 2));
941
- }
942
-
943
- // =============================================================================
944
- // SARIF OUTPUT
945
- // =============================================================================
946
-
947
- /**
948
- * SARIF for GitHub Code Scanning.
949
- *
950
- * Delegates to the shared serializer in `cli/core/output/sarif.js` (P-IMP-062). This was
951
- * a private copy, hardcoding a driver version of `4.0.0` while the package was at a
952
- * different number entirely, and it carried no `security-severity` — so the default
953
- * `praxis scan` lost severity fidelity in Code Scanning.
954
- */
955
- function outputSARIF(findings, rootPath) {
956
- console.log(renderFindingsSARIF(findings, { rootPath }));
957
- }
958
-
959
- // =============================================================================
960
- // FILE SCANNING (inline from scan.js to avoid circular deps)
961
- // =============================================================================
962
-
963
- // Walk up from `start` looking for `name`. Returns the absolute path or null.
964
- // Bounded to 8 ancestors to avoid runaway loops on weird filesystems.
965
- function findUpwards(start, name) {
966
- let dir = path.resolve(start);
967
- for (let i = 0; i < 8; i++) {
968
- const candidate = path.join(dir, name);
969
- if (fs.existsSync(candidate)) return candidate;
970
- const parent = path.dirname(dir);
971
- if (parent === dir) return null;
972
- dir = parent;
973
- }
974
- return null;
975
- }
976
-
977
- async function findFiles(rootPath) {
978
- const globIgnore = Array.from(SKIP_DIRS).map(dir => `**/${dir}/**`);
979
-
980
- // Respect .gitignore patterns
981
- const gitignoreGlobs = loadGitignorePatterns(rootPath);
982
- globIgnore.push(...gitignoreGlobs);
983
-
984
- // Load .praxisignore — walk up to the project root so subdirectory scans
985
- // still honor the repo-level ignore file.
986
- const ignorePath = findUpwards(rootPath, '.praxisignore');
987
- if (ignorePath) {
988
- try {
989
- const patterns = fs.readFileSync(ignorePath, 'utf-8')
990
- .split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));
991
- for (const p of patterns) {
992
- if (p.endsWith('/')) { globIgnore.push(`**/${p}**`); }
993
- else { globIgnore.push(`**/${p}`); globIgnore.push(p); }
994
- }
995
- } catch { /* skip */ }
996
- }
997
-
998
- const files = await fg('**/*', {
999
- cwd: rootPath, absolute: true, onlyFiles: true, ignore: globIgnore, dot: true
1000
- });
1001
-
1002
- return files.filter(file => {
1003
- const ext = path.extname(file).toLowerCase();
1004
- if (SKIP_EXTENSIONS.has(ext)) return false;
1005
- if (SKIP_FILENAMES.has(path.basename(file))) return false;
1006
- if (path.basename(file).endsWith('.min.js') || path.basename(file).endsWith('.min.css')) return false;
1007
- try { if (fs.statSync(file).size > MAX_FILE_SIZE) return false; } catch { return false; }
1008
- return true;
1009
- });
1010
- }
1011
-
1012
- function scanFileForSecrets(filePath) {
1013
- const findings = [];
1014
- try {
1015
- const content = fs.readFileSync(filePath, 'utf-8');
1016
- const lines = content.split('\n');
1017
- for (let lineNum = 0; lineNum < lines.length; lineNum++) {
1018
- const line = lines[lineNum];
1019
- if (/praxis-ignore/i.test(line)) continue;
1020
- for (const pattern of SECRET_PATTERNS) {
1021
- pattern.pattern.lastIndex = 0;
1022
- let match;
1023
- while ((match = pattern.pattern.exec(line)) !== null) {
1024
- if (pattern.requiresEntropyCheck && !isHighEntropyMatch(match[0])) continue;
1025
- findings.push({
1026
- line: lineNum + 1, column: match.index + 1, matched: match[0],
1027
- patternName: pattern.name, severity: pattern.severity,
1028
- confidence: getConfidence(pattern, match[0]),
1029
- description: pattern.description, category: pattern.category || 'secret'
1030
- });
1031
- }
1032
- }
1033
- }
1034
- } catch { /* skip */ }
1035
-
1036
- const seen = new Set();
1037
- return findings.filter(f => {
1038
- const key = `${f.line}:${f.matched}`;
1039
- if (seen.has(key)) return false;
1040
- seen.add(key);
1041
- return true;
1042
- });
1043
- }
1044
-
1045
- function deduplicateFindings(findings) {
1046
- const seen = new Set();
1047
- return findings.filter(f => {
1048
- const key = `${f.file}:${f.line}:${f.rule}`;
1049
- if (seen.has(key)) return false;
1050
- seen.add(key);
1051
- return true;
1052
- });
1053
- }
1054
-
1055
- // =============================================================================
1056
- // SUPPRESSION COUNTING
1057
- // =============================================================================
1058
-
1059
- function countSuppressions(files) {
1060
- const suppressions = {};
1061
- let total = 0;
1062
- for (const file of files) {
1063
- try {
1064
- const content = fs.readFileSync(file, 'utf-8');
1065
- const lines = content.split('\n');
1066
- for (const line of lines) {
1067
- if (/praxis-ignore/i.test(line)) {
1068
- total++;
1069
- // Try to extract rule name from comment: praxis-ignore RULE_NAME
1070
- const match = line.match(/praxis-ignore\s+(\w+)/i);
1071
- const rule = match ? match[1] : '_unspecified';
1072
- suppressions[rule] = (suppressions[rule] || 0) + 1;
1073
- }
1074
- }
1075
- } catch { /* skip */ }
1076
- }
1077
- return total > 0 ? { total, rules: suppressions } : null;
1078
- }
1079
-
1080
- // =============================================================================
1081
- // CSV OUTPUT
1082
- // =============================================================================
1083
-
1084
- function outputCSV(findings, depVulns, scoreResult, rootPath) {
1085
- const escape = (s) => {
1086
- if (!s) return '';
1087
- const str = String(s).replace(/"/g, '""');
1088
- return str.includes(',') || str.includes('"') || str.includes('\n') ? `"${str}"` : str;
1089
- };
1090
-
1091
- console.log('severity,category,rule,file,line,title,description,fix');
1092
- for (const f of findings) {
1093
- const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
1094
- console.log([
1095
- escape(f.severity), escape(f.category), escape(f.rule),
1096
- escape(relFile), f.line || '', escape(f.title),
1097
- escape(f.description), escape(f.fix),
1098
- ].join(','));
1099
- }
1100
- for (const d of depVulns) {
1101
- console.log([
1102
- escape(d.severity), 'deps', escape(d.id || d.package),
1103
- 'package.json', '', escape(`Vulnerable: ${d.package || d.id}`),
1104
- escape(d.description), escape('Update to patched version'),
1105
- ].join(','));
1106
- }
1107
- }
1108
-
1109
- // =============================================================================
1110
- // MARKDOWN OUTPUT
1111
- // =============================================================================
1112
-
1113
- function outputMarkdown(scoreResult, findings, depVulns, remediationPlan, rootPath) {
1114
- const lines = [];
1115
- lines.push('# Praxis Security Report');
1116
- lines.push('');
1117
- lines.push(`**Score: ${scoreResult.score}/100 (${scoreResult.grade.letter})** — ${scoreResult.grade.label}`);
1118
- lines.push('');
1119
- lines.push(`> Generated: ${new Date().toISOString()}`);
1120
- lines.push('');
1121
-
1122
- // Category breakdown
1123
- lines.push('## Category Breakdown');
1124
- lines.push('');
1125
- lines.push('| Category | Issues | Deduction |');
1126
- lines.push('|----------|--------|-----------|');
1127
- for (const [, cat] of Object.entries(scoreResult.categories)) {
1128
- const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
1129
- lines.push(`| ${cat.label} | ${count} | -${cat.deduction} |`);
1130
- }
1131
- lines.push('');
1132
-
1133
- // Findings by severity
1134
- for (const sev of SEV_ORDER) {
1135
- const sevFindings = findings.filter(f => f.severity === sev);
1136
- if (sevFindings.length === 0) continue;
1137
-
1138
- lines.push(`## ${sev.charAt(0).toUpperCase() + sev.slice(1)} (${sevFindings.length})`);
1139
- lines.push('');
1140
- lines.push('| File | Rule | Description | Fix |');
1141
- lines.push('|------|------|-------------|-----|');
1142
- for (const f of sevFindings) {
1143
- const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
1144
- lines.push(`| ${relFile}:${f.line} | ${f.rule} | ${(f.description || '').slice(0, 80)} | ${(f.fix || '').slice(0, 60)} |`);
1145
- }
1146
- lines.push('');
1147
- }
1148
-
1149
- // Dep vulns
1150
- if (depVulns.length > 0) {
1151
- lines.push('## Dependency Vulnerabilities');
1152
- lines.push('');
1153
- lines.push('| Severity | Package | Description |');
1154
- lines.push('|----------|---------|-------------|');
1155
- for (const d of depVulns) {
1156
- lines.push(`| ${d.severity} | ${d.package || d.id} | ${(d.description || '').slice(0, 80)} |`);
1157
- }
1158
- lines.push('');
1159
- }
1160
-
1161
- console.log(lines.join('\n'));
1162
- }
1163
-
1164
- // =============================================================================
1165
- // COMPARISON OUTPUT
1166
- // =============================================================================
1167
-
1168
- function printComparison(scoringEngine, rootPath, scoreResult) {
1169
- const history = scoringEngine.loadHistory(rootPath);
1170
- if (history.length < 2) {
1171
- console.log(chalk.gray('\n No previous scan to compare against.'));
1172
- return;
1173
- }
1174
-
1175
- const prev = history[history.length - 2];
1176
- console.log();
1177
- console.log(chalk.cyan.bold(' Detailed Comparison'));
1178
- console.log(chalk.gray(' ' + '─'.repeat(56)));
1179
- console.log(chalk.gray(` Previous scan: ${new Date(prev.timestamp).toLocaleString()}`));
1180
- console.log();
1181
- console.log(chalk.white(' Category'.padEnd(26)) + chalk.white('Previous'.padEnd(12)) + chalk.white('Current'.padEnd(12)) + chalk.white('Delta'));
1182
- console.log(chalk.gray(' ' + '─'.repeat(56)));
1183
-
1184
- for (const [key, cat] of Object.entries(scoreResult.categories)) {
1185
- const prevCat = prev.categoryScores?.[key];
1186
- const prevDed = prevCat ? prevCat.deduction : 0;
1187
- const curDed = cat.deduction;
1188
- const delta = prevDed - curDed;
1189
-
1190
- let deltaStr;
1191
- if (delta > 0) deltaStr = chalk.green(`+${delta} improved`);
1192
- else if (delta < 0) deltaStr = chalk.red(`${delta} regressed`);
1193
- else deltaStr = chalk.gray('→ unchanged');
1194
-
1195
- console.log(
1196
- ` ${chalk.white(cat.label.padEnd(24))}` +
1197
- `${chalk.gray(String(-prevDed).padEnd(12))}` +
1198
- `${chalk.gray(String(-curDed).padEnd(12))}` +
1199
- deltaStr
1200
- );
1201
- }
1202
-
1203
- const overallDiff = scoreResult.score - prev.score;
1204
- let overallDelta;
1205
- if (overallDiff > 0) overallDelta = chalk.green(`+${overallDiff} improved`);
1206
- else if (overallDiff < 0) overallDelta = chalk.red(`${overallDiff} regressed`);
1207
- else overallDelta = chalk.gray('→ unchanged');
1208
-
1209
- console.log(chalk.gray(' ' + '─'.repeat(56)));
1210
- console.log(
1211
- ` ${chalk.white.bold('Overall'.padEnd(24))}` +
1212
- `${chalk.gray(`${prev.score}/100 ${prev.grade}`.padEnd(12))}` +
1213
- `${chalk.gray(`${scoreResult.score}/100 ${scoreResult.grade.letter}`.padEnd(12))}` +
1214
- overallDelta
1215
- );
1216
- }
1
+ /**
2
+ * Audit Command — Full Security Audit
3
+ * =====================================
4
+ *
5
+ * One command to run everything: secrets, agents, deps, score, and
6
+ * generate a comprehensive report with a prioritized remediation plan.
7
+ *
8
+ * USAGE:
9
+ * npx praxis-sec audit [path] Full audit with HTML report
10
+ * npx praxis-sec audit . --json JSON output
11
+ * npx praxis-sec audit . --html report.html Custom report path
12
+ * npx praxis-sec audit . --no-deps Skip dependency audit
13
+ */
14
+
15
+ import fs from 'fs';
16
+ import path from 'path';
17
+ import { renderFindingsSARIF } from '../core/output/sarif.js';
18
+ import chalk from 'chalk';
19
+ import ora from 'ora';
20
+ import { displayPath } from '../core/paths.js';
21
+ import fg from '../core/glob.js';
22
+ import { buildOrchestrator, buildOrchestratorAsync } from '../agents/index.js';
23
+ import { LegalRiskAgent } from '../agents/legal-risk-agent.js';
24
+ import { ScoringEngine } from '../agents/scoring-engine.js';
25
+ import { PolicyEngine } from '../agents/policy-engine.js';
26
+ import { HTMLReporter } from '../agents/html-reporter.js';
27
+ import { SBOMGenerator } from '../agents/sbom-generator.js';
28
+ import { autoDetectProvider } from '../providers/llm-provider.js';
29
+ import { runDepsAudit } from './deps.js';
30
+ import {
31
+ SECRET_PATTERNS,
32
+ SECURITY_PATTERNS,
33
+ SKIP_DIRS,
34
+ SKIP_EXTENSIONS,
35
+ SKIP_FILENAMES,
36
+ MAX_FILE_SIZE,
37
+ loadGitignorePatterns
38
+ } from '../utils/patterns.js';
39
+ import { isHighEntropyMatch, getConfidence } from '../utils/entropy.js';
40
+ import { printBanner } from '../utils/output.js';
41
+ import { CacheManager } from '../utils/cache-manager.js';
42
+ import { filterBaseline } from './baseline.js';
43
+ import { SecurityMemory } from '../utils/security-memory.js';
44
+ import { ScanPlaybook } from '../utils/scan-playbook.js';
45
+ import { generatePDF, generatePrintHTML, isChromeAvailable } from '../utils/pdf-generator.js';
46
+ import { SecretsVerifier } from '../utils/secrets-verifier.js';
47
+ import { applyInlineAnnotations } from './autofix.js';
48
+ import { buildScanFingerprint } from '../utils/scan-fingerprint.js';
49
+ import { isGitUrl, cloneGitRepo, redactGitUrl } from '../core/git-clone.js';
50
+
51
+ // =============================================================================
52
+ // CONSTANTS
53
+ // =============================================================================
54
+
55
+ const ALL_PATTERNS = [...SECRET_PATTERNS, ...SECURITY_PATTERNS];
56
+
57
+ const SEV_ORDER = ['critical', 'high', 'medium', 'low'];
58
+
59
+ const CATEGORY_LABELS = {
60
+ secrets: 'Secrets',
61
+ injection: 'Code Vulnerabilities',
62
+ deps: 'Dependencies',
63
+ auth: 'Auth & Access Control',
64
+ config: 'Configuration',
65
+ 'supply-chain': 'Supply Chain',
66
+ api: 'API Security',
67
+ llm: 'AI/LLM Security',
68
+ legal: 'Legal Risk',
69
+ };
70
+
71
+ const EFFORT_MAP = {
72
+ secrets: 'low',
73
+ config: 'low',
74
+ deps: 'medium',
75
+ injection: 'medium',
76
+ auth: 'medium',
77
+ 'supply-chain': 'medium',
78
+ api: 'medium',
79
+ llm: 'high',
80
+ legal: 'low',
81
+ };
82
+
83
+ // =============================================================================
84
+ // MAIN COMMAND
85
+ // =============================================================================
86
+
87
+ export async function auditCommand(targetPath = '.', options = {}) {
88
+ const machineOutput = options.json || options.sarif || options.csv || options.md;
89
+ let gitClone = null;
90
+ let effectivePath = targetPath;
91
+
92
+ // ── Remote Git Repository Support ─────────────────────────────────────────
93
+ if (isGitUrl(targetPath)) {
94
+ if (!machineOutput) printBanner();
95
+ const gitSpinner = machineOutput ? null : ora({ text: chalk.cyan(`Cloning remote Git repository: ${redactGitUrl(targetPath)}...`), color: 'cyan' }).start();
96
+ try {
97
+ gitClone = cloneGitRepo(targetPath, {
98
+ branch: options.branch,
99
+ depth: options.depth,
100
+ gitToken: options.gitToken,
101
+ submodules: options.submodules,
102
+ gitHistory: options.gitHistory,
103
+ });
104
+ effectivePath = gitClone.tempDir;
105
+ if (gitSpinner) gitSpinner.succeed(chalk.green(`Cloned ${gitClone.repoName} (${gitClone.displayUrl}) to temporary workspace`));
106
+ } catch (err) {
107
+ if (gitSpinner) gitSpinner.fail(chalk.red(err.message));
108
+ else console.error(chalk.red(err.message));
109
+ process.exitCode = 1;
110
+ return;
111
+ }
112
+ }
113
+
114
+ try {
115
+ const absolutePath = path.resolve(effectivePath);
116
+
117
+ if (!fs.existsSync(absolutePath)) {
118
+ console.error(chalk.red(` Path does not exist: ${absolutePath}`));
119
+ process.exitCode = 1;
120
+ return;
121
+ }
122
+
123
+ if (!machineOutput && !gitClone) {
124
+ printBanner();
125
+ }
126
+
127
+ // ── Cache Layer ──────────────────────────────────────────────────────────
128
+ // --deep forces a fresh scan so taint analysis covers every finding,
129
+ // not just the ones from files changed since the last cached run.
130
+ const useCache = options.cache !== false && !options.deep;
131
+ const cache = new CacheManager(absolutePath);
132
+ let cacheData = useCache ? cache.load() : null;
133
+ let cacheDiff = null;
134
+ let allFiles = [];
135
+
136
+ // ── Phase 1: Secret Scan ──────────────────────────────────────────────────
137
+ const secretSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 1/4] Scanning for secrets...'), color: 'cyan' }).start();
138
+ let secretFindings = [];
139
+ let filesScanned = 0;
140
+
141
+ try {
142
+ allFiles = await findFiles(absolutePath);
143
+ filesScanned = allFiles.length;
144
+
145
+ // Determine which files need scanning (incremental if cache exists)
146
+ let filesToScan = allFiles;
147
+ let cachedSecretFindings = [];
148
+
149
+ if (cacheData) {
150
+ cacheDiff = cache.diff(allFiles);
151
+ filesToScan = cacheDiff.changedFiles;
152
+ // Reuse cached findings for unchanged files (secrets only)
153
+ cachedSecretFindings = cacheDiff.cachedFindings.filter(
154
+ f => f.category === 'secrets' || f.category === 'secret'
155
+ );
156
+ }
157
+
158
+ for (const file of filesToScan) {
159
+ const fileResults = scanFileForSecrets(file);
160
+ for (const f of fileResults) {
161
+ secretFindings.push({
162
+ // Normalised here so secret findings are indistinguishable from agent
163
+ // findings by the time anything renders them.
164
+ file: displayPath(file, absolutePath),
165
+ line: f.line,
166
+ column: f.column,
167
+ severity: f.severity,
168
+ category: f.category || 'secrets',
169
+ rule: f.patternName,
170
+ title: f.patternName.replace(/_/g, ' '),
171
+ description: f.description,
172
+ matched: f.matched,
173
+ confidence: f.confidence,
174
+ fix: file.match(/\.env(\..*)?$/)
175
+ ? `Ensure .env is in .gitignore and use a secrets manager for production`
176
+ : `Move to environment variable or secrets manager`,
177
+ });
178
+ }
179
+ }
180
+
181
+ // Downgrade .env findings if the file is gitignored (properly managed)
182
+ const gitignoreContent = (() => {
183
+ try { return fs.readFileSync(path.join(absolutePath, '.gitignore'), 'utf-8'); } catch { return ''; }
184
+ })();
185
+ const envIsGitignored = gitignoreContent.split('\n')
186
+ .map(l => l.trim())
187
+ .some(l => /^\.env(\s|$)/.test(l) || l === '*.env' || l === '.env*' || l === '.env.local' || l === '.env.production');
188
+
189
+ if (envIsGitignored) {
190
+ for (const f of secretFindings) {
191
+ if (f.file.match(/\.env(\..*)?$/) && !f.file.includes('node_modules')) {
192
+ f.severity = 'low';
193
+ f.confidence = 'low';
194
+ f.fix = 'Already gitignored — ensure secrets manager is used for production deploys';
195
+ }
196
+ }
197
+ }
198
+
199
+ // Downgrade secrets in test files (intentional test fixtures)
200
+ const TEST_PATH = /(?:__tests__|\.test\.|\.spec\.|\/test\/|\/tests\/|\/fixtures?\/)/i;
201
+ for (const f of secretFindings) {
202
+ if (TEST_PATH.test(f.file)) {
203
+ f.confidence = 'low';
204
+ }
205
+ }
206
+
207
+ // Merge with cached findings for unchanged files
208
+ secretFindings = [...secretFindings, ...cachedSecretFindings];
209
+
210
+ const cacheNote = cacheDiff && cacheDiff.changedFiles.length < allFiles.length
211
+ ? ` (${cacheDiff.changedFiles.length} changed, ${cacheDiff.unchangedCount} cached)`
212
+ : '';
213
+
214
+ if (secretSpinner) secretSpinner.succeed(
215
+ secretFindings.length === 0
216
+ ? chalk.green(`[Phase 1/4] Secrets: clean${cacheNote}`)
217
+ : chalk.red(`[Phase 1/4] Secrets: ${secretFindings.length} found${cacheNote}`)
218
+ );
219
+ } catch (err) {
220
+ if (secretSpinner) secretSpinner.fail(chalk.red(`[Phase 1/4] Secret scan failed: ${err.message}`));
221
+ }
222
+
223
+ // ── Phase 2: Agent Scan ───────────────────────────────────────────────────
224
+ const orchestrator = await buildOrchestratorAsync(absolutePath, { quiet: true, trustPlugins: !gitClone && options.trustPlugins === true });
225
+
226
+ // --hermes-only: filter to llm + supply-chain category agents only
227
+ if (options.hermesOnly && orchestrator.agents) {
228
+ const hermesCategories = new Set(['llm', 'supply-chain']);
229
+ orchestrator.agents = orchestrator.agents.filter(a =>
230
+ hermesCategories.has(a.category) || hermesCategories.has(a.constructor?.category)
231
+ );
232
+ }
233
+
234
+ const registeredAgentCount = orchestrator.agents?.length || 15;
235
+ const agentSpinner = machineOutput ? null : ora({ text: chalk.white(`[Phase 2/4] Running ${registeredAgentCount} security agents...`), color: 'cyan' }).start();
236
+ let agentFindings = [];
237
+ let recon = null;
238
+ let agentResults = [];
239
+
240
+ try {
241
+ // Suppress individual agent spinners by using quiet mode
242
+ // Pass changedFiles for incremental scanning if cache is valid
243
+ const orchestratorOpts = { quiet: true };
244
+ if (options.deep) orchestratorOpts.deep = true;
245
+ if (options.local) orchestratorOpts.local = true;
246
+ if (options.model) orchestratorOpts.model = options.model;
247
+ if (options.provider) orchestratorOpts.provider = options.provider;
248
+ if (options.baseUrl) orchestratorOpts.baseUrl = options.baseUrl;
249
+ if (options.budget) orchestratorOpts.budget = options.budget;
250
+ if (options.verbose) orchestratorOpts.verbose = true;
251
+ // Deliberately NOT passing `changedFiles` to the orchestrator.
252
+ //
253
+ // BaseAgent.getFilesToScan() returns `context.changedFiles || context.files`,
254
+ // so passing it makes an agent scan only changed files — and on an unchanged
255
+ // tree that list is empty, so the agent reports nothing at all. The cache
256
+ // cannot cover for that: the restore below is filtered to
257
+ // `category === 'secrets'`, so agent findings for unchanged files were never
258
+ // coming back. A warm scan silently lost every finding from
259
+ // PromptInjectionProberAgent, VibeCodingAgent and ExceptionHandlerAgent —
260
+ // 9 findings on this tree, under-reporting on the second run of any project.
261
+ //
262
+ // 25 of 28 agents already ignore `changedFiles` and read `context.files`, so
263
+ // the hint only ever narrowed three of them while making them wrong. Phase 1
264
+ // (secrets) is where the cache actually pays for itself, and it still uses
265
+ // it. Passing an unsafe optimisation is worse than not optimising.
266
+ const results = await orchestrator.runAll(absolutePath, orchestratorOpts); // praxis-ignore — orchestrator result, not LLM output triggering actions
267
+ recon = results.recon;
268
+ agentFindings = results.findings;
269
+ agentResults = results.agentResults;
270
+
271
+ const totalAgentFindings = agentFindings.length;
272
+ const agentCount = agentResults.filter(a => a.success).length;
273
+ if (agentSpinner) agentSpinner.succeed(
274
+ totalAgentFindings === 0
275
+ ? chalk.green(`[Phase 2/4] ${agentCount} agents: clean`)
276
+ : chalk.yellow(`[Phase 2/4] ${agentCount} agents: ${totalAgentFindings} finding(s)`)
277
+ );
278
+ } catch (err) {
279
+ if (agentSpinner) agentSpinner.fail(chalk.red(`[Phase 2/4] Agent scan failed: ${err.message}`));
280
+ }
281
+
282
+ // ── Phase 3: Dependency Audit ─────────────────────────────────────────────
283
+ let depVulns = [];
284
+ if (options.deps !== false) {
285
+ const depSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 3/4] Auditing dependencies...'), color: 'cyan' }).start();
286
+ try {
287
+ const depResult = await runDepsAudit(absolutePath);
288
+ depVulns = depResult.vulns || [];
289
+ if (depSpinner) depSpinner.succeed(
290
+ depVulns.length === 0
291
+ ? chalk.green('[Phase 3/4] Dependencies: clean')
292
+ : chalk.red(`[Phase 3/4] Dependencies: ${depVulns.length} CVE(s)`)
293
+ );
294
+ } catch {
295
+ if (depSpinner) depSpinner.succeed(chalk.gray('[Phase 3/4] Dependencies: skipped (no manifest)'));
296
+ }
297
+ } else if (!machineOutput) {
298
+ console.log(chalk.gray(' [Phase 3/4] Dependencies: skipped (--no-deps)'));
299
+ }
300
+
301
+ // ── Phase 3b: Legal Risk Scan (opt-in) ───────────────────────────────────
302
+ let legalFindings = [];
303
+ if (options.includeLegal) {
304
+ const legalSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 3b] Legal risk scan…'), color: 'cyan' }).start();
305
+ try {
306
+ const legalAgent = new LegalRiskAgent();
307
+ legalFindings = await legalAgent.analyze({ rootPath: absolutePath, files: allFiles });
308
+ if (legalSpinner) legalSpinner.succeed(
309
+ legalFindings.length === 0
310
+ ? chalk.green('[Phase 3b] Legal: clean')
311
+ : chalk.yellow(`[Phase 3b] Legal: ${legalFindings.length} finding(s)`)
312
+ );
313
+ } catch {
314
+ if (legalSpinner) legalSpinner.succeed(chalk.gray('[Phase 3b] Legal: skipped'));
315
+ }
316
+ }
317
+
318
+ // ── Phase 4: Merge, Score, and Build Plan ─────────────────────────────────
319
+ const scoreSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 4/4] Computing security score...'), color: 'cyan' }).start();
320
+
321
+ // Merge secret findings + agent findings + legal findings, deduplicate
322
+ const allFindings = deduplicateFindings([...secretFindings, ...agentFindings, ...legalFindings]);
323
+
324
+ // Apply policy
325
+ const policy = PolicyEngine.load(absolutePath);
326
+ let filteredFindings = policy.applyPolicy(allFindings);
327
+
328
+ // Apply baseline filter (only show new findings)
329
+ if (options.baseline) {
330
+ const beforeCount = filteredFindings.length;
331
+ filteredFindings = filterBaseline(filteredFindings, absolutePath);
332
+ if (!machineOutput && beforeCount !== filteredFindings.length) {
333
+ console.log(chalk.gray(` Baseline: ${beforeCount - filteredFindings.length} known finding(s) filtered, ${filteredFindings.length} new`));
334
+ }
335
+ }
336
+
337
+ // ── Security Memory Filter ──────────────────────────────────────────────
338
+ // Auto-learn false positives from deep analysis results, then suppress
339
+ // any finding that memory recognises from a previous scan.
340
+ const secMemory = new SecurityMemory(absolutePath);
341
+ if (options.deep) {
342
+ // After deep analysis ran, learn any new false positives
343
+ const newFPs = secMemory.learnFromAnalysis(filteredFindings);
344
+ if (newFPs > 0 && !machineOutput) {
345
+ console.log(chalk.gray(` Memory: ${newFPs} new false positive(s) learned and will be suppressed in future scans`));
346
+ }
347
+ }
348
+ const { kept: memFiltered, suppressedCount: memSuppressed } = secMemory.filter(filteredFindings);
349
+ filteredFindings = memFiltered;
350
+ if (memSuppressed > 0 && !machineOutput) {
351
+ console.log(chalk.gray(` Memory: ${memSuppressed} previously-confirmed false positive(s) suppressed`));
352
+ }
353
+
354
+ // Count suppressions (praxis-ignore comments)
355
+ const suppressions = countSuppressions(allFiles);
356
+
357
+ // Score
358
+ const scoringEngine = new ScoringEngine();
359
+ const scoreResult = scoringEngine.compute(filteredFindings, depVulns);
360
+ // Round score to 1 decimal place to avoid floating-point noise (e.g., 63.300000000000004)
361
+ scoreResult.score = Math.round(scoreResult.score * 10) / 10;
362
+ scoringEngine.saveToHistory(absolutePath, scoreResult, suppressions);
363
+
364
+ // Score and filtered findings must exist before the best-effort playbook update.
365
+ try {
366
+ const playbook = new ScanPlaybook(absolutePath);
367
+ const suppressedRules = secMemory.list().map(entry => entry.rule).filter(Boolean);
368
+ playbook.update(recon, { score: scoreResult.score, grade: scoreResult.grade?.letter || scoreResult.grade, totalFindings: filteredFindings.length }, filteredFindings, suppressedRules);
369
+ } catch { /* non-fatal */ }
370
+
371
+ const gradeColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
372
+ if (scoreSpinner) scoreSpinner.succeed(
373
+ chalk.white('[Phase 4/4] Score: ') + gradeColor(`${scoreResult.score}/100 ${scoreResult.grade.letter}`)
374
+ );
375
+
376
+ // ── AI Classification (optional, with LLM cache) ───────────────────────
377
+ if (options.ai !== false && !options.noAi) {
378
+ const provider = autoDetectProvider(absolutePath, {
379
+ provider: options.provider,
380
+ baseUrl: options.baseUrl,
381
+ model: options.model,
382
+ think: options.think || false,
383
+ });
384
+ if (provider && filteredFindings.length > 0 && filteredFindings.length <= 50) {
385
+ const aiSpinner = machineOutput ? null : ora({ text: `Classifying with ${provider.name}...`, color: 'cyan' }).start();
386
+ try {
387
+ // Check LLM cache for existing classifications
388
+ const llmCache = cache.loadLLMClassifications();
389
+ const uncachedFindings = [];
390
+ let cachedCount = 0;
391
+
392
+ for (const finding of filteredFindings) {
393
+ const key = cache.getLLMCacheKey(finding);
394
+ const cached = llmCache[key];
395
+ if (cached) {
396
+ finding.aiClassification = cached.classification;
397
+ finding.aiReason = cached.reason;
398
+ finding.aiFix = cached.fix;
399
+ cachedCount++;
400
+ } else {
401
+ uncachedFindings.push(finding);
402
+ }
403
+ }
404
+
405
+ // Only send uncached findings to LLM
406
+ if (uncachedFindings.length > 0) {
407
+ const classifications = await provider.classify(uncachedFindings);
408
+ const newCacheEntries = {};
409
+ for (const cl of classifications) {
410
+ const finding = filteredFindings.find(f => `${f.file}:${f.line}` === cl.id);
411
+ if (finding) {
412
+ finding.aiClassification = cl.classification;
413
+ finding.aiReason = cl.reason;
414
+ finding.aiFix = cl.fix;
415
+ const key = cache.getLLMCacheKey(finding);
416
+ newCacheEntries[key] = {
417
+ classification: cl.classification,
418
+ reason: cl.reason,
419
+ fix: cl.fix,
420
+ cachedAt: new Date().toISOString(),
421
+ };
422
+ }
423
+ }
424
+ cache.saveLLMClassifications(newCacheEntries);
425
+ }
426
+
427
+ const cacheNote = cachedCount > 0 ? `, ${cachedCount} cached` : '';
428
+ if (aiSpinner) aiSpinner.succeed(chalk.green(`AI classification complete (${provider.name}${cacheNote})`));
429
+ } catch (err) {
430
+ if (aiSpinner) aiSpinner.fail(chalk.yellow(`AI classification failed: ${err.message}`));
431
+ }
432
+ }
433
+ }
434
+
435
+ // ── Secrets Verification (optional, --verify flag) ─────────────────────
436
+ if (options.verify) {
437
+ const verifySpinner = machineOutput ? null : ora({ text: 'Verifying leaked secrets against provider APIs...', color: 'cyan' }).start();
438
+ try {
439
+ const verifier = new SecretsVerifier();
440
+ const verifyResults = await verifier.verify(filteredFindings);
441
+ const activeCount = verifyResults.filter(r => r.result.active === true).length;
442
+ const inactiveCount = verifyResults.filter(r => r.result.active === false).length;
443
+ if (verifySpinner) {
444
+ verifySpinner.succeed(chalk.green(
445
+ `Secrets verified: ${activeCount} active, ${inactiveCount} inactive, ${verifyResults.length - activeCount - inactiveCount} unknown`
446
+ ));
447
+ }
448
+ // Show active secrets warning
449
+ if (activeCount > 0 && !machineOutput) {
450
+ console.log(chalk.red.bold(' ⚠ ACTIVE SECRETS DETECTED — rotate immediately:'));
451
+ for (const r of verifyResults.filter(r => r.result.active === true)) {
452
+ const rel = path.relative(absolutePath, r.finding.file).replace(/\\/g, '/');
453
+ console.log(chalk.red(` ${r.result.provider}: ${rel}:${r.finding.line} — ${r.result.info}`));
454
+ }
455
+ }
456
+ } catch (err) {
457
+ if (verifySpinner) verifySpinner.fail(chalk.yellow(`Secrets verification failed: ${err.message}`));
458
+ }
459
+ }
460
+
461
+ // ── Save Cache ──────────────────────────────────────────────────────────
462
+ if (useCache) {
463
+ try {
464
+ // Merge agent findings back for cache (secret + agent findings from changed files)
465
+ // plus cached findings from unchanged files
466
+ const cachedAgentFindings = cacheData && cacheDiff
467
+ ? cacheDiff.cachedFindings.filter(f => f.category !== 'secrets' && f.category !== 'secret')
468
+ : [];
469
+ const allFindingsForCache = [...secretFindings, ...agentFindings, ...cachedAgentFindings];
470
+ cache.save(allFiles, deduplicateFindings(allFindingsForCache), recon, scoreResult);
471
+ } catch {
472
+ // Silent — caching should never break a scan
473
+ }
474
+ }
475
+
476
+ // ── Build Remediation Plan ────────────────────────────────────────────────
477
+ const remediationPlan = buildRemediationPlan(filteredFindings, depVulns, absolutePath);
478
+
479
+ // Skip all output and file generation for inner agentic re-scans
480
+ if (options._agenticInner) {
481
+ return { score: scoreResult.score, findings: filteredFindings };
482
+ }
483
+
484
+ // ── Output ────────────────────────────────────────────────────────────────
485
+ if (!machineOutput) console.log();
486
+
487
+ if (options.csv) {
488
+ outputCSV(filteredFindings, depVulns, scoreResult, absolutePath);
489
+ } else if (options.md) {
490
+ outputMarkdown(scoreResult, filteredFindings, depVulns, remediationPlan, absolutePath);
491
+ } else if (options.json) {
492
+ outputJSON(scoreResult, filteredFindings, depVulns, recon, agentResults, remediationPlan, suppressions, options.compare ? scoringEngine.loadHistory(absolutePath) : null, filesScanned, absolutePath);
493
+ } else if (options.sarif) {
494
+ outputSARIF(filteredFindings, absolutePath);
495
+ } else {
496
+ printReport(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, filesScanned);
497
+ }
498
+
499
+ // ── HTML Report — always on for human output, or when --html is explicit ──
500
+ const explicitHtml = typeof options.html === 'string' || options.html === true;
501
+ if (explicitHtml || (!options.json && !options.sarif && !options.csv && !options.md)) {
502
+ const htmlPath = typeof options.html === 'string' ? options.html : 'praxis-report.html';
503
+ const reporter = new HTMLReporter();
504
+ reporter.generateToFile(scoreResult, filteredFindings, recon, absolutePath, htmlPath, agentResults, filesScanned);
505
+
506
+ // If --html-dir or --suite specified, also generate granular multi-page report suite
507
+ if (options.htmlDir || options['html-dir'] || options.suite) {
508
+ const suiteDir = typeof (options.htmlDir || options['html-dir'] || options.suite) === 'string'
509
+ ? (options.htmlDir || options['html-dir'] || options.suite)
510
+ : 'report';
511
+ reporter.generateReportSuite(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, suiteDir, agentResults, filesScanned);
512
+ }
513
+
514
+ // Keep stdout pure JSON/SARIF when combined with machine output
515
+ const note = machineOutput ? console.error : console.log;
516
+ note();
517
+ note(chalk.cyan(` Full report: ${chalk.white.bold(htmlPath)}`));
518
+ note(chalk.gray(` Dashboard: `) + chalk.cyan(''));
519
+
520
+ // PDF export
521
+ if (options.pdf) {
522
+ const pdfPath = typeof options.pdf === 'string' ? options.pdf : 'praxis-report.pdf';
523
+ const result = generatePDF(path.resolve(htmlPath), path.resolve(pdfPath));
524
+ if (result) {
525
+ note(chalk.cyan(` PDF report: ${chalk.white.bold(pdfPath)}`));
526
+ } else {
527
+ // Fallback: print-optimized HTML
528
+ const fallbackPath = pdfPath.replace(/\.pdf$/, '.print.html');
529
+ generatePrintHTML(path.resolve(htmlPath), path.resolve(fallbackPath));
530
+ note(chalk.yellow(` Chrome not found — saved print-optimized HTML: ${fallbackPath}`));
531
+ note(chalk.gray(' Open in a browser and Print → Save as PDF'));
532
+ }
533
+ }
534
+ }
535
+
536
+ if (!machineOutput && !options.csv && !options.md) {
537
+ // ── Policy Violations ──────────────────────────────────────────────────
538
+ const violations = policy.evaluate(scoreResult, filteredFindings, {
539
+ agentResults,
540
+ depsRun: options.deps !== false,
541
+ secretsRun: true,
542
+ depVulns,
543
+ });
544
+ if (violations.length > 0) {
545
+ console.log();
546
+ console.log(chalk.red.bold(' Policy Violations:'));
547
+ for (const v of violations.slice(0, 5)) {
548
+ console.log(chalk.red(` ✗ ${v.message}`));
549
+ }
550
+ }
551
+
552
+ // ── Trend ───────────────────────────────────────────────────────────────
553
+ const trend = scoringEngine.getTrend(absolutePath, scoreResult.score);
554
+ if (trend) {
555
+ const arrow = trend.diff > 0 ? chalk.green('↑') : trend.diff < 0 ? chalk.red('↓') : chalk.gray('→');
556
+ const roundedDiff = Math.round(trend.diff * 10) / 10;
557
+ const diffLabel = roundedDiff === 0 ? chalk.gray('no change') : chalk.white(`${roundedDiff > 0 ? '+' : ''}${roundedDiff}`);
558
+ console.log(chalk.gray(` Trend: ${trend.previousScore} → ${trend.currentScore} ${arrow} (`) + diffLabel + chalk.gray(')'));
559
+ }
560
+
561
+ // ── Detailed Comparison ────────────────────────────────────────────────
562
+ if (options.compare) {
563
+ printComparison(scoringEngine, absolutePath, scoreResult);
564
+ }
565
+
566
+ console.log();
567
+ console.log(chalk.cyan('═'.repeat(60)));
568
+ console.log();
569
+ }
570
+
571
+ // ── Agentic Loop (--agentic) ────────────────────────────────────────────
572
+ // Scan → annotate fixes → re-scan cycle until score >= target or maxIter.
573
+ // NOTE: process.exit() is deferred until after the loop so all iterations
574
+ // can run. The inner re-scans use _agenticInner: true to skip process.exit.
575
+ if (options.agentic && !options._agenticInner) {
576
+ const maxIter = typeof options.agentic === 'number' ? options.agentic : 3;
577
+ const targetScore = options.agenticTarget ?? 75;
578
+ let iteration = 1;
579
+ let currentScore = scoreResult.score;
580
+ let currentFindings = filteredFindings;
581
+
582
+ if (!machineOutput) {
583
+ console.log();
584
+ console.log(chalk.cyan.bold(` Agentic mode: scan→fix→verify loop (max ${maxIter} iterations, target score: ${targetScore})`));
585
+ }
586
+
587
+ while (currentScore < targetScore && iteration <= maxIter) {
588
+ if (!machineOutput) {
589
+ console.log(chalk.cyan(`\n ─── Agentic iteration ${iteration}/${maxIter} (current score: ${currentScore}) ───`));
590
+ }
591
+
592
+ const actionable = currentFindings.filter(f => f.fix && f.severity !== 'low');
593
+ if (actionable.length === 0) {
594
+ if (!machineOutput) console.log(chalk.gray(' No auto-fixable findings — stopping agentic loop.'));
595
+ break;
596
+ }
597
+
598
+ // Delegate annotation to autofix module (handles comment style, idempotency, NEVER_EDIT list)
599
+ const fixCount = applyInlineAnnotations(actionable);
600
+ if (!machineOutput) {
601
+ console.log(chalk.yellow(` Annotated ${fixCount} finding(s). Re-scanning...`));
602
+ }
603
+ if (fixCount === 0) break;
604
+
605
+ // Re-scan without recursing into the agentic loop or calling process.exit
606
+ const innerResult = await runAuditInner(targetPath, {
607
+ ...options,
608
+ agentic: false,
609
+ _agenticInner: true,
610
+ json: false,
611
+ sarif: false,
612
+ csv: false,
613
+ md: false,
614
+ html: false,
615
+ pdf: false,
616
+ quiet: true,
617
+ });
618
+
619
+ const prevScore = currentScore;
620
+ currentScore = innerResult?.score ?? currentScore;
621
+ currentFindings = innerResult?.findings ?? currentFindings;
622
+
623
+ if (!machineOutput) {
624
+ const diff = currentScore - prevScore;
625
+ const arrow = diff > 0 ? chalk.green(`↑ +${diff.toFixed(1)}`) : diff < 0 ? chalk.red(`↓ ${diff.toFixed(1)}`) : chalk.gray('→ 0');
626
+ console.log(chalk.cyan(` Re-scan score: ${currentScore} ${arrow}`));
627
+ }
628
+
629
+ iteration++;
630
+ }
631
+
632
+ if (!machineOutput) {
633
+ if (currentScore >= targetScore) {
634
+ console.log(chalk.green.bold(`\n Agentic loop complete — target score ${targetScore} reached (${currentScore}).`));
635
+ } else {
636
+ console.log(chalk.yellow(`\n Agentic loop stopped after ${iteration - 1} iteration(s). Final score: ${currentScore}`));
637
+ }
638
+ }
639
+ }
640
+
641
+ // ── Exit code logic ─────────────────────────────────────────────────────
642
+ // Only gate the exit code when --fail-below is explicitly requested;
643
+ // a plain scan reports findings and exits 0 (CI gating belongs to `scan ci`).
644
+ // Use process.exitCode (natural event-loop drain) instead of process.exit()
645
+ // so in-flight libuv handles (plugin dynamic imports, etc.) close cleanly.
646
+ if (options.failBelow !== undefined) {
647
+ let threshold = 75;
648
+ if (options.failBelow === 'baseline') {
649
+ // Read baseline score from .praxis/hermes-baseline.json
650
+ const baselinePath = path.join(absolutePath, '.praxis', 'hermes-baseline.json');
651
+ try {
652
+ const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf-8'));
653
+ threshold = baseline.score || 0;
654
+ if (!machineOutput) {
655
+ console.log(chalk.gray(` Baseline threshold: ${threshold}/100 (from ${baselinePath})`));
656
+ }
657
+ } catch {
658
+ if (!machineOutput) {
659
+ console.log(chalk.yellow(` Warning: could not read baseline — using score 0 as threshold`));
660
+ }
661
+ threshold = 0;
662
+ }
663
+ } else {
664
+ const parsed = parseInt(options.failBelow, 10);
665
+ threshold = Number.isNaN(parsed) ? 75 : parsed;
666
+ }
667
+ process.exitCode = scoreResult.score >= threshold ? 0 : 1;
668
+ }
669
+ } finally {
670
+ if (gitClone) {
671
+ if (!options.keepClone) {
672
+ gitClone.cleanup();
673
+ } else if (!machineOutput) {
674
+ console.log(chalk.gray(`\n Cloned repository retained at: ${gitClone.tempDir}`));
675
+ }
676
+ }
677
+ }
678
+ }
679
+
680
+ /**
681
+ * Run a lightweight inner audit that returns { score, findings } without
682
+ * calling process.exit(). Used exclusively by the --agentic loop.
683
+ */
684
+ async function runAuditInner(targetPath, options) {
685
+ try {
686
+ return await auditCommand(targetPath, options);
687
+ } catch {
688
+ return null;
689
+ }
690
+ }
691
+
692
+ // =============================================================================
693
+ // REMEDIATION PLAN BUILDER
694
+ // =============================================================================
695
+
696
+ function buildRemediationPlan(findings, depVulns, rootPath) {
697
+ const plan = [];
698
+ let priority = 1;
699
+
700
+ // Exclude low-confidence findings (test files, docs, comments) from remediation plan
701
+ const actionable = findings.filter(f => f.confidence !== 'low');
702
+
703
+ // Priority order: secrets first, then by severity
704
+ const secretFindings = actionable.filter(f => f.category === 'secrets' || f.category === 'secret');
705
+ const otherFindings = actionable.filter(f => f.category !== 'secrets' && f.category !== 'secret');
706
+
707
+ // Group and sort
708
+ for (const sev of SEV_ORDER) {
709
+ // Secrets at this severity — group .env findings by file
710
+ const sevSecrets = secretFindings.filter(s => s.severity === sev);
711
+ const envGroups = new Map();
712
+ const nonEnvSecrets = [];
713
+
714
+ for (const f of sevSecrets) {
715
+ const relFile = displayPath(f.file, rootPath);
716
+ if (f.file.match(/\.env(\..*)?$/)) {
717
+ if (!envGroups.has(relFile)) envGroups.set(relFile, []);
718
+ envGroups.get(relFile).push(f);
719
+ } else {
720
+ nonEnvSecrets.push(f);
721
+ }
722
+ }
723
+
724
+ // One plan item per .env file
725
+ for (const [relFile, envFindings] of envGroups) {
726
+ const names = envFindings.map(f => f.title || f.rule).join(', ');
727
+ plan.push({
728
+ priority: priority++,
729
+ severity: sev,
730
+ category: 'secrets',
731
+ categoryLabel: 'SECRETS',
732
+ title: `${envFindings.length} secret${envFindings.length > 1 ? 's' : ''} in ${relFile} (${names})`,
733
+ file: relFile,
734
+ action: envFindings[0].fix || 'Ensure .env is in .gitignore and use a secrets manager for production',
735
+ effort: 'low',
736
+ });
737
+ }
738
+
739
+ // Individual items for non-.env secrets
740
+ for (const f of nonEnvSecrets) {
741
+ plan.push({
742
+ priority: priority++,
743
+ severity: sev,
744
+ category: 'secrets',
745
+ categoryLabel: 'SECRETS',
746
+ title: f.title || f.rule,
747
+ file: `${displayPath(f.file, rootPath)}:${f.line}`,
748
+ action: f.aiFix || f.fix || f.description,
749
+ effort: 'low',
750
+ });
751
+ }
752
+
753
+ // Other findings at this severity
754
+ for (const f of otherFindings.filter(s => s.severity === sev)) {
755
+ plan.push({
756
+ priority: priority++,
757
+ severity: sev,
758
+ category: f.category,
759
+ categoryLabel: (CATEGORY_LABELS[f.category] || f.category).toUpperCase(),
760
+ title: f.title || f.rule,
761
+ file: `${displayPath(f.file, rootPath)}:${f.line}`,
762
+ action: f.aiFix || f.fix || f.description,
763
+ effort: EFFORT_MAP[f.category] || 'medium',
764
+ });
765
+ }
766
+
767
+ // Dep vulns at this severity
768
+ for (const d of depVulns.filter(v => v.severity === sev || (sev === 'medium' && v.severity === 'moderate'))) {
769
+ plan.push({
770
+ priority: priority++,
771
+ severity: sev,
772
+ category: 'deps',
773
+ categoryLabel: 'DEPENDENCIES',
774
+ title: `Vulnerable: ${d.package || d.id}`,
775
+ file: 'package.json',
776
+ action: d.description ? `${d.description.slice(0, 80)}` : 'Update to patched version',
777
+ effort: 'medium',
778
+ });
779
+ }
780
+ }
781
+
782
+ return plan;
783
+ }
784
+
785
+ // =============================================================================
786
+ // CONSOLE OUTPUT
787
+ // =============================================================================
788
+
789
+ function printReport(scoreResult, findings, depVulns, recon, plan, rootPath, filesScanned) {
790
+ const GRADE_COLOR = { A: chalk.green.bold, B: chalk.cyan.bold, C: chalk.yellow.bold, D: chalk.red, F: chalk.red.bold };
791
+ const SEV_ICON = { critical: '🔴', high: '🟠', medium: '🟡', low: '🔵' };
792
+ const SEV_LABEL = { critical: 'CRITICAL — fix immediately', high: 'HIGH — fix before deploy', medium: 'MEDIUM — fix soon', low: 'LOW — review when possible' };
793
+
794
+ // ── Score ─────────────────────────────────────────────────────────────────
795
+ const gradeColor = GRADE_COLOR[scoreResult.grade.letter] || chalk.white;
796
+ const scoreColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
797
+
798
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
799
+ console.log(
800
+ chalk.white.bold(' Security Score: ') +
801
+ scoreColor(`${scoreResult.score}/100 `) +
802
+ gradeColor(scoreResult.grade.letter) +
803
+ chalk.gray(` — ${scoreResult.grade.label}`)
804
+ );
805
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
806
+ console.log();
807
+
808
+ // ── Category Breakdown ────────────────────────────────────────────────────
809
+ console.log(chalk.white.bold(' Category Breakdown'));
810
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
811
+
812
+ for (const [key, cat] of Object.entries(scoreResult.categories)) {
813
+ const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
814
+ const icon = count === 0 ? chalk.green('✔') : chalk.red('✘');
815
+ const status = count === 0 ? chalk.green('clean') : chalk.red(`${count} issue(s)`);
816
+ const deduction = cat.deduction > 0 ? chalk.red(`-${Math.round(cat.deduction * 10) / 10} pts`) : chalk.gray('+0');
817
+ console.log(` ${icon} ${chalk.white(cat.label.padEnd(22))} ${status.padEnd(25)} ${deduction}`);
818
+ }
819
+
820
+ // Deps row — only print if not already included in scoreResult.categories
821
+ const hasDepsCategory = Object.values(scoreResult.categories).some(c => c.label?.toLowerCase().includes('depend'));
822
+ if (!hasDepsCategory) {
823
+ const depIcon = depVulns.length === 0 ? chalk.green('✔') : chalk.red('✘');
824
+ const depStatus = depVulns.length === 0 ? chalk.green('clean') : chalk.red(`${depVulns.length} CVE(s)`);
825
+ console.log(` ${depIcon} ${chalk.white('Dependencies'.padEnd(22))} ${depStatus}`);
826
+ }
827
+
828
+ console.log(chalk.gray(`\n Files scanned: ${filesScanned} | Findings: ${findings.length} | CVEs: ${depVulns.length}`));
829
+
830
+ // ── Remediation Plan ──────────────────────────────────────────────────────
831
+ if (plan.length > 0) {
832
+ console.log();
833
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
834
+ console.log(chalk.cyan.bold(' Remediation Plan'));
835
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
836
+
837
+ let currentSev = null;
838
+ let shown = 0;
839
+ const maxItems = 30;
840
+
841
+ for (const item of plan) {
842
+ if (shown >= maxItems) {
843
+ console.log(chalk.gray(`\n ... and ${plan.length - maxItems} more items in the full report`));
844
+ break;
845
+ }
846
+
847
+ if (item.severity !== currentSev) {
848
+ currentSev = item.severity;
849
+ console.log();
850
+ console.log(chalk.white.bold(` ${SEV_ICON[currentSev] || '⚪'} ${SEV_LABEL[currentSev] || currentSev.toUpperCase()}`));
851
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
852
+ }
853
+
854
+ console.log(
855
+ chalk.white(` ${String(item.priority).padStart(2)}.`) +
856
+ chalk.gray(` [${item.categoryLabel}] `) +
857
+ chalk.white(item.title)
858
+ );
859
+ console.log(
860
+ chalk.gray(` ${item.file}`) +
861
+ chalk.gray(' → ') +
862
+ chalk.green((item.action || '').slice(0, 70))
863
+ );
864
+ shown++;
865
+ }
866
+ } else {
867
+ console.log();
868
+ console.log(chalk.green.bold(' All clear — safe to ship!'));
869
+ }
870
+
871
+ // ── Attack Surface ────────────────────────────────────────────────────────
872
+ if (recon) {
873
+ console.log();
874
+ console.log(chalk.gray(' Attack Surface:'));
875
+ if (recon.frameworks?.length) console.log(chalk.gray(` Frameworks: ${recon.frameworks.join(', ')}`));
876
+ if (recon.databases?.length) console.log(chalk.gray(` Databases: ${recon.databases.join(', ')}`));
877
+ if (recon.authPatterns?.length) console.log(chalk.gray(` Auth: ${recon.authPatterns.join(', ')}`));
878
+ if (recon.apiRoutes?.length) console.log(chalk.gray(` API Routes: ${recon.apiRoutes.length} discovered`));
879
+ }
880
+ }
881
+
882
+ // =============================================================================
883
+ // JSON OUTPUT
884
+ // =============================================================================
885
+
886
+ function outputJSON(scoreResult, findings, depVulns, recon, agentResults, remediationPlan, suppressions, history, filesScanned = null, absolutePath = process.cwd()) {
887
+ const output = {
888
+ score: scoreResult.score,
889
+ grade: scoreResult.grade.letter,
890
+ gradeLabel: scoreResult.grade.label,
891
+ totalFindings: findings.length,
892
+ totalDepVulns: depVulns.length,
893
+ categories: Object.fromEntries(
894
+ Object.entries(scoreResult.categories).map(([k, v]) => [k, {
895
+ label: v.label,
896
+ findingCount: Object.values(v.counts).reduce((a, b) => a + b, 0),
897
+ deduction: v.deduction,
898
+ counts: v.counts,
899
+ }])
900
+ ),
901
+ findings: findings.map(f => {
902
+ return {
903
+ // Secret findings are built here rather than by an agent, so they never
904
+ // pass through the orchestrator's normalisation. Do it at the source —
905
+ // see cli/core/paths.js. This used to be the fourth copy of the same
906
+ // strippers, which is how an absolute path reached the JSON report with
907
+ // its drive letter removed and the username left behind.
908
+ file: displayPath(f.file, absolutePath),
909
+ line: f.line, severity: f.severity, category: f.category,
910
+ rule: f.rule, title: f.title, description: f.description, fix: f.fix,
911
+ cwe: f.cwe, owasp: f.owasp,
912
+ ...(f.eaa ? { eaa: f.eaa } : {}),
913
+ ...(f.confidence ? { confidence: f.confidence } : {}),
914
+ ...(f.standards ? { standards: f.standards } : {}),
915
+ ...(f.deepAnalysis ? { deepAnalysis: f.deepAnalysis } : {}),
916
+ ...(f.aiClassification ? {
917
+ aiClassification: f.aiClassification,
918
+ ...(f.aiReason ? { aiReason: f.aiReason } : {}),
919
+ ...(f.aiFix ? { aiFix: f.aiFix } : {}),
920
+ } : {}),
921
+ };
922
+ }),
923
+ depVulns: depVulns.map(d => ({
924
+ severity: d.severity, package: d.package || d.id, description: d.description,
925
+ })),
926
+ remediationPlan,
927
+ recon,
928
+ agents: agentResults,
929
+ // Provenance: which tool, runtime and vendored data produced these numbers.
930
+ fingerprint: buildScanFingerprint({ filesScanned }),
931
+ };
932
+ if (scoreResult.compliance) output.compliance = scoreResult.compliance;
933
+ if (scoreResult.standardsSummary) output.standardsSummary = scoreResult.standardsSummary;
934
+ if (scoreResult.agenticSummary) output.agenticSummary = scoreResult.agenticSummary;
935
+ if (suppressions) output.suppressions = suppressions;
936
+ if (history && history.length >= 2) {
937
+ const prev = history[history.length - 2];
938
+ output.comparison = {
939
+ previousScore: prev.score,
940
+ previousGrade: prev.grade,
941
+ previousDate: prev.timestamp,
942
+ diff: scoreResult.score - prev.score,
943
+ categoryComparison: Object.fromEntries(
944
+ Object.entries(scoreResult.categories).map(([k, v]) => {
945
+ const prevCat = prev.categoryScores?.[k];
946
+ return [k, {
947
+ label: v.label,
948
+ current: -v.deduction,
949
+ previous: prevCat ? -prevCat.deduction : 0,
950
+ delta: prevCat ? prevCat.deduction - v.deduction : 0,
951
+ }];
952
+ })
953
+ ),
954
+ };
955
+ }
956
+ console.log(JSON.stringify(output, null, 2));
957
+ }
958
+
959
+ // =============================================================================
960
+ // SARIF OUTPUT
961
+ // =============================================================================
962
+
963
+ /**
964
+ * SARIF for GitHub Code Scanning.
965
+ *
966
+ * Delegates to the shared serializer in `cli/core/output/sarif.js`. This was
967
+ * a private copy, hardcoding a driver version of `4.0.0` while the package was at a
968
+ * different number entirely, and it carried no `security-severity` — so the default
969
+ * `praxis scan` lost severity fidelity in Code Scanning.
970
+ */
971
+ function outputSARIF(findings, rootPath) {
972
+ console.log(renderFindingsSARIF(findings, { rootPath }));
973
+ }
974
+
975
+ // =============================================================================
976
+ // FILE SCANNING (inline from scan.js to avoid circular deps)
977
+ // =============================================================================
978
+
979
+ // Walk up from `start` looking for `name`. Returns the absolute path or null.
980
+ // Bounded to 8 ancestors to avoid runaway loops on weird filesystems.
981
+ function findUpwards(start, name) {
982
+ let dir = path.resolve(start);
983
+ for (let i = 0; i < 8; i++) {
984
+ const candidate = path.join(dir, name);
985
+ if (fs.existsSync(candidate)) return candidate;
986
+ const parent = path.dirname(dir);
987
+ if (parent === dir) return null;
988
+ dir = parent;
989
+ }
990
+ return null;
991
+ }
992
+
993
+ async function findFiles(rootPath) {
994
+ const globIgnore = Array.from(SKIP_DIRS).map(dir => `**/${dir}/**`);
995
+
996
+ // Respect .gitignore patterns
997
+ const gitignoreGlobs = loadGitignorePatterns(rootPath);
998
+ globIgnore.push(...gitignoreGlobs);
999
+
1000
+ // Load .praxisignore — walk up to the project root so subdirectory scans
1001
+ // still honor the repo-level ignore file.
1002
+ const ignorePath = findUpwards(rootPath, '.praxisignore');
1003
+ if (ignorePath) {
1004
+ try {
1005
+ const patterns = fs.readFileSync(ignorePath, 'utf-8')
1006
+ .split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));
1007
+ for (const p of patterns) {
1008
+ if (p.endsWith('/')) { globIgnore.push(`**/${p}**`); }
1009
+ else { globIgnore.push(`**/${p}`); globIgnore.push(p); }
1010
+ }
1011
+ } catch { /* skip */ }
1012
+ }
1013
+
1014
+ const files = await fg('**/*', {
1015
+ cwd: rootPath, absolute: true, onlyFiles: true, ignore: globIgnore, dot: true
1016
+ });
1017
+
1018
+ return files.filter(file => {
1019
+ const ext = path.extname(file).toLowerCase();
1020
+ if (SKIP_EXTENSIONS.has(ext)) return false;
1021
+ if (SKIP_FILENAMES.has(path.basename(file))) return false;
1022
+ if (path.basename(file).endsWith('.min.js') || path.basename(file).endsWith('.min.css')) return false;
1023
+ try { if (fs.statSync(file).size > MAX_FILE_SIZE) return false; } catch { return false; }
1024
+ return true;
1025
+ });
1026
+ }
1027
+
1028
+ function scanFileForSecrets(filePath) {
1029
+ const findings = [];
1030
+ try {
1031
+ const content = fs.readFileSync(filePath, 'utf-8');
1032
+ const lines = content.split('\n');
1033
+ for (let lineNum = 0; lineNum < lines.length; lineNum++) {
1034
+ const line = lines[lineNum];
1035
+ if (/praxis-ignore/i.test(line)) continue;
1036
+ for (const pattern of SECRET_PATTERNS) {
1037
+ pattern.pattern.lastIndex = 0;
1038
+ let match;
1039
+ while ((match = pattern.pattern.exec(line)) !== null) {
1040
+ if (pattern.requiresEntropyCheck && !isHighEntropyMatch(match[0])) continue;
1041
+ findings.push({
1042
+ line: lineNum + 1, column: match.index + 1, matched: match[0],
1043
+ patternName: pattern.name, severity: pattern.severity,
1044
+ confidence: getConfidence(pattern, match[0]),
1045
+ description: pattern.description, category: pattern.category || 'secret'
1046
+ });
1047
+ }
1048
+ }
1049
+ }
1050
+ } catch { /* skip */ }
1051
+
1052
+ const seen = new Set();
1053
+ return findings.filter(f => {
1054
+ const key = `${f.line}:${f.matched}`;
1055
+ if (seen.has(key)) return false;
1056
+ seen.add(key);
1057
+ return true;
1058
+ });
1059
+ }
1060
+
1061
+ function deduplicateFindings(findings) {
1062
+ const seen = new Set();
1063
+ return findings.filter(f => {
1064
+ const key = `${f.file}:${f.line}:${f.rule}`;
1065
+ if (seen.has(key)) return false;
1066
+ seen.add(key);
1067
+ return true;
1068
+ });
1069
+ }
1070
+
1071
+ // =============================================================================
1072
+ // SUPPRESSION COUNTING
1073
+ // =============================================================================
1074
+
1075
+ function countSuppressions(files) {
1076
+ const suppressions = {};
1077
+ let total = 0;
1078
+ for (const file of files) {
1079
+ try {
1080
+ const content = fs.readFileSync(file, 'utf-8');
1081
+ const lines = content.split('\n');
1082
+ for (const line of lines) {
1083
+ if (/praxis-ignore/i.test(line)) {
1084
+ total++;
1085
+ // Try to extract rule name from comment: praxis-ignore RULE_NAME
1086
+ const match = line.match(/praxis-ignore\s+(\w+)/i);
1087
+ const rule = match ? match[1] : '_unspecified';
1088
+ suppressions[rule] = (suppressions[rule] || 0) + 1;
1089
+ }
1090
+ }
1091
+ } catch { /* skip */ }
1092
+ }
1093
+ return total > 0 ? { total, rules: suppressions } : null;
1094
+ }
1095
+
1096
+ // =============================================================================
1097
+ // CSV OUTPUT
1098
+ // =============================================================================
1099
+
1100
+ function outputCSV(findings, depVulns, scoreResult, rootPath) {
1101
+ const escape = (s) => {
1102
+ if (!s) return '';
1103
+ const str = String(s).replace(/"/g, '""');
1104
+ return str.includes(',') || str.includes('"') || str.includes('\n') ? `"${str}"` : str;
1105
+ };
1106
+
1107
+ console.log('severity,category,rule,file,line,title,description,fix');
1108
+ for (const f of findings) {
1109
+ const relFile = displayPath(f.file, rootPath);
1110
+ console.log([
1111
+ escape(f.severity), escape(f.category), escape(f.rule),
1112
+ escape(relFile), f.line || '', escape(f.title),
1113
+ escape(f.description), escape(f.fix),
1114
+ ].join(','));
1115
+ }
1116
+ for (const d of depVulns) {
1117
+ console.log([
1118
+ escape(d.severity), 'deps', escape(d.id || d.package),
1119
+ 'package.json', '', escape(`Vulnerable: ${d.package || d.id}`),
1120
+ escape(d.description), escape('Update to patched version'),
1121
+ ].join(','));
1122
+ }
1123
+ }
1124
+
1125
+ // =============================================================================
1126
+ // MARKDOWN OUTPUT
1127
+ // =============================================================================
1128
+
1129
+ function outputMarkdown(scoreResult, findings, depVulns, remediationPlan, rootPath) {
1130
+ const lines = [];
1131
+ lines.push('# Praxis Security Report');
1132
+ lines.push('');
1133
+ lines.push(`**Score: ${scoreResult.score}/100 (${scoreResult.grade.letter})** — ${scoreResult.grade.label}`);
1134
+ lines.push('');
1135
+ lines.push(`> Generated: ${new Date().toISOString()}`);
1136
+ lines.push('');
1137
+
1138
+ // Category breakdown
1139
+ lines.push('## Category Breakdown');
1140
+ lines.push('');
1141
+ lines.push('| Category | Issues | Deduction |');
1142
+ lines.push('|----------|--------|-----------|');
1143
+ for (const [, cat] of Object.entries(scoreResult.categories)) {
1144
+ const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
1145
+ lines.push(`| ${cat.label} | ${count} | -${cat.deduction} |`);
1146
+ }
1147
+ lines.push('');
1148
+
1149
+ // Findings by severity
1150
+ for (const sev of SEV_ORDER) {
1151
+ const sevFindings = findings.filter(f => f.severity === sev);
1152
+ if (sevFindings.length === 0) continue;
1153
+
1154
+ lines.push(`## ${sev.charAt(0).toUpperCase() + sev.slice(1)} (${sevFindings.length})`);
1155
+ lines.push('');
1156
+ lines.push('| File | Rule | Description | Fix |');
1157
+ lines.push('|------|------|-------------|-----|');
1158
+ for (const f of sevFindings) {
1159
+ const relFile = displayPath(f.file, rootPath);
1160
+ lines.push(`| ${relFile}:${f.line} | ${f.rule} | ${(f.description || '').slice(0, 80)} | ${(f.fix || '').slice(0, 60)} |`);
1161
+ }
1162
+ lines.push('');
1163
+ }
1164
+
1165
+ // Dep vulns
1166
+ if (depVulns.length > 0) {
1167
+ lines.push('## Dependency Vulnerabilities');
1168
+ lines.push('');
1169
+ lines.push('| Severity | Package | Description |');
1170
+ lines.push('|----------|---------|-------------|');
1171
+ for (const d of depVulns) {
1172
+ lines.push(`| ${d.severity} | ${d.package || d.id} | ${(d.description || '').slice(0, 80)} |`);
1173
+ }
1174
+ lines.push('');
1175
+ }
1176
+
1177
+ console.log(lines.join('\n'));
1178
+ }
1179
+
1180
+ // =============================================================================
1181
+ // COMPARISON OUTPUT
1182
+ // =============================================================================
1183
+
1184
+ function printComparison(scoringEngine, rootPath, scoreResult) {
1185
+ const history = scoringEngine.loadHistory(rootPath);
1186
+ if (history.length < 2) {
1187
+ console.log(chalk.gray('\n No previous scan to compare against.'));
1188
+ return;
1189
+ }
1190
+
1191
+ const prev = history[history.length - 2];
1192
+ console.log();
1193
+ console.log(chalk.cyan.bold(' Detailed Comparison'));
1194
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
1195
+ console.log(chalk.gray(` Previous scan: ${new Date(prev.timestamp).toLocaleString()}`));
1196
+ console.log();
1197
+ console.log(chalk.white(' Category'.padEnd(26)) + chalk.white('Previous'.padEnd(12)) + chalk.white('Current'.padEnd(12)) + chalk.white('Delta'));
1198
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
1199
+
1200
+ for (const [key, cat] of Object.entries(scoreResult.categories)) {
1201
+ const prevCat = prev.categoryScores?.[key];
1202
+ const prevDed = prevCat ? prevCat.deduction : 0;
1203
+ const curDed = cat.deduction;
1204
+ const delta = prevDed - curDed;
1205
+
1206
+ let deltaStr;
1207
+ if (delta > 0) deltaStr = chalk.green(`+${delta} improved`);
1208
+ else if (delta < 0) deltaStr = chalk.red(`${delta} regressed`);
1209
+ else deltaStr = chalk.gray('→ unchanged');
1210
+
1211
+ console.log(
1212
+ ` ${chalk.white(cat.label.padEnd(24))}` +
1213
+ `${chalk.gray(String(-prevDed).padEnd(12))}` +
1214
+ `${chalk.gray(String(-curDed).padEnd(12))}` +
1215
+ deltaStr
1216
+ );
1217
+ }
1218
+
1219
+ const overallDiff = scoreResult.score - prev.score;
1220
+ let overallDelta;
1221
+ if (overallDiff > 0) overallDelta = chalk.green(`+${overallDiff} improved`);
1222
+ else if (overallDiff < 0) overallDelta = chalk.red(`${overallDiff} regressed`);
1223
+ else overallDelta = chalk.gray('→ unchanged');
1224
+
1225
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
1226
+ console.log(
1227
+ ` ${chalk.white.bold('Overall'.padEnd(24))}` +
1228
+ `${chalk.gray(`${prev.score}/100 ${prev.grade}`.padEnd(12))}` +
1229
+ `${chalk.gray(`${scoreResult.score}/100 ${scoreResult.grade.letter}`.padEnd(12))}` +
1230
+ overallDelta
1231
+ );
1232
+ }