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,433 +0,0 @@
1
- /**
2
- * Application Agent: Planning Agent (Architect)
3
- * Specialized agent for creating detailed, step-by-step modification plans
4
- *
5
- * Based on enterprise architecture: Separate Planning Agent from PlanningUseCase
6
- * Role: Creates detailed plans before execution
7
- */
8
- import { GitTool } from '../../tools/git-tool.js';
9
- import { findCodebaseRoot } from '../../domain/services/codebase-detector.js';
10
- import { agentValidationHelper } from '../../infrastructure/validation/agent-validation-helper.js';
11
- export class PlanningAgent {
12
- aiService;
13
- memoryStream;
14
- memoryRepository;
15
- cwd;
16
- decisionRecorder;
17
- patternRepository;
18
- knowledgeAccess;
19
- gitTool;
20
- constructor(aiService, memoryStream, memoryRepository, cwd = process.cwd(), decisionRecorder, // Optional - only record if provided
21
- patternRepository, // Optional - for pattern suggestions
22
- knowledgeAccess // Optional - for knowledge retrieval
23
- ) {
24
- this.aiService = aiService;
25
- this.memoryStream = memoryStream;
26
- this.memoryRepository = memoryRepository;
27
- this.cwd = cwd;
28
- this.decisionRecorder = decisionRecorder;
29
- this.patternRepository = patternRepository;
30
- this.knowledgeAccess = knowledgeAccess;
31
- this.gitTool = new GitTool(cwd);
32
- }
33
- /**
34
- * Create detailed modification plan
35
- * This is the architect role - plans before execution
36
- */
37
- async createPlan(request) {
38
- // Start validation context
39
- const codebaseInfo = findCodebaseRoot(this.cwd);
40
- const validationContext = agentValidationHelper.startAgentOperation('planning-agent', 'createPlan', {
41
- query: request.goal,
42
- codebaseId: codebaseInfo?.codebaseId,
43
- });
44
- try {
45
- // Input validation - fail fast
46
- if (!request.goal || request.goal.trim().length === 0) {
47
- throw new Error('Goal cannot be empty');
48
- }
49
- // 1. Detect codebase context (for codebase-aware operations)
50
- const codebaseId = codebaseInfo?.codebaseId;
51
- const codebasePath = codebaseInfo?.rootPath;
52
- // 2. Gather context: Git state, memories (filtered by codebase if available)
53
- const gitContext = await this.gatherGitContext();
54
- let recentMemories;
55
- let relevantMemories;
56
- if (codebaseId) {
57
- // Use codebase-aware memory retrieval
58
- recentMemories = await this.memoryRepository.findRecentByCodebase(codebaseId, 100);
59
- relevantMemories = await this.memoryStream.retrieveByCodebase(request.goal, codebaseId, 50);
60
- }
61
- else {
62
- // Fallback to global memory retrieval (backward compatibility)
63
- recentMemories = await this.memoryRepository.findRecent(100);
64
- relevantMemories = await this.memoryStream.retrieve(request.goal, 50);
65
- }
66
- // 2. Synthesize memories into reflections
67
- // Skip synthesis if no memories - fail fast
68
- const reflections = [];
69
- const salientQuestions = [];
70
- if (recentMemories.length > 0) {
71
- // Only synthesize if we have meaningful memories (skip for speed)
72
- // For now, use memory descriptions directly as reflections
73
- // Full synthesis can be done asynchronously if needed
74
- reflections.push(...recentMemories.slice(0, 5).map(m => m.description));
75
- }
76
- // 3. Retrieve relevant patterns for plan generation (if pattern repository available)
77
- let relevantPatterns = [];
78
- if (this.patternRepository && codebaseId) {
79
- try {
80
- relevantPatterns = await this.patternRepository.search(codebaseId, request.goal, 5);
81
- }
82
- catch (error) {
83
- // Non-critical - pattern retrieval shouldn't fail planning
84
- console.warn('Pattern retrieval failed (non-critical):', error);
85
- }
86
- }
87
- // 4. Generate hierarchical plan with detailed steps (including Git context and patterns)
88
- const plan = await this.generateDetailedPlan(request.goal, reflections, relevantMemories, request.context, gitContext, relevantPatterns);
89
- // 5. Assess plan confidence
90
- const confidence = await this.assessPlanConfidence(plan, relevantMemories);
91
- // 6. Store plan in memory (with codebase context)
92
- await this.memoryStream.recordPlan(`Planning Agent created plan for: "${request.goal}"`, plan, codebaseId, codebasePath);
93
- // 7. Extract and record decisions from planning context (if decision recorder available)
94
- if (this.decisionRecorder && codebaseId) {
95
- try {
96
- await this.decisionRecorder.extractDecisionFromPlanning({
97
- goal: request.goal,
98
- plan,
99
- constraints: request.context?.constraints,
100
- }, codebaseId, this.aiService);
101
- }
102
- catch (error) {
103
- // Don't fail planning if decision recording fails
104
- console.warn('Decision recording failed (non-critical):', error);
105
- }
106
- }
107
- // Calculate plan metrics for validation
108
- const planComplexity = plan.metadata?.complexity || 'medium';
109
- const unresolvedDependencies = plan.subPlans.filter(sp => sp.dependencies.some(depId => !plan.subPlans.find(sp2 => sp2.id === depId)));
110
- // Complete validation and get summary
111
- const validationResult = await agentValidationHelper.completeAgentOperation(validationContext, {
112
- plan,
113
- reflections,
114
- salientQuestions,
115
- memoriesUsed: relevantMemories,
116
- confidence,
117
- }, {
118
- outcome: 'success',
119
- validationChecks: [
120
- {
121
- check: 'Plan generated',
122
- passed: true,
123
- message: `Plan with ${plan.subPlans.length} sub-plans created`,
124
- },
125
- {
126
- check: 'Dependencies resolved',
127
- passed: unresolvedDependencies.length === 0,
128
- message: unresolvedDependencies.length === 0
129
- ? 'All dependencies resolved'
130
- : `${unresolvedDependencies.length} unresolved dependencies`,
131
- },
132
- {
133
- check: 'Plan complexity assessed',
134
- passed: true,
135
- message: `Complexity: ${planComplexity}`,
136
- },
137
- ],
138
- metrics: {
139
- changesProposed: plan.subPlans.length,
140
- },
141
- additionalContext: {
142
- query: request.goal,
143
- codebaseId,
144
- codebaseType: codebaseInfo?.type,
145
- planComplexity,
146
- numberOfSteps: plan.subPlans.length,
147
- unresolvedDependencies: unresolvedDependencies.length,
148
- riskEstimation: plan.metadata?.complexity === 'complex' ? 'high' :
149
- plan.metadata?.complexity === 'simple' ? 'low' : 'medium',
150
- },
151
- });
152
- return {
153
- plan,
154
- reflections,
155
- salientQuestions,
156
- memoriesUsed: relevantMemories,
157
- confidence,
158
- validationSummary: validationResult.summary,
159
- feedbackId: validationResult.feedbackId || undefined,
160
- runId: validationResult.runId || undefined,
161
- };
162
- }
163
- catch (error) {
164
- // Record failure in validation
165
- await agentValidationHelper.completeAgentOperation(validationContext, null, {
166
- outcome: 'failure',
167
- errors: [error instanceof Error ? error.message : String(error)],
168
- additionalContext: {
169
- query: request.goal,
170
- codebaseId: codebaseInfo?.codebaseId,
171
- },
172
- });
173
- throw error;
174
- }
175
- }
176
- /**
177
- * Gather Git context for planning
178
- */
179
- async gatherGitContext() {
180
- try {
181
- const status = await this.gitTool.status();
182
- // status returns: { branch, modified, staged, untracked }
183
- const currentBranch = status.branch;
184
- const uncommittedFiles = [
185
- ...status.modified,
186
- ...status.staged,
187
- ...status.untracked,
188
- ];
189
- const hasUncommittedChanges = uncommittedFiles.length > 0;
190
- // Get recent commits (last 5)
191
- const log = await this.gitTool.log(5);
192
- const recentCommits = [];
193
- if (Array.isArray(log)) {
194
- for (const commit of log.slice(0, 5)) {
195
- recentCommits.push(commit.hash.substring(0, 12)); // Short hash
196
- }
197
- }
198
- return {
199
- currentBranch,
200
- hasUncommittedChanges,
201
- uncommittedFiles,
202
- recentCommits,
203
- };
204
- }
205
- catch {
206
- // Git not available or not a git repo
207
- return {
208
- hasUncommittedChanges: false,
209
- uncommittedFiles: [],
210
- recentCommits: [],
211
- };
212
- }
213
- }
214
- /**
215
- * Generate detailed hierarchical plan
216
- */
217
- async generateDetailedPlan(goal, reflections, memories, context, gitContext, relevantPatterns = [], relevantKnowledge = []) {
218
- const memoryContext = memories.map(m => `- ${m.description} (Type: ${m.type})`).join('\n');
219
- const reflectionContext = reflections.map(r => `- ${r}`).join('\n');
220
- const fileContext = context?.files && context.files.length > 0
221
- ? `\n\n**IMPORTANT - FILES CONSTRAINT:**\nYou MUST focus on these specific files: ${context.files.join(', ')}\nEach sub-plan that modifies code MUST reference one of these files explicitly in its description (e.g., "Edit ${context.files[0]} to...").`
222
- : '';
223
- const constraintsContext = context?.constraints
224
- ? `\n\nConstraints: ${context.constraints.join(', ')}`
225
- : '';
226
- // Git context
227
- let gitContextText = '';
228
- if (gitContext) {
229
- gitContextText = `\n\nGit Context:`;
230
- if (gitContext.currentBranch) {
231
- gitContextText += `\n- Current branch: ${gitContext.currentBranch}`;
232
- }
233
- if (gitContext.hasUncommittedChanges) {
234
- gitContextText += `\n- Uncommitted changes in: ${gitContext.uncommittedFiles.slice(0, 5).join(', ')}${gitContext.uncommittedFiles.length > 5 ? '...' : ''}`;
235
- gitContextText += `\n⚠️ WARNING: There are uncommitted changes. Consider committing or stashing before making modifications.`;
236
- }
237
- if (gitContext.recentCommits.length > 0) {
238
- gitContextText += `\n- Recent commits: ${gitContext.recentCommits.join(', ')}`;
239
- }
240
- }
241
- // Detect if this is a multi-file operation
242
- const isMultiFile = /(refactor|migrate|update|implement|create|add|introduce).*(system|codebase|all|multiple|several|across|architecture|pattern|components|layer|abstraction)/i.test(goal);
243
- // Detect if this requires file/directory creation (architecture patterns, new layers, etc.)
244
- const requiresFileCreation = /(add|create|introduce).*(repository|service|controller|middleware|pattern|layer|abstraction|directory|folder|file)/i.test(goal) ||
245
- /(repository|service|controller|middleware)\s+(pattern|layer)/i.test(goal);
246
- const multiFileGuidance = isMultiFile ? `
247
-
248
- **IMPORTANT - MULTI-FILE OPERATION DETECTED:**
249
- This goal requires changes across multiple files. Your plan MUST:
250
- 1. Create separate sub-plans for EACH file that needs modification or creation
251
- 2. Include sub-plans to search and identify ALL files that need changes
252
- 3. Specify the exact filepath in each sub-plan description (e.g., "Edit src/auth/auth-service.ts to add JWT" or "Create src/repositories/user-repository.ts")
253
- 4. Ensure dependencies are set correctly (search → edit file 1 → edit file 2)
254
- 5. For file creation, use type "implement" and include the full filepath in the description
255
- 6. Coordinate changes across files to ensure consistency
256
- ${requiresFileCreation ? `
257
-
258
- **FILE CREATION REQUIRED:**
259
- This operation requires creating new files/directories. For each new file:
260
- - Use type "implement" in the sub-plan
261
- - Include the full directory path in the description (e.g., "Create src/repositories/user-repository.ts")
262
- - Ensure parent directories are created as needed
263
- - For patterns like "repository pattern", create:
264
- * Interface files (e.g., "src/repositories/interfaces/user-repository.interface.ts")
265
- * Implementation files (e.g., "src/repositories/user-repository.ts")
266
- * Update existing files to use the new pattern
267
- ` : ''}
268
-
269
- Example multi-file plan structure:
270
- - Sub-plan 1: "Search codebase for authentication-related files"
271
- - Sub-plan 2: "Edit src/auth/auth-service.ts to implement JWT token generation"
272
- - Sub-plan 3: "Edit src/auth/middleware.ts to add JWT validation middleware"
273
- - Sub-plan 4: "Update src/config/auth-config.ts to include JWT settings"
274
- ${requiresFileCreation ? `
275
- Example file creation plan structure:
276
- - Sub-plan 1: "Search codebase for data access patterns"
277
- - Sub-plan 2: "Create src/repositories/interfaces/user-repository.interface.ts with IUserRepository interface"
278
- - Sub-plan 3: "Create src/repositories/user-repository.ts implementing IUserRepository"
279
- - Sub-plan 4: "Update src/services/user-service.ts to use UserRepository instead of direct data access"
280
- ` : ''}
281
- ` : '';
282
- const prompt = `You are a Planning Agent (Architect) for an AI coding system. Your role is to create detailed, step-by-step modification plans.
283
-
284
- Goal: "${goal}"${fileContext}${constraintsContext}${gitContextText}${multiFileGuidance}
285
-
286
- Consider:
287
- - **Relevant Past Experiences/Memories**:
288
- ${memoryContext || 'No relevant past experiences.'}
289
- - **Synthesized Reflections/Insights**:
290
- ${reflectionContext || 'No specific reflections.'}
291
- ${relevantPatterns.length > 0 ? `
292
- - **Relevant Patterns from Codebase**:
293
- ${relevantPatterns.map(p => ` - ${p.name}: ${p.description}${p.codeExample ? `\n Example: ${p.codeExample.substring(0, 200)}...` : ''}`).join('\n')}
294
-
295
- **IMPORTANT**: Consider reusing or following these existing patterns from the codebase when creating your plan.
296
- ` : ''}
297
-
298
- Create a detailed plan with:
299
- 1. Clear sub-plans with specific actions
300
- 2. Dependencies between sub-plans
301
- 3. Estimated complexity for each sub-plan
302
- 4. Required tools/resources for each step
303
-
304
- For each sub-plan, specify:
305
- - \`id\`: Unique identifier (e.g., "subplan_1")
306
- - \`description\`: Clear, actionable description WITH filepath if applicable (e.g., "Edit src/auth/auth-service.ts to add JWT")
307
- - \`type\`: Action type (search, edit, refactor, review, analyze, implement, test, debug)
308
- - \`dependencies\`: Array of sub-plan IDs that must complete first
309
- - \`status\`: Always "pending" initially
310
- - \`estimatedComplexity\`: "low" | "medium" | "high"
311
- - \`requiredTools\`: Array of tool names needed (e.g., ["search", "edit"])
312
-
313
- ${isMultiFile ? '**For multi-file operations, create one sub-plan per file, each with explicit filepath in description.**' : ''}
314
-
315
- Respond with ONLY a JSON array of sub-plan objects.
316
-
317
- Example:
318
- [
319
- {
320
- "id": "subplan_1",
321
- "description": "Search codebase for existing authentication patterns",
322
- "type": "search",
323
- "dependencies": [],
324
- "status": "pending",
325
- "estimatedComplexity": "low",
326
- "requiredTools": ["search"]
327
- },
328
- {
329
- "id": "subplan_2",
330
- "description": "Implement JWT token generation in src/auth/jwt.ts",
331
- "type": "implement",
332
- "dependencies": ["subplan_1"],
333
- "status": "pending",
334
- "estimatedComplexity": "high",
335
- "requiredTools": ["edit", "bash"]
336
- }
337
- ]
338
-
339
- JSON only, no other text:`;
340
- let response;
341
- try {
342
- // Add timeout protection for planning calls (60 seconds max)
343
- const timeoutPromise = new Promise((_, reject) => {
344
- setTimeout(() => reject(new Error('Planning API call timed out after 60 seconds')), 60000);
345
- });
346
- response = await Promise.race([
347
- this.aiService.chat(prompt, []),
348
- timeoutPromise,
349
- ]);
350
- }
351
- catch (error) {
352
- const errorMsg = error instanceof Error ? error.message : String(error);
353
- console.error('Planning Agent: API call failed:', errorMsg);
354
- // Provide more helpful error messages
355
- if (errorMsg.includes('timeout') || errorMsg.includes('timed out')) {
356
- throw new Error(`Failed to generate plan: API call timed out. The Cohere API may be slow or unresponsive. Please check your API key and network connection.`);
357
- }
358
- else if (errorMsg.includes('401') || errorMsg.includes('Unauthorized')) {
359
- throw new Error(`Failed to generate plan: API authentication failed. Please check your COHERE_API_KEY is valid.`);
360
- }
361
- else if (errorMsg.includes('429') || errorMsg.includes('rate limit') || errorMsg.includes('TooManyRequests')) {
362
- // Check if it's a trial key monthly limit
363
- const isTrialLimit = errorMsg.includes('Trial key') || errorMsg.includes('1000 API calls');
364
- if (isTrialLimit) {
365
- throw new Error(`Failed to generate plan: Trial API key has reached monthly limit (1000 calls/month). Please upgrade to a Production key or wait for the limit to reset. See https://dashboard.cohere.com/api-keys`);
366
- }
367
- throw new Error(`Failed to generate plan: API rate limit exceeded (429). Please wait and try again or upgrade your API key.`);
368
- }
369
- throw new Error(`Failed to generate plan: API call failed. ${errorMsg}`);
370
- }
371
- // Check for empty response
372
- if (!response || response.trim().length === 0) {
373
- console.error('Planning Agent: Empty response from API');
374
- throw new Error('Failed to generate plan: API returned empty response');
375
- }
376
- try {
377
- // Try to extract JSON from response (handle cases where LLM adds extra text)
378
- let jsonStr = response.trim();
379
- // Try to find JSON array in response
380
- const jsonArrayMatch = jsonStr.match(/\[[\s\S]*\]/);
381
- if (jsonArrayMatch) {
382
- jsonStr = jsonArrayMatch[0];
383
- }
384
- const subPlans = JSON.parse(jsonStr);
385
- // Validate subPlans
386
- if (!Array.isArray(subPlans) || subPlans.length === 0) {
387
- console.error('Planning Agent: Invalid subPlans array:', subPlans);
388
- throw new Error('Failed to generate plan: API returned empty or invalid sub-plans array');
389
- }
390
- return {
391
- id: `plan_${Date.now()}`,
392
- goal,
393
- description: goal,
394
- subPlans,
395
- status: 'draft',
396
- createdAt: new Date(),
397
- updatedAt: new Date(),
398
- dependencies: [],
399
- metadata: {
400
- memoriesUsed: memories.map(m => m.id || ''),
401
- reflections: reflections,
402
- complexity: 'medium',
403
- priority: 5,
404
- },
405
- };
406
- }
407
- catch (e) {
408
- // User-friendly error for minimal mode
409
- console.error('Planning agent returned an unexpected response.');
410
- console.error('This is usually a provider/model issue. Try again or check your AI provider configuration.');
411
- // Verbose details for debugging (when CODEHERE_CLI_STYLE=verbose)
412
- if (process.env.CODEHERE_CLI_STYLE === 'verbose') {
413
- console.error('\nDebug details:');
414
- console.error(' Response length:', response?.length || 0);
415
- console.error(' Response preview:', response?.substring(0, 200) || 'empty');
416
- console.error(' Parse error:', e instanceof Error ? e.message : String(e));
417
- }
418
- throw new Error(`Planning failed: AI response was not valid JSON. Try again or switch providers.`);
419
- }
420
- }
421
- /**
422
- * Assess confidence in plan quality
423
- */
424
- async assessPlanConfidence(plan, memories) {
425
- // Simple heuristic: more memories = higher confidence
426
- // More detailed sub-plans = higher confidence
427
- const memoryFactor = Math.min(memories.length / 10, 1.0);
428
- const detailFactor = Math.min(plan.subPlans.length / 5, 1.0);
429
- const dependencyFactor = plan.subPlans.some(sp => sp.dependencies.length > 0) ? 0.2 : 0;
430
- return Math.min(memoryFactor * 0.4 + detailFactor * 0.4 + dependencyFactor, 1.0);
431
- }
432
- }
433
- //# sourceMappingURL=planning-agent.js.map