codehere 0.2.2 → 0.3.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/README.md +88 -68
  2. package/dist/domain/entities/task.js +4 -4
  3. package/dist/error-handler.js +4 -9
  4. package/dist/index.js +261 -1224
  5. package/dist/infrastructure/config/product-context.js +7 -6
  6. package/dist/infrastructure/hooks/claude-sdk-hook.js +348 -72
  7. package/dist/infrastructure/observability/execution-tracer.js +11 -6
  8. package/dist/infrastructure/orchestration/agent-adapter.js +13 -0
  9. package/dist/infrastructure/orchestration/agent-installer.js +101 -0
  10. package/dist/infrastructure/orchestration/agents-config-seed.js +56 -0
  11. package/dist/infrastructure/orchestration/aider-adapter.js +319 -0
  12. package/dist/infrastructure/orchestration/artifacts-extractor.js +175 -0
  13. package/dist/infrastructure/orchestration/claude-code-adapter.js +352 -0
  14. package/dist/infrastructure/orchestration/codex-adapter.js +310 -0
  15. package/dist/infrastructure/orchestration/conductor-adapter.js +340 -0
  16. package/dist/infrastructure/orchestration/generic-cli-adapter.js +553 -0
  17. package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
  18. package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
  19. package/dist/infrastructure/orchestration/readiness.js +106 -0
  20. package/dist/infrastructure/orchestration/session-manager.js +278 -0
  21. package/dist/infrastructure/orchestration/session-persistence.js +109 -0
  22. package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
  23. package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
  24. package/dist/infrastructure/protocols/probe-port.js +36 -0
  25. package/dist/infrastructure/protocols/ui-page.js +1827 -0
  26. package/dist/infrastructure/security/file-collection.js +115 -0
  27. package/dist/infrastructure/security/trust-scorer.js +301 -56
  28. package/dist/infrastructure/storage/task-repository.js +8 -7
  29. package/dist/monitoring.js +9 -38
  30. package/dist/presentation/cli/commands/help-command.js +96 -139
  31. package/dist/presentation/cli/commands/hook-command.js +17 -24
  32. package/dist/presentation/cli/commands/report-command.js +59 -72
  33. package/dist/presentation/cli/commands/setup-command.js +4 -4
  34. package/dist/presentation/cli/commands/status-command.js +321 -30
  35. package/dist/presentation/cli/commands/trust-command.js +84 -72
  36. package/dist/presentation/cli/error-display.js +17 -21
  37. package/dist/presentation/cli/repl.js +474 -0
  38. package/dist/ui.js +11 -11
  39. package/package.json +24 -62
  40. package/dist/agents/base.js +0 -101
  41. package/dist/agents/orchestrator-model-driven.js +0 -141
  42. package/dist/agents/react-orchestrator-agent.js +0 -54
  43. package/dist/application/agents/execution-agent.js +0 -508
  44. package/dist/application/agents/multi-agent-orchestrator.js +0 -295
  45. package/dist/application/agents/planning-agent.js +0 -433
  46. package/dist/application/agents/validation-agent.js +0 -317
  47. package/dist/application/architectures/plan-and-act.js +0 -242
  48. package/dist/application/index.js +0 -12
  49. package/dist/application/services/agent-factory.js +0 -28
  50. package/dist/application/services/dependency-container.js +0 -596
  51. package/dist/application/services/git-context-service.js +0 -83
  52. package/dist/application/services/intelligent-router.js +0 -934
  53. package/dist/application/services/tool-executor-service.js +0 -94
  54. package/dist/application/use-cases/ask-question-use-case.js +0 -338
  55. package/dist/application/use-cases/edit-file-use-case.js +0 -830
  56. package/dist/application/use-cases/explain-file-use-case.js +0 -50
  57. package/dist/application/use-cases/index-codebase-use-case.js +0 -113
  58. package/dist/application/use-cases/planning-use-case.js +0 -276
  59. package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
  60. package/dist/application/use-cases/reflexion-use-case.js +0 -30
  61. package/dist/application/workflows/deterministic-workflows.js +0 -189
  62. package/dist/ast-parser.js +0 -331
  63. package/dist/cache.js +0 -180
  64. package/dist/chat.js +0 -251
  65. package/dist/code-analysis.js +0 -327
  66. package/dist/context.js +0 -187
  67. package/dist/docs.js +0 -146
  68. package/dist/domain/entities/code-chunk.js +0 -6
  69. package/dist/domain/entities/decision.js +0 -9
  70. package/dist/domain/entities/edit.js +0 -6
  71. package/dist/domain/entities/knowledge-node.js +0 -9
  72. package/dist/domain/entities/knowledge-preservation.js +0 -10
  73. package/dist/domain/entities/memory.js +0 -6
  74. package/dist/domain/entities/pattern.js +0 -7
  75. package/dist/domain/entities/plan.js +0 -6
  76. package/dist/domain/entities/query.js +0 -6
  77. package/dist/domain/errors/embeddings-not-found-error.js +0 -13
  78. package/dist/domain/index.js +0 -19
  79. package/dist/domain/interfaces/ai-service.interface.js +0 -6
  80. package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
  81. package/dist/domain/interfaces/decision-repository.interface.js +0 -9
  82. package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
  83. package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
  84. package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
  85. package/dist/domain/interfaces/memory-repository.interface.js +0 -6
  86. package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
  87. package/dist/domain/interfaces/verification-service.interface.js +0 -6
  88. package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
  89. package/dist/domain/services/decision-recorder.js +0 -223
  90. package/dist/domain/services/decision-retriever.js +0 -133
  91. package/dist/domain/services/environment-mode-manager.js +0 -22
  92. package/dist/domain/services/graded-memory-activation.js +0 -69
  93. package/dist/domain/services/knowledge-access.js +0 -132
  94. package/dist/domain/services/knowledge-extractor.js +0 -247
  95. package/dist/domain/services/knowledge-graph-builder.js +0 -268
  96. package/dist/domain/services/knowledge-graph-query.js +0 -187
  97. package/dist/domain/services/memory-retriever.js +0 -82
  98. package/dist/domain/services/memory-synthesizer.js +0 -91
  99. package/dist/domain/services/pattern-extractor.js +0 -442
  100. package/dist/domain/services/query-intent-classifier.js +0 -140
  101. package/dist/domain/services/react-loop.js +0 -186
  102. package/dist/domain/services/risk-tier-detector.js +0 -78
  103. package/dist/edit.js +0 -319
  104. package/dist/embed.js +0 -459
  105. package/dist/formatter.js +0 -168
  106. package/dist/git.js +0 -198
  107. package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
  108. package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
  109. package/dist/infrastructure/ai/model-config.js +0 -84
  110. package/dist/infrastructure/ai/provider-ai-service.js +0 -477
  111. package/dist/infrastructure/cache/embedding-cache.js +0 -175
  112. package/dist/infrastructure/cache/query-result-cache.js +0 -66
  113. package/dist/infrastructure/cache/response-cache.js +0 -48
  114. package/dist/infrastructure/cache/security-scan-cache.js +0 -47
  115. package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
  116. package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
  117. package/dist/infrastructure/context/context-compressor.js +0 -329
  118. package/dist/infrastructure/context/conversation-context.js +0 -128
  119. package/dist/infrastructure/context/session-manager.js +0 -94
  120. package/dist/infrastructure/cost/cost-tracker.js +0 -360
  121. package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
  122. package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
  123. package/dist/infrastructure/governance/policy-as-code.js +0 -258
  124. package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
  125. package/dist/infrastructure/index.js +0 -7
  126. package/dist/infrastructure/observability/prompt-versioner.js +0 -145
  127. package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
  128. package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
  129. package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
  130. package/dist/infrastructure/protocols/mcp-server.js +0 -333
  131. package/dist/infrastructure/protocols/streaming-handler.js +0 -103
  132. package/dist/infrastructure/providers/cohere-provider.js +0 -444
  133. package/dist/infrastructure/providers/fake-provider.js +0 -130
  134. package/dist/infrastructure/providers/local-llm-provider.js +0 -330
  135. package/dist/infrastructure/providers/model-config.types.js +0 -9
  136. package/dist/infrastructure/providers/model-provider.interface.js +0 -8
  137. package/dist/infrastructure/providers/openai-provider.js +0 -413
  138. package/dist/infrastructure/providers/openrouter-provider.js +0 -399
  139. package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
  140. package/dist/infrastructure/providers/provider-config-loader.js +0 -120
  141. package/dist/infrastructure/providers/provider-registry.js +0 -88
  142. package/dist/infrastructure/safety/pattern-detector.js +0 -133
  143. package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
  144. package/dist/infrastructure/security/docker-sandbox.js +0 -178
  145. package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
  146. package/dist/infrastructure/security/license-scanner.js +0 -167
  147. package/dist/infrastructure/security/provider-bias-detector.js +0 -164
  148. package/dist/infrastructure/security/sandbox-executor.js +0 -64
  149. package/dist/infrastructure/serialization/toon-serializer.js +0 -119
  150. package/dist/infrastructure/storage/memory-stream-service.js +0 -204
  151. package/dist/infrastructure/storage/plan-repository.js +0 -96
  152. package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
  153. package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
  154. package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
  155. package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
  156. package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
  157. package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
  158. package/dist/infrastructure/storage/task-helpers.js +0 -197
  159. package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
  160. package/dist/infrastructure/ux/appropriate-friction.js +0 -213
  161. package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
  162. package/dist/infrastructure/ux/capability-boundaries.js +0 -42
  163. package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
  164. package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
  165. package/dist/infrastructure/ux/expectation-management.js +0 -327
  166. package/dist/infrastructure/ux/feature-discovery.js +0 -14
  167. package/dist/infrastructure/ux/feedback-prompt.js +0 -45
  168. package/dist/infrastructure/ux/hitl-validation.js +0 -297
  169. package/dist/infrastructure/ux/progress-indicator.js +0 -116
  170. package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
  171. package/dist/infrastructure/ux/review-checkpoint.js +0 -72
  172. package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
  173. package/dist/infrastructure/ux/stream-markdown.js +0 -151
  174. package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
  175. package/dist/infrastructure/ux/team-standards.js +0 -196
  176. package/dist/infrastructure/ux/transparency.js +0 -71
  177. package/dist/infrastructure/validation/agent-feedback.js +0 -55
  178. package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
  179. package/dist/infrastructure/validation/review-handler.js +0 -40
  180. package/dist/infrastructure/validation/summary-aggregator.js +0 -70
  181. package/dist/infrastructure/validation/summary-extractor.js +0 -45
  182. package/dist/infrastructure/validation/trace-summary.js +0 -52
  183. package/dist/infrastructure/verification/verification-service.js +0 -47
  184. package/dist/infrastructure/xai/attention-visualizer.js +0 -172
  185. package/dist/infrastructure/xai/cot-visualizer.js +0 -283
  186. package/dist/infrastructure/xai/decision-tree-log.js +0 -212
  187. package/dist/infrastructure/xai/interactive-xai.js +0 -260
  188. package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
  189. package/dist/intelligent-retrieval.js +0 -272
  190. package/dist/intent/classifier.js +0 -2
  191. package/dist/intent/context.js +0 -2
  192. package/dist/iterative-refinement.js +0 -189
  193. package/dist/learning.js +0 -232
  194. package/dist/log.js +0 -31
  195. package/dist/migrate.js +0 -133
  196. package/dist/parallel-processor.js +0 -534
  197. package/dist/planner.js +0 -198
  198. package/dist/policy.js +0 -26
  199. package/dist/presentation/cli/commands/ask-command.js +0 -314
  200. package/dist/presentation/cli/commands/cost-command.js +0 -191
  201. package/dist/presentation/cli/commands/decision-command.js +0 -207
  202. package/dist/presentation/cli/commands/docs-command.js +0 -25
  203. package/dist/presentation/cli/commands/fix-command.js +0 -53
  204. package/dist/presentation/cli/commands/knowledge-command.js +0 -129
  205. package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
  206. package/dist/presentation/cli/commands/models-command.js +0 -194
  207. package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
  208. package/dist/presentation/cli/commands/plan-command.js +0 -246
  209. package/dist/presentation/cli/commands/product-command.js +0 -199
  210. package/dist/presentation/cli/commands/react-command.js +0 -181
  211. package/dist/presentation/cli/commands/review-command.js +0 -154
  212. package/dist/presentation/cli/commands/run-command.js +0 -188
  213. package/dist/presentation/cli/commands/smart-command.js +0 -395
  214. package/dist/presentation/cli/commands/suggest-command.js +0 -138
  215. package/dist/presentation/cli/commands/trace-command.js +0 -129
  216. package/dist/presentation/cli/commands/undo-command.js +0 -150
  217. package/dist/query-optimizer.js +0 -205
  218. package/dist/refactor.js +0 -116
  219. package/dist/review.js +0 -206
  220. package/dist/search.js +0 -163
  221. package/dist/session.js +0 -704
  222. package/dist/task-verification.js +0 -336
  223. package/dist/testgen.js +0 -166
  224. package/dist/token-optimizer.js +0 -277
  225. package/dist/tools/bash.js +0 -213
  226. package/dist/tools/edit.js +0 -235
  227. package/dist/tools/executor.js +0 -153
  228. package/dist/tools/git-tool.js +0 -292
  229. package/dist/tools/parser.js +0 -158
  230. package/dist/tools/registry.js +0 -302
  231. package/dist/tools/search.js +0 -100
  232. package/dist/types.js +0 -2
  233. package/dist/utils/check-api-status.js +0 -100
  234. package/dist/utils/diff-parser.js +0 -162
  235. package/dist/verification/backup.js +0 -259
  236. package/dist/verification/compiler.js +0 -264
  237. package/dist/verification/index.js +0 -273
  238. package/dist/verification/test-runner.js +0 -379
