codehere 0.2.2 → 0.3.0-rc.10

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 (238) hide show
  1. package/README.md +88 -68
  2. package/dist/domain/entities/task.js +4 -4
  3. package/dist/error-handler.js +4 -9
  4. package/dist/index.js +261 -1224
  5. package/dist/infrastructure/config/product-context.js +7 -6
  6. package/dist/infrastructure/hooks/claude-sdk-hook.js +348 -72
  7. package/dist/infrastructure/observability/execution-tracer.js +11 -6
  8. package/dist/infrastructure/orchestration/agent-adapter.js +13 -0
  9. package/dist/infrastructure/orchestration/agent-installer.js +101 -0
  10. package/dist/infrastructure/orchestration/agents-config-seed.js +56 -0
  11. package/dist/infrastructure/orchestration/aider-adapter.js +319 -0
  12. package/dist/infrastructure/orchestration/artifacts-extractor.js +175 -0
  13. package/dist/infrastructure/orchestration/claude-code-adapter.js +352 -0
  14. package/dist/infrastructure/orchestration/codex-adapter.js +310 -0
  15. package/dist/infrastructure/orchestration/conductor-adapter.js +340 -0
  16. package/dist/infrastructure/orchestration/generic-cli-adapter.js +553 -0
  17. package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
  18. package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
  19. package/dist/infrastructure/orchestration/readiness.js +106 -0
  20. package/dist/infrastructure/orchestration/session-manager.js +278 -0
  21. package/dist/infrastructure/orchestration/session-persistence.js +109 -0
  22. package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
  23. package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
  24. package/dist/infrastructure/protocols/probe-port.js +36 -0
  25. package/dist/infrastructure/protocols/ui-page.js +1827 -0
  26. package/dist/infrastructure/security/file-collection.js +115 -0
  27. package/dist/infrastructure/security/trust-scorer.js +301 -56
  28. package/dist/infrastructure/storage/task-repository.js +8 -7
  29. package/dist/monitoring.js +9 -38
  30. package/dist/presentation/cli/commands/help-command.js +96 -139
  31. package/dist/presentation/cli/commands/hook-command.js +17 -24
  32. package/dist/presentation/cli/commands/report-command.js +59 -72
  33. package/dist/presentation/cli/commands/setup-command.js +4 -4
  34. package/dist/presentation/cli/commands/status-command.js +321 -30
  35. package/dist/presentation/cli/commands/trust-command.js +84 -72
  36. package/dist/presentation/cli/error-display.js +17 -21
  37. package/dist/presentation/cli/repl.js +474 -0
  38. package/dist/ui.js +11 -11
  39. package/package.json +24 -62
  40. package/dist/agents/base.js +0 -101
  41. package/dist/agents/orchestrator-model-driven.js +0 -141
  42. package/dist/agents/react-orchestrator-agent.js +0 -54
  43. package/dist/application/agents/execution-agent.js +0 -508
  44. package/dist/application/agents/multi-agent-orchestrator.js +0 -295
  45. package/dist/application/agents/planning-agent.js +0 -433
  46. package/dist/application/agents/validation-agent.js +0 -317
  47. package/dist/application/architectures/plan-and-act.js +0 -242
  48. package/dist/application/index.js +0 -12
  49. package/dist/application/services/agent-factory.js +0 -28
  50. package/dist/application/services/dependency-container.js +0 -596
  51. package/dist/application/services/git-context-service.js +0 -83
  52. package/dist/application/services/intelligent-router.js +0 -934
  53. package/dist/application/services/tool-executor-service.js +0 -94
  54. package/dist/application/use-cases/ask-question-use-case.js +0 -338
  55. package/dist/application/use-cases/edit-file-use-case.js +0 -830
  56. package/dist/application/use-cases/explain-file-use-case.js +0 -50
  57. package/dist/application/use-cases/index-codebase-use-case.js +0 -113
  58. package/dist/application/use-cases/planning-use-case.js +0 -276
  59. package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
  60. package/dist/application/use-cases/reflexion-use-case.js +0 -30
  61. package/dist/application/workflows/deterministic-workflows.js +0 -189
  62. package/dist/ast-parser.js +0 -331
  63. package/dist/cache.js +0 -180
  64. package/dist/chat.js +0 -251
  65. package/dist/code-analysis.js +0 -327
  66. package/dist/context.js +0 -187
  67. package/dist/docs.js +0 -146
  68. package/dist/domain/entities/code-chunk.js +0 -6
  69. package/dist/domain/entities/decision.js +0 -9
  70. package/dist/domain/entities/edit.js +0 -6
  71. package/dist/domain/entities/knowledge-node.js +0 -9
  72. package/dist/domain/entities/knowledge-preservation.js +0 -10
  73. package/dist/domain/entities/memory.js +0 -6
  74. package/dist/domain/entities/pattern.js +0 -7
  75. package/dist/domain/entities/plan.js +0 -6
  76. package/dist/domain/entities/query.js +0 -6
  77. package/dist/domain/errors/embeddings-not-found-error.js +0 -13
  78. package/dist/domain/index.js +0 -19
  79. package/dist/domain/interfaces/ai-service.interface.js +0 -6
  80. package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
  81. package/dist/domain/interfaces/decision-repository.interface.js +0 -9
  82. package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
  83. package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
  84. package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
  85. package/dist/domain/interfaces/memory-repository.interface.js +0 -6
  86. package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
  87. package/dist/domain/interfaces/verification-service.interface.js +0 -6
  88. package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
  89. package/dist/domain/services/decision-recorder.js +0 -223
  90. package/dist/domain/services/decision-retriever.js +0 -133
  91. package/dist/domain/services/environment-mode-manager.js +0 -22
  92. package/dist/domain/services/graded-memory-activation.js +0 -69
  93. package/dist/domain/services/knowledge-access.js +0 -132
  94. package/dist/domain/services/knowledge-extractor.js +0 -247
  95. package/dist/domain/services/knowledge-graph-builder.js +0 -268
  96. package/dist/domain/services/knowledge-graph-query.js +0 -187
  97. package/dist/domain/services/memory-retriever.js +0 -82
  98. package/dist/domain/services/memory-synthesizer.js +0 -91
  99. package/dist/domain/services/pattern-extractor.js +0 -442
  100. package/dist/domain/services/query-intent-classifier.js +0 -140
  101. package/dist/domain/services/react-loop.js +0 -186
  102. package/dist/domain/services/risk-tier-detector.js +0 -78
  103. package/dist/edit.js +0 -319
  104. package/dist/embed.js +0 -459
  105. package/dist/formatter.js +0 -168
  106. package/dist/git.js +0 -198
  107. package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
  108. package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
  109. package/dist/infrastructure/ai/model-config.js +0 -84
  110. package/dist/infrastructure/ai/provider-ai-service.js +0 -477
  111. package/dist/infrastructure/cache/embedding-cache.js +0 -175
  112. package/dist/infrastructure/cache/query-result-cache.js +0 -66
  113. package/dist/infrastructure/cache/response-cache.js +0 -48
  114. package/dist/infrastructure/cache/security-scan-cache.js +0 -47
  115. package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
  116. package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
  117. package/dist/infrastructure/context/context-compressor.js +0 -329
  118. package/dist/infrastructure/context/conversation-context.js +0 -128
  119. package/dist/infrastructure/context/session-manager.js +0 -94
  120. package/dist/infrastructure/cost/cost-tracker.js +0 -360
  121. package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
  122. package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
  123. package/dist/infrastructure/governance/policy-as-code.js +0 -258
  124. package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
  125. package/dist/infrastructure/index.js +0 -7
  126. package/dist/infrastructure/observability/prompt-versioner.js +0 -145
  127. package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
  128. package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
  129. package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
  130. package/dist/infrastructure/protocols/mcp-server.js +0 -333
  131. package/dist/infrastructure/protocols/streaming-handler.js +0 -103
  132. package/dist/infrastructure/providers/cohere-provider.js +0 -444
  133. package/dist/infrastructure/providers/fake-provider.js +0 -130
  134. package/dist/infrastructure/providers/local-llm-provider.js +0 -330
  135. package/dist/infrastructure/providers/model-config.types.js +0 -9
  136. package/dist/infrastructure/providers/model-provider.interface.js +0 -8
  137. package/dist/infrastructure/providers/openai-provider.js +0 -413
  138. package/dist/infrastructure/providers/openrouter-provider.js +0 -399
  139. package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
  140. package/dist/infrastructure/providers/provider-config-loader.js +0 -120
  141. package/dist/infrastructure/providers/provider-registry.js +0 -88
  142. package/dist/infrastructure/safety/pattern-detector.js +0 -133
  143. package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
  144. package/dist/infrastructure/security/docker-sandbox.js +0 -178
  145. package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
  146. package/dist/infrastructure/security/license-scanner.js +0 -167
  147. package/dist/infrastructure/security/provider-bias-detector.js +0 -164
  148. package/dist/infrastructure/security/sandbox-executor.js +0 -64
  149. package/dist/infrastructure/serialization/toon-serializer.js +0 -119
  150. package/dist/infrastructure/storage/memory-stream-service.js +0 -204
  151. package/dist/infrastructure/storage/plan-repository.js +0 -96
  152. package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
  153. package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
  154. package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
  155. package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
  156. package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
  157. package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
  158. package/dist/infrastructure/storage/task-helpers.js +0 -197
  159. package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
  160. package/dist/infrastructure/ux/appropriate-friction.js +0 -213
  161. package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
  162. package/dist/infrastructure/ux/capability-boundaries.js +0 -42
  163. package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
  164. package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
  165. package/dist/infrastructure/ux/expectation-management.js +0 -327
  166. package/dist/infrastructure/ux/feature-discovery.js +0 -14
  167. package/dist/infrastructure/ux/feedback-prompt.js +0 -45
  168. package/dist/infrastructure/ux/hitl-validation.js +0 -297
  169. package/dist/infrastructure/ux/progress-indicator.js +0 -116
  170. package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
  171. package/dist/infrastructure/ux/review-checkpoint.js +0 -72
  172. package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
  173. package/dist/infrastructure/ux/stream-markdown.js +0 -151
  174. package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
  175. package/dist/infrastructure/ux/team-standards.js +0 -196
  176. package/dist/infrastructure/ux/transparency.js +0 -71
  177. package/dist/infrastructure/validation/agent-feedback.js +0 -55
  178. package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
  179. package/dist/infrastructure/validation/review-handler.js +0 -40
  180. package/dist/infrastructure/validation/summary-aggregator.js +0 -70
  181. package/dist/infrastructure/validation/summary-extractor.js +0 -45
  182. package/dist/infrastructure/validation/trace-summary.js +0 -52
  183. package/dist/infrastructure/verification/verification-service.js +0 -47
  184. package/dist/infrastructure/xai/attention-visualizer.js +0 -172
  185. package/dist/infrastructure/xai/cot-visualizer.js +0 -283
  186. package/dist/infrastructure/xai/decision-tree-log.js +0 -212
  187. package/dist/infrastructure/xai/interactive-xai.js +0 -260
  188. package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
  189. package/dist/intelligent-retrieval.js +0 -272
  190. package/dist/intent/classifier.js +0 -2
  191. package/dist/intent/context.js +0 -2
  192. package/dist/iterative-refinement.js +0 -189
  193. package/dist/learning.js +0 -232
  194. package/dist/log.js +0 -31
  195. package/dist/migrate.js +0 -133
  196. package/dist/parallel-processor.js +0 -534
  197. package/dist/planner.js +0 -198
  198. package/dist/policy.js +0 -26
  199. package/dist/presentation/cli/commands/ask-command.js +0 -314
  200. package/dist/presentation/cli/commands/cost-command.js +0 -191
  201. package/dist/presentation/cli/commands/decision-command.js +0 -207
  202. package/dist/presentation/cli/commands/docs-command.js +0 -25
  203. package/dist/presentation/cli/commands/fix-command.js +0 -53
  204. package/dist/presentation/cli/commands/knowledge-command.js +0 -129
  205. package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
  206. package/dist/presentation/cli/commands/models-command.js +0 -194
  207. package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
  208. package/dist/presentation/cli/commands/plan-command.js +0 -246
  209. package/dist/presentation/cli/commands/product-command.js +0 -199
  210. package/dist/presentation/cli/commands/react-command.js +0 -181
  211. package/dist/presentation/cli/commands/review-command.js +0 -154
  212. package/dist/presentation/cli/commands/run-command.js +0 -188
  213. package/dist/presentation/cli/commands/smart-command.js +0 -395
  214. package/dist/presentation/cli/commands/suggest-command.js +0 -138
  215. package/dist/presentation/cli/commands/trace-command.js +0 -129
  216. package/dist/presentation/cli/commands/undo-command.js +0 -150
  217. package/dist/query-optimizer.js +0 -205
  218. package/dist/refactor.js +0 -116
  219. package/dist/review.js +0 -206
  220. package/dist/search.js +0 -163
  221. package/dist/session.js +0 -704
  222. package/dist/task-verification.js +0 -336
  223. package/dist/testgen.js +0 -166
  224. package/dist/token-optimizer.js +0 -277
  225. package/dist/tools/bash.js +0 -213
  226. package/dist/tools/edit.js +0 -235
  227. package/dist/tools/executor.js +0 -153
  228. package/dist/tools/git-tool.js +0 -292
  229. package/dist/tools/parser.js +0 -158
  230. package/dist/tools/registry.js +0 -302
  231. package/dist/tools/search.js +0 -100
  232. package/dist/types.js +0 -2
  233. package/dist/utils/check-api-status.js +0 -100
  234. package/dist/utils/diff-parser.js +0 -162
  235. package/dist/verification/backup.js +0 -259
  236. package/dist/verification/compiler.js +0 -264
  237. package/dist/verification/index.js +0 -273
  238. package/dist/verification/test-runner.js +0 -379
