codehere 0.2.1 → 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 +10 -49
  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 +334 -43
  33. package/dist/presentation/cli/commands/trust-command.js +115 -99
  34. package/dist/presentation/cli/error-display.js +17 -21
  35. package/dist/ui.js +17 -12
  36. package/package.json +35 -67
  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 -530
  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 -652
  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,329 +0,0 @@
1
- /**
2
- * Infrastructure: Context Compression Service
3
- *
4
- * Prevents context bloat through intelligent compression techniques
5
- * Research: Context bloat leads to escalating costs and degraded reliability
6
- *
7
- * Techniques:
8
- * 1. LLM Summarization: Compress large contexts into concise summaries
9
- * 2. Observation Masking: Remove redundant observations in ReAct loops
10
- * 3. Hybrid Memory: Combine transient (session) and persistent (long-term) memory
11
- * 4. Selective Context: Keep only most relevant chunks based on attention scores
12
- */
13
- /**
14
- * Context Compressor Service
15
- * Implements multiple compression techniques to prevent context bloat
16
- */
17
- export class ContextCompressor {
18
- aiService;
19
- constructor(aiService) {
20
- this.aiService = aiService;
21
- }
22
- /**
23
- * Compress context using multi-stage compression (selective + summarization)
24
- * OPTIMIZED: Multi-stage approach achieves 50%+ reduction
25
- */
26
- async compressWithSummarization(chunks, query, strategy) {
27
- const originalTokenCount = this.estimateTokens(chunks);
28
- if (originalTokenCount <= strategy.maxTokens) {
29
- // No compression needed
30
- return {
31
- chunks,
32
- memories: [],
33
- originalTokenCount,
34
- compressedTokenCount: originalTokenCount,
35
- reductionPercent: 0,
36
- strategy,
37
- };
38
- }
39
- // STAGE 1: Selective compression - keep only most relevant chunks
40
- // Target: Reduce to 70% of original (30% reduction)
41
- const targetAfterSelective = Math.floor(originalTokenCount * 0.7);
42
- const maxChunksAfterSelective = Math.ceil((chunks.length * targetAfterSelective) / originalTokenCount);
43
- const selectiveChunks = this.selectiveCompression(chunks, query, maxChunksAfterSelective);
44
- const selectiveTokenCount = this.estimateTokens(selectiveChunks);
45
- // If selective compression is enough, return early
46
- if (selectiveTokenCount <= strategy.maxTokens) {
47
- const reductionPercent = ((originalTokenCount - selectiveTokenCount) / originalTokenCount) * 100;
48
- return {
49
- chunks: selectiveChunks,
50
- memories: [],
51
- summary: `Selective compression: ${chunks.length} → ${selectiveChunks.length} chunks`,
52
- originalTokenCount,
53
- compressedTokenCount: selectiveTokenCount,
54
- reductionPercent,
55
- strategy,
56
- };
57
- }
58
- // STAGE 2: Code-aware preprocessing - remove comments, whitespace, etc.
59
- const preprocessedChunks = this.preprocessCode(selectiveChunks);
60
- const preprocessedTokenCount = this.estimateTokens(preprocessedChunks);
61
- // If preprocessing is enough, return
62
- if (preprocessedTokenCount <= strategy.maxTokens) {
63
- const reductionPercent = ((originalTokenCount - preprocessedTokenCount) / originalTokenCount) * 100;
64
- return {
65
- chunks: preprocessedChunks,
66
- memories: [],
67
- summary: `Preprocessed: removed comments/whitespace`,
68
- originalTokenCount,
69
- compressedTokenCount: preprocessedTokenCount,
70
- reductionPercent,
71
- strategy,
72
- };
73
- }
74
- // STAGE 3: LLM summarization - aggressive compression
75
- // Group chunks by file for better summarization
76
- const chunksByFile = this.groupChunksByFile(preprocessedChunks);
77
- const compressedChunks = [];
78
- for (const [filepath, fileChunks] of Object.entries(chunksByFile)) {
79
- const fileContent = fileChunks.map(c => c.content).join('\n\n---\n\n');
80
- if (strategy.preserveCode) {
81
- // Aggressive compression: Keep only essential code, summarize rest
82
- const summary = await this.summarizeFileContextAggressive(fileContent, query, filepath);
83
- compressedChunks.push({
84
- filepath,
85
- content: summary.summarized,
86
- score: fileChunks[0]?.score || 0.5,
87
- });
88
- }
89
- else {
90
- // Full summarization with aggressive target
91
- const summary = await this.summarizeFileContentAggressive(fileContent, query, filepath);
92
- compressedChunks.push({
93
- filepath,
94
- content: summary,
95
- score: fileChunks[0]?.score || 0.5,
96
- });
97
- }
98
- }
99
- const compressedTokenCount = this.estimateTokens(compressedChunks);
100
- const reductionPercent = ((originalTokenCount - compressedTokenCount) / originalTokenCount) * 100;
101
- return {
102
- chunks: compressedChunks,
103
- memories: [],
104
- summary: `Multi-stage compression: ${chunks.length} chunks, ${originalTokenCount} → ${compressedTokenCount} tokens (${reductionPercent.toFixed(1)}% reduction)`,
105
- originalTokenCount,
106
- compressedTokenCount,
107
- reductionPercent,
108
- strategy,
109
- };
110
- }
111
- /**
112
- * Mask observations in ReAct loops
113
- * Remove redundant observations while preserving critical information
114
- */
115
- maskObservations(observations, toolCalls, errors, mask) {
116
- let maskedObservations = [];
117
- let maskedToolCalls = [];
118
- let maskedErrors = [];
119
- // Keep only recent observations if masking enabled
120
- if (mask.observations) {
121
- maskedObservations = observations.slice(-mask.maxHistoryLength);
122
- }
123
- else {
124
- maskedObservations = observations;
125
- }
126
- // Always keep tool calls (they're compact)
127
- maskedToolCalls = mask.toolCalls ? toolCalls.slice(-mask.maxHistoryLength) : toolCalls;
128
- // Always keep errors (critical information)
129
- maskedErrors = mask.errors ? errors : errors;
130
- return {
131
- maskedObservations,
132
- maskedToolCalls,
133
- maskedErrors,
134
- };
135
- }
136
- /**
137
- * Compress memories by summarizing similar memories
138
- */
139
- async compressMemories(memories, query, maxMemories = 10) {
140
- if (memories.length <= maxMemories) {
141
- return memories;
142
- }
143
- // Group similar memories
144
- const grouped = this.groupSimilarMemories(memories);
145
- // Keep most relevant from each group
146
- const compressed = [];
147
- for (const group of grouped) {
148
- // Sort by relevance to query
149
- const relevant = group.sort((a, b) => {
150
- const aRelevance = this.calculateRelevance(a.description, query);
151
- const bRelevance = this.calculateRelevance(b.description, query);
152
- return bRelevance - aRelevance;
153
- });
154
- // Keep top 1-2 from each group
155
- compressed.push(...relevant.slice(0, Math.min(2, group.length)));
156
- if (compressed.length >= maxMemories) {
157
- break;
158
- }
159
- }
160
- return compressed.slice(0, maxMemories);
161
- }
162
- /**
163
- * Hybrid memory compression: Combine transient and persistent
164
- */
165
- createHybridContext(transientMemories, // Recent session memories
166
- persistentMemories, // Long-term memories
167
- query) {
168
- // Prioritize transient (more relevant to current session)
169
- const hybrid = [...transientMemories];
170
- // Add persistent only if they add new information
171
- for (const persistent of persistentMemories) {
172
- const isDuplicate = hybrid.some(t => this.calculateRelevance(t.description, persistent.description) > 0.8);
173
- if (!isDuplicate && this.calculateRelevance(persistent.description, query) > 0.5) {
174
- hybrid.push(persistent);
175
- }
176
- }
177
- return hybrid.slice(0, 20); // Limit total hybrid memories
178
- }
179
- /**
180
- * Selective context compression: Keep only most relevant chunks
181
- */
182
- selectiveCompression(chunks, query, maxChunks, attentionScores // Optional attention scores from visualizer
183
- ) {
184
- // Score chunks by relevance
185
- const scored = chunks.map(chunk => ({
186
- chunk,
187
- score: attentionScores?.get(chunk.filepath) ||
188
- this.calculateRelevance(chunk.content, query),
189
- }));
190
- // Sort by score and keep top N
191
- return scored
192
- .sort((a, b) => b.score - a.score)
193
- .slice(0, maxChunks)
194
- .map(s => s.chunk);
195
- }
196
- // Private helper methods
197
- /**
198
- * Preprocess code: remove comments, excessive whitespace, etc.
199
- * Achieves ~15-20% reduction without LLM calls
200
- */
201
- preprocessCode(chunks) {
202
- return chunks.map(chunk => {
203
- let content = chunk.content;
204
- // Remove single-line comments (// ...)
205
- content = content.replace(/\/\/.*$/gm, '');
206
- // Remove multi-line comments (/* ... */)
207
- content = content.replace(/\/\*[\s\S]*?\*\//g, '');
208
- // Remove excessive blank lines (more than 2 consecutive)
209
- content = content.replace(/\n{3,}/g, '\n\n');
210
- // Remove trailing whitespace
211
- content = content.split('\n').map(line => line.trimEnd()).join('\n');
212
- return {
213
- ...chunk,
214
- content: content.trim(),
215
- };
216
- });
217
- }
218
- async summarizeFileContext(content, query, filepath) {
219
- const prompt = `Summarize the context and comments in this code file, but keep the actual code intact.
220
-
221
- File: ${filepath}
222
- Query: ${query}
223
-
224
- Code:
225
- ${content}
226
-
227
- Return a summary that preserves code structure but compresses comments and context.`;
228
- const summary = await this.aiService.chat(prompt, []);
229
- return { summarized: summary || content };
230
- }
231
- /**
232
- * Aggressive summarization: Target 50%+ reduction
233
- */
234
- async summarizeFileContextAggressive(content, query, filepath) {
235
- const prompt = `Compress this code file aggressively while preserving functionality relevant to: ${query}
236
-
237
- File: ${filepath}
238
- Query: ${query}
239
-
240
- Code:
241
- ${content}
242
-
243
- Instructions:
244
- - Remove all comments and docstrings
245
- - Keep only code directly relevant to the query
246
- - Summarize helper functions in 1-2 lines
247
- - Preserve function signatures and critical logic
248
- - Target: 50%+ token reduction
249
-
250
- Return compressed code:`;
251
- const summary = await this.aiService.chat(prompt, []);
252
- return { summarized: summary || content };
253
- }
254
- async summarizeFileContent(content, query, filepath) {
255
- const prompt = `Provide a concise summary of this code file, focusing on how it relates to: ${query}
256
-
257
- File: ${filepath}
258
- Code:
259
- ${content}
260
-
261
- Return a brief summary (2-3 sentences) of the key functionality.`;
262
- const summary = await this.aiService.chat(prompt, []);
263
- return summary || content;
264
- }
265
- /**
266
- * Aggressive summarization: Target 50%+ reduction
267
- */
268
- async summarizeFileContentAggressive(content, query, filepath) {
269
- const prompt = `Provide an extremely concise summary (1-2 sentences) of this code file, focusing ONLY on: ${query}
270
-
271
- File: ${filepath}
272
- Code:
273
- ${content}
274
-
275
- Return ONLY the essential functionality relevant to the query. Be extremely brief.`;
276
- const summary = await this.aiService.chat(prompt, []);
277
- return summary || content;
278
- }
279
- groupChunksByFile(chunks) {
280
- const grouped = {};
281
- for (const chunk of chunks) {
282
- if (!grouped[chunk.filepath]) {
283
- grouped[chunk.filepath] = [];
284
- }
285
- grouped[chunk.filepath].push(chunk);
286
- }
287
- return grouped;
288
- }
289
- groupSimilarMemories(memories) {
290
- const groups = [];
291
- const processed = new Set();
292
- for (let i = 0; i < memories.length; i++) {
293
- if (processed.has(i))
294
- continue;
295
- const group = [memories[i]];
296
- processed.add(i);
297
- // Find similar memories
298
- for (let j = i + 1; j < memories.length; j++) {
299
- if (processed.has(j))
300
- continue;
301
- const similarity = this.calculateRelevance(memories[i].description, memories[j].description);
302
- if (similarity > 0.7) {
303
- group.push(memories[j]);
304
- processed.add(j);
305
- }
306
- }
307
- groups.push(group);
308
- }
309
- return groups;
310
- }
311
- calculateRelevance(text1, text2) {
312
- // Simple word overlap similarity (could be enhanced with embeddings)
313
- const words1 = new Set(text1.toLowerCase().split(/\s+/));
314
- const words2 = new Set(text2.toLowerCase().split(/\s+/));
315
- const intersection = new Set([...words1].filter(w => words2.has(w)));
316
- const union = new Set([...words1, ...words2]);
317
- return union.size > 0 ? intersection.size / union.size : 0;
318
- }
319
- estimateTokens(chunks) {
320
- // Improved estimation: Code has more tokens per character than prose
321
- // Average: ~3.5 characters per token for code, ~4 for prose
322
- return chunks.reduce((sum, chunk) => {
323
- const isCode = chunk.filepath.match(/\.(ts|js|py|java|cpp|go|rs)$/);
324
- const charsPerToken = isCode ? 3.5 : 4;
325
- return sum + Math.ceil(chunk.content.length / charsPerToken);
326
- }, 0);
327
- }
328
- }
329
- //# sourceMappingURL=context-compressor.js.map
@@ -1,128 +0,0 @@
1
- /**
2
- * Conversation Context Manager
3
- * Manages conversation history and context for session-aware interactions
4
- *
5
- * Phase 1: v0.5.0-alpha.0
6
- */
7
- /**
8
- * In-memory conversation context manager
9
- * Stores conversation history per session for reference resolution
10
- */
11
- class ConversationContextManager {
12
- sessions = new Map();
13
- maxHistoryPerSession = 50;
14
- /**
15
- * Get conversation history for a session
16
- */
17
- getHistory(sessionId, limit = 10) {
18
- const session = this.sessions.get(sessionId);
19
- if (!session) {
20
- return [];
21
- }
22
- // Return most recent turns, up to limit
23
- const turns = session.turns.slice(-limit);
24
- return turns.map(turn => ({
25
- query: turn.query,
26
- response: turn.response,
27
- timestamp: turn.timestamp,
28
- }));
29
- }
30
- /**
31
- * Resolve references in query (e.g., "it", "that", "the previous")
32
- */
33
- resolveReferences(sessionId, query) {
34
- const history = this.getHistory(sessionId, 3);
35
- if (history.length === 0) {
36
- return query;
37
- }
38
- // Simple reference resolution - replace common references
39
- let resolved = query;
40
- const lastTurn = history[history.length - 1];
41
- // Replace "it" with last mentioned entity/context
42
- if (/\bit\b/i.test(query) && lastTurn.response) {
43
- // Extract key entities from last response (simple heuristic)
44
- const lastResponse = lastTurn.response;
45
- const words = lastResponse.split(/\s+/).filter(w => w.length > 3);
46
- if (words.length > 0) {
47
- // Try to replace "it" with last significant noun phrase
48
- resolved = resolved.replace(/\bit\b/gi, words[words.length - 1]);
49
- }
50
- }
51
- // Replace "that" with last query
52
- if (/\bthat\b/i.test(query)) {
53
- resolved = resolved.replace(/\bthat\b/gi, `"${lastTurn.query}"`);
54
- }
55
- // Replace "the previous" with last query
56
- if (/\bthe previous\b/i.test(query)) {
57
- resolved = resolved.replace(/\bthe previous\b/gi, `"${lastTurn.query}"`);
58
- }
59
- return resolved;
60
- }
61
- /**
62
- * Extract entities from text (simple heuristic-based extraction)
63
- */
64
- extractEntities(text, options) {
65
- // Simple entity extraction - can be enhanced later
66
- const entities = [];
67
- // Extract file paths
68
- const filePathRegex = /[\w\/\-\.]+\.(ts|js|tsx|jsx|json|md|yaml|yml|txt|py|go|rs|java|cpp|h|hpp)/g;
69
- const filePaths = text.match(filePathRegex) || [];
70
- filePaths.forEach(path => {
71
- entities.push({ type: 'file', value: path });
72
- });
73
- // Extract function/class names (simple heuristic)
74
- const functionRegex = /(?:function|class|const|let|var)\s+([A-Z][a-zA-Z0-9_]+|[a-z][a-zA-Z0-9_]+)/g;
75
- const matches = text.matchAll(functionRegex);
76
- for (const match of matches) {
77
- entities.push({ type: 'symbol', value: match[1] });
78
- }
79
- return entities;
80
- }
81
- /**
82
- * Add a conversation turn
83
- */
84
- addTurn(sessionId, query, response, entities = [], intent) {
85
- let session = this.sessions.get(sessionId);
86
- if (!session) {
87
- session = {
88
- sessionId,
89
- turns: [],
90
- createdAt: Date.now(),
91
- lastUpdated: Date.now(),
92
- };
93
- this.sessions.set(sessionId, session);
94
- }
95
- const turn = {
96
- query,
97
- response,
98
- timestamp: new Date().toISOString(),
99
- entities,
100
- intent,
101
- };
102
- session.turns.push(turn);
103
- session.lastUpdated = Date.now();
104
- // Trim history if too long
105
- if (session.turns.length > this.maxHistoryPerSession) {
106
- session.turns = session.turns.slice(-this.maxHistoryPerSession);
107
- }
108
- }
109
- /**
110
- * Get full context for a session
111
- */
112
- getContext(sessionId) {
113
- return this.sessions.get(sessionId) || null;
114
- }
115
- /**
116
- * Clear conversation history for a session
117
- */
118
- clear(sessionId) {
119
- if (sessionId) {
120
- this.sessions.delete(sessionId);
121
- }
122
- else {
123
- this.sessions.clear();
124
- }
125
- }
126
- }
127
- export const conversationContextManager = new ConversationContextManager();
128
- //# sourceMappingURL=conversation-context.js.map
@@ -1,94 +0,0 @@
1
- /**
2
- * Session Manager
3
- * Manages CLI sessions for context tracking
4
- *
5
- * Phase 1: v0.5.0-alpha.0
6
- */
7
- /**
8
- * Session manager for tracking CLI sessions
9
- */
10
- class SessionManager {
11
- sessions = new Map();
12
- sessionTimeout = 24 * 60 * 60 * 1000; // 24 hours
13
- /**
14
- * Get or create session ID for a working directory
15
- */
16
- getSessionId(cwd) {
17
- // Normalize cwd path
18
- const normalizedCwd = cwd || process.cwd();
19
- // Check if session exists and is still valid
20
- const existingSession = this.sessions.get(normalizedCwd);
21
- if (existingSession) {
22
- const age = Date.now() - existingSession.lastActivity;
23
- if (age < this.sessionTimeout) {
24
- existingSession.lastActivity = Date.now();
25
- return existingSession.sessionId;
26
- }
27
- else {
28
- // Session expired, remove it
29
- this.sessions.delete(normalizedCwd);
30
- }
31
- }
32
- // Create new session
33
- const sessionId = `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
34
- const session = {
35
- sessionId,
36
- cwd: normalizedCwd,
37
- startedAt: Date.now(),
38
- lastActivity: Date.now(),
39
- };
40
- this.sessions.set(normalizedCwd, session);
41
- return sessionId;
42
- }
43
- /**
44
- * Get current session for a working directory
45
- */
46
- getCurrentSession(cwd) {
47
- const normalizedCwd = cwd || process.cwd();
48
- return this.sessions.get(normalizedCwd) || null;
49
- }
50
- /**
51
- * Create a new session explicitly
52
- */
53
- createSession(cwd) {
54
- const normalizedCwd = cwd || process.cwd();
55
- const sessionId = `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
56
- const session = {
57
- sessionId,
58
- cwd: normalizedCwd,
59
- startedAt: Date.now(),
60
- lastActivity: Date.now(),
61
- };
62
- this.sessions.set(normalizedCwd, session);
63
- return session;
64
- }
65
- /**
66
- * End a session
67
- */
68
- endSession(cwd) {
69
- const normalizedCwd = cwd || process.cwd();
70
- this.sessions.delete(normalizedCwd);
71
- }
72
- /**
73
- * Clean up expired sessions
74
- */
75
- cleanup() {
76
- const now = Date.now();
77
- for (const [cwd, session] of this.sessions.entries()) {
78
- const age = now - session.lastActivity;
79
- if (age >= this.sessionTimeout) {
80
- this.sessions.delete(cwd);
81
- }
82
- }
83
- }
84
- }
85
- export const sessionManager = new SessionManager();
86
- // Cleanup expired sessions periodically
87
- // Use .unref() to allow process to exit even with timer active
88
- if (typeof setInterval !== 'undefined') {
89
- const cleanupInterval = setInterval(() => {
90
- sessionManager.cleanup();
91
- }, 60 * 60 * 1000); // Every hour
92
- cleanupInterval.unref();
93
- }
94
- //# sourceMappingURL=session-manager.js.map