codehere 0.2.2 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) 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 +253 -1219
  5. package/dist/infrastructure/config/product-context.js +7 -6
  6. package/dist/infrastructure/hooks/claude-sdk-hook.js +335 -63
  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/generic-cli-adapter.js +553 -0
  16. package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
  17. package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
  18. package/dist/infrastructure/orchestration/readiness.js +106 -0
  19. package/dist/infrastructure/orchestration/session-manager.js +272 -0
  20. package/dist/infrastructure/orchestration/session-persistence.js +109 -0
  21. package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
  22. package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
  23. package/dist/infrastructure/protocols/ui-page.js +1827 -0
  24. package/dist/infrastructure/security/file-collection.js +115 -0
  25. package/dist/infrastructure/security/trust-scorer.js +301 -56
  26. package/dist/infrastructure/storage/task-repository.js +8 -7
  27. package/dist/monitoring.js +9 -38
  28. package/dist/presentation/cli/commands/help-command.js +96 -139
  29. package/dist/presentation/cli/commands/hook-command.js +17 -24
  30. package/dist/presentation/cli/commands/report-command.js +59 -72
  31. package/dist/presentation/cli/commands/setup-command.js +4 -4
  32. package/dist/presentation/cli/commands/status-command.js +321 -30
  33. package/dist/presentation/cli/commands/trust-command.js +84 -72
  34. package/dist/presentation/cli/error-display.js +17 -21
  35. package/dist/ui.js +11 -11
  36. package/package.json +24 -62
  37. package/dist/agents/base.js +0 -101
  38. package/dist/agents/orchestrator-model-driven.js +0 -141
  39. package/dist/agents/react-orchestrator-agent.js +0 -54
  40. package/dist/application/agents/execution-agent.js +0 -508
  41. package/dist/application/agents/multi-agent-orchestrator.js +0 -295
  42. package/dist/application/agents/planning-agent.js +0 -433
  43. package/dist/application/agents/validation-agent.js +0 -317
  44. package/dist/application/architectures/plan-and-act.js +0 -242
  45. package/dist/application/index.js +0 -12
  46. package/dist/application/services/agent-factory.js +0 -28
  47. package/dist/application/services/dependency-container.js +0 -596
  48. package/dist/application/services/git-context-service.js +0 -83
  49. package/dist/application/services/intelligent-router.js +0 -934
  50. package/dist/application/services/tool-executor-service.js +0 -94
  51. package/dist/application/use-cases/ask-question-use-case.js +0 -338
  52. package/dist/application/use-cases/edit-file-use-case.js +0 -830
  53. package/dist/application/use-cases/explain-file-use-case.js +0 -50
  54. package/dist/application/use-cases/index-codebase-use-case.js +0 -113
  55. package/dist/application/use-cases/planning-use-case.js +0 -276
  56. package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
  57. package/dist/application/use-cases/reflexion-use-case.js +0 -30
  58. package/dist/application/workflows/deterministic-workflows.js +0 -189
  59. package/dist/ast-parser.js +0 -331
  60. package/dist/cache.js +0 -180
  61. package/dist/chat.js +0 -251
  62. package/dist/code-analysis.js +0 -327
  63. package/dist/context.js +0 -187
  64. package/dist/docs.js +0 -146
  65. package/dist/domain/entities/code-chunk.js +0 -6
  66. package/dist/domain/entities/decision.js +0 -9
  67. package/dist/domain/entities/edit.js +0 -6
  68. package/dist/domain/entities/knowledge-node.js +0 -9
  69. package/dist/domain/entities/knowledge-preservation.js +0 -10
  70. package/dist/domain/entities/memory.js +0 -6
  71. package/dist/domain/entities/pattern.js +0 -7
  72. package/dist/domain/entities/plan.js +0 -6
  73. package/dist/domain/entities/query.js +0 -6
  74. package/dist/domain/errors/embeddings-not-found-error.js +0 -13
  75. package/dist/domain/index.js +0 -19
  76. package/dist/domain/interfaces/ai-service.interface.js +0 -6
  77. package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
  78. package/dist/domain/interfaces/decision-repository.interface.js +0 -9
  79. package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
  80. package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
  81. package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
  82. package/dist/domain/interfaces/memory-repository.interface.js +0 -6
  83. package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
  84. package/dist/domain/interfaces/verification-service.interface.js +0 -6
  85. package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
  86. package/dist/domain/services/decision-recorder.js +0 -223
  87. package/dist/domain/services/decision-retriever.js +0 -133
  88. package/dist/domain/services/environment-mode-manager.js +0 -22
  89. package/dist/domain/services/graded-memory-activation.js +0 -69
  90. package/dist/domain/services/knowledge-access.js +0 -132
  91. package/dist/domain/services/knowledge-extractor.js +0 -247
  92. package/dist/domain/services/knowledge-graph-builder.js +0 -268
  93. package/dist/domain/services/knowledge-graph-query.js +0 -187
  94. package/dist/domain/services/memory-retriever.js +0 -82
  95. package/dist/domain/services/memory-synthesizer.js +0 -91
  96. package/dist/domain/services/pattern-extractor.js +0 -442
  97. package/dist/domain/services/query-intent-classifier.js +0 -140
  98. package/dist/domain/services/react-loop.js +0 -186
  99. package/dist/domain/services/risk-tier-detector.js +0 -78
  100. package/dist/edit.js +0 -319
  101. package/dist/embed.js +0 -459
  102. package/dist/formatter.js +0 -168
  103. package/dist/git.js +0 -198
  104. package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
  105. package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
  106. package/dist/infrastructure/ai/model-config.js +0 -84
  107. package/dist/infrastructure/ai/provider-ai-service.js +0 -477
  108. package/dist/infrastructure/cache/embedding-cache.js +0 -175
  109. package/dist/infrastructure/cache/query-result-cache.js +0 -66
  110. package/dist/infrastructure/cache/response-cache.js +0 -48
  111. package/dist/infrastructure/cache/security-scan-cache.js +0 -47
  112. package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
  113. package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
  114. package/dist/infrastructure/context/context-compressor.js +0 -329
  115. package/dist/infrastructure/context/conversation-context.js +0 -128
  116. package/dist/infrastructure/context/session-manager.js +0 -94
  117. package/dist/infrastructure/cost/cost-tracker.js +0 -360
  118. package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
  119. package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
  120. package/dist/infrastructure/governance/policy-as-code.js +0 -258
  121. package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
  122. package/dist/infrastructure/index.js +0 -7
  123. package/dist/infrastructure/observability/prompt-versioner.js +0 -145
  124. package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
  125. package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
  126. package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
  127. package/dist/infrastructure/protocols/mcp-server.js +0 -333
  128. package/dist/infrastructure/protocols/streaming-handler.js +0 -103
  129. package/dist/infrastructure/providers/cohere-provider.js +0 -444
  130. package/dist/infrastructure/providers/fake-provider.js +0 -130
  131. package/dist/infrastructure/providers/local-llm-provider.js +0 -330
  132. package/dist/infrastructure/providers/model-config.types.js +0 -9
  133. package/dist/infrastructure/providers/model-provider.interface.js +0 -8
  134. package/dist/infrastructure/providers/openai-provider.js +0 -413
  135. package/dist/infrastructure/providers/openrouter-provider.js +0 -399
  136. package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
  137. package/dist/infrastructure/providers/provider-config-loader.js +0 -120
  138. package/dist/infrastructure/providers/provider-registry.js +0 -88
  139. package/dist/infrastructure/safety/pattern-detector.js +0 -133
  140. package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
  141. package/dist/infrastructure/security/docker-sandbox.js +0 -178
  142. package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
  143. package/dist/infrastructure/security/license-scanner.js +0 -167
  144. package/dist/infrastructure/security/provider-bias-detector.js +0 -164
  145. package/dist/infrastructure/security/sandbox-executor.js +0 -64
  146. package/dist/infrastructure/serialization/toon-serializer.js +0 -119
  147. package/dist/infrastructure/storage/memory-stream-service.js +0 -204
  148. package/dist/infrastructure/storage/plan-repository.js +0 -96
  149. package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
  150. package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
  151. package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
  152. package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
  153. package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
  154. package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
  155. package/dist/infrastructure/storage/task-helpers.js +0 -197
  156. package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
  157. package/dist/infrastructure/ux/appropriate-friction.js +0 -213
  158. package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
  159. package/dist/infrastructure/ux/capability-boundaries.js +0 -42
  160. package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
  161. package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
  162. package/dist/infrastructure/ux/expectation-management.js +0 -327
  163. package/dist/infrastructure/ux/feature-discovery.js +0 -14
  164. package/dist/infrastructure/ux/feedback-prompt.js +0 -45
  165. package/dist/infrastructure/ux/hitl-validation.js +0 -297
  166. package/dist/infrastructure/ux/progress-indicator.js +0 -116
  167. package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
  168. package/dist/infrastructure/ux/review-checkpoint.js +0 -72
  169. package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
  170. package/dist/infrastructure/ux/stream-markdown.js +0 -151
  171. package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
  172. package/dist/infrastructure/ux/team-standards.js +0 -196
  173. package/dist/infrastructure/ux/transparency.js +0 -71
  174. package/dist/infrastructure/validation/agent-feedback.js +0 -55
  175. package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
  176. package/dist/infrastructure/validation/review-handler.js +0 -40
  177. package/dist/infrastructure/validation/summary-aggregator.js +0 -70
  178. package/dist/infrastructure/validation/summary-extractor.js +0 -45
  179. package/dist/infrastructure/validation/trace-summary.js +0 -52
  180. package/dist/infrastructure/verification/verification-service.js +0 -47
  181. package/dist/infrastructure/xai/attention-visualizer.js +0 -172
  182. package/dist/infrastructure/xai/cot-visualizer.js +0 -283
  183. package/dist/infrastructure/xai/decision-tree-log.js +0 -212
  184. package/dist/infrastructure/xai/interactive-xai.js +0 -260
  185. package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
  186. package/dist/intelligent-retrieval.js +0 -272
  187. package/dist/intent/classifier.js +0 -2
  188. package/dist/intent/context.js +0 -2
  189. package/dist/iterative-refinement.js +0 -189
  190. package/dist/learning.js +0 -232
  191. package/dist/log.js +0 -31
  192. package/dist/migrate.js +0 -133
  193. package/dist/parallel-processor.js +0 -534
  194. package/dist/planner.js +0 -198
  195. package/dist/policy.js +0 -26
  196. package/dist/presentation/cli/commands/ask-command.js +0 -314
  197. package/dist/presentation/cli/commands/cost-command.js +0 -191
  198. package/dist/presentation/cli/commands/decision-command.js +0 -207
  199. package/dist/presentation/cli/commands/docs-command.js +0 -25
  200. package/dist/presentation/cli/commands/fix-command.js +0 -53
  201. package/dist/presentation/cli/commands/knowledge-command.js +0 -129
  202. package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
  203. package/dist/presentation/cli/commands/models-command.js +0 -194
  204. package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
  205. package/dist/presentation/cli/commands/plan-command.js +0 -246
  206. package/dist/presentation/cli/commands/product-command.js +0 -199
  207. package/dist/presentation/cli/commands/react-command.js +0 -181
  208. package/dist/presentation/cli/commands/review-command.js +0 -154
  209. package/dist/presentation/cli/commands/run-command.js +0 -188
  210. package/dist/presentation/cli/commands/smart-command.js +0 -395
  211. package/dist/presentation/cli/commands/suggest-command.js +0 -138
  212. package/dist/presentation/cli/commands/trace-command.js +0 -129
  213. package/dist/presentation/cli/commands/undo-command.js +0 -150
  214. package/dist/query-optimizer.js +0 -205
  215. package/dist/refactor.js +0 -116
  216. package/dist/review.js +0 -206
  217. package/dist/search.js +0 -163
  218. package/dist/session.js +0 -704
  219. package/dist/task-verification.js +0 -336
  220. package/dist/testgen.js +0 -166
  221. package/dist/token-optimizer.js +0 -277
  222. package/dist/tools/bash.js +0 -213
  223. package/dist/tools/edit.js +0 -235
  224. package/dist/tools/executor.js +0 -153
  225. package/dist/tools/git-tool.js +0 -292
  226. package/dist/tools/parser.js +0 -158
  227. package/dist/tools/registry.js +0 -302
  228. package/dist/tools/search.js +0 -100
  229. package/dist/types.js +0 -2
  230. package/dist/utils/check-api-status.js +0 -100
  231. package/dist/utils/diff-parser.js +0 -162
  232. package/dist/verification/backup.js +0 -259
  233. package/dist/verification/compiler.js +0 -264
  234. package/dist/verification/index.js +0 -273
  235. package/dist/verification/test-runner.js +0 -379