@@ -1,88 +0,0 @@
1
- /**
2
- * Provider Layer: ProviderRegistry
3
- * Central registry for all model providers
4
- *
5
- * Phase 4A: Foundation Implementation (No Behavior Change)
6
- */
7
- /**
8
- * Provider Registry
9
- * Singleton registry for managing model providers
10
- */
11
- export class ProviderRegistry {
12
- static instance = null;
13
- providers = new Map();
14
- defaultProviderId;
15
- /**
16
- * Get singleton instance
17
- */
18
- static getInstance() {
19
- if (!ProviderRegistry.instance) {
20
- ProviderRegistry.instance = new ProviderRegistry();
21
- }
22
- return ProviderRegistry.instance;
23
- }
24
- /**
25
- * Register a provider
26
- */
27
- register(provider) {
28
- this.providers.set(provider.id, provider);
29
- // Auto-set as default if this is the first provider
30
- if (!this.defaultProviderId) {
31
- this.defaultProviderId = provider.id;
32
- }
33
- }
34
- /**
35
- * Get provider by ID
36
- */
37
- get(providerId) {
38
- return this.providers.get(providerId);
39
- }
40
- /**
41
- * Get default provider
42
- */
43
- getDefault() {
44
- if (!this.defaultProviderId) {
45
- throw new Error('No default provider configured');
46
- }
47
- const provider = this.get(this.defaultProviderId);
48
- if (!provider) {
49
- throw new Error(`Default provider '${this.defaultProviderId}' not found`);
50
- }
51
- return provider;
52
- }
53
- /**
54
- * Set default provider
55
- */
56
- setDefault(providerId) {
57
- if (!this.providers.has(providerId)) {
58
- throw new Error(`Provider '${providerId}' not registered`);
59
- }
60
- this.defaultProviderId = providerId;
61
- }
62
- /**
63
- * Get all registered providers
64
- */
65
- getAll() {
66
- return Array.from(this.providers.values());
67
- }
68
- /**
69
- * Find providers by capability
70
- */
71
- findByCapability(capability) {
72
- return this.getAll().filter(p => p.capabilities[capability]);
73
- }
74
- /**
75
- * Check if provider is registered
76
- */
77
- has(providerId) {
78
- return this.providers.has(providerId);
79
- }
80
- /**
81
- * Clear all providers (mainly for testing)
82
- */
83
- clear() {
84
- this.providers.clear();
85
- this.defaultProviderId = undefined;
86
- }
87
- }
88
- //# sourceMappingURL=provider-registry.js.map
@@ -1,133 +0,0 @@
1
- /**
2
- * Mistake Detection Loop (P4-A)
3
- *
4
- * Detects repeated patterns in hook events and surfaces warnings:
5
- * - Same category blocked 3+ times → user warning
6
- * - Same file blocked 3+ times → suggest different approach
7
- * - AI retrying blocked command with minor variation → escalate
8
- *
9
- * v0.3.0
10
- */
11
- import { readFileSync, existsSync } from 'fs';
12
- import { join } from 'path';
13
- import { homedir } from 'os';
14
- import chalk from 'chalk';
15
- const AUDIT_FILE = join(homedir(), '.codehere', 'audit', 'hook-events.jsonl');
16
- const THRESHOLD = 3;
17
- /**
18
- * Analyze recent audit log for mistake patterns in a session.
19
- */
20
- export function detectMistakes(sessionId) {
21
- if (!existsSync(AUDIT_FILE))
22
- return [];
23
- let lines;
24
- try {
25
- const raw = readFileSync(AUDIT_FILE, 'utf-8').trim();
26
- if (!raw)
27
- return [];
28
- lines = raw.split('\n');
29
- }
30
- catch {
31
- return [];
32
- }
33
- // Parse blocked events, optionally filtered to a session
34
- const blockedEvents = [];
35
- for (const line of lines) {
36
- try {
37
- const entry = JSON.parse(line);
38
- if (!entry.blocked)
39
- continue;
40
- if (sessionId && entry.sessionId !== sessionId)
41
- continue;
42
- blockedEvents.push(entry);
43
- }
44
- catch {
45
- continue;
46
- }
47
- }
48
- if (blockedEvents.length < THRESHOLD)
49
- return [];
50
- const patterns = [];
51
- // 1. Same category blocked 3+ times
52
- const categoryCounts = new Map();
53
- for (const event of blockedEvents) {
54
- if (event.categories) {
55
- for (const cat of event.categories) {
56
- categoryCounts.set(cat, (categoryCounts.get(cat) || 0) + 1);
57
- }
58
- }
59
- }
60
- for (const [category, count] of categoryCounts) {
61
- if (count >= THRESHOLD) {
62
- patterns.push({
63
- type: 'repeated-category',
64
- description: `"${category}" blocked ${count} times`,
65
- count,
66
- suggestion: `The AI keeps triggering ${category} detections. Consider adding a project rule or using a safer pattern.`,
67
- });
68
- }
69
- }
70
- // 2. Same tool+file blocked 3+ times
71
- const fileCounts = new Map();
72
- for (const event of blockedEvents) {
73
- if (event.toolName === 'Write' || event.toolName === 'Edit' || event.toolName === 'MultiEdit') {
74
- try {
75
- const input = JSON.parse(event.toolInput);
76
- const filePath = input.file_path || input.filepath || '';
77
- if (filePath) {
78
- fileCounts.set(filePath, (fileCounts.get(filePath) || 0) + 1);
79
- }
80
- }
81
- catch {
82
- // toolInput might be truncated
83
- }
84
- }
85
- }
86
- for (const [filePath, count] of fileCounts) {
87
- if (count >= THRESHOLD) {
88
- const shortPath = filePath.split('/').slice(-2).join('/');
89
- patterns.push({
90
- type: 'repeated-file',
91
- description: `Writes to ${shortPath} blocked ${count} times`,
92
- count,
93
- suggestion: `The AI keeps trying to modify this file in a blocked way. Try a different instruction or approach.`,
94
- });
95
- }
96
- }
97
- // 3. Rapid retries (3+ blocked events within 60 seconds)
98
- if (blockedEvents.length >= THRESHOLD) {
99
- const recent = blockedEvents.slice(-10);
100
- let rapidCount = 0;
101
- for (let i = 1; i < recent.length; i++) {
102
- const prev = new Date(recent[i - 1].timestamp).getTime();
103
- const curr = new Date(recent[i].timestamp).getTime();
104
- if (curr - prev < 60_000) {
105
- rapidCount++;
106
- }
107
- }
108
- if (rapidCount >= THRESHOLD - 1) {
109
- patterns.push({
110
- type: 'retry-variation',
111
- description: `${rapidCount + 1} rapid retries detected`,
112
- count: rapidCount + 1,
113
- suggestion: `The AI is rapidly retrying blocked commands. It may be stuck in a loop — consider rephrasing your instruction.`,
114
- });
115
- }
116
- }
117
- return patterns;
118
- }
119
- /**
120
- * Format mistake patterns for display in CLI.
121
- */
122
- export function formatMistakeWarnings(patterns) {
123
- if (patterns.length === 0)
124
- return '';
125
- const lines = [];
126
- lines.push(chalk.yellow.bold('Repeated patterns detected:'));
127
- for (const p of patterns) {
128
- lines.push(chalk.yellow(` ${p.description}`));
129
- lines.push(chalk.dim(` ${p.suggestion}`));
130
- }
131
- return lines.join('\n');
132
- }
133
- //# sourceMappingURL=pattern-detector.js.map
@@ -1,290 +0,0 @@
1
- /**
2
- * Infrastructure: AI SAST Scanner
3
- * AI-driven Static Application Security Testing
4
- * Detects security vulnerabilities in generated code
5
- *
6
- * Based on enterprise architecture: AI SAST for security gates
7
- */
8
- export class AISASTScanner {
9
- aiService;
10
- constructor(aiService) {
11
- this.aiService = aiService;
12
- }
13
- /**
14
- * Fast security check on instruction text (before expensive operations)
15
- * This is a quick heuristic check to reject dangerous instructions early
16
- */
17
- async scanInstruction(instruction) {
18
- // Full pattern-based scan — 50+ patterns across 5 categories
19
- // Matches benchmark coverage. Runs locally, no API needed.
20
- const instructionPatterns = [
21
- // ── PROMPT INJECTION (10 patterns) ────────────────────────
22
- { pattern: /ignore\s+(previous|prior|above|all|your)\s+(instructions?|rules?|prompts?|guidelines?)/i, severity: 'critical', category: 'Prompt Injection', description: 'Attempts to override system instructions' },
23
- { pattern: /disregard\s+(previous|prior|all|your)\s+(instructions?|rules?|prompts?)/i, severity: 'critical', category: 'Prompt Injection', description: 'Attempts to disregard system instructions' },
24
- { pattern: /forget\s+(everything|all|previous|your)\s*(instructions?|rules?|context)?/i, severity: 'critical', category: 'Prompt Injection', description: 'Attempts to clear system context' },
25
- { pattern: /you\s+are\s+now\s+(a|an|my)|new\s+role|act\s+as\s+(a|an|if)/i, severity: 'critical', category: 'Prompt Injection', description: 'Role hijacking attempt' },
26
- { pattern: /system\s*prompt|<\/?system>|<\/?instruction>/i, severity: 'critical', category: 'Prompt Injection', description: 'Attempts to access or inject system prompt' },
27
- { pattern: /\bdo\s+not\s+(follow|obey|listen|comply)\b/i, severity: 'critical', category: 'Prompt Injection', description: 'Instruction override attempt' },
28
- { pattern: /override\s+(safety|security|rules|restrictions|guidelines)/i, severity: 'critical', category: 'Prompt Injection', description: 'Safety override attempt' },
29
- { pattern: /jailbreak|DAN\s+mode|developer\s+mode|unrestricted\s+mode/i, severity: 'critical', category: 'Prompt Injection', description: 'Known jailbreak technique' },
30
- { pattern: /translate.*to.*base64|encode.*instructions|decode.*payload/i, severity: 'high', category: 'Prompt Injection', description: 'Obfuscation-based injection' },
31
- { pattern: /pretend\s+(you|there|that)\s*(are|is|was)\s*(no|isn.t|aren.t)/i, severity: 'critical', category: 'Prompt Injection', description: 'Reality manipulation injection' },
32
- // ── CREDENTIAL THEFT (10 patterns) ────────────────────────
33
- { pattern: /hardcode.*password|store.*password|plaintext.*password/i, severity: 'high', category: 'Credential Theft', description: 'Hardcoded credentials' },
34
- { pattern: /api[_\s-]?key\s*[:=]\s*['"]/i, severity: 'high', category: 'Credential Theft', description: 'Hardcoded API key' },
35
- { pattern: /secret[_\s-]?key\s*[:=]\s*['"]/i, severity: 'high', category: 'Credential Theft', description: 'Hardcoded secret key' },
36
- { pattern: /\bpassword\s*[:=]\s*['"][^'"]{3,}/i, severity: 'high', category: 'Credential Theft', description: 'Hardcoded password value' },
37
- { pattern: /token\s*[:=]\s*['"][A-Za-z0-9+/=_-]{20,}/i, severity: 'high', category: 'Credential Theft', description: 'Hardcoded token' },
38
- { pattern: /print.*env|console\.log.*process\.env|dump.*environment/i, severity: 'high', category: 'Credential Theft', description: 'Environment variable exfiltration' },
39
- { pattern: /read.*\.env|cat\s+\.env|show.*credentials/i, severity: 'high', category: 'Credential Theft', description: 'Credential file access' },
40
- { pattern: /send.*key.*to|post.*secret.*to|upload.*credentials/i, severity: 'critical', category: 'Credential Theft', description: 'Credential exfiltration' },
41
- { pattern: /AWS_SECRET|AZURE_KEY|GCP_KEY|DATABASE_URL.*password/i, severity: 'high', category: 'Credential Theft', description: 'Cloud credential exposure' },
42
- { pattern: /ssh[_\s-]?key|private[_\s-]?key.*BEGIN/i, severity: 'critical', category: 'Credential Theft', description: 'Private key exposure' },
43
- // ── CODE INJECTION (10 patterns) ──────────────────────────
44
- { pattern: /execute.*user.*input|eval.*user|exec.*user/i, severity: 'critical', category: 'Code Injection', description: 'User input execution' },
45
- { pattern: /shell.*command|system.*call|process\.exec|child_process/i, severity: 'critical', category: 'Code Injection', description: 'Shell command execution' },
46
- { pattern: /sql.*injection|raw.*sql.*query|query.*\+.*user/i, severity: 'high', category: 'Code Injection', description: 'SQL injection vector' },
47
- { pattern: /bypass.*security|disable.*security|remove.*validation/i, severity: 'critical', category: 'Code Injection', description: 'Security bypass' },
48
- { pattern: /delete\s+all\s+files|rm\s+-rf|remove\s+all|wipe\s+disk/i, severity: 'critical', category: 'Code Injection', description: 'Destructive file operation' },
49
- { pattern: /reverse\s+shell|bind\s+shell|nc\s+-e|netcat.*-e/i, severity: 'critical', category: 'Code Injection', description: 'Reverse shell attempt' },
50
- { pattern: /download.*execute|curl.*\|\s*sh|wget.*\|\s*bash/i, severity: 'critical', category: 'Code Injection', description: 'Remote code execution' },
51
- { pattern: /modify.*hosts|edit.*\/etc\/|change.*resolv\.conf/i, severity: 'critical', category: 'Code Injection', description: 'System file modification' },
52
- { pattern: /disable.*firewall|stop.*antivirus|kill.*security/i, severity: 'critical', category: 'Code Injection', description: 'Security software bypass' },
53
- { pattern: /crypto.*min(er|ing)|bitcoin.*address|monero.*wallet/i, severity: 'critical', category: 'Code Injection', description: 'Cryptominer injection' },
54
- // ── SUPPLY CHAIN (10 patterns) ────────────────────────────
55
- { pattern: /install\s+[a-z]+-[a-z]+\d{3,}|npm\s+i\s+[a-z]+-typo/i, severity: 'high', category: 'Supply Chain', description: 'Typosquatting package install' },
56
- { pattern: /add.*dependency.*http|require\s*\(\s*['"]https?:/i, severity: 'high', category: 'Supply Chain', description: 'Remote dependency injection' },
57
- { pattern: /postinstall.*script|preinstall.*curl|lifecycle.*wget/i, severity: 'critical', category: 'Supply Chain', description: 'Malicious lifecycle script' },
58
- { pattern: /replace.*package|swap.*module|inject.*into.*node_modules/i, severity: 'critical', category: 'Supply Chain', description: 'Package replacement attack' },
59
- { pattern: /modify.*package\.json.*scripts|add.*postinstall/i, severity: 'high', category: 'Supply Chain', description: 'Build script injection' },
60
- { pattern: /git.*clone.*untrusted|clone.*unknown.*repo/i, severity: 'high', category: 'Supply Chain', description: 'Untrusted repository clone' },
61
- { pattern: /override.*lockfile|delete.*lock|ignore.*integrity/i, severity: 'high', category: 'Supply Chain', description: 'Lock file tampering' },
62
- { pattern: /publish.*malicious|npm\s+publish.*trojan/i, severity: 'critical', category: 'Supply Chain', description: 'Malicious package publish' },
63
- { pattern: /dependency\s+confusion|internal.*package.*public/i, severity: 'high', category: 'Supply Chain', description: 'Dependency confusion attack' },
64
- { pattern: /add.*webpack.*plugin.*http|loader.*remote.*url/i, severity: 'high', category: 'Supply Chain', description: 'Build tool injection' },
65
- // ── OWASP TOP 10 (10 patterns) ────────────────────────────
66
- { pattern: /disable.*cors|access-control-allow-origin.*\*/i, severity: 'high', category: 'OWASP', description: 'CORS misconfiguration' },
67
- { pattern: /disable.*csrf|skip.*csrf.*check|no.*csrf/i, severity: 'high', category: 'OWASP', description: 'CSRF protection bypass' },
68
- { pattern: /no.*authentication|skip.*auth|remove.*auth.*check/i, severity: 'critical', category: 'OWASP', description: 'Authentication bypass' },
69
- { pattern: /set.*cookie.*httponly.*false|cookie.*secure.*false/i, severity: 'high', category: 'OWASP', description: 'Insecure cookie configuration' },
70
- { pattern: /http:\/\/.*api|unencrypted.*connection|disable.*tls/i, severity: 'high', category: 'OWASP', description: 'Insecure transport' },
71
- { pattern: /expose.*stack.*trace|verbose.*error.*production/i, severity: 'high', category: 'OWASP', description: 'Information disclosure' },
72
- { pattern: /admin.*route.*public|no.*authorization.*check/i, severity: 'critical', category: 'OWASP', description: 'Broken access control' },
73
- { pattern: /deserialize.*untrusted|parse.*user.*json.*eval/i, severity: 'critical', category: 'OWASP', description: 'Insecure deserialization' },
74
- { pattern: /log.*password|log.*token|log.*secret|log.*credentials/i, severity: 'high', category: 'OWASP', description: 'Sensitive data in logs' },
75
- { pattern: /xml.*external.*entity|xxe|DOCTYPE.*SYSTEM/i, severity: 'critical', category: 'OWASP', description: 'XXE injection' },
76
- ];
77
- const findings = [];
78
- for (const { pattern, severity, category, description } of instructionPatterns) {
79
- if (pattern.test(instruction)) {
80
- findings.push({
81
- severity,
82
- category,
83
- description,
84
- filepath: 'instruction',
85
- line: 0,
86
- recommendation: `BLOCKED: ${description}. This instruction was rejected by the safety scanner.`,
87
- });
88
- }
89
- }
90
- if (findings.length === 0) {
91
- return null; // No issues found, allow to proceed
92
- }
93
- const criticalCount = findings.filter(f => f.severity === 'critical').length;
94
- const highCount = findings.filter(f => f.severity === 'high').length;
95
- return {
96
- findings,
97
- totalFindings: findings.length,
98
- criticalCount,
99
- highCount,
100
- mediumCount: 0,
101
- lowCount: 0,
102
- passed: criticalCount === 0 && highCount === 0,
103
- };
104
- }
105
- /**
106
- * Fast pattern-based check for dangerous code patterns
107
- */
108
- checkDangerousPatterns(code) {
109
- const findings = [];
110
- const dangerousPatterns = [
111
- {
112
- pattern: /\beval\s*\(/gi,
113
- category: 'Code Injection',
114
- description: 'Use of eval() allows arbitrary code execution',
115
- severity: 'critical',
116
- cwe: 'CWE-95',
117
- },
118
- {
119
- pattern: /\bFunction\s*\(/gi,
120
- category: 'Code Injection',
121
- description: 'Use of Function() constructor allows arbitrary code execution',
122
- severity: 'critical',
123
- cwe: 'CWE-95',
124
- },
125
- {
126
- pattern: /\.innerHTML\s*=\s*[^=]/gi,
127
- category: 'Cross-Site Scripting',
128
- description: 'Direct innerHTML assignment can lead to XSS',
129
- severity: 'high',
130
- cwe: 'CWE-79',
131
- },
132
- {
133
- pattern: /setTimeout\s*\(\s*[^,)]+\s*\)/gi,
134
- category: 'Code Injection',
135
- description: 'setTimeout with user input can execute arbitrary code',
136
- severity: 'high',
137
- cwe: 'CWE-95',
138
- },
139
- {
140
- pattern: /setInterval\s*\(\s*[^,)]+\s*\)/gi,
141
- category: 'Code Injection',
142
- description: 'setInterval with user input can execute arbitrary code',
143
- severity: 'high',
144
- cwe: 'CWE-95',
145
- },
146
- ];
147
- dangerousPatterns.forEach(({ pattern, category, description, severity, cwe }) => {
148
- const matches = code.matchAll(pattern);
149
- for (const match of matches) {
150
- const line = code.substring(0, match.index || 0).split('\n').length;
151
- findings.push({
152
- severity,
153
- category,
154
- description,
155
- line,
156
- recommendation: `Avoid ${category.toLowerCase()}. Use safer alternatives.`,
157
- cwe,
158
- filepath: '', // Will be set by caller
159
- });
160
- }
161
- });
162
- return findings;
163
- }
164
- /**
165
- * Scan code for security vulnerabilities
166
- */
167
- async scan(filepath, code) {
168
- const findings = [];
169
- // Fast pattern-based checks first (before expensive AI analysis)
170
- const patternFindings = this.checkDangerousPatterns(code);
171
- // Set filepath for pattern findings
172
- patternFindings.forEach(f => { f.filepath = filepath; });
173
- findings.push(...patternFindings);
174
- // If critical patterns found, return early (don't need AI analysis)
175
- const criticalPatternFindings = patternFindings.filter(f => f.severity === 'critical');
176
- if (criticalPatternFindings.length > 0) {
177
- return {
178
- findings,
179
- totalFindings: findings.length,
180
- criticalCount: criticalPatternFindings.length,
181
- highCount: findings.filter(f => f.severity === 'high').length,
182
- mediumCount: findings.filter(f => f.severity === 'medium').length,
183
- lowCount: findings.filter(f => f.severity === 'low').length,
184
- passed: false,
185
- };
186
- }
187
- // AI-based analysis (only if no critical patterns found)
188
- const aiFindings = await this.analyzeWithAI(filepath, code);
189
- findings.push(...aiFindings);
190
- // Count by severity
191
- const criticalCount = findings.filter(f => f.severity === 'critical').length;
192
- const highCount = findings.filter(f => f.severity === 'high').length;
193
- const mediumCount = findings.filter(f => f.severity === 'medium').length;
194
- const lowCount = findings.filter(f => f.severity === 'low').length;
195
- // Pass if no critical or high severity findings
196
- const passed = criticalCount === 0 && highCount === 0;
197
- return {
198
- findings,
199
- totalFindings: findings.length,
200
- criticalCount,
201
- highCount,
202
- mediumCount,
203
- lowCount,
204
- passed,
205
- };
206
- }
207
- /**
208
- * Scan multiple files
209
- */
210
- async scanFiles(files) {
211
- const allFindings = [];
212
- for (const file of files) {
213
- const result = await this.scan(file.filepath, file.code);
214
- allFindings.push(...result.findings);
215
- }
216
- const criticalCount = allFindings.filter(f => f.severity === 'critical').length;
217
- const highCount = allFindings.filter(f => f.severity === 'high').length;
218
- const mediumCount = allFindings.filter(f => f.severity === 'medium').length;
219
- const lowCount = allFindings.filter(f => f.severity === 'low').length;
220
- const passed = criticalCount === 0 && highCount === 0;
221
- return {
222
- findings: allFindings,
223
- totalFindings: allFindings.length,
224
- criticalCount,
225
- highCount,
226
- mediumCount,
227
- lowCount,
228
- passed,
229
- };
230
- }
231
- /**
232
- * Analyze code with AI for security vulnerabilities
233
- */
234
- async analyzeWithAI(filepath, code) {
235
- const prompt = `Analyze the following code for security vulnerabilities. Focus on:
236
- - SQL Injection (CWE-89)
237
- - Cross-Site Scripting / XSS (CWE-79)
238
- - Code Injection (CWE-94, CWE-95) - including eval(), Function(), setTimeout/setInterval with user input
239
- - Command Injection (CWE-78)
240
- - Path Traversal (CWE-22)
241
- - Insecure Deserialization (CWE-502)
242
- - Authentication/Authorization flaws
243
- - Sensitive data exposure
244
- - Insecure dependencies
245
- - Dangerous JavaScript patterns: eval(), Function(), innerHTML with user input, dangerous regex
246
-
247
- Code from ${filepath}:
248
- \`\`\`
249
- ${code}
250
- \`\`\`
251
-
252
- Respond with a JSON array of findings. Each finding should have:
253
- - severity: "critical" | "high" | "medium" | "low"
254
- - category: e.g., "SQL Injection"
255
- - description: Brief description of the vulnerability
256
- - line: Line number (approximate)
257
- - recommendation: How to fix it
258
- - cwe: CWE identifier if applicable
259
-
260
- If no vulnerabilities found, return empty array [].
261
-
262
- JSON only, no other text:`;
263
- try {
264
- const response = await this.aiService.chat(prompt, []);
265
- // Extract JSON from response
266
- const jsonMatch = response.match(/\[[\s\S]*\]/);
267
- if (!jsonMatch) {
268
- return [];
269
- }
270
- const findings = JSON.parse(jsonMatch[0]);
271
- // Add filepath to each finding
272
- return findings.map(f => ({
273
- ...f,
274
- filepath,
275
- }));
276
- }
277
- catch (error) {
278
- console.warn('AI SAST analysis failed:', error);
279
- return [];
280
- }
281
- }
282
- /**
283
- * Check if code passes security gates
284
- */
285
- async passesSecurityGates(filepath, code) {
286
- const result = await this.scan(filepath, code);
287
- return result.passed;
288
- }
289
- }
290
- //# sourceMappingURL=ai-sast-scanner.js.map