praxis-sec 1.0.0

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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +170 -0
  3. package/ai-defense/cost-protection.md +292 -0
  4. package/ai-defense/llm-security-checklist.md +324 -0
  5. package/ai-defense/prompt-injection-patterns.js +283 -0
  6. package/ai-defense/system-prompt-armor.md +327 -0
  7. package/checklists/launch-day.md +168 -0
  8. package/cli/agents/abom-generator.js +225 -0
  9. package/cli/agents/agent-attestation-agent.js +318 -0
  10. package/cli/agents/agent-config-scanner.js +787 -0
  11. package/cli/agents/agent-telemetry-agent.js +415 -0
  12. package/cli/agents/agentic-security-agent.js +296 -0
  13. package/cli/agents/agentic-supply-chain-agent.js +463 -0
  14. package/cli/agents/ai-infra-inventory-agent.js +449 -0
  15. package/cli/agents/api-fuzzer.js +345 -0
  16. package/cli/agents/auth-bypass-agent.js +348 -0
  17. package/cli/agents/base-agent.js +280 -0
  18. package/cli/agents/cicd-scanner.js +300 -0
  19. package/cli/agents/config-auditor.js +757 -0
  20. package/cli/agents/deep-analyzer.js +776 -0
  21. package/cli/agents/endpoint-agent-abuse-agent.js +404 -0
  22. package/cli/agents/exception-handler-agent.js +187 -0
  23. package/cli/agents/git-history-scanner.js +169 -0
  24. package/cli/agents/governance-audits.js +138 -0
  25. package/cli/agents/hermes-security-agent.js +536 -0
  26. package/cli/agents/html-reporter.js +1125 -0
  27. package/cli/agents/index.js +147 -0
  28. package/cli/agents/injection-tester.js +502 -0
  29. package/cli/agents/legal-risk-agent.js +328 -0
  30. package/cli/agents/llm-redteam.js +199 -0
  31. package/cli/agents/managed-agent-scanner.js +333 -0
  32. package/cli/agents/mcp-security-agent.js +588 -0
  33. package/cli/agents/memory-poisoning-agent.js +305 -0
  34. package/cli/agents/mobile-scanner.js +231 -0
  35. package/cli/agents/model-file-scanner.js +259 -0
  36. package/cli/agents/orchestrator.js +355 -0
  37. package/cli/agents/pii-compliance-agent.js +301 -0
  38. package/cli/agents/policy-engine.js +229 -0
  39. package/cli/agents/prompt-injection-prober.js +224 -0
  40. package/cli/agents/rag-security-agent.js +204 -0
  41. package/cli/agents/recon-agent.js +207 -0
  42. package/cli/agents/sbom-generator.js +265 -0
  43. package/cli/agents/scoring-engine.js +273 -0
  44. package/cli/agents/ssrf-prober.js +130 -0
  45. package/cli/agents/stateful-watcher.js +238 -0
  46. package/cli/agents/supabase-rls-agent.js +154 -0
  47. package/cli/agents/supply-chain-agent.js +857 -0
  48. package/cli/agents/swarm-orchestrator.js +200 -0
  49. package/cli/agents/verifier-agent.js +303 -0
  50. package/cli/agents/vibe-coding-agent.js +250 -0
  51. package/cli/bin/praxis.js +866 -0
  52. package/cli/commands/abom.js +73 -0
  53. package/cli/commands/agent-fix.js +1245 -0
  54. package/cli/commands/audit.js +1180 -0
  55. package/cli/commands/autofix.js +383 -0
  56. package/cli/commands/baseline.js +193 -0
  57. package/cli/commands/benchmark.js +327 -0
  58. package/cli/commands/checklist.js +223 -0
  59. package/cli/commands/ci.js +403 -0
  60. package/cli/commands/deps.js +516 -0
  61. package/cli/commands/diff.js +200 -0
  62. package/cli/commands/doctor.js +195 -0
  63. package/cli/commands/env-audit.js +349 -0
  64. package/cli/commands/fix.js +218 -0
  65. package/cli/commands/guard.js +396 -0
  66. package/cli/commands/hooks.js +278 -0
  67. package/cli/commands/init.js +514 -0
  68. package/cli/commands/legal.js +158 -0
  69. package/cli/commands/live-advisories.js +241 -0
  70. package/cli/commands/mcp.js +660 -0
  71. package/cli/commands/openclaw.js +386 -0
  72. package/cli/commands/red-team.js +350 -0
  73. package/cli/commands/redteam.js +78 -0
  74. package/cli/commands/remediate.js +797 -0
  75. package/cli/commands/rotate.js +768 -0
  76. package/cli/commands/rules.js +196 -0
  77. package/cli/commands/scan-mcp.js +534 -0
  78. package/cli/commands/scan-skill.js +588 -0
  79. package/cli/commands/scan-standard.js +251 -0
  80. package/cli/commands/scan.js +524 -0
  81. package/cli/commands/score.js +449 -0
  82. package/cli/commands/shell.js +514 -0
  83. package/cli/commands/team-report.js +398 -0
  84. package/cli/commands/undo.js +161 -0
  85. package/cli/commands/update-intel.js +126 -0
  86. package/cli/commands/vibe-check.js +276 -0
  87. package/cli/commands/watch.js +757 -0
  88. package/cli/commands/web.js +63 -0
  89. package/cli/core/ast/guardrail-detector.js +141 -0
  90. package/cli/core/ast/index.js +22 -0
  91. package/cli/core/ast/parser.js +676 -0
  92. package/cli/core/ast/scope-tree.js +287 -0
  93. package/cli/core/ast/taint-tracker.js +158 -0
  94. package/cli/core/branding.js +37 -0
  95. package/cli/core/env.js +38 -0
  96. package/cli/core/errors.js +61 -0
  97. package/cli/core/fs.js +62 -0
  98. package/cli/core/output/compliance.js +90 -0
  99. package/cli/core/output/html-theme.js +158 -0
  100. package/cli/core/output/index.js +57 -0
  101. package/cli/core/output/json.js +48 -0
  102. package/cli/core/output/sarif.js +240 -0
  103. package/cli/core/version.js +67 -0
  104. package/cli/core/web/jobs.js +183 -0
  105. package/cli/core/web/projects.js +146 -0
  106. package/cli/core/web/server.js +439 -0
  107. package/cli/data/atlas-knowledge.json +5640 -0
  108. package/cli/data/eaa-catalog.json +39 -0
  109. package/cli/data/known-mcps.json +26 -0
  110. package/cli/data/probes/prompt-injection-corpus.json +271 -0
  111. package/cli/data/threat-intel.json +85 -0
  112. package/cli/data/threatpacks/latest.json +41 -0
  113. package/cli/hooks/patterns.js +313 -0
  114. package/cli/hooks/post-tool-use.js +140 -0
  115. package/cli/hooks/pre-tool-use.js +186 -0
  116. package/cli/index.js +90 -0
  117. package/cli/providers/llm-provider.js +766 -0
  118. package/cli/utils/autofix-rules.js +74 -0
  119. package/cli/utils/cache-manager.js +310 -0
  120. package/cli/utils/compliance-map.js +191 -0
  121. package/cli/utils/entropy.js +132 -0
  122. package/cli/utils/fix-ledger.js +127 -0
  123. package/cli/utils/hermes-tool-registry.js +252 -0
  124. package/cli/utils/intel/cache.js +61 -0
  125. package/cli/utils/intel/http.js +88 -0
  126. package/cli/utils/intel/index.js +235 -0
  127. package/cli/utils/intel/merge.js +229 -0
  128. package/cli/utils/intel/sources/epss.js +54 -0
  129. package/cli/utils/intel/sources/ghsa.js +81 -0
  130. package/cli/utils/intel/sources/gitguardian.js +40 -0
  131. package/cli/utils/intel/sources/gitleaks.js +101 -0
  132. package/cli/utils/intel/sources/kev.js +38 -0
  133. package/cli/utils/intel/sources/nvd.js +84 -0
  134. package/cli/utils/intel/sources/osv.js +132 -0
  135. package/cli/utils/intel/sources/phylum.js +44 -0
  136. package/cli/utils/intel/sources/snyk.js +46 -0
  137. package/cli/utils/intel/sources/socket.js +69 -0
  138. package/cli/utils/intel/sources/sonatype.js +84 -0
  139. package/cli/utils/intel/sources/threatpack.js +69 -0
  140. package/cli/utils/mcp-trust.js +60 -0
  141. package/cli/utils/output.js +251 -0
  142. package/cli/utils/patterns.js +1130 -0
  143. package/cli/utils/pdf-generator.js +94 -0
  144. package/cli/utils/plugin-loader.js +364 -0
  145. package/cli/utils/rule-import.js +228 -0
  146. package/cli/utils/rule-registry.js +426 -0
  147. package/cli/utils/scan-fingerprint.js +109 -0
  148. package/cli/utils/scan-playbook.js +312 -0
  149. package/cli/utils/score-history.js +119 -0
  150. package/cli/utils/secrets-verifier.js +247 -0
  151. package/cli/utils/security-memory.js +296 -0
  152. package/cli/utils/standards/atlas-knowledge.js +87 -0
  153. package/cli/utils/standards/index.js +127 -0
  154. package/cli/utils/standards/sources/avid.js +45 -0
  155. package/cli/utils/standards/sources/eu-ai-act.js +89 -0
  156. package/cli/utils/standards/sources/google-saif.js +39 -0
  157. package/cli/utils/standards/sources/iso-42001.js +94 -0
  158. package/cli/utils/standards/sources/mitre-atlas.js +54 -0
  159. package/cli/utils/standards/sources/nist-ai-600-1.js +45 -0
  160. package/cli/utils/standards/sources/owasp-llm.js +45 -0
  161. package/cli/utils/standards/sources/owasp-ml.js +45 -0
  162. package/cli/utils/threat-intel.js +265 -0
  163. package/configs/firebase/firestore-rules.txt +215 -0
  164. package/configs/firebase/security-checklist.md +236 -0
  165. package/configs/firebase/storage-rules.txt +206 -0
  166. package/configs/gitignore-template +258 -0
  167. package/configs/nextjs-security-headers.js +220 -0
  168. package/configs/praxisignore-template +50 -0
  169. package/configs/supabase/secure-client.ts +225 -0
  170. package/configs/supabase/security-checklist.md +278 -0
  171. package/docs/THIRD_PARTY_NOTICES.md +26 -0
  172. package/docs/THREAT_INTEL.md +292 -0
  173. package/docs/USAGE.md +1205 -0
  174. package/docs/design/WEB-UI.md +82 -0
  175. package/package.json +71 -0
  176. package/scripts/check-determinism.mjs +119 -0
  177. package/snippets/README.md +122 -0
  178. package/snippets/api-security/api-security-checklist.md +412 -0
  179. package/snippets/api-security/cors-config.ts +322 -0
  180. package/snippets/api-security/input-validation.ts +430 -0
  181. package/snippets/auth/jwt-checklist.md +322 -0
  182. package/snippets/rate-limiting/nextjs-middleware.ts +211 -0
  183. package/snippets/rate-limiting/upstash-ratelimit.ts +229 -0
