codehere 0.2.1 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/README.md +88 -68
  2. package/dist/domain/entities/task.js +4 -4
  3. package/dist/error-handler.js +4 -9
  4. package/dist/index.js +253 -1219
  5. package/dist/infrastructure/config/product-context.js +7 -6
  6. package/dist/infrastructure/hooks/claude-sdk-hook.js +335 -63
  7. package/dist/infrastructure/observability/execution-tracer.js +11 -6
  8. package/dist/infrastructure/orchestration/agent-adapter.js +13 -0
  9. package/dist/infrastructure/orchestration/agent-installer.js +101 -0
  10. package/dist/infrastructure/orchestration/agents-config-seed.js +56 -0
  11. package/dist/infrastructure/orchestration/aider-adapter.js +319 -0
  12. package/dist/infrastructure/orchestration/artifacts-extractor.js +175 -0
  13. package/dist/infrastructure/orchestration/claude-code-adapter.js +352 -0
  14. package/dist/infrastructure/orchestration/codex-adapter.js +310 -0
  15. package/dist/infrastructure/orchestration/generic-cli-adapter.js +553 -0
  16. package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
  17. package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
  18. package/dist/infrastructure/orchestration/readiness.js +106 -0
  19. package/dist/infrastructure/orchestration/session-manager.js +272 -0
  20. package/dist/infrastructure/orchestration/session-persistence.js +109 -0
  21. package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
  22. package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
  23. package/dist/infrastructure/protocols/ui-page.js +1827 -0
  24. package/dist/infrastructure/security/file-collection.js +115 -0
  25. package/dist/infrastructure/security/trust-scorer.js +301 -56
  26. package/dist/infrastructure/storage/task-repository.js +8 -7
  27. package/dist/monitoring.js +10 -49
  28. package/dist/presentation/cli/commands/help-command.js +96 -139
  29. package/dist/presentation/cli/commands/hook-command.js +17 -24
  30. package/dist/presentation/cli/commands/report-command.js +59 -72
  31. package/dist/presentation/cli/commands/setup-command.js +4 -4
  32. package/dist/presentation/cli/commands/status-command.js +334 -43
  33. package/dist/presentation/cli/commands/trust-command.js +115 -99
  34. package/dist/presentation/cli/error-display.js +17 -21
  35. package/dist/ui.js +17 -12
  36. package/package.json +35 -67
  37. package/dist/agents/base.js +0 -101
  38. package/dist/agents/orchestrator-model-driven.js +0 -141
  39. package/dist/agents/react-orchestrator-agent.js +0 -54
  40. package/dist/application/agents/execution-agent.js +0 -508
  41. package/dist/application/agents/multi-agent-orchestrator.js +0 -295
  42. package/dist/application/agents/planning-agent.js +0 -433
  43. package/dist/application/agents/validation-agent.js +0 -317
  44. package/dist/application/architectures/plan-and-act.js +0 -242
  45. package/dist/application/index.js +0 -12
  46. package/dist/application/services/agent-factory.js +0 -28
  47. package/dist/application/services/dependency-container.js +0 -596
  48. package/dist/application/services/git-context-service.js +0 -83
  49. package/dist/application/services/intelligent-router.js +0 -934
  50. package/dist/application/services/tool-executor-service.js +0 -94
  51. package/dist/application/use-cases/ask-question-use-case.js +0 -338
  52. package/dist/application/use-cases/edit-file-use-case.js +0 -830
  53. package/dist/application/use-cases/explain-file-use-case.js +0 -50
  54. package/dist/application/use-cases/index-codebase-use-case.js +0 -113
  55. package/dist/application/use-cases/planning-use-case.js +0 -276
  56. package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
  57. package/dist/application/use-cases/reflexion-use-case.js +0 -30
  58. package/dist/application/workflows/deterministic-workflows.js +0 -189
  59. package/dist/ast-parser.js +0 -331
  60. package/dist/cache.js +0 -180
  61. package/dist/chat.js +0 -251
  62. package/dist/code-analysis.js +0 -327
  63. package/dist/context.js +0 -187
  64. package/dist/docs.js +0 -146
  65. package/dist/domain/entities/code-chunk.js +0 -6
  66. package/dist/domain/entities/decision.js +0 -9
  67. package/dist/domain/entities/edit.js +0 -6
  68. package/dist/domain/entities/knowledge-node.js +0 -9
  69. package/dist/domain/entities/knowledge-preservation.js +0 -10
  70. package/dist/domain/entities/memory.js +0 -6
  71. package/dist/domain/entities/pattern.js +0 -7
  72. package/dist/domain/entities/plan.js +0 -6
  73. package/dist/domain/entities/query.js +0 -6
  74. package/dist/domain/errors/embeddings-not-found-error.js +0 -13
  75. package/dist/domain/index.js +0 -19
  76. package/dist/domain/interfaces/ai-service.interface.js +0 -6
  77. package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
  78. package/dist/domain/interfaces/decision-repository.interface.js +0 -9
  79. package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
  80. package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
  81. package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
  82. package/dist/domain/interfaces/memory-repository.interface.js +0 -6
  83. package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
  84. package/dist/domain/interfaces/verification-service.interface.js +0 -6
  85. package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
  86. package/dist/domain/services/decision-recorder.js +0 -223
  87. package/dist/domain/services/decision-retriever.js +0 -133
  88. package/dist/domain/services/environment-mode-manager.js +0 -22
  89. package/dist/domain/services/graded-memory-activation.js +0 -69
  90. package/dist/domain/services/knowledge-access.js +0 -132
  91. package/dist/domain/services/knowledge-extractor.js +0 -247
  92. package/dist/domain/services/knowledge-graph-builder.js +0 -268
  93. package/dist/domain/services/knowledge-graph-query.js +0 -187
  94. package/dist/domain/services/memory-retriever.js +0 -82
  95. package/dist/domain/services/memory-synthesizer.js +0 -91
  96. package/dist/domain/services/pattern-extractor.js +0 -442
  97. package/dist/domain/services/query-intent-classifier.js +0 -140
  98. package/dist/domain/services/react-loop.js +0 -186
  99. package/dist/domain/services/risk-tier-detector.js +0 -78
  100. package/dist/edit.js +0 -319
  101. package/dist/embed.js +0 -459
  102. package/dist/formatter.js +0 -168
  103. package/dist/git.js +0 -198
  104. package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
  105. package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
  106. package/dist/infrastructure/ai/model-config.js +0 -84
  107. package/dist/infrastructure/ai/provider-ai-service.js +0 -477
  108. package/dist/infrastructure/cache/embedding-cache.js +0 -175
  109. package/dist/infrastructure/cache/query-result-cache.js +0 -66
  110. package/dist/infrastructure/cache/response-cache.js +0 -48
  111. package/dist/infrastructure/cache/security-scan-cache.js +0 -47
  112. package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
  113. package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
  114. package/dist/infrastructure/context/context-compressor.js +0 -329
  115. package/dist/infrastructure/context/conversation-context.js +0 -128
  116. package/dist/infrastructure/context/session-manager.js +0 -94
  117. package/dist/infrastructure/cost/cost-tracker.js +0 -360
  118. package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
  119. package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
  120. package/dist/infrastructure/governance/policy-as-code.js +0 -258
  121. package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
  122. package/dist/infrastructure/index.js +0 -7
  123. package/dist/infrastructure/observability/prompt-versioner.js +0 -145
  124. package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
  125. package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
  126. package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
  127. package/dist/infrastructure/protocols/mcp-server.js +0 -333
  128. package/dist/infrastructure/protocols/streaming-handler.js +0 -103
  129. package/dist/infrastructure/providers/cohere-provider.js +0 -444
  130. package/dist/infrastructure/providers/fake-provider.js +0 -130
  131. package/dist/infrastructure/providers/local-llm-provider.js +0 -330
  132. package/dist/infrastructure/providers/model-config.types.js +0 -9
  133. package/dist/infrastructure/providers/model-provider.interface.js +0 -8
  134. package/dist/infrastructure/providers/openai-provider.js +0 -413
  135. package/dist/infrastructure/providers/openrouter-provider.js +0 -399
  136. package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
  137. package/dist/infrastructure/providers/provider-config-loader.js +0 -120
  138. package/dist/infrastructure/providers/provider-registry.js +0 -88
  139. package/dist/infrastructure/safety/pattern-detector.js +0 -133
  140. package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
  141. package/dist/infrastructure/security/docker-sandbox.js +0 -178
  142. package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
  143. package/dist/infrastructure/security/license-scanner.js +0 -167
  144. package/dist/infrastructure/security/provider-bias-detector.js +0 -164
  145. package/dist/infrastructure/security/sandbox-executor.js +0 -64
  146. package/dist/infrastructure/serialization/toon-serializer.js +0 -119
  147. package/dist/infrastructure/storage/memory-stream-service.js +0 -204
  148. package/dist/infrastructure/storage/plan-repository.js +0 -96
  149. package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
  150. package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
  151. package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
  152. package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
  153. package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
  154. package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
  155. package/dist/infrastructure/storage/task-helpers.js +0 -197
  156. package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
  157. package/dist/infrastructure/ux/appropriate-friction.js +0 -213
  158. package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
  159. package/dist/infrastructure/ux/capability-boundaries.js +0 -42
  160. package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
  161. package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
  162. package/dist/infrastructure/ux/expectation-management.js +0 -327
  163. package/dist/infrastructure/ux/feature-discovery.js +0 -14
  164. package/dist/infrastructure/ux/feedback-prompt.js +0 -45
  165. package/dist/infrastructure/ux/hitl-validation.js +0 -297
  166. package/dist/infrastructure/ux/progress-indicator.js +0 -116
  167. package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
  168. package/dist/infrastructure/ux/review-checkpoint.js +0 -72
  169. package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
  170. package/dist/infrastructure/ux/stream-markdown.js +0 -151
  171. package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
  172. package/dist/infrastructure/ux/team-standards.js +0 -196
  173. package/dist/infrastructure/ux/transparency.js +0 -71
  174. package/dist/infrastructure/validation/agent-feedback.js +0 -55
  175. package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
  176. package/dist/infrastructure/validation/review-handler.js +0 -40
  177. package/dist/infrastructure/validation/summary-aggregator.js +0 -70
  178. package/dist/infrastructure/validation/summary-extractor.js +0 -45
  179. package/dist/infrastructure/validation/trace-summary.js +0 -52
  180. package/dist/infrastructure/verification/verification-service.js +0 -47
  181. package/dist/infrastructure/xai/attention-visualizer.js +0 -172
  182. package/dist/infrastructure/xai/cot-visualizer.js +0 -283
  183. package/dist/infrastructure/xai/decision-tree-log.js +0 -212
  184. package/dist/infrastructure/xai/interactive-xai.js +0 -260
  185. package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
  186. package/dist/intelligent-retrieval.js +0 -272
  187. package/dist/intent/classifier.js +0 -2
  188. package/dist/intent/context.js +0 -2
  189. package/dist/iterative-refinement.js +0 -189
  190. package/dist/learning.js +0 -232
  191. package/dist/log.js +0 -31
  192. package/dist/migrate.js +0 -133
  193. package/dist/parallel-processor.js +0 -530
  194. package/dist/planner.js +0 -198
  195. package/dist/policy.js +0 -26
  196. package/dist/presentation/cli/commands/ask-command.js +0 -314
  197. package/dist/presentation/cli/commands/cost-command.js +0 -191
  198. package/dist/presentation/cli/commands/decision-command.js +0 -207
  199. package/dist/presentation/cli/commands/docs-command.js +0 -25
  200. package/dist/presentation/cli/commands/fix-command.js +0 -53
  201. package/dist/presentation/cli/commands/knowledge-command.js +0 -129
  202. package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
  203. package/dist/presentation/cli/commands/models-command.js +0 -194
  204. package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
  205. package/dist/presentation/cli/commands/plan-command.js +0 -246
  206. package/dist/presentation/cli/commands/product-command.js +0 -199
  207. package/dist/presentation/cli/commands/react-command.js +0 -181
  208. package/dist/presentation/cli/commands/review-command.js +0 -154
  209. package/dist/presentation/cli/commands/run-command.js +0 -188
  210. package/dist/presentation/cli/commands/smart-command.js +0 -395
  211. package/dist/presentation/cli/commands/suggest-command.js +0 -138
  212. package/dist/presentation/cli/commands/trace-command.js +0 -129
  213. package/dist/presentation/cli/commands/undo-command.js +0 -150
  214. package/dist/query-optimizer.js +0 -205
  215. package/dist/refactor.js +0 -116
  216. package/dist/review.js +0 -206
  217. package/dist/search.js +0 -163
  218. package/dist/session.js +0 -652
  219. package/dist/task-verification.js +0 -336
  220. package/dist/testgen.js +0 -166
  221. package/dist/token-optimizer.js +0 -277
  222. package/dist/tools/bash.js +0 -213
  223. package/dist/tools/edit.js +0 -235
  224. package/dist/tools/executor.js +0 -153
  225. package/dist/tools/git-tool.js +0 -292
  226. package/dist/tools/parser.js +0 -158
  227. package/dist/tools/registry.js +0 -302
  228. package/dist/tools/search.js +0 -100
  229. package/dist/types.js +0 -2
  230. package/dist/utils/check-api-status.js +0 -100
  231. package/dist/utils/diff-parser.js +0 -162
  232. package/dist/verification/backup.js +0 -259
  233. package/dist/verification/compiler.js +0 -264
  234. package/dist/verification/index.js +0 -273
  235. package/dist/verification/test-runner.js +0 -379
