codehere 0.2.2 → 0.3.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +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/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,94 +0,0 @@
1
- /**
2
- * Application Service: ToolExecutorService
3
- * Wraps tool executor for ReAct loop integration
4
- */
5
- import { ToolExecutor } from '../../tools/executor.js';
6
- import { getToolRegistry } from '../../tools/registry.js';
7
- export class ToolExecutorService {
8
- executor;
9
- constructor() {
10
- this.executor = new ToolExecutor();
11
- }
12
- /**
13
- * Execute action from ReAct loop
14
- */
15
- async executeAction(action) {
16
- if (action.type === 'tool') {
17
- try {
18
- const toolRegistry = getToolRegistry();
19
- const tool = toolRegistry.get(action.name);
20
- if (!tool) {
21
- return {
22
- result: null,
23
- success: false,
24
- error: `Tool "${action.name}" not found. Available: ${toolRegistry.getAll().map(t => t.name).join(', ')}`,
25
- };
26
- }
27
- // Convert action parameters to tool call format
28
- const toolCall = {
29
- tool: action.name,
30
- parameters: action.parameters || {},
31
- };
32
- const result = await this.executor.execute(toolCall);
33
- // Ensure structured output (JSON format)
34
- // All tools must return { success: boolean, result?: any, error?: string }
35
- if (!result || typeof result !== 'object') {
36
- return {
37
- result: null,
38
- success: false,
39
- error: `Tool "${action.name}" returned invalid output: expected object, got ${typeof result}`,
40
- };
41
- }
42
- // Validate required fields
43
- if (typeof result.success !== 'boolean') {
44
- return {
45
- result: null,
46
- success: false,
47
- error: `Tool "${action.name}" returned invalid output: missing or invalid "success" field`,
48
- };
49
- }
50
- // Format result for observation (preserve structure)
51
- let formattedResult = result.result;
52
- // If result is an object with specific structure, extract key info for display
53
- // But preserve full structure in result
54
- if (result.result && typeof result.result === 'object') {
55
- // Keep full object structure for tool chaining
56
- formattedResult = result.result;
57
- }
58
- // Return structured observation
59
- return {
60
- result: formattedResult,
61
- success: result.success,
62
- error: result.error || (result.success ? undefined : 'Tool execution failed'),
63
- };
64
- }
65
- catch (error) {
66
- return {
67
- result: null,
68
- success: false,
69
- error: error instanceof Error ? error.message : String(error),
70
- };
71
- }
72
- }
73
- if (action.type === 'agent') {
74
- // TODO: Wire up agent calls
75
- return {
76
- result: `Agent "${action.name}" called (not yet implemented)`,
77
- success: false,
78
- error: 'Agent calls not yet integrated',
79
- };
80
- }
81
- if (action.type === 'answer') {
82
- return {
83
- result: action.parameters?.answer || 'No answer provided',
84
- success: true,
85
- };
86
- }
87
- return {
88
- result: null,
89
- success: false,
90
- error: `Unknown action type: ${action.type}`,
91
- };
92
- }
93
- }
94
- //# sourceMappingURL=tool-executor-service.js.map
@@ -1,338 +0,0 @@
1
- /**
2
- * Application Use Case: AskQuestionUseCase
3
- * Handles the "ask" command - answers questions about codebase
4
- */
5
- import { MemoryRetriever } from '../../domain/services/memory-retriever.js';
6
- import { getEmbeddingCache } from '../../infrastructure/cache/embedding-cache.js';
7
- import { getQueryResultCache } from '../../infrastructure/cache/query-result-cache.js';
8
- import { getResponseCache } from '../../infrastructure/cache/response-cache.js';
9
- export class AskQuestionUseCase {
10
- embeddingRepository;
11
- aiService;
12
- memoryRepository;
13
- uncertaintyQuantifier;
14
- memoryRetriever;
15
- embeddingCache = getEmbeddingCache();
16
- queryResultCache = getQueryResultCache();
17
- responseCache = getResponseCache();
18
- constructor(embeddingRepository, aiService, memoryRepository, uncertaintyQuantifier) {
19
- this.embeddingRepository = embeddingRepository;
20
- this.aiService = aiService;
21
- this.memoryRepository = memoryRepository;
22
- this.uncertaintyQuantifier = uncertaintyQuantifier;
23
- this.memoryRetriever = new MemoryRetriever();
24
- }
25
- async execute(request) {
26
- // 0. Check if query is git-related and use git tool directly
27
- const gitKeywords = ['git', 'modified', 'changed', 'status', 'commit', 'branch', 'diff', 'staged', 'untracked'];
28
- const isGitQuery = gitKeywords.some(keyword => request.query.toLowerCase().includes(keyword));
29
- if (isGitQuery) {
30
- try {
31
- const { GitTool } = await import('../../tools/git-tool.js');
32
- // Use process.cwd() for working directory (request doesn't have context property)
33
- const gitTool = new GitTool(process.cwd());
34
- // Check if it's a git repository first
35
- const isRepo = await gitTool.isRepository();
36
- if (!isRepo) {
37
- return {
38
- answer: 'This directory is not a Git repository. Initialize a Git repository first with `git init`.',
39
- chunks: [],
40
- memories: [],
41
- };
42
- }
43
- const gitStatus = await gitTool.status();
44
- // Format git status response
45
- let gitAnswer = `Git Repository Status:\n`;
46
- gitAnswer += `Branch: ${gitStatus.branch}\n\n`;
47
- if (gitStatus.modified.length > 0) {
48
- gitAnswer += `Modified files:\n${gitStatus.modified.map(f => ` - ${f}`).join('\n')}\n\n`;
49
- }
50
- if (gitStatus.staged.length > 0) {
51
- gitAnswer += `Staged files:\n${gitStatus.staged.map(f => ` - ${f}`).join('\n')}\n\n`;
52
- }
53
- if (gitStatus.untracked.length > 0) {
54
- gitAnswer += `Untracked files:\n${gitStatus.untracked.map(f => ` - ${f}`).join('\n')}\n\n`;
55
- }
56
- if (gitStatus.modified.length === 0 && gitStatus.staged.length === 0 && gitStatus.untracked.length === 0) {
57
- gitAnswer += `No changes detected. Working directory is clean.`;
58
- }
59
- return {
60
- answer: gitAnswer,
61
- chunks: [],
62
- memories: [],
63
- };
64
- }
65
- catch (error) {
66
- // Fallback to regular search if git tool fails
67
- // Log error for debugging but don't show to user
68
- const errorMessage = error instanceof Error ? error.message : String(error);
69
- console.warn('[AskQuestionUseCase] Git tool failed, falling back to regular search:', errorMessage);
70
- // Continue to regular search flow below
71
- }
72
- }
73
- // 1. Generate query embedding using search_query input type (better matching!)
74
- // Performance: Check cache first to avoid redundant API calls
75
- const embeddingStart = Date.now();
76
- let queryEmbedding = this.embeddingCache.get(request.query);
77
- const embeddingCacheTime = Date.now() - embeddingStart;
78
- let embeddingGenTime = 0;
79
- if (!queryEmbedding) {
80
- const genStart = Date.now();
81
- // Use embedQuery if available, fallback to embed for backward compatibility
82
- if ('embedQuery' in this.aiService && typeof this.aiService.embedQuery === 'function') {
83
- const embedding = await this.aiService.embedQuery(request.query);
84
- queryEmbedding = Array.isArray(embedding) && !Array.isArray(embedding[0]) ? embedding : null;
85
- }
86
- else {
87
- const embedding = await this.aiService.embed(request.query);
88
- if (Array.isArray(embedding[0])) {
89
- throw new Error('Expected single embedding vector');
90
- }
91
- queryEmbedding = embedding;
92
- }
93
- embeddingGenTime = Date.now() - genStart;
94
- if (!queryEmbedding) {
95
- throw new Error('Failed to generate query embedding');
96
- }
97
- // Cache the embedding for future use
98
- this.embeddingCache.set(request.query, queryEmbedding);
99
- }
100
- // Ensure we have a valid embedding
101
- if (!queryEmbedding) {
102
- throw new Error('Failed to generate query embedding');
103
- }
104
- // 2. PARALLEL EXECUTION: Search codebase and retrieve memories simultaneously
105
- // OPTIMIZATION: For simple queries, reduce operations and skip memory if not needed
106
- const isSimpleQuery = this.isSimpleQuery(request.query);
107
- // AGGRESSIVE OPTIMIZATION: For simple queries, use minimal operations
108
- // OPTIMIZATION: Reduce initial search limit to reduce processing time
109
- const initialLimit = isSimpleQuery
110
- ? 3 // Only need top 3 chunks for simple queries (fast!)
111
- : Math.min((request.maxResults || 8) * 2, 20); // Reduced from 50 to 20 for faster search
112
- // Check query result cache first (performance optimization)
113
- const cachedResults = this.queryResultCache.get(request.query, initialLimit);
114
- let initialChunks;
115
- let allMemories = [];
116
- let searchTime = 0; // Performance metrics
117
- let rerankTime = 0; // Performance metrics
118
- // Progress is owned by the caller (REPL spinner or CLI command)
119
- let searchProgress = null;
120
- if (cachedResults) {
121
- // Cache hit - use cached results
122
- this.queryResultCache.recordHit();
123
- initialChunks = cachedResults;
124
- // Still retrieve memories in parallel (if not simple query)
125
- if (!isSimpleQuery && this.memoryRepository && queryEmbedding) {
126
- allMemories = await this.memoryRepository.retrieve(request.query, 10).catch(() => []);
127
- }
128
- }
129
- else {
130
- // Cache miss - perform search
131
- this.queryResultCache.recordMiss();
132
- // Run code search and memory retrieval in parallel (skip memory for simple queries)
133
- const searchStart = Date.now();
134
- const results = await Promise.all([
135
- // Code search - minimal for simple queries
136
- this.embeddingRepository.searchWithEmbedding(queryEmbedding, initialLimit),
137
- // Memory retrieval: Skip for simple queries to save time (they don't need context)
138
- !isSimpleQuery && this.memoryRepository && queryEmbedding
139
- ? this.memoryRepository.retrieve(request.query, 10).catch(() => []) // Graceful fallback
140
- : Promise.resolve([]),
141
- ]);
142
- searchTime = Date.now() - searchStart;
143
- initialChunks = results[0];
144
- allMemories = results[1];
145
- // Cache the results for future use
146
- this.queryResultCache.set(request.query, initialLimit, initialChunks);
147
- // Stop progress indicator
148
- if (searchProgress) {
149
- searchProgress.stop(true, `Found ${initialChunks.length} chunks`);
150
- }
151
- }
152
- if (initialChunks.length === 0) {
153
- return {
154
- answer: 'No relevant code found. Please run "codehere index" first.',
155
- chunks: [],
156
- };
157
- }
158
- // 3. PARALLEL EXECUTION: Rerank + Memory Processing (Story 1: Parallel Context Processing)
159
- // OPTIMIZATION: These operations are independent and can run in parallel
160
- // OPTIMIZATION: Skip rerank for simple queries to improve speed
161
- let chunks = initialChunks;
162
- let memories = [];
163
- // For simple queries, use minimal chunks (top 3) for fastest response
164
- // Story 2: Optimized execution path - reduced context window, minimal processing
165
- if (isSimpleQuery) {
166
- chunks = initialChunks.slice(0, 3); // Top 3 for simple queries (aggressive optimization)
167
- // Process memories synchronously for simple queries (minimal processing, already fast)
168
- if (allMemories.length > 0 && queryEmbedding) {
169
- memories = this.memoryRetriever.retrieve(allMemories, queryEmbedding, 3); // Minimal for simple queries
170
- }
171
- }
172
- else {
173
- // For complex queries: Parallelize rerank + memory processing
174
- const documents = initialChunks.map((chunk) => chunk.content);
175
- // Run rerank and memory processing in parallel (they're independent)
176
- // OPTIMIZATION: Reduce maxResults for complex queries to reduce AI Chat latency
177
- // Target: 8 chunks max (down from 15) to reduce context window by ~47%
178
- const maxChunksForAI = Math.min(request.maxResults || 8, 8); // Aggressive: max 8 chunks
179
- const rerankStart = Date.now();
180
- const [rerankResults, processedMemories] = await Promise.all([
181
- // Rerank operation (only if we have enough results)
182
- initialChunks.length > 5
183
- ? this.aiService.rerank(request.query, documents, maxChunksForAI)
184
- .then(results => results.map((result) => {
185
- const chunk = initialChunks[result.index];
186
- return {
187
- ...chunk,
188
- score: result.relevanceScore,
189
- };
190
- }))
191
- .catch((error) => {
192
- // Fallback to initial results if rerank fails
193
- console.warn('Rerank API failed, using initial results:', error instanceof Error ? error.message : String(error));
194
- return initialChunks.slice(0, maxChunksForAI);
195
- })
196
- : Promise.resolve(initialChunks.slice(0, maxChunksForAI)),
197
- // Memory processing (reuse query embedding, no recomputation needed)
198
- allMemories.length > 0 && queryEmbedding
199
- ? Promise.resolve(this.memoryRetriever.retrieve(allMemories, queryEmbedding, 5))
200
- : Promise.resolve([]),
201
- ]);
202
- rerankTime = Date.now() - rerankStart;
203
- chunks = rerankResults;
204
- memories = processedMemories;
205
- }
206
- // 3. Pass conversation history through context chunks (metadata) for AI service
207
- const chunksWithHistory = request.conversationHistory && request.conversationHistory.length > 0
208
- ? chunks.map((chunk, idx) => {
209
- if (idx === 0) {
210
- // Attach conversation history to first chunk as metadata
211
- return {
212
- ...chunk,
213
- conversationHistory: request.conversationHistory,
214
- };
215
- }
216
- return chunk;
217
- })
218
- : chunks;
219
- // 3. Generate AI response with context (with optional streaming)
220
- // OPTIMIZATION: Check response cache first to avoid redundant AI calls
221
- const contextHash = this.responseCache.generateContextHash(chunks);
222
- let answer = '';
223
- let chatTime = 0;
224
- let wasResponseCached = false;
225
- // Check cache (skip for streaming as it's real-time)
226
- if (!request.streamHandler) {
227
- const cachedAnswer = this.responseCache.get(request.query, contextHash, true);
228
- if (cachedAnswer) {
229
- answer = cachedAnswer;
230
- wasResponseCached = true;
231
- chatTime = 0; // Cache hit = instant
232
- }
233
- }
234
- // If not cached, call AI service
235
- if (!wasResponseCached) {
236
- const chatStart = Date.now();
237
- if (request.streamHandler && 'chatStream' in this.aiService && typeof this.aiService.chatStream === 'function') {
238
- // Use streaming if available
239
- answer = await this.aiService.chatStream(request.query, chunksWithHistory, memories, request.streamHandler);
240
- }
241
- else {
242
- // Fallback to regular chat
243
- answer = await this.aiService.chat(request.query, chunksWithHistory, memories);
244
- }
245
- chatTime = Date.now() - chatStart;
246
- // Cache the response for future use
247
- if (answer && !request.streamHandler) {
248
- this.responseCache.set(request.query, answer, contextHash);
249
- }
250
- }
251
- // 4. Estimate tokens (rough: 1 token ≈ 4 characters)
252
- const tokenEstimate = chunks.reduce((sum, chunk) => sum + Math.ceil(chunk.content.length / 4), 0);
253
- // 5. Quantify uncertainty in answer (XAI Foundation - Research: Uncertainty Quantification)
254
- let uncertainty;
255
- if (this.uncertaintyQuantifier && answer) {
256
- uncertainty = await this.uncertaintyQuantifier.quantifyUncertainty(request.query, answer, { chunks });
257
- }
258
- // Get cache statistics
259
- const cacheStats = this.queryResultCache.getStats();
260
- const wasCacheHit = cachedResults !== null;
261
- // Get compression metrics from execution tracer if available
262
- let compressionMetrics;
263
- try {
264
- const { executionTracer } = await import('../../infrastructure/observability/execution-tracer.js');
265
- const runId = executionTracer.getCurrentRunId();
266
- if (runId) {
267
- // Get the current run to find compression trace
268
- const currentRun = executionTracer.currentRun;
269
- if (currentRun) {
270
- const compressionTrace = currentRun.traces.find((t) => t.operationType === 'context_compression' && t.operationName === 'compress_context');
271
- if (compressionTrace && compressionTrace.output) {
272
- compressionMetrics = {
273
- originalTokens: compressionTrace.output.originalTokens || 0,
274
- compressedTokens: compressionTrace.output.compressedTokens || 0,
275
- reductionPercent: compressionTrace.output.reductionPercent || 0,
276
- };
277
- }
278
- }
279
- }
280
- }
281
- catch {
282
- // Execution tracer not available, skip compression metrics
283
- }
284
- // Calculate total time
285
- const totalTime = Date.now() - request.__startTime || 0;
286
- return {
287
- answer,
288
- chunks,
289
- memories,
290
- tokenEstimate,
291
- uncertainty, // XAI Foundation - Uncertainty quantification for transparency
292
- cacheHit: wasCacheHit,
293
- performanceMetrics: {
294
- embeddingCacheTime,
295
- embeddingGenTime,
296
- searchTime: cachedResults ? 0 : searchTime,
297
- rerankTime: isSimpleQuery ? 0 : rerankTime,
298
- chatTime,
299
- totalTime,
300
- },
301
- cacheStats: {
302
- hitRate: cacheStats.hitRate,
303
- totalHits: cacheStats.totalHits,
304
- totalMisses: cacheStats.totalMisses,
305
- },
306
- compressionMetrics, // Context compression metrics (P1)
307
- };
308
- }
309
- /**
310
- * Check if query is simple (short, question-like, single intent)
311
- * Simple queries can skip rerank for better performance
312
- */
313
- /**
314
- * Check if query is simple (short, question-like, single intent)
315
- * Story 2: Enhanced detection with improved accuracy (target: >90%)
316
- * Simple queries can skip rerank for better performance
317
- */
318
- isSimpleQuery(query) {
319
- const lower = query.toLowerCase().trim();
320
- // Enhanced detection patterns (Story 2: Query Simplification)
321
- // 1. Short query (< 50 chars) - primary indicator
322
- const isShort = query.length < 50;
323
- // 2. Question-like patterns (expanded list for better accuracy)
324
- const questionPatterns = /^(what|where|how|why|when|who|which|is|are|does|do|can|could|will|would|explain|describe|tell|show|find|locate|search|where|what's|what is|how to|how do|how does)/i;
325
- const isQuestion = questionPatterns.test(lower);
326
- // 3. Single intent indicators (no complex conjunctions)
327
- const complexIndicators = /(and|also|then|next|first|second|finally|multiple|several|steps|after|before|while|during|create|implement|add|modify|refactor|change|update|delete|remove)/i;
328
- const isSingleIntent = !complexIndicators.test(lower);
329
- // 4. Simple structure (no nested clauses, no semicolons, no colons for lists)
330
- const hasComplexStructure = /[;:]|\(|\)|\[|\]/.test(query);
331
- // 5. No code-specific keywords (indicates need for code analysis)
332
- const codeKeywords = /(function|class|interface|type|import|export|const|let|var|async|await|return|if|else|for|while|try|catch)/i;
333
- const hasCodeKeywords = codeKeywords.test(lower);
334
- // Simple query if: short + question-like + single intent + no complex structure + no code keywords
335
- return isShort && isQuestion && isSingleIntent && !hasComplexStructure && !hasCodeKeywords;
336
- }
337
- }
338
- //# sourceMappingURL=ask-question-use-case.js.map