@@ -0,0 +1,514 @@
1
+ /**
2
+ * Shell Command — Interactive REPL
3
+ * =================================
4
+ *
5
+ * `praxis shell` drops you into a persistent interactive session.
6
+ *
7
+ * Slash commands:
8
+ * /scan Re-scan the project and show a summary
9
+ * /agent Run the interactive agent fix loop
10
+ * /undo Revert the last fix
11
+ * /findings List findings from the last scan
12
+ * /show <n> Show the full detail of finding number <n>
13
+ * /clear Clear the screen
14
+ * /help List commands
15
+ * /quit Exit the shell
16
+ *
17
+ * Anything else is treated as a free-form prompt to the configured LLM,
18
+ * with the last scan results provided as context.
19
+ */
20
+
21
+ import { createInterface } from 'readline';
22
+ import { execFileSync, spawnSync } from 'child_process';
23
+ import path from 'path';
24
+ import chalk from 'chalk';
25
+ import ora from 'ora';
26
+ import { autoDetectProvider } from '../providers/llm-provider.js';
27
+ import { toolVersion } from '../core/version.js';
28
+ import { auditCommand } from './audit.js';
29
+ import { agentFixCommand } from './agent-fix.js';
30
+ import { undoCommand } from './undo.js';
31
+ import * as output from '../utils/output.js';
32
+
33
+ const SEV_RANK = { critical: 4, high: 3, medium: 2, low: 1, info: 0 };
34
+
35
+ // Version comes from the single source in `cli/core/version.js` so the REPL banner
36
+ // stays in sync with releases without its own copy of the lookup.
37
+ const PKG_VERSION = toolVersion();
38
+
39
+ const BANNER_LINES = [
40
+ ' ███████╗██╗ ██╗██╗██████╗ ███████╗ █████╗ ███████╗███████╗',
41
+ ' ██╔════╝██║ ██║██║██╔══██╗ ██╔════╝██╔══██╗██╔════╝██╔════╝',
42
+ ' ███████╗███████║██║██████╔╝ ███████╗███████║█████╗ █████╗ ',
43
+ ' ╚════██║██╔══██║██║██╔═══╝ ╚════██║██╔══██║██╔══╝ ██╔══╝ ',
44
+ ' ███████║██║ ██║██║██║ ███████║██║ ██║██║ ███████╗',
45
+ ' ╚══════╝╚═╝ ╚═╝╚═╝╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚══════╝',
46
+ ];
47
+
48
+ // Characters drawn from the same box-drawing + block set the banner uses,
49
+ // so random frames look plausibly related rather than pure noise.
50
+ const GLITCH_CHARS = '█▓▒░╔╗╚╝╠╣╦╩╬═║┼┤├┬┴┐└┘┌─│╱╲╳';
51
+
52
+ function glitchFrame(line, reveal) {
53
+ // `reveal` is 0.0..1.0 — characters left of the reveal frontier are real,
54
+ // everything to the right is randomised from the glitch set.
55
+ return line.split('').map((ch, i) => {
56
+ const pos = i / line.length;
57
+ if (pos < reveal || ch === ' ') return ch;
58
+ return GLITCH_CHARS[Math.floor(Math.random() * GLITCH_CHARS.length)];
59
+ }).join('');
60
+ }
61
+
62
+ function sleep(ms) {
63
+ return new Promise(r => setTimeout(r, ms));
64
+ }
65
+
66
+ async function praxisBannerAnimated() {
67
+ const cols = process.stdout.columns;
68
+ const narrow = typeof cols === 'number' && cols > 0 && cols < 70;
69
+ if (narrow) {
70
+ console.log(chalk.cyan.bold(' S H I P S A F E'));
71
+ return;
72
+ }
73
+
74
+ const lines = BANNER_LINES;
75
+ const FRAMES = 8; // glitch passes before the line locks in
76
+ const FRAME_MS = 18; // ms between frames within a line
77
+ const LINE_MS = 28; // ms between lines starting
78
+
79
+ // Print an empty placeholder so we know exactly where each line lives.
80
+ // We'll overwrite them in-place using cursor-up escape codes.
81
+ process.stdout.write('\n');
82
+ for (const line of lines) {
83
+ process.stdout.write(' '.repeat(line.length) + '\n');
84
+ }
85
+ process.stdout.write('\n');
86
+
87
+ for (let li = 0; li < lines.length; li++) {
88
+ const line = lines[li];
89
+ // Move cursor up to this line's row (from the blank line after the banner).
90
+ const stepsUp = lines.length - li + 1;
91
+ process.stdout.write(`\x1B[${stepsUp}A`); // cursor up N
92
+
93
+ // Animate: reveal marches from 0 → 1 across FRAMES frames.
94
+ for (let f = 0; f <= FRAMES; f++) {
95
+ const reveal = f / FRAMES;
96
+ const scrambled = glitchFrame(line, reveal);
97
+ process.stdout.write('\r' + chalk.cyan(scrambled));
98
+ if (f < FRAMES) await sleep(FRAME_MS);
99
+ }
100
+
101
+ // Write the final clean line and move back down to the bottom blank line.
102
+ process.stdout.write('\r' + chalk.cyan(line));
103
+ process.stdout.write(`\x1B[${stepsUp}B`); // cursor down N
104
+ await sleep(LINE_MS);
105
+ }
106
+ }
107
+
108
+ export async function shellCommand(targetPath = '.', options = {}) {
109
+ const root = path.resolve(targetPath);
110
+
111
+ // Session state — persists across commands within this REPL
112
+ const state = {
113
+ root,
114
+ provider: null,
115
+ lastScan: null,
116
+ history: [], // [{ role: 'user'|'assistant', content }]
117
+ };
118
+
119
+ // Try to load a provider eagerly (non-fatal if none available)
120
+ state.provider = autoDetectProvider(root, {
121
+ provider: options.provider,
122
+ model: options.model,
123
+ think: options.think || false,
124
+ });
125
+
126
+ // Branded entry: big wordmark, version + provider + cwd, then a CTA hint.
127
+ // Modeled on Claude Code / Gemini CLI / Aider — establish the tool's identity
128
+ // in the first second, then get out of the way.
129
+ console.log();
130
+ await praxisBannerAnimated();
131
+ // trailing blank line is already written by the animation loop
132
+ const ver = PKG_VERSION ? `v${PKG_VERSION}` : '';
133
+ const prov = state.provider ? chalk.cyan(state.provider.name) : chalk.yellow('no provider');
134
+ const cwd = chalk.gray(prettyCwd(root));
135
+ console.log(` ${chalk.bold(ver)} ${chalk.gray('·')} ${prov} ${chalk.gray('·')} ${cwd}`);
136
+ console.log();
137
+ console.log(chalk.gray(' /scan to find issues · /agent to fix them · /help for more'));
138
+ console.log();
139
+
140
+ const rl = createInterface({
141
+ input: process.stdin,
142
+ output: process.stdout,
143
+ terminal: true,
144
+ });
145
+
146
+ const ask = (prompt) => new Promise(resolve => rl.question(prompt, resolve));
147
+
148
+ // Graceful Ctrl-D
149
+ rl.on('close', () => {
150
+ console.log();
151
+ process.exit(0);
152
+ });
153
+
154
+ let running = true;
155
+ while (running) {
156
+ const line = (await ask(chalk.cyan('praxis › '))).trim();
157
+ if (!line) continue;
158
+
159
+ if (line.startsWith('/')) {
160
+ running = await handleSlashCommand(line, state, options);
161
+ } else {
162
+ await handlePrompt(line, state);
163
+ }
164
+ }
165
+
166
+ rl.close();
167
+ }
168
+
169
+ // =============================================================================
170
+ // SLASH COMMANDS
171
+ // =============================================================================
172
+
173
+ async function handleSlashCommand(line, state, options) {
174
+ const [raw, ...args] = line.slice(1).split(/\s+/);
175
+ const cmd = raw.toLowerCase();
176
+
177
+ switch (cmd) {
178
+ case 'help':
179
+ case '?':
180
+ printHelp();
181
+ return true;
182
+
183
+ case 'quit':
184
+ case 'exit':
185
+ case 'bye':
186
+ console.log(chalk.gray(' Bye.'));
187
+ return false;
188
+
189
+ case 'clear':
190
+ process.stdout.write('\x1Bc');
191
+ return true;
192
+
193
+ case 'scan':
194
+ case 'rescan': {
195
+ const spinner = ora({ text: 'Scanning...', color: 'cyan' }).start();
196
+ try {
197
+ const result = await auditCommand(state.root, { _agenticInner: true, deep: false, deps: false, noAi: true });
198
+ state.lastScan = result;
199
+ spinner.stop();
200
+ printScanSummary(result);
201
+ } catch (err) {
202
+ spinner.fail(err.message);
203
+ }
204
+ return true;
205
+ }
206
+
207
+ case 'diff': {
208
+ // Show working-tree diff so the user can review changes from /agent
209
+ try {
210
+ const out = execFileSync('git', ['diff', '--no-color', ...args], { cwd: state.root, stdio: ['ignore', 'pipe', 'pipe'] }).toString();
211
+ if (!out.trim()) {
212
+ console.log(chalk.gray(' No changes.'));
213
+ } else {
214
+ console.log();
215
+ console.log(out);
216
+ }
217
+ } catch (err) {
218
+ console.log(chalk.red(` git diff failed: ${err.message}`));
219
+ }
220
+ return true;
221
+ }
222
+
223
+ case 'git': {
224
+ // Pass through to git so the user can poke around (status, log, stash, etc.)
225
+ // without leaving the shell. Inherit stdio so paged commands work.
226
+ const result = spawnSync('git', args, { cwd: state.root, stdio: 'inherit' });
227
+ if (result.error) console.log(chalk.red(` ${result.error.message}`));
228
+ return true;
229
+ }
230
+
231
+ case 'plan': {
232
+ // Preview a fix plan for ONE finding without applying.
233
+ // Usage: /plan <n> (1-based, from /findings)
234
+ if (!state.lastScan) {
235
+ console.log(chalk.yellow(' No scan results yet. Run /scan first.'));
236
+ return true;
237
+ }
238
+ const findings = getSortedFindings(state);
239
+ const n = parseInt(args[0], 10);
240
+ if (!Number.isInteger(n) || n < 1 || n > findings.length) {
241
+ console.log(chalk.yellow(` Usage: /plan <n> (1..${findings.length})`));
242
+ return true;
243
+ }
244
+ const f = findings[n - 1];
245
+ if (!f.file) {
246
+ console.log(chalk.yellow(' Finding has no file path — cannot plan.'));
247
+ return true;
248
+ }
249
+ // Delegate to agent in plan-only mode, scoped narrowly.
250
+ // Building a one-finding workflow inline duplicates a lot of agent-fix logic;
251
+ // run the full agent restricted to this file's directory + plan-only.
252
+ const dir = path.dirname(path.resolve(state.root, f.file));
253
+ console.log(chalk.gray(` Generating plan for finding ${n} in ${f.file}...`));
254
+ try {
255
+ await agentFixCommand(dir, { ...options, planOnly: true, allowDirty: true, severity: f.severity || 'low' });
256
+ } catch (err) {
257
+ console.log(chalk.red(` Plan failed: ${err.message}`));
258
+ }
259
+ return true;
260
+ }
261
+
262
+ case 'findings': {
263
+ if (!state.lastScan) {
264
+ console.log(chalk.yellow(' No scan results yet. Run /scan first.'));
265
+ return true;
266
+ }
267
+ printFindingsList(getSortedFindings(state));
268
+ return true;
269
+ }
270
+
271
+ case 'show': {
272
+ if (!state.lastScan) {
273
+ console.log(chalk.yellow(' No scan results yet. Run /scan first.'));
274
+ return true;
275
+ }
276
+ const n = parseInt(args[0], 10);
277
+ const findings = getSortedFindings(state);
278
+ if (!Number.isInteger(n) || n < 1 || n > findings.length) {
279
+ console.log(chalk.yellow(` Usage: /show <n> (1..${findings.length})`));
280
+ return true;
281
+ }
282
+ printFindingDetail(findings[n - 1], n);
283
+ return true;
284
+ }
285
+
286
+ case 'agent':
287
+ case 'fix': {
288
+ // Hand off to agent command. Pass through caller options + any inline flags.
289
+ // Forward the active provider key so /provider switches take effect.
290
+ const opts = { ...options };
291
+ if (state.providerKey) opts.provider = state.providerKey;
292
+ for (const a of args) {
293
+ if (a === '--plan-only') opts.planOnly = true;
294
+ if (a === '--allow-dirty') opts.allowDirty = true;
295
+ if (a === '--branch') opts.branch = true;
296
+ if (a === '--pr') opts.pr = true;
297
+ if (a.startsWith('--severity=')) opts.severity = a.slice('--severity='.length);
298
+ if (a.startsWith('--provider=')) opts.provider = a.slice('--provider='.length);
299
+ }
300
+ try {
301
+ await agentFixCommand(state.root, opts);
302
+ } catch (err) {
303
+ console.log(chalk.red(` Agent failed: ${err.message}`));
304
+ }
305
+ return true;
306
+ }
307
+
308
+ case 'undo': {
309
+ try {
310
+ await undoCommand(state.root, { all: args.includes('--all'), dryRun: args.includes('--dry-run') });
311
+ } catch (err) {
312
+ console.log(chalk.red(` Undo failed: ${err.message}`));
313
+ }
314
+ return true;
315
+ }
316
+
317
+ case 'provider': {
318
+ const name = args[0];
319
+ if (!name) {
320
+ console.log(chalk.gray(` Current: ${state.provider?.name ?? 'none'}`));
321
+ console.log(chalk.gray(' Usage: /provider <deepseek-flash|openai|kimi|anthropic|deepseek>'));
322
+ return true;
323
+ }
324
+ const next = autoDetectProvider(state.root, { provider: name });
325
+ if (!next) {
326
+ console.log(chalk.yellow(` Could not load provider "${name}" — is the API key set?`));
327
+ } else {
328
+ state.provider = next;
329
+ state.providerKey = name; // keep the string so /agent can forward it
330
+ console.log(chalk.green(` Provider switched to ${next.name}.`));
331
+ }
332
+ return true;
333
+ }
334
+
335
+ default:
336
+ console.log(chalk.yellow(` Unknown command: /${cmd}. Type /help for the list.`));
337
+ return true;
338
+ }
339
+ }
340
+
341
+ // =============================================================================
342
+ // FREE-FORM PROMPT
343
+ // =============================================================================
344
+
345
+ async function handlePrompt(text, state) {
346
+ if (!state.provider) {
347
+ console.log(chalk.yellow(' No LLM provider available. Set DEEPSEEK_API_KEY (or another supported key) and restart.'));
348
+ return;
349
+ }
350
+
351
+ state.history.push({ role: 'user', content: text });
352
+
353
+ const systemPrompt = buildSystemPrompt(state);
354
+ const userPrompt = buildConversationPrompt(state);
355
+
356
+ // Stream tokens as they arrive so the REPL feels alive.
357
+ // Falls back transparently to one-shot complete() for providers without
358
+ // real streaming (the base class default yields the whole response).
359
+ process.stdout.write('\n ');
360
+ let collected = '';
361
+ try {
362
+ for await (const chunk of state.provider.stream(systemPrompt, userPrompt, { maxTokens: 1500 })) {
363
+ collected += chunk;
364
+ // Indent any new lines that appear inside a streamed chunk
365
+ process.stdout.write(chalk.white(chunk.replace(/\n/g, '\n ')));
366
+ }
367
+ process.stdout.write('\n\n');
368
+ state.history.push({ role: 'assistant', content: collected.trim() });
369
+ } catch (err) {
370
+ process.stdout.write('\n');
371
+ console.log(chalk.red(` Provider call failed: ${err.message}`));
372
+ }
373
+ }
374
+
375
+ function buildSystemPrompt(state) {
376
+ const scanSummary = state.lastScan
377
+ ? `Latest scan: score ${state.lastScan.score ?? '?'}/100, ${state.lastScan.findings?.length ?? 0} finding(s).`
378
+ : 'No scan has been run yet in this session.';
379
+
380
+ return [
381
+ 'You are the Praxis security agent embedded in a developer\'s CLI.',
382
+ 'You give precise, security-focused answers. Prefer concrete fixes and references over abstract advice.',
383
+ `Project root: ${state.root}`,
384
+ scanSummary,
385
+ 'When findings are referenced, cite them by index (1-based, in the order shown by /findings).',
386
+ ].join('\n');
387
+ }
388
+
389
+ function buildConversationPrompt(state) {
390
+ // Keep last ~10 turns to bound context size
391
+ const recent = state.history.slice(-10);
392
+
393
+ let context = '';
394
+ if (state.lastScan?.findings?.length) {
395
+ const findings = state.lastScan.findings.slice(0, 25).map((f, i) =>
396
+ `${i + 1}. [${f.severity}] ${f.title}${f.file ? ` — ${f.file}${f.line ? `:${f.line}` : ''}` : ''}`,
397
+ ).join('\n');
398
+ context = `\nKnown findings:\n${findings}\n\n`;
399
+ }
400
+
401
+ const turns = recent.map(t => `${t.role === 'user' ? 'USER' : 'ASSISTANT'}: ${t.content}`).join('\n\n');
402
+ return `${context}${turns}\n\nASSISTANT:`;
403
+ }
404
+
405
+ function formatAssistant(text) {
406
+ return text
407
+ .split('\n')
408
+ .map(line => chalk.white(` ${line}`))
409
+ .join('\n');
410
+ }
411
+
412
+ // =============================================================================
413
+ // PRINTING
414
+ // =============================================================================
415
+
416
+ function printHelp() {
417
+ console.log();
418
+ console.log(chalk.bold(' Commands:'));
419
+ console.log(' /scan, /rescan Re-scan the project');
420
+ console.log(' /findings List the latest scan\'s findings');
421
+ console.log(' /show <n> Show full detail of finding <n>');
422
+ console.log(' /plan <n> Preview a fix plan for finding <n> (no writes)');
423
+ console.log(' /agent [--plan-only] Run the interactive fix loop');
424
+ console.log(' /undo [--all] Revert the last fix (or all)');
425
+ console.log(' /diff [path] Show git working-tree diff');
426
+ console.log(' /git <args> Pass through to git (status, log, stash, ...)');
427
+ console.log(' /provider <name> Switch LLM provider');
428
+ console.log(' /clear Clear the screen');
429
+ console.log(' /quit Exit');
430
+ console.log();
431
+ console.log(chalk.gray(' Or just type a question — the agent will answer with scan context.'));
432
+ console.log();
433
+ }
434
+
435
+ function printScanSummary(result) {
436
+ const findings = result.findings ?? [];
437
+ const counts = { critical: 0, high: 0, medium: 0, low: 0 };
438
+ for (const f of findings) counts[f.severity] = (counts[f.severity] ?? 0) + 1;
439
+
440
+ console.log();
441
+ console.log(chalk.bold(` Score: ${gradeColor(result.score)(`${result.score ?? '?'}/100`)}`));
442
+ console.log(` Findings: ${chalk.red(counts.critical || 0)} critical, ${chalk.red(counts.high || 0)} high, ${chalk.yellow(counts.medium || 0)} medium, ${chalk.blue(counts.low || 0)} low`);
443
+ console.log();
444
+ console.log(chalk.gray(' /findings to list, /agent to fix.'));
445
+ console.log();
446
+ }
447
+
448
+ function printFindingsList(findings) {
449
+ if (findings.length === 0) {
450
+ console.log(chalk.green(' No findings.'));
451
+ return;
452
+ }
453
+ // Sort by severity desc
454
+ const sorted = [...findings].sort((a, b) => (SEV_RANK[b.severity] ?? 0) - (SEV_RANK[a.severity] ?? 0));
455
+ console.log();
456
+ for (let i = 0; i < sorted.length; i++) {
457
+ const f = sorted[i];
458
+ console.log(` ${chalk.gray(`${i + 1}.`.padStart(4))} ${sevTag(f.severity)} ${f.title} ${chalk.gray(f.file ?? '')}${f.line ? chalk.gray(`:${f.line}`) : ''}`);
459
+ }
460
+ console.log();
461
+ }
462
+
463
+ function printFindingDetail(f, n) {
464
+ console.log();
465
+ console.log(chalk.bold(` Finding ${n}: ${f.title}`));
466
+ console.log(` Severity: ${sevTag(f.severity)}`);
467
+ if (f.file) console.log(` File: ${f.file}${f.line ? `:${f.line}` : ''}`);
468
+ if (f.rule) console.log(` Rule: ${f.rule}`);
469
+ if (f.cwe) console.log(` CWE: ${f.cwe}`);
470
+ if (f.description) {
471
+ console.log();
472
+ console.log(chalk.gray(' Description:'));
473
+ console.log(` ${f.description}`);
474
+ }
475
+ if (f.fix) {
476
+ console.log();
477
+ console.log(chalk.gray(' Suggested fix:'));
478
+ console.log(` ${f.fix}`);
479
+ }
480
+ console.log();
481
+ }
482
+
483
+ function sevTag(sev) {
484
+ switch (sev) {
485
+ case 'critical': return chalk.red.bold('[CRITICAL]');
486
+ case 'high': return chalk.red('[HIGH]');
487
+ case 'medium': return chalk.yellow('[MEDIUM]');
488
+ case 'low': return chalk.blue('[LOW]');
489
+ default: return chalk.gray(`[${(sev || 'INFO').toUpperCase()}]`);
490
+ }
491
+ }
492
+
493
+ function prettyCwd(p) {
494
+ const home = process.env.HOME || '';
495
+ if (home && p.startsWith(home + '/')) return '~' + p.slice(home.length);
496
+ return p;
497
+ }
498
+
499
+ function gradeColor(score) {
500
+ if (score == null) return chalk.gray;
501
+ if (score >= 80) return chalk.green;
502
+ if (score >= 60) return chalk.yellow;
503
+ return chalk.red;
504
+ }
505
+
506
+ function getSortedFindings(state) {
507
+ if (!state.lastScan || !state.lastScan.findings) return [];
508
+ if (!state.lastScan.findingsSorted) {
509
+ state.lastScan.findingsSorted = [...state.lastScan.findings].sort(
510
+ (a, b) => (SEV_RANK[b.severity] ?? 0) - (SEV_RANK[a.severity] ?? 0)
511
+ );
512
+ }
513
+ return state.lastScan.findingsSorted;
514
+ }