@@ -1,47 +0,0 @@
1
- /**
2
- * Infrastructure: VerificationService
3
- * Implements IVerificationService using existing verification system
4
- */
5
- import { verifyFile } from '../../verification/index.js';
6
- export class VerificationService {
7
- async verifyCompilation(filepath) {
8
- const result = await verifyFile(filepath, {
9
- verifyCompilation: true,
10
- runTests: false,
11
- });
12
- return {
13
- success: result.success,
14
- compiled: result.compiled,
15
- testsPassed: false,
16
- errors: result.errors,
17
- warnings: result.warnings,
18
- };
19
- }
20
- async runTests(filepath) {
21
- const result = await verifyFile(filepath, {
22
- verifyCompilation: false,
23
- runTests: true,
24
- });
25
- return {
26
- success: result.success,
27
- compiled: true,
28
- testsPassed: result.testsPassed,
29
- errors: result.errors,
30
- warnings: result.warnings,
31
- };
32
- }
33
- async verify(filepath) {
34
- const result = await verifyFile(filepath, {
35
- verifyCompilation: true,
36
- runTests: true,
37
- });
38
- return {
39
- success: result.success,
40
- compiled: result.compiled,
41
- testsPassed: result.testsPassed,
42
- errors: result.errors,
43
- warnings: result.warnings,
44
- };
45
- }
46
- }
47
- //# sourceMappingURL=verification-service.js.map
@@ -1,172 +0,0 @@
1
- /**
2
- * INTERNAL ONLY — infrastructure helper, not a user-facing feature.
3
- *
4
- * Attention Visualizer - Visualizes which parts of code/context the AI is focusing on.
5
- * Used internally for logging/debugging. Not guaranteed to be stable.
6
- *
7
- * Do not rely on this directly.
8
- *
9
- * @internal
10
- */
11
- /**
12
- * Attention Visualizer
13
- * Identifies and visualizes code regions the AI is focusing on
14
- */
15
- export class AttentionVisualizer {
16
- /**
17
- * Generate attention map from code chunks and relevance scores
18
- */
19
- generateAttentionMap(query, chunks) {
20
- const spans = chunks.map((chunk, index) => {
21
- // Normalize score to 0-1 range (if not already)
22
- const rawScore = chunk.score || 0;
23
- const maxScore = Math.max(...chunks.map(c => c.score || 0), 1);
24
- const attentionScore = maxScore > 0 ? rawScore / maxScore : 0;
25
- // Extract line numbers if available
26
- const startLine = chunk.startLine || 1;
27
- const endLine = chunk.endLine || startLine + chunk.content.split('\n').length;
28
- return {
29
- filepath: chunk.filepath,
30
- startLine,
31
- endLine,
32
- content: chunk.content,
33
- attentionScore,
34
- relevanceReason: this.generateRelevanceReason(chunk, attentionScore),
35
- };
36
- });
37
- // Sort by attention score (descending)
38
- spans.sort((a, b) => b.attentionScore - a.attentionScore);
39
- const averageAttentionScore = spans.reduce((sum, span) => sum + span.attentionScore, 0) / spans.length;
40
- return {
41
- query,
42
- spans,
43
- totalContextLines: spans.reduce((sum, span) => sum + (span.endLine - span.startLine + 1), 0),
44
- averageAttentionScore,
45
- topAttentionSpans: spans.slice(0, 5), // Top 5 most attended spans
46
- createdAt: Date.now(),
47
- };
48
- }
49
- /**
50
- * Format attention map for console output
51
- */
52
- formatForConsole(attentionMap, options) {
53
- const { maxSpans = 10, showContent = false } = options || {};
54
- const spansToShow = attentionMap.topAttentionSpans.slice(0, maxSpans);
55
- let output = '';
56
- output += `\n${'═'.repeat(80)}\n`;
57
- output += `Attention Map: ${attentionMap.query.substring(0, 60)}${attentionMap.query.length > 60 ? '...' : ''}\n`;
58
- output += `${'═'.repeat(80)}\n\n`;
59
- output += `Total context: ${attentionMap.totalContextLines} lines across ${attentionMap.spans.length} spans\n`;
60
- output += `Average attention score: ${(attentionMap.averageAttentionScore * 100).toFixed(1)}%\n\n`;
61
- output += `Top ${spansToShow.length} Most Attended Code Regions:\n`;
62
- output += `${'─'.repeat(80)}\n\n`;
63
- for (let i = 0; i < spansToShow.length; i++) {
64
- const span = spansToShow[i];
65
- const attentionBar = this.generateAttentionBar(span.attentionScore);
66
- output += `${i + 1}. ${span.filepath} (lines ${span.startLine}-${span.endLine})\n`;
67
- output += ` Attention: ${attentionBar} ${(span.attentionScore * 100).toFixed(1)}%\n`;
68
- if (span.relevanceReason) {
69
- output += ` Reason: ${span.relevanceReason}\n`;
70
- }
71
- if (showContent) {
72
- const preview = span.content.split('\n').slice(0, 5).join('\n');
73
- output += ` Preview:\n${preview.split('\n').map(line => ` ${line}`).join('\n')}\n`;
74
- if (span.content.split('\n').length > 5) {
75
- output += ` ... (${span.content.split('\n').length - 5} more lines)\n`;
76
- }
77
- }
78
- output += '\n';
79
- }
80
- return output;
81
- }
82
- /**
83
- * Generate attention heatmap data (for UI visualization)
84
- */
85
- generateHeatmapData(attentionMap) {
86
- // Group spans by filepath
87
- const fileMap = new Map();
88
- for (const span of attentionMap.spans) {
89
- if (!fileMap.has(span.filepath)) {
90
- fileMap.set(span.filepath, []);
91
- }
92
- fileMap.get(span.filepath).push(span);
93
- }
94
- // Generate heatmap data for each file
95
- const heatmapData = [];
96
- for (const [filepath, spans] of fileMap.entries()) {
97
- const lineMap = new Map();
98
- // Collect attention scores per line
99
- for (const span of spans) {
100
- const lines = span.content.split('\n');
101
- for (let i = 0; i < lines.length; i++) {
102
- const lineNumber = span.startLine + i;
103
- const existing = lineMap.get(lineNumber);
104
- // Use max attention score if line appears in multiple spans
105
- const score = existing
106
- ? Math.max(existing.score, span.attentionScore)
107
- : span.attentionScore;
108
- lineMap.set(lineNumber, {
109
- score,
110
- content: lines[i],
111
- });
112
- }
113
- }
114
- // Convert to array and sort by line number
115
- const lines = Array.from(lineMap.entries())
116
- .map(([lineNumber, data]) => ({
117
- lineNumber,
118
- attentionScore: data.score,
119
- content: data.content,
120
- }))
121
- .sort((a, b) => a.lineNumber - b.lineNumber);
122
- heatmapData.push({
123
- filepath,
124
- lines,
125
- });
126
- }
127
- return heatmapData;
128
- }
129
- /**
130
- * Verify context grounding (check if attention spans actually relate to query)
131
- */
132
- verifyGrounding(attentionMap, query) {
133
- const issues = [];
134
- let totalScore = 0;
135
- for (const span of attentionMap.topAttentionSpans.slice(0, 3)) {
136
- totalScore += span.attentionScore;
137
- // Check if high-attention spans have low relevance
138
- if (span.attentionScore > 0.8 && !span.relevanceReason) {
139
- issues.push(`High attention span (${span.filepath}) lacks clear relevance reason`);
140
- }
141
- }
142
- const averageTopScore = totalScore / Math.min(3, attentionMap.topAttentionSpans.length);
143
- const grounded = averageTopScore > 0.5 && issues.length === 0;
144
- const confidence = averageTopScore;
145
- return {
146
- grounded,
147
- confidence,
148
- issues: issues.length > 0 ? issues : undefined,
149
- };
150
- }
151
- // Private helpers
152
- generateRelevanceReason(chunk, attentionScore) {
153
- if (attentionScore > 0.8) {
154
- return 'Highly relevant - direct match to query';
155
- }
156
- else if (attentionScore > 0.5) {
157
- return 'Relevant - related functionality';
158
- }
159
- else if (attentionScore > 0.2) {
160
- return 'Somewhat relevant - contextual reference';
161
- }
162
- else {
163
- return 'Low relevance - background context';
164
- }
165
- }
166
- generateAttentionBar(score, length = 20) {
167
- const filled = Math.round(score * length);
168
- const empty = length - filled;
169
- return '█'.repeat(filled) + '░'.repeat(empty);
170
- }
171
- }
172
- //# sourceMappingURL=attention-visualizer.js.map
@@ -1,283 +0,0 @@
1
- /**
2
- * INTERNAL ONLY — infrastructure helper, not a user-facing feature.
3
- *
4
- * Chain-of-Thought (CoT) Visualizer - Visualizes AI reasoning steps in a human-readable format.
5
- * Used internally for logging and debugging. Not guaranteed to be stable.
6
- *
7
- * Do not rely on this directly.
8
- *
9
- * @internal
10
- */
11
- import { colors } from '../../ui.js';
12
- /**
13
- * Chain-of-Thought Visualizer
14
- * Formats reasoning steps for human-readable display
15
- */
16
- export class CoTVisualizer {
17
- /**
18
- * Create new CoT trajectory
19
- */
20
- createTrajectory(query) {
21
- return {
22
- trajectoryId: `cot-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
23
- query,
24
- steps: [],
25
- currentStep: 0,
26
- status: 'in_progress',
27
- startedAt: Date.now(),
28
- };
29
- }
30
- /**
31
- * Add thought step
32
- */
33
- addThought(trajectory, thought, metadata) {
34
- const stepId = `step-${Date.now()}-thought`;
35
- const step = {
36
- stepId,
37
- stepNumber: trajectory.steps.length + 1,
38
- type: 'thought',
39
- content: thought,
40
- timestamp: Date.now(),
41
- metadata,
42
- };
43
- trajectory.steps.push(step);
44
- trajectory.currentStep = trajectory.steps.length;
45
- return stepId;
46
- }
47
- /**
48
- * Add action step (tool call, edit, etc.)
49
- */
50
- addAction(trajectory, action, metadata) {
51
- const stepId = `step-${Date.now()}-action`;
52
- const step = {
53
- stepId,
54
- stepNumber: trajectory.steps.length + 1,
55
- type: 'action',
56
- content: action,
57
- timestamp: Date.now(),
58
- metadata,
59
- };
60
- trajectory.steps.push(step);
61
- trajectory.currentStep = trajectory.steps.length;
62
- return stepId;
63
- }
64
- /**
65
- * Add observation step (tool result, file content, etc.)
66
- */
67
- addObservation(trajectory, observation, metadata) {
68
- const stepId = `step-${Date.now()}-observation`;
69
- const step = {
70
- stepId,
71
- stepNumber: trajectory.steps.length + 1,
72
- type: 'observation',
73
- content: observation,
74
- timestamp: Date.now(),
75
- metadata,
76
- };
77
- trajectory.steps.push(step);
78
- trajectory.currentStep = trajectory.steps.length;
79
- return stepId;
80
- }
81
- /**
82
- * Add decision step (choice point, branching)
83
- */
84
- addDecision(trajectory, decision, options, chosen, rationale) {
85
- const stepId = `step-${Date.now()}-decision`;
86
- const step = {
87
- stepId,
88
- stepNumber: trajectory.steps.length + 1,
89
- type: 'decision',
90
- content: decision,
91
- timestamp: Date.now(),
92
- metadata: {
93
- options,
94
- chosen,
95
- reasoning: rationale,
96
- },
97
- };
98
- trajectory.steps.push(step);
99
- trajectory.currentStep = trajectory.steps.length;
100
- return stepId;
101
- }
102
- /**
103
- * Add error step
104
- */
105
- addError(trajectory, error, errorDetails) {
106
- const stepId = `step-${Date.now()}-error`;
107
- const step = {
108
- stepId,
109
- stepNumber: trajectory.steps.length + 1,
110
- type: 'error',
111
- content: error,
112
- timestamp: Date.now(),
113
- metadata: {
114
- errorDetails,
115
- },
116
- };
117
- trajectory.steps.push(step);
118
- trajectory.currentStep = trajectory.steps.length;
119
- trajectory.status = 'failed';
120
- return stepId;
121
- }
122
- /**
123
- * Mark trajectory as completed
124
- */
125
- completeTrajectory(trajectory) {
126
- trajectory.status = 'completed';
127
- trajectory.completedAt = Date.now();
128
- }
129
- /**
130
- * Format trajectory for console output (human-readable)
131
- */
132
- formatForConsole(trajectory, options) {
133
- const { showMetadata = false, maxSteps, compact = false } = options || {};
134
- const steps = maxSteps ? trajectory.steps.slice(0, maxSteps) : trajectory.steps;
135
- let output = '';
136
- if (!compact) {
137
- output += `\n${'═'.repeat(80)}\n`;
138
- output += `Chain of Thought: ${trajectory.query.substring(0, 60)}${trajectory.query.length > 60 ? '...' : ''}\n`;
139
- output += `${'═'.repeat(80)}\n\n`;
140
- }
141
- for (const step of steps) {
142
- output += this.formatStep(step, { showMetadata, compact });
143
- }
144
- if (trajectory.status === 'completed' && !compact) {
145
- output += `\n${'─'.repeat(80)}\n`;
146
- output += `✓ Completed in ${trajectory.steps.length} steps`;
147
- if (trajectory.completedAt && trajectory.startedAt) {
148
- const duration = ((trajectory.completedAt - trajectory.startedAt) / 1000).toFixed(2);
149
- output += ` (${duration}s)\n`;
150
- }
151
- output += `${'─'.repeat(80)}\n`;
152
- }
153
- return output;
154
- }
155
- /**
156
- * Format trajectory for JSON export
157
- */
158
- formatForJSON(trajectory) {
159
- return JSON.stringify(trajectory, null, 2);
160
- }
161
- /**
162
- * Format trajectory for interactive UI (structured data)
163
- */
164
- formatForUI(trajectory) {
165
- return {
166
- query: trajectory.query,
167
- status: trajectory.status,
168
- steps: trajectory.steps.map(step => ({
169
- number: step.stepNumber,
170
- type: step.type,
171
- content: step.content,
172
- timestamp: step.timestamp,
173
- metadata: step.metadata,
174
- })),
175
- duration: trajectory.completedAt && trajectory.startedAt
176
- ? trajectory.completedAt - trajectory.startedAt
177
- : undefined,
178
- };
179
- }
180
- // Private helpers
181
- formatStep(step, options) {
182
- const { showMetadata = false, compact = false } = options;
183
- let output = '';
184
- const maxWidth = process.stdout.columns || 80;
185
- const indent = ' ';
186
- const contentWidth = maxWidth - indent.length - 10; // Reserve space for prefix/icon
187
- const prefix = compact ? '' : `[Step ${step.stepNumber}] `;
188
- const icon = this.getStepIcon(step.type);
189
- // Word wrap helper for long content
190
- const wrapText = (text, width, prefix = '') => {
191
- if (compact && text.length > 150) {
192
- // In compact mode, truncate long content
193
- return text.substring(0, 150) + '...';
194
- }
195
- const words = text.split(' ');
196
- const lines = [];
197
- let currentLine = '';
198
- for (const word of words) {
199
- if ((currentLine + word).length > width) {
200
- if (currentLine)
201
- lines.push(prefix + currentLine.trim());
202
- currentLine = word + ' ';
203
- }
204
- else {
205
- currentLine += word + ' ';
206
- }
207
- }
208
- if (currentLine)
209
- lines.push(prefix + currentLine.trim());
210
- return lines.join('\n');
211
- };
212
- switch (step.type) {
213
- case 'thought':
214
- output += colors.dim(`${prefix}${icon}`) + ` ${colors.bold('Thought:')}\n`;
215
- output += wrapText(step.content, contentWidth, indent);
216
- // Show reasoning quality if available
217
- if (showMetadata && step.metadata?.confidence !== undefined) {
218
- const conf = step.metadata.confidence;
219
- const confLabel = conf >= 0.8 ? colors.green('✓ High') : conf >= 0.6 ? colors.yellow('⚠ Medium') : colors.red('✗ Low');
220
- output += `\n${indent}└─ Confidence: ${confLabel} ${colors.dim(`(${(conf * 100).toFixed(0)}%)`)}`;
221
- }
222
- break;
223
- case 'action':
224
- output += colors.dim(`${prefix}${icon}`) + ` ${colors.cyan('Action:')} ${colors.cyan(step.content)}\n`;
225
- if (showMetadata && step.metadata?.tool) {
226
- output += `${indent}└─ Tool: ${colors.cyan(step.metadata.tool)}\n`;
227
- if (step.metadata.reasoning) {
228
- output += `${indent}└─ Reasoning: ${colors.dim(wrapText(step.metadata.reasoning, contentWidth - 14, ''))}\n`;
229
- }
230
- }
231
- break;
232
- case 'observation':
233
- const obsText = compact && step.content.length > 150
234
- ? step.content.substring(0, 150) + '...'
235
- : step.content;
236
- output += colors.dim(`${prefix}${icon}`) + ` ${colors.green('Observation:')}\n`;
237
- output += wrapText(obsText, contentWidth, indent);
238
- break;
239
- case 'decision':
240
- output += colors.dim(`${prefix}${icon}`) + ` ${colors.magenta('Decision:')} ${colors.magenta(step.content)}\n`;
241
- if (showMetadata && step.metadata?.options) {
242
- output += `${indent}└─ Options: ${colors.dim(step.metadata.options.join(', '))}\n`;
243
- output += `${indent}└─ Chosen: ${colors.green(step.metadata.chosen)}\n`;
244
- if (step.metadata.reasoning) {
245
- output += `${indent}└─ Reasoning: ${colors.dim(wrapText(step.metadata.reasoning, contentWidth - 14, ''))}\n`;
246
- }
247
- if (step.metadata.confidence !== undefined) {
248
- const conf = step.metadata.confidence;
249
- const confLabel = conf >= 0.8 ? colors.green('✓ High') : conf >= 0.6 ? colors.yellow('⚠ Medium') : colors.red('✗ Low');
250
- output += `${indent}└─ Confidence: ${confLabel} ${colors.dim(`(${(conf * 100).toFixed(0)}%)`)}\n`;
251
- }
252
- }
253
- break;
254
- case 'error':
255
- output += colors.dim(`${prefix}${icon}`) + ` ${colors.red('Error:')} ${colors.red(step.content)}\n`;
256
- if (showMetadata && step.metadata?.errorDetails) {
257
- output += `${indent}└─ Details: ${colors.dim(JSON.stringify(step.metadata.errorDetails))}\n`;
258
- }
259
- break;
260
- }
261
- if (!compact) {
262
- output += '\n';
263
- }
264
- return output;
265
- }
266
- getStepIcon(type) {
267
- switch (type) {
268
- case 'thought':
269
- return '💭';
270
- case 'action':
271
- return '⚡';
272
- case 'observation':
273
- return '👁️';
274
- case 'decision':
275
- return '🔀';
276
- case 'error':
277
- return '❌';
278
- default:
279
- return '•';
280
- }
281
- }
282
- }
283
- //# sourceMappingURL=cot-visualizer.js.map