@@ -1,178 +0,0 @@
1
- /**
2
- * Infrastructure: Docker Sandbox Executor
3
- * Executes code in isolated Docker containers for security
4
- *
5
- * MANDATORY: All code execution must use this for security
6
- */
7
- import { exec } from 'child_process';
8
- import { promisify } from 'util';
9
- import { randomUUID } from 'crypto';
10
- import { writeFileSync, unlinkSync, existsSync, mkdirSync } from 'fs';
11
- import { join } from 'path';
12
- const execAsync = promisify(exec);
13
- export class DockerSandbox {
14
- DEFAULT_TIMEOUT = 30000; // 30 seconds
15
- DEFAULT_MEMORY = '512m';
16
- DEFAULT_CPU = '0.5';
17
- SANDBOX_IMAGE = 'node:18-alpine'; // Lightweight Node.js image
18
- TEMP_DIR = '/tmp/codehere-sandbox';
19
- constructor() {
20
- // Ensure temp directory exists
21
- if (!existsSync(this.TEMP_DIR)) {
22
- mkdirSync(this.TEMP_DIR, { recursive: true });
23
- }
24
- }
25
- /**
26
- * Execute code in isolated Docker container
27
- */
28
- async execute(code, language = 'bash', options = {}) {
29
- const startTime = Date.now();
30
- const containerId = randomUUID().substring(0, 8);
31
- const timeout = options.timeout || this.DEFAULT_TIMEOUT;
32
- try {
33
- // Create temporary file with code
34
- const tempFile = join(this.TEMP_DIR, `${containerId}.${this.getFileExtension(language)}`);
35
- writeFileSync(tempFile, code, 'utf-8');
36
- // Build Docker run command with security restrictions
37
- const dockerCommand = this.buildDockerCommand(containerId, tempFile, language, options);
38
- // Execute in Docker container with timeout
39
- const { stdout, stderr } = await Promise.race([
40
- execAsync(dockerCommand, { timeout }),
41
- this.createTimeout(timeout),
42
- ]);
43
- // Cleanup
44
- this.cleanup(containerId, tempFile);
45
- const duration = Date.now() - startTime;
46
- return {
47
- success: !stderr || stderr.length === 0,
48
- output: stdout,
49
- error: stderr || undefined,
50
- exitCode: 0,
51
- duration,
52
- };
53
- }
54
- catch (error) {
55
- // Cleanup on error
56
- this.cleanup(containerId, join(this.TEMP_DIR, `${containerId}.${this.getFileExtension(language)}`));
57
- const duration = Date.now() - startTime;
58
- if (error.code === 'ETIMEDOUT' || error.signal === 'SIGTERM') {
59
- return {
60
- success: false,
61
- output: '',
62
- error: `Execution timed out after ${timeout}ms`,
63
- exitCode: 124,
64
- duration,
65
- };
66
- }
67
- return {
68
- success: false,
69
- output: '',
70
- error: error.message || String(error),
71
- exitCode: error.code || 1,
72
- duration,
73
- };
74
- }
75
- }
76
- /**
77
- * Execute bash command in sandbox
78
- */
79
- async executeBash(command, options = {}) {
80
- // Use execute method with bash language
81
- return await this.execute(command, 'bash', options);
82
- }
83
- /**
84
- * Build Docker command with security restrictions
85
- */
86
- buildDockerCommand(containerId, codeFile, language, options) {
87
- const memory = options.memoryLimit || this.DEFAULT_MEMORY;
88
- const cpu = options.cpuLimit || this.DEFAULT_CPU;
89
- const network = options.networkAccess ? '' : '--network none';
90
- const readOnly = '--read-only';
91
- const tmpfs = '--tmpfs /tmp:rw,noexec,nosuid,size=100m';
92
- // Determine execution command based on language
93
- let execCommand;
94
- switch (language) {
95
- case 'javascript':
96
- case 'typescript':
97
- execCommand = `node /code/${containerId}.js`;
98
- break;
99
- case 'python':
100
- execCommand = `python /code/${containerId}.py`;
101
- break;
102
- case 'bash':
103
- default:
104
- execCommand = `sh /code/${containerId}.sh`;
105
- break;
106
- }
107
- // Copy code file into container and execute
108
- const dockerCommand = `docker run --rm \
109
- --name codehere-sandbox-${containerId} \
110
- --memory ${memory} \
111
- --cpus ${cpu} \
112
- ${network} \
113
- ${readOnly} \
114
- ${tmpfs} \
115
- --security-opt no-new-privileges:true \
116
- --cap-drop ALL \
117
- --user 1000:1000 \
118
- -v ${codeFile}:/code/${containerId}.${this.getFileExtension(language)}:ro \
119
- ${this.SANDBOX_IMAGE} \
120
- ${execCommand}`;
121
- return dockerCommand;
122
- }
123
- /**
124
- * Get file extension for language
125
- */
126
- getFileExtension(language) {
127
- const extensions = {
128
- javascript: 'js',
129
- typescript: 'ts',
130
- python: 'py',
131
- bash: 'sh',
132
- };
133
- return extensions[language] || 'sh';
134
- }
135
- /**
136
- * Create timeout promise
137
- */
138
- createTimeout(ms) {
139
- return new Promise((_, reject) => {
140
- setTimeout(() => reject(new Error('Timeout')), ms);
141
- });
142
- }
143
- /**
144
- * Cleanup container and temp files
145
- */
146
- async cleanup(containerId, tempFile) {
147
- try {
148
- // Try to stop container if still running
149
- try {
150
- await execAsync(`docker stop codehere-sandbox-${containerId} 2>/dev/null || true`);
151
- }
152
- catch {
153
- // Container already stopped or doesn't exist
154
- }
155
- // Remove temp file
156
- if (existsSync(tempFile)) {
157
- unlinkSync(tempFile);
158
- }
159
- }
160
- catch (error) {
161
- // Log but don't fail on cleanup errors
162
- console.warn('Sandbox cleanup warning:', error);
163
- }
164
- }
165
- /**
166
- * Check if Docker is available
167
- */
168
- async isAvailable() {
169
- try {
170
- await execAsync('docker --version');
171
- return true;
172
- }
173
- catch {
174
- return false;
175
- }
176
- }
177
- }
178
- //# sourceMappingURL=docker-sandbox.js.map
@@ -1,151 +0,0 @@
1
- /**
2
- * Infrastructure: Enhanced Security Gate
3
- * Comprehensive security validation combining all security scanners
4
- *
5
- * Research-Driven Security:
6
- * - AI SAST Scanner (existing) - 45% of AI code has flaws
7
- * - License Scanner - 35% license contamination risk
8
- * - Provider Bias Detector - Vendor lock-in prevention
9
- * - Uncertainty Quantifier - Hallucination risk
10
- *
11
- * All checks must pass before code generation/editing
12
- */
13
- import { getSecurityScanCache } from '../cache/security-scan-cache.js';
14
- /**
15
- * Enhanced Security Gate
16
- * Orchestrates all security scanners
17
- */
18
- export class EnhancedSecurityGate {
19
- sastScanner;
20
- licenseScanner;
21
- providerBiasDetector;
22
- uncertaintyQuantifier;
23
- scanCache = getSecurityScanCache();
24
- constructor(sastScanner, licenseScanner, providerBiasDetector, uncertaintyQuantifier) {
25
- this.sastScanner = sastScanner;
26
- this.licenseScanner = licenseScanner;
27
- this.providerBiasDetector = providerBiasDetector;
28
- this.uncertaintyQuantifier = uncertaintyQuantifier;
29
- }
30
- /**
31
- * Comprehensive security scan
32
- * PERFORMANCE OPTIMIZATION: Parallelizes independent scans for ~3x speedup
33
- */
34
- async scan(filepath, code, instruction, context) {
35
- const errors = [];
36
- const warnings = [];
37
- // PERFORMANCE: Check cache first (bypasses expensive scans for unchanged files)
38
- const cachedResults = this.scanCache.get(filepath, code);
39
- if (cachedResults) {
40
- // Return cached results (skip expensive scans)
41
- const passed = cachedResults.sast.passed && cachedResults.license.passed;
42
- if (!cachedResults.sast.passed) {
43
- errors.push(`Security vulnerabilities: ${cachedResults.sast.criticalCount} critical, ${cachedResults.sast.highCount} high`);
44
- }
45
- if (!cachedResults.license.passed) {
46
- errors.push(`License conflicts: ${cachedResults.license.criticalCount} critical issues`);
47
- }
48
- if (!cachedResults.providerBias.passed) {
49
- warnings.push(`Provider bias detected: ${cachedResults.providerBias.criticalCount} critical issues`);
50
- }
51
- // Still run uncertainty quantification if needed (it's fast and context-dependent)
52
- let uncertainty;
53
- if (this.uncertaintyQuantifier && context?.query && code) {
54
- uncertainty = await this.uncertaintyQuantifier.quantifyUncertainty(context.query, code, { chunks: context.chunks }).catch(() => undefined);
55
- if (uncertainty?.isHallucinationRisk) {
56
- warnings.push(`High epistemic uncertainty detected: Possible hallucination risk`);
57
- }
58
- }
59
- return {
60
- passed: errors.length === 0,
61
- sast: cachedResults.sast,
62
- license: cachedResults.license,
63
- providerBias: cachedResults.providerBias,
64
- uncertainty,
65
- errors,
66
- warnings,
67
- };
68
- }
69
- // PERFORMANCE: Parallelize independent scans (SAST, License, Provider Bias)
70
- // These scans are independent and can run concurrently
71
- const scanPromises = [
72
- // 1. Fast security check on instruction (if provided)
73
- instruction
74
- ? this.sastScanner.scanInstruction(instruction).catch(err => {
75
- console.warn(`[EnhancedSecurityGate] Instruction scan failed: ${err instanceof Error ? err.message : String(err)}`);
76
- return null;
77
- })
78
- : Promise.resolve(null),
79
- // 2. SAST scan on code
80
- this.sastScanner.scan(filepath, code).catch(err => {
81
- console.warn(`[EnhancedSecurityGate] SAST scan failed: ${err instanceof Error ? err.message : String(err)}`);
82
- return { passed: true, findings: [], criticalCount: 0, highCount: 0 };
83
- }),
84
- // 3. License scan
85
- this.licenseScanner.scan(filepath, code).catch(err => {
86
- console.warn(`[EnhancedSecurityGate] License scan failed: ${err instanceof Error ? err.message : String(err)}`);
87
- return { passed: true, findings: [], criticalCount: 0 };
88
- }),
89
- // 4. Provider bias detection
90
- this.providerBiasDetector.scan(filepath, code).catch(err => {
91
- console.warn(`[EnhancedSecurityGate] Provider bias scan failed: ${err instanceof Error ? err.message : String(err)}`);
92
- return { passed: true, findings: [], criticalCount: 0 };
93
- }),
94
- ];
95
- // Execute all scans in parallel
96
- const [instructionSast, sast, license, providerBias] = await Promise.all(scanPromises);
97
- // Process results
98
- if (instructionSast && !instructionSast.passed) {
99
- errors.push(`Security vulnerabilities in instruction: ${instructionSast.findings.length} findings`);
100
- }
101
- if (!sast.passed) {
102
- errors.push(`Security vulnerabilities: ${sast.criticalCount} critical, ${sast.highCount} high`);
103
- }
104
- if (!license.passed) {
105
- errors.push(`License conflicts: ${license.criticalCount} critical issues`);
106
- }
107
- if (!providerBias.passed) {
108
- warnings.push(`Provider bias detected: ${providerBias.criticalCount} critical issues`);
109
- // Provider bias is a warning, not blocking (unless policy enforces)
110
- }
111
- // 5. Uncertainty quantification (runs after parallel scans, depends on context)
112
- // This is independent but typically faster, so can run in parallel with scans if needed
113
- let uncertainty;
114
- if (this.uncertaintyQuantifier && context?.query && code) {
115
- uncertainty = await this.uncertaintyQuantifier.quantifyUncertainty(context.query, code, { chunks: context.chunks }).catch(err => {
116
- console.warn(`[EnhancedSecurityGate] Uncertainty quantification failed: ${err instanceof Error ? err.message : String(err)}`);
117
- return undefined;
118
- });
119
- if (uncertainty?.isHallucinationRisk) {
120
- warnings.push(`High epistemic uncertainty detected: Possible hallucination risk`);
121
- }
122
- }
123
- const passed = errors.length === 0; // Only fail on critical errors
124
- // Cache results for future use (performance optimization)
125
- this.scanCache.set(filepath, code, sast, license, providerBias);
126
- return {
127
- passed,
128
- sast,
129
- license,
130
- providerBias,
131
- uncertainty,
132
- errors,
133
- warnings,
134
- };
135
- }
136
- /**
137
- * Fast pre-check on instruction (before expensive operations)
138
- */
139
- async fastCheck(instruction) {
140
- const findings = [];
141
- const sastResult = await this.sastScanner.scanInstruction(instruction);
142
- if (sastResult && !sastResult.passed) {
143
- findings.push(...sastResult.findings.map(f => `${f.severity}: ${f.description}`));
144
- }
145
- return {
146
- allowed: findings.length === 0,
147
- findings,
148
- };
149
- }
150
- }
151
- //# sourceMappingURL=enhanced-security-gate.js.map
@@ -1,167 +0,0 @@
1
- /**
2
- * Infrastructure: License Scanner
3
- * Detects license contamination in AI-generated code
4
- *
5
- * Research Finding: 35% of AI-generated code contains license irregularities
6
- * Critical for preventing IP contamination and legal liability
7
- *
8
- * Based on research: AI Ethics for Coding Assistants
9
- * - GPL/MIT/Apache conflicts are common
10
- * - Automated detection prevents legal liability
11
- * - Must integrate into CI/CD pipeline
12
- */
13
- /**
14
- * License Compatibility Matrix
15
- * Based on common open-source license compatibility rules
16
- */
17
- const LICENSE_COMPATIBILITY = {
18
- // GPL is incompatible with most proprietary licenses
19
- 'GPL-2.0': ['proprietary', 'Apache-2.0'], // GPL-2.0 incompatible with Apache-2.0
20
- 'GPL-3.0': ['proprietary', 'Apache-2.0'],
21
- // MIT is permissive and compatible with most
22
- 'MIT': [], // MIT is compatible with everything
23
- // Apache-2.0 is compatible with most except GPL-2.0
24
- 'Apache-2.0': ['GPL-2.0'],
25
- // BSD is permissive
26
- 'BSD-2-Clause': [],
27
- 'BSD-3-Clause': [],
28
- };
29
- /**
30
- * License Scanner
31
- * Scans code for license headers and detects conflicts
32
- */
33
- export class LicenseScanner {
34
- /**
35
- * Scan code for license information
36
- */
37
- async scan(filepath, code) {
38
- const findings = [];
39
- const detectedLicenses = new Set();
40
- // 1. Detect license headers in code
41
- const licenseHeaders = this.detectLicenseHeaders(code);
42
- // 2. Check for license conflicts
43
- for (const detectedLicense of licenseHeaders) {
44
- detectedLicenses.add(detectedLicense);
45
- // Check compatibility with other detected licenses
46
- for (const otherLicense of licenseHeaders) {
47
- if (detectedLicense !== otherLicense) {
48
- const incompatibilities = LICENSE_COMPATIBILITY[detectedLicense] || [];
49
- if (incompatibilities.includes(otherLicense)) {
50
- findings.push({
51
- license: detectedLicense,
52
- filepath,
53
- conflictType: 'incompatible',
54
- description: `License conflict: ${detectedLicense} is incompatible with ${otherLicense}`,
55
- recommendation: `Remove one of the conflicting licenses or use a compatible license`,
56
- severity: 'critical',
57
- });
58
- }
59
- }
60
- }
61
- }
62
- // 3. Check for missing licenses in generated code
63
- // If code appears to use open-source patterns but has no license, warn
64
- if (licenseHeaders.length === 0 && this.hasOpenSourcePatterns(code)) {
65
- findings.push({
66
- license: 'unknown',
67
- filepath,
68
- conflictType: 'missing',
69
- description: 'Generated code may contain open-source patterns but no license header detected',
70
- recommendation: 'Add appropriate license header or clarify license status',
71
- severity: 'medium',
72
- });
73
- }
74
- // 4. Check for ambiguous license statements
75
- const ambiguousLicenses = this.detectAmbiguousLicenses(code);
76
- for (const ambiguous of ambiguousLicenses) {
77
- findings.push({
78
- license: ambiguous,
79
- filepath,
80
- conflictType: 'ambiguous',
81
- description: `Ambiguous license statement detected: ${ambiguous}`,
82
- recommendation: 'Clarify license type explicitly',
83
- severity: 'low',
84
- });
85
- }
86
- const criticalCount = findings.filter(f => f.severity === 'critical').length;
87
- const licenseSummary = {};
88
- detectedLicenses.forEach(license => {
89
- licenseSummary[license] = (licenseSummary[license] || 0) + 1;
90
- });
91
- return {
92
- findings,
93
- totalFindings: findings.length,
94
- criticalCount,
95
- passed: criticalCount === 0,
96
- licenseSummary,
97
- };
98
- }
99
- /**
100
- * Detect license headers in code
101
- */
102
- detectLicenseHeaders(code) {
103
- const licenses = [];
104
- const upperCode = code.toUpperCase();
105
- // Common license patterns
106
- const patterns = [
107
- { pattern: /GPL.*?v?[23]/i, license: 'GPL-3.0' },
108
- { pattern: /GNU.*?GENERAL.*?PUBLIC.*?LICENSE/i, license: 'GPL-3.0' },
109
- { pattern: /MIT.*?LICENSE/i, license: 'MIT' },
110
- { pattern: /THE.*?MIT.*?LICENSE/i, license: 'MIT' },
111
- { pattern: /APACHE.*?LICENSE.*?v?2/i, license: 'Apache-2.0' },
112
- { pattern: /BSD.*?LICENSE/i, license: 'BSD-3-Clause' },
113
- { pattern: /BSD.*?2.*?CLAUSE/i, license: 'BSD-2-Clause' },
114
- { pattern: /ISC.*?LICENSE/i, license: 'ISC' },
115
- { pattern: /PROPRIETARY/i, license: 'proprietary' },
116
- ];
117
- for (const { pattern, license } of patterns) {
118
- if (pattern.test(code)) {
119
- licenses.push(license);
120
- }
121
- }
122
- return [...new Set(licenses)]; // Remove duplicates
123
- }
124
- /**
125
- * Check if code has open-source patterns (might need license)
126
- */
127
- hasOpenSourcePatterns(code) {
128
- // Patterns that suggest open-source code
129
- const patterns = [
130
- /copyright/i,
131
- /license/i,
132
- /github\.com/i,
133
- /npm/i,
134
- /import.*from.*['"]/i,
135
- /require\(/i,
136
- ];
137
- return patterns.some(pattern => pattern.test(code));
138
- }
139
- /**
140
- * Detect ambiguous license statements
141
- */
142
- detectAmbiguousLicenses(code) {
143
- const ambiguous = [];
144
- // Ambiguous patterns
145
- if (/open.*?source/i.test(code) && !this.hasExplicitLicense(code)) {
146
- ambiguous.push('open-source (unclear)');
147
- }
148
- if (/free.*?software/i.test(code) && !this.hasExplicitLicense(code)) {
149
- ambiguous.push('free software (unclear)');
150
- }
151
- return ambiguous;
152
- }
153
- /**
154
- * Check if code has explicit license statement
155
- */
156
- hasExplicitLicense(code) {
157
- const explicitPatterns = [
158
- /MIT/i,
159
- /GPL/i,
160
- /Apache/i,
161
- /BSD/i,
162
- /LICENSE.*?FILE/i,
163
- ];
164
- return explicitPatterns.some(pattern => pattern.test(code));
165
- }
166
- }
167
- //# sourceMappingURL=license-scanner.js.map
@@ -1,164 +0,0 @@
1
- /**
2
- * Infrastructure: Provider Bias Detector
3
- * Detects vendor-specific SDK/API usage that creates vendor lock-in
4
- *
5
- * Research Finding: LLMs systematically favor Google/Amazon services
6
- * This creates structural vendor lock-in and violates neutrality
7
- *
8
- * Based on research: AI Ethics for Coding Assistants
9
- * - Provider bias detected in LLM outputs
10
- * - Creates vendor lock-in risk
11
- * - Must audit and enforce vendor neutrality
12
- */
13
- /**
14
- * Provider-specific patterns
15
- * Maps common provider services to vendor names
16
- */
17
- const PROVIDER_PATTERNS = {
18
- google: {
19
- provider: 'Google Cloud',
20
- services: [
21
- /@google-cloud\//i,
22
- /google\.cloud\./i,
23
- /googleapis\.com/i,
24
- /firebase/i,
25
- /gcp/i,
26
- /cloud\.google\.com/i,
27
- ],
28
- },
29
- amazon: {
30
- provider: 'Amazon Web Services',
31
- services: [
32
- /@aws-sdk\//i,
33
- /aws\./i,
34
- /amazonaws\.com/i,
35
- /lambda/i,
36
- /s3/i,
37
- /dynamodb/i,
38
- /@aws-amplify/i,
39
- ],
40
- },
41
- microsoft: {
42
- provider: 'Microsoft Azure',
43
- services: [
44
- /@azure\//i,
45
- /azure\./i,
46
- /azurewebsites\.net/i,
47
- /blob\.core\.windows\.net/i,
48
- /@microsoft\/azure/i,
49
- ],
50
- },
51
- };
52
- /**
53
- * Provider Bias Detector
54
- * Scans code for provider-specific dependencies and flags vendor lock-in risks
55
- */
56
- export class ProviderBiasDetector {
57
- allowedProviders; // If set, only these providers are allowed
58
- constructor(allowedProviders) {
59
- this.allowedProviders = allowedProviders;
60
- }
61
- /**
62
- * Scan code for provider bias
63
- */
64
- async scan(filepath, code) {
65
- const findings = [];
66
- const providerCounts = {};
67
- // 1. Detect provider-specific services
68
- const detectedProviders = this.detectProviders(code);
69
- // 2. Count provider usage
70
- for (const provider of detectedProviders) {
71
- providerCounts[provider] = (providerCounts[provider] || 0) + 1;
72
- }
73
- // 3. Check for vendor lock-in patterns
74
- if (Object.keys(providerCounts).length > 0) {
75
- // Check if only one provider is used (lock-in risk)
76
- const uniqueProviders = Object.keys(providerCounts);
77
- if (uniqueProviders.length === 1 && !this.allowedProviders?.includes(uniqueProviders[0])) {
78
- findings.push({
79
- provider: uniqueProviders[0],
80
- service: 'multiple',
81
- filepath,
82
- description: `Code exclusively uses ${uniqueProviders[0]} services, creating vendor lock-in risk`,
83
- recommendation: `Consider vendor-neutral alternatives or multi-cloud architecture to maintain flexibility`,
84
- severity: 'high',
85
- });
86
- }
87
- // Check if provider is not in allowed list
88
- if (this.allowedProviders && uniqueProviders.length > 0) {
89
- for (const provider of uniqueProviders) {
90
- if (!this.allowedProviders.includes(provider)) {
91
- findings.push({
92
- provider,
93
- service: 'multiple',
94
- filepath,
95
- description: `Provider ${provider} is not in allowed providers list`,
96
- recommendation: `Use an allowed provider or update policy to allow ${provider}`,
97
- severity: 'critical',
98
- });
99
- }
100
- }
101
- }
102
- }
103
- // 4. Check for provider-specific hardcoding
104
- const hardcodedServices = this.detectHardcodedServices(code);
105
- for (const service of hardcodedServices) {
106
- findings.push({
107
- provider: service.provider,
108
- service: service.name,
109
- filepath,
110
- description: `Hardcoded ${service.provider} service: ${service.name}`,
111
- recommendation: `Use environment variables or configuration to make service provider configurable`,
112
- severity: 'medium',
113
- });
114
- }
115
- const criticalCount = findings.filter(f => f.severity === 'critical').length;
116
- return {
117
- findings,
118
- totalFindings: findings.length,
119
- criticalCount,
120
- providerSummary: providerCounts,
121
- passed: criticalCount === 0,
122
- };
123
- }
124
- /**
125
- * Detect provider-specific services in code
126
- */
127
- detectProviders(code) {
128
- const providers = [];
129
- for (const [key, { provider, services }] of Object.entries(PROVIDER_PATTERNS)) {
130
- for (const pattern of services) {
131
- if (pattern.test(code)) {
132
- providers.push(provider);
133
- break; // Found this provider, move to next
134
- }
135
- }
136
- }
137
- return [...new Set(providers)]; // Remove duplicates
138
- }
139
- /**
140
- * Detect hardcoded service endpoints/configurations
141
- */
142
- detectHardcodedServices(code) {
143
- const hardcoded = [];
144
- // Hardcoded endpoints
145
- const endpointPatterns = [
146
- { pattern: /https?:\/\/.*\.amazonaws\.com/i, provider: 'Amazon Web Services', name: 'AWS endpoint' },
147
- { pattern: /https?:\/\/.*\.googleapis\.com/i, provider: 'Google Cloud', name: 'Google API endpoint' },
148
- { pattern: /https?:\/\/.*\.azurewebsites\.net/i, provider: 'Microsoft Azure', name: 'Azure endpoint' },
149
- ];
150
- for (const { pattern, provider, name } of endpointPatterns) {
151
- if (pattern.test(code)) {
152
- hardcoded.push({ provider, name });
153
- }
154
- }
155
- return hardcoded;
156
- }
157
- /**
158
- * Set allowed providers (enforces vendor neutrality policy)
159
- */
160
- setAllowedProviders(providers) {
161
- this.allowedProviders = providers;
162
- }
163
- }
164
- //# sourceMappingURL=provider-bias-detector.js.map