@@ -1,150 +0,0 @@
1
- /**
2
- * CLI Command: Undo
3
- * Undo file changes by restoring from backups
4
- *
5
- * Clean Architecture: Presentation Layer
6
- */
7
- import { rollbackFile, listBackups, findLatestBackup } from '../../../verification/backup.js';
8
- import { colors, sectionHeader, success, error, warning, info, newline, createBanner, createTable, } from '../../../ui.js';
9
- import { displayError } from '../error-display.js';
10
- import { executionTracer } from '../../../infrastructure/observability/execution-tracer.js';
11
- export async function executeUndoCommand(action, filepath, backupPath) {
12
- // Start execution tracing
13
- const runId = executionTracer.startRun('undo', {
14
- codebaseId: process.cwd(),
15
- });
16
- try {
17
- console.log(createBanner('Undo System', 'File recovery and rollback'));
18
- newline();
19
- switch (action) {
20
- case 'undo': {
21
- if (!filepath) {
22
- console.log(error('File path is required for undo'));
23
- console.log(info('Usage: codehere undo <filepath>'));
24
- return;
25
- }
26
- await undoFile(filepath);
27
- break;
28
- }
29
- case 'list': {
30
- if (!filepath) {
31
- console.log(error('File path is required for list'));
32
- console.log(info('Usage: codehere undo list <filepath>'));
33
- return;
34
- }
35
- await listFileBackups(filepath);
36
- break;
37
- }
38
- case 'restore': {
39
- if (!filepath || !backupPath) {
40
- console.log(error('File path and backup path are required for restore'));
41
- console.log(info('Usage: codehere undo restore <filepath> <backupPath>'));
42
- return;
43
- }
44
- await restoreFromBackup(filepath, backupPath);
45
- break;
46
- }
47
- default:
48
- console.log(error(`Unknown action: ${action}`));
49
- console.log(info('Available actions: undo, list, restore'));
50
- }
51
- }
52
- catch (err) {
53
- displayError(err, {
54
- operation: `undo-${action}`,
55
- showSuggestions: true,
56
- });
57
- throw err;
58
- }
59
- finally {
60
- executionTracer.endRun();
61
- }
62
- }
63
- async function undoFile(filepath) {
64
- const { join } = await import('path');
65
- const fullPath = join(process.cwd(), filepath);
66
- sectionHeader('Undo File Changes');
67
- newline();
68
- try {
69
- const latestBackup = await findLatestBackup(fullPath);
70
- if (!latestBackup) {
71
- console.log(warning(`No backup found for: ${filepath}`));
72
- console.log(colors.dim(' Backups are created automatically before edits.'));
73
- console.log(colors.dim(' If you haven\'t made any edits, there may be no backup.'));
74
- newline();
75
- return;
76
- }
77
- console.log(colors.bold('Restoring from backup:'));
78
- console.log(colors.dim(` File: ${filepath}`));
79
- console.log(colors.dim(` Backup: ${latestBackup}`));
80
- newline();
81
- await rollbackFile(fullPath, latestBackup);
82
- console.log(success('File restored'));
83
- newline();
84
- }
85
- catch (err) {
86
- displayError(err, {
87
- operation: 'undo',
88
- filepath: filepath,
89
- showSuggestions: true,
90
- });
91
- throw err;
92
- }
93
- }
94
- async function listFileBackups(filepath) {
95
- const { join } = await import('path');
96
- const fullPath = join(process.cwd(), filepath);
97
- sectionHeader('Available Backups');
98
- newline();
99
- try {
100
- const backups = await listBackups(fullPath);
101
- if (backups.length === 0) {
102
- console.log(warning(`No backups found for: ${filepath}`));
103
- newline();
104
- return;
105
- }
106
- const backupRows = backups.map((backup, index) => [
107
- String(index + 1),
108
- backup.timestamp.toISOString(),
109
- backup.backupPath,
110
- ]);
111
- const table = createTable(['#', 'Timestamp', 'Backup Path'], backupRows);
112
- console.log(table.toString());
113
- newline();
114
- console.log(colors.dim(`Total backups: ${backups.length}`));
115
- console.log(colors.dim(`Use: codehere undo restore <filepath> <backupPath> to restore a specific backup`));
116
- newline();
117
- }
118
- catch (err) {
119
- displayError(err, {
120
- operation: 'undo-list',
121
- filepath: filepath,
122
- showSuggestions: true,
123
- });
124
- throw err;
125
- }
126
- }
127
- async function restoreFromBackup(filepath, backupPath) {
128
- const { join } = await import('path');
129
- const fullPath = join(process.cwd(), filepath);
130
- sectionHeader('Restore from Backup');
131
- newline();
132
- try {
133
- console.log(colors.bold('Restoring:'));
134
- console.log(colors.dim(` File: ${filepath}`));
135
- console.log(colors.dim(` Backup: ${backupPath}`));
136
- newline();
137
- await rollbackFile(fullPath, backupPath);
138
- console.log(success('File restored'));
139
- newline();
140
- }
141
- catch (err) {
142
- displayError(err, {
143
- operation: 'undo-restore',
144
- filepath: filepath,
145
- showSuggestions: true,
146
- });
147
- throw err;
148
- }
149
- }
150
- //# sourceMappingURL=undo-command.js.map
@@ -1,205 +0,0 @@
1
- /**
2
- * Query Understanding & Optimization System
3
- * Classify intent, select strategy, optimize query, select best model
4
- */
5
- import { classifyQueryIntent } from './intelligent-retrieval.js';
6
- /**
7
- * Optimize query for best results
8
- */
9
- export function optimizeQuery(query) {
10
- const intent = classifyQueryIntent(query);
11
- const keywords = extractKeywords(query);
12
- const symbols = extractSymbols(query);
13
- const optimizedQuery = enhanceQuery(query, intent, keywords, symbols);
14
- const strategy = selectStrategy(intent, query);
15
- return {
16
- optimizedQuery,
17
- strategy,
18
- keywords,
19
- symbols,
20
- };
21
- }
22
- /**
23
- * Extract keywords from query
24
- */
25
- function extractKeywords(query) {
26
- // Remove common stop words
27
- const stopWords = new Set([
28
- 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
29
- 'of', 'with', 'by', 'from', 'as', 'is', 'was', 'are', 'were', 'be',
30
- 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will',
31
- 'would', 'should', 'could', 'may', 'might', 'must', 'can', 'this',
32
- 'that', 'these', 'those', 'what', 'which', 'who', 'whom', 'where',
33
- 'when', 'why', 'how', 'does', 'do', 'is', 'are', 'was', 'were',
34
- ]);
35
- const words = query
36
- .toLowerCase()
37
- .replace(/[^\w\s]/g, ' ')
38
- .split(/\s+/)
39
- .filter(word => word.length > 2 && !stopWords.has(word));
40
- return [...new Set(words)];
41
- }
42
- /**
43
- * Extract symbol names from query
44
- */
45
- function extractSymbols(query) {
46
- const patterns = [
47
- /function\s+(\w+)/gi,
48
- /class\s+(\w+)/gi,
49
- /interface\s+(\w+)/gi,
50
- /type\s+(\w+)/gi,
51
- /const\s+(\w+)/gi,
52
- /let\s+(\w+)/gi,
53
- /var\s+(\w+)/gi,
54
- /([A-Z][a-zA-Z0-9]+)/g, // Capitalized words (likely class names)
55
- /([a-z][a-zA-Z0-9]*\(\))/g, // camelCase followed by () (likely function calls)
56
- /`([^`]+)`/g, // Code in backticks
57
- /'([^']+)'/g, // Code in single quotes
58
- /"([^"]+)"/g, // Code in double quotes
59
- ];
60
- const symbols = new Set();
61
- for (const pattern of patterns) {
62
- const matches = query.matchAll(pattern);
63
- for (const match of matches) {
64
- if (match[1]) {
65
- symbols.add(match[1]);
66
- }
67
- }
68
- }
69
- return Array.from(symbols);
70
- }
71
- /**
72
- * Enhance query with context
73
- */
74
- function enhanceQuery(query, intent, keywords, symbols) {
75
- let enhanced = query;
76
- // Add intent-specific context
77
- switch (intent) {
78
- case 'explain':
79
- if (!query.toLowerCase().includes('how') && !query.toLowerCase().includes('what')) {
80
- enhanced = `Explain how ${query}`;
81
- }
82
- break;
83
- case 'refactor':
84
- if (!query.toLowerCase().includes('refactor')) {
85
- enhanced = `Refactor: ${query}`;
86
- }
87
- break;
88
- case 'debug':
89
- if (!query.toLowerCase().includes('bug') && !query.toLowerCase().includes('error')) {
90
- enhanced = `Debug: ${query}`;
91
- }
92
- break;
93
- case 'find':
94
- if (!query.toLowerCase().includes('find') && !query.toLowerCase().includes('where')) {
95
- enhanced = `Find: ${query}`;
96
- }
97
- break;
98
- }
99
- // Add symbol context if symbols found
100
- if (symbols.length > 0) {
101
- enhanced += ` (symbols: ${symbols.join(', ')})`;
102
- }
103
- return enhanced;
104
- }
105
- /**
106
- * Select optimal strategy based on intent
107
- */
108
- function selectStrategy(intent, query) {
109
- const baseStrategy = {
110
- intent,
111
- contextStrategy: 'relevant-only',
112
- maxTokens: 2000,
113
- maxChunks: 10,
114
- includeRelationships: true,
115
- includeCallGraph: false,
116
- };
117
- switch (intent) {
118
- case 'explain':
119
- return {
120
- ...baseStrategy,
121
- contextStrategy: 'function-level',
122
- maxTokens: 3000,
123
- maxChunks: 15,
124
- includeCallGraph: true, // Need call graph for explanations
125
- };
126
- case 'refactor':
127
- return {
128
- ...baseStrategy,
129
- contextStrategy: 'file-level',
130
- maxTokens: 4000,
131
- maxChunks: 20,
132
- includeRelationships: true,
133
- includeCallGraph: true, // Need to understand dependencies
134
- };
135
- case 'debug':
136
- return {
137
- ...baseStrategy,
138
- contextStrategy: 'relevant-only',
139
- maxTokens: 2500,
140
- maxChunks: 12,
141
- includeRelationships: true,
142
- includeCallGraph: false,
143
- };
144
- case 'implement':
145
- return {
146
- ...baseStrategy,
147
- contextStrategy: 'compressed',
148
- maxTokens: 3000,
149
- maxChunks: 15,
150
- includeRelationships: true,
151
- includeCallGraph: false,
152
- };
153
- case 'find':
154
- return {
155
- ...baseStrategy,
156
- contextStrategy: 'relevant-only',
157
- maxTokens: 1500,
158
- maxChunks: 8,
159
- includeRelationships: false,
160
- includeCallGraph: false,
161
- };
162
- case 'modify':
163
- return {
164
- ...baseStrategy,
165
- contextStrategy: 'function-level',
166
- maxTokens: 2000,
167
- maxChunks: 10,
168
- includeRelationships: true,
169
- includeCallGraph: false,
170
- };
171
- default: // 'understand'
172
- return {
173
- ...baseStrategy,
174
- contextStrategy: 'relevant-only',
175
- maxTokens: 2000,
176
- maxChunks: 10,
177
- includeRelationships: true,
178
- includeCallGraph: false,
179
- };
180
- }
181
- }
182
- /**
183
- * Select best model for task (future: multi-model support)
184
- */
185
- export function selectModel(intent, complexity) {
186
- // For now, always use Cohere
187
- // Future: Use GPT-4 for complex tasks, Claude for reasoning, etc.
188
- return 'cohere';
189
- }
190
- /**
191
- * Estimate query complexity
192
- */
193
- export function estimateComplexity(query, symbols) {
194
- const queryLength = query.length;
195
- const symbolCount = symbols.length;
196
- const hasMultipleConcepts = query.split(/\s+(and|or|but)\s+/i).length > 2;
197
- if (queryLength < 50 && symbolCount === 0 && !hasMultipleConcepts) {
198
- return 'simple';
199
- }
200
- if (queryLength < 200 && symbolCount < 3 && !hasMultipleConcepts) {
201
- return 'medium';
202
- }
203
- return 'complex';
204
- }
205
- //# sourceMappingURL=query-optimizer.js.map
package/dist/refactor.js DELETED
@@ -1,116 +0,0 @@
1
- /**
2
- * Multi-File Refactoring System
3
- * Enterprise-grade cross-file operations
4
- */
5
- import { readFileSync, writeFileSync, existsSync, readdirSync, statSync } from 'fs';
6
- import { join, relative } from 'path';
7
- import { generateDiff } from './chat.js';
8
- import { checkPolicy } from './policy.js';
9
- import { applyUnifiedDiff, parseDiffStats } from './edit.js';
10
- import { retryWithBackoff } from './error-handler.js';
11
- /**
12
- * Refactor multiple files with coordinated changes
13
- */
14
- export async function refactorMultiFile(files, instruction, options = {}) {
15
- const { dryRun = false, maxFiles = 10 } = options;
16
- if (files.length > maxFiles) {
17
- throw new Error(`Too many files (${files.length}). Maximum is ${maxFiles}.`);
18
- }
19
- const results = {
20
- success: false,
21
- filesChanged: [],
22
- totalChanges: {
23
- linesAdded: 0,
24
- linesRemoved: 0,
25
- filesChanged: 0,
26
- },
27
- policyResults: new Map(),
28
- errors: [],
29
- };
30
- // Process each file
31
- for (const file of files) {
32
- try {
33
- const fullPath = join(process.cwd(), file);
34
- if (!existsSync(fullPath)) {
35
- results.errors.push({ file, error: 'File not found' });
36
- continue;
37
- }
38
- const content = readFileSync(fullPath, 'utf-8');
39
- // Generate diff for this file
40
- const diff = await retryWithBackoff(() => generateDiff(content, instruction, file), {
41
- maxRetries: 3,
42
- operationName: `generateDiff:${file}`,
43
- });
44
- // Parse diff stats first
45
- const diffStats = parseDiffStats(diff);
46
- // Check policy
47
- const policyResult = checkPolicy(file, diffStats);
48
- results.policyResults.set(file, policyResult);
49
- if (!policyResult.allowed) {
50
- results.errors.push({
51
- file,
52
- error: policyResult.reason || 'Policy check failed',
53
- });
54
- continue;
55
- }
56
- // Apply diff if not dry run
57
- if (!dryRun) {
58
- const newContent = applyUnifiedDiff(content, diff);
59
- writeFileSync(fullPath, newContent, 'utf-8');
60
- results.filesChanged.push(file);
61
- }
62
- else {
63
- results.filesChanged.push(file + ' (dry-run)');
64
- }
65
- // Calculate stats
66
- const stats = parseDiffStats(diff);
67
- results.totalChanges.linesAdded += stats.linesAdded;
68
- results.totalChanges.linesRemoved += stats.linesRemoved;
69
- results.totalChanges.filesChanged += 1;
70
- }
71
- catch (error) {
72
- results.errors.push({
73
- file,
74
- error: error instanceof Error ? error.message : String(error),
75
- });
76
- }
77
- }
78
- // Success if at least one file changed and no critical errors
79
- results.success = results.filesChanged.length > 0 && results.errors.length === 0;
80
- return results;
81
- }
82
- /**
83
- * Find files matching pattern
84
- */
85
- export function findFilesByPattern(pattern, baseDir = process.cwd()) {
86
- // Simple glob pattern matching
87
- // For production, consider using a proper glob library
88
- const files = [];
89
- const regex = new RegExp(pattern.replace(/\*/g, '.*'));
90
- function walkDir(dir) {
91
- try {
92
- const entries = readdirSync(dir);
93
- for (const entry of entries) {
94
- const fullPath = join(dir, entry);
95
- const relPath = relative(baseDir, fullPath);
96
- // Skip common ignore patterns
97
- if (relPath.includes('node_modules') || relPath.includes('.git')) {
98
- continue;
99
- }
100
- const stat = statSync(fullPath);
101
- if (stat.isDirectory()) {
102
- walkDir(fullPath);
103
- }
104
- else if (stat.isFile() && regex.test(relPath)) {
105
- files.push(relPath);
106
- }
107
- }
108
- }
109
- catch (error) {
110
- // Skip directories we can't read
111
- }
112
- }
113
- walkDir(baseDir);
114
- return files;
115
- }
116
- //# sourceMappingURL=refactor.js.map
package/dist/review.js DELETED
@@ -1,206 +0,0 @@
1
- /**
2
- * Automated Code Review System
3
- * Senior-level code analysis and suggestions
4
- */
5
- import { readFileSync, existsSync } from 'fs';
6
- import { join } from 'path';
7
- import { chatWithContext } from './chat.js';
8
- import { getEnhancedContext } from './context.js';
9
- import { cleanResponse } from './formatter.js';
10
- /**
11
- * Review a single file
12
- */
13
- export async function reviewFile(filepath) {
14
- const fullPath = join(process.cwd(), filepath);
15
- if (!existsSync(fullPath)) {
16
- throw new Error(`File not found: ${filepath}`);
17
- }
18
- const content = readFileSync(fullPath, 'utf-8');
19
- const lines = content.split('\n');
20
- // Get context about the file
21
- const context = await getEnhancedContext(`Review code in ${filepath}`, {
22
- primaryChunks: 10,
23
- includeRelationships: false,
24
- });
25
- // Create review context
26
- const reviewContext = [{
27
- filepath,
28
- content,
29
- score: 1.0,
30
- }];
31
- // Generate review using AI
32
- const reviewPrompt = `You are a senior code reviewer. Review this code file and identify:
33
- 1. Security vulnerabilities
34
- 2. Performance issues
35
- 3. Best practice violations
36
- 4. Potential bugs
37
- 5. Code style issues
38
-
39
- File: ${filepath}
40
- Code:
41
- \`\`\`
42
- ${content}
43
- \`\`\`
44
-
45
- Provide a structured review with specific issues and suggestions.`;
46
- const aiReviewRaw = await chatWithContext(reviewPrompt, reviewContext);
47
- const aiReview = cleanResponse(aiReviewRaw);
48
- // Parse AI review and extract issues
49
- const issues = parseReviewResponse(aiReview, lines);
50
- // Calculate score (100 - (errors * 10) - (warnings * 5) - (info * 1))
51
- const errorCount = issues.filter(i => i.severity === 'error').length;
52
- const warningCount = issues.filter(i => i.severity === 'warning').length;
53
- const infoCount = issues.filter(i => i.severity === 'info').length;
54
- const score = Math.max(0, 100 - (errorCount * 10) - (warningCount * 5) - (infoCount * 1));
55
- // Extract suggestions
56
- const suggestions = issues
57
- .filter(i => i.suggestion)
58
- .map(i => i.suggestion)
59
- .filter((v, i, a) => a.indexOf(v) === i); // Deduplicate
60
- return {
61
- file: filepath,
62
- issues,
63
- score,
64
- summary: generateSummary(issues, score),
65
- suggestions,
66
- };
67
- }
68
- /**
69
- * Review multiple files
70
- */
71
- export async function reviewFiles(filepaths) {
72
- const reviews = [];
73
- for (const filepath of filepaths) {
74
- try {
75
- const review = await reviewFile(filepath);
76
- reviews.push(review);
77
- }
78
- catch (error) {
79
- // Continue with other files if one fails
80
- reviews.push({
81
- file: filepath,
82
- issues: [{
83
- severity: 'error',
84
- category: 'bug',
85
- message: `Failed to review: ${error instanceof Error ? error.message : String(error)}`,
86
- }],
87
- score: 0,
88
- summary: 'Review failed',
89
- suggestions: [],
90
- });
91
- }
92
- }
93
- return reviews;
94
- }
95
- /**
96
- * Parse AI review response into structured issues
97
- */
98
- function parseReviewResponse(aiReview, lines) {
99
- const issues = [];
100
- // Simple parsing - look for common patterns
101
- const lines_review = aiReview.split('\n');
102
- for (let i = 0; i < lines_review.length; i++) {
103
- const line = lines_review[i];
104
- const lowerLine = line.toLowerCase();
105
- // Detect severity
106
- let severity = 'info';
107
- if (lowerLine.includes('error') || lowerLine.includes('critical') || lowerLine.includes('security')) {
108
- severity = 'error';
109
- }
110
- else if (lowerLine.includes('warning') || lowerLine.includes('should') || lowerLine.includes('consider')) {
111
- severity = 'warning';
112
- }
113
- // Detect category
114
- let category = 'best-practice';
115
- if (lowerLine.includes('security') || lowerLine.includes('vulnerability')) {
116
- category = 'security';
117
- }
118
- else if (lowerLine.includes('performance') || lowerLine.includes('slow') || lowerLine.includes('optimize')) {
119
- category = 'performance';
120
- }
121
- else if (lowerLine.includes('bug') || lowerLine.includes('error') || lowerLine.includes('incorrect')) {
122
- category = 'bug';
123
- }
124
- else if (lowerLine.includes('style') || lowerLine.includes('format')) {
125
- category = 'style';
126
- }
127
- // Extract line number if mentioned
128
- const lineMatch = line.match(/line\s+(\d+)/i);
129
- const lineNumber = lineMatch ? parseInt(lineMatch[1], 10) : undefined;
130
- // Extract suggestion
131
- const suggestionMatch = line.match(/suggestion[:\s]+(.+)/i);
132
- const suggestion = suggestionMatch ? suggestionMatch[1].trim() : undefined;
133
- if (line.trim() && (severity !== 'info' || lineNumber || suggestion)) {
134
- issues.push({
135
- severity,
136
- category,
137
- message: line.trim(),
138
- line: lineNumber,
139
- suggestion,
140
- });
141
- }
142
- }
143
- // If no issues found, create a summary issue
144
- if (issues.length === 0) {
145
- issues.push({
146
- severity: 'info',
147
- category: 'best-practice',
148
- message: 'AI review completed. See full review text for details.',
149
- });
150
- }
151
- return issues;
152
- }
153
- /**
154
- * Generate summary from issues
155
- */
156
- function generateSummary(issues, score) {
157
- const errorCount = issues.filter(i => i.severity === 'error').length;
158
- const warningCount = issues.filter(i => i.severity === 'warning').length;
159
- const infoCount = issues.filter(i => i.severity === 'info').length;
160
- if (score >= 90) {
161
- return `Excellent code quality (${score}/100). ${errorCount} errors, ${warningCount} warnings.`;
162
- }
163
- else if (score >= 70) {
164
- return `Good code quality (${score}/100). ${errorCount} errors, ${warningCount} warnings need attention.`;
165
- }
166
- else if (score >= 50) {
167
- return `Moderate code quality (${score}/100). ${errorCount} errors and ${warningCount} warnings should be addressed.`;
168
- }
169
- else {
170
- return `Poor code quality (${score}/100). ${errorCount} critical errors and ${warningCount} warnings require immediate attention.`;
171
- }
172
- }
173
- /**
174
- * Format review for display
175
- */
176
- export function formatReview(review) {
177
- let output = `\nFile: ${review.file}\n`;
178
- output += `Score: ${review.score}/100\n`;
179
- output += `Summary: ${review.summary}\n\n`;
180
- if (review.issues.length > 0) {
181
- output += 'Issues:\n';
182
- for (const issue of review.issues) {
183
- const icon = {
184
- error: '✗',
185
- warning: '⚠',
186
- info: '→',
187
- }[issue.severity];
188
- output += ` ${icon} [${issue.category}] ${issue.message}`;
189
- if (issue.line) {
190
- output += ` (line ${issue.line})`;
191
- }
192
- output += '\n';
193
- if (issue.suggestion) {
194
- output += ` Suggestion: ${issue.suggestion}\n`;
195
- }
196
- }
197
- }
198
- if (review.suggestions.length > 0) {
199
- output += '\nSuggestions:\n';
200
- for (const suggestion of review.suggestions) {
201
- output += ` • ${suggestion}\n`;
202
- }
203
- }
204
- return output;
205
- }
206
- //# sourceMappingURL=review.js.map