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,212 +0,0 @@
1
- /**
2
- * INTERNAL ONLY — infrastructure helper, not a user-facing feature.
3
- *
4
- * Decision Tree Log - Complete audit trail for multi-step agentic workflows.
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
- * Decision Tree Log
13
- * Maintains complete execution trace for agentic workflows
14
- */
15
- export class DecisionTreeLog {
16
- nodes = new Map();
17
- rootNodeId = null;
18
- /**
19
- * Log goal interpretation
20
- */
21
- logGoalInterpretation(goalId, interpretation, parentId) {
22
- if (!this.rootNodeId) {
23
- this.rootNodeId = goalId;
24
- }
25
- const node = {
26
- id: goalId,
27
- type: 'goal',
28
- timestamp: Date.now(),
29
- description: `Goal: ${interpretation.parsedIntent}`,
30
- metadata: {
31
- parsedIntent: interpretation.parsedIntent,
32
- constraints: interpretation.constraints,
33
- dependencies: interpretation.dependencies,
34
- confidence: interpretation.confidence,
35
- },
36
- parentId,
37
- };
38
- this.nodes.set(goalId, node);
39
- return goalId;
40
- }
41
- /**
42
- * Log plan step
43
- */
44
- logPlanStep(planId, stepDescription, metadata, parentId) {
45
- const node = {
46
- id: planId,
47
- type: 'plan',
48
- timestamp: Date.now(),
49
- description: stepDescription,
50
- metadata,
51
- parentId,
52
- };
53
- this.nodes.set(planId, node);
54
- this.addChild(parentId, planId);
55
- return planId;
56
- }
57
- /**
58
- * Log tool execution with rationale
59
- */
60
- logToolExecution(toolId, rationale, parentId) {
61
- const node = {
62
- id: toolId,
63
- type: 'tool',
64
- timestamp: Date.now(),
65
- description: `Tool: ${rationale.toolName}`,
66
- metadata: {
67
- toolName: rationale.toolName,
68
- parameters: rationale.parameters,
69
- reasoning: rationale.reasoning,
70
- alternativeTools: rationale.alternativeTools,
71
- executionTime: rationale.executionTime,
72
- rawOutput: rationale.rawOutput, // Unaltered tool result for provenance
73
- },
74
- parentId,
75
- };
76
- this.nodes.set(toolId, node);
77
- this.addChild(parentId, toolId);
78
- return toolId;
79
- }
80
- /**
81
- * Log external data provenance
82
- */
83
- logExternalData(dataId, provenance, parentId) {
84
- const node = {
85
- id: dataId,
86
- type: 'tool', // External data comes via tools
87
- timestamp: Date.now(),
88
- description: `External Data: ${provenance.source}`,
89
- metadata: {
90
- source: provenance.source,
91
- timestamp: provenance.timestamp,
92
- freshness: provenance.freshness,
93
- trustLevel: provenance.trustLevel,
94
- url: provenance.url,
95
- dataAge: Date.now() - provenance.timestamp, // Age in milliseconds
96
- },
97
- parentId,
98
- };
99
- this.nodes.set(dataId, node);
100
- this.addChild(parentId, dataId);
101
- return dataId;
102
- }
103
- /**
104
- * Log integration step (how LLM processed external data)
105
- */
106
- logIntegrationStep(integrationId, step, parentId) {
107
- const node = {
108
- id: integrationId,
109
- type: 'synthesis',
110
- timestamp: Date.now(),
111
- description: step.processingDescription,
112
- metadata: {
113
- inputData: step.inputData,
114
- outputData: step.outputData,
115
- transformations: step.transformations,
116
- },
117
- parentId,
118
- };
119
- this.nodes.set(integrationId, node);
120
- this.addChild(parentId, integrationId);
121
- return integrationId;
122
- }
123
- /**
124
- * Log error
125
- */
126
- logError(errorId, error, context, parentId) {
127
- const node = {
128
- id: errorId,
129
- type: 'error',
130
- timestamp: Date.now(),
131
- description: `Error: ${error.message}`,
132
- metadata: {
133
- error: error.message,
134
- stack: error.stack,
135
- context,
136
- },
137
- parentId,
138
- };
139
- this.nodes.set(errorId, node);
140
- this.addChild(parentId, errorId);
141
- return errorId;
142
- }
143
- /**
144
- * Get complete execution tree
145
- */
146
- getExecutionTree() {
147
- if (!this.rootNodeId) {
148
- return null;
149
- }
150
- return this.buildTree(this.rootNodeId);
151
- }
152
- /**
153
- * Build tree structure recursively
154
- */
155
- buildTree(nodeId) {
156
- const node = this.nodes.get(nodeId);
157
- if (!node) {
158
- return null;
159
- }
160
- const children = [];
161
- if (node.childNodeIds && node.childNodeIds.length > 0) {
162
- for (const childId of node.childNodeIds) {
163
- const childNode = this.buildTree(childId);
164
- if (childNode) {
165
- children.push(childNode);
166
- }
167
- }
168
- }
169
- return {
170
- ...node,
171
- children: children.length > 0 ? children : undefined,
172
- };
173
- }
174
- /**
175
- * Add child node to parent
176
- */
177
- addChild(parentId, childId) {
178
- const parent = this.nodes.get(parentId);
179
- if (parent) {
180
- if (!parent.childNodeIds) {
181
- parent.childNodeIds = [];
182
- }
183
- if (!parent.childNodeIds.includes(childId)) {
184
- parent.childNodeIds.push(childId);
185
- }
186
- }
187
- }
188
- /**
189
- * Get trace for fault attribution
190
- */
191
- getErrorTrace(errorId) {
192
- const trace = [];
193
- let currentId = errorId;
194
- while (currentId) {
195
- const node = this.nodes.get(currentId);
196
- if (!node) {
197
- break;
198
- }
199
- trace.unshift(node);
200
- currentId = node.parentId;
201
- }
202
- return trace;
203
- }
204
- /**
205
- * Clear log
206
- */
207
- clear() {
208
- this.nodes.clear();
209
- this.rootNodeId = null;
210
- }
211
- }
212
- //# sourceMappingURL=decision-tree-log.js.map
@@ -1,260 +0,0 @@
1
- /**
2
- * INTERNAL ONLY — experimental feature, not a user-facing feature.
3
- *
4
- * Interactive XAI System - Allows users to click on code for explanations.
5
- * Experimental infrastructure. Not guaranteed to be stable. May be moved to experimental directory.
6
- *
7
- * Do not rely on this directly.
8
- *
9
- * @internal
10
- */
11
- /**
12
- * Interactive XAI System
13
- * Enables users to explore AI reasoning interactively
14
- */
15
- export class InteractiveXAI {
16
- sessions = new Map();
17
- /**
18
- * Create new interactive XAI session
19
- */
20
- createSession(sessionId, query, options) {
21
- const state = {
22
- sessionId,
23
- query,
24
- explanations: new Map(),
25
- cotTrajectoryId: options?.cotTrajectoryId,
26
- attentionMapId: options?.attentionMapId,
27
- createdAt: Date.now(),
28
- };
29
- this.sessions.set(sessionId, state);
30
- return state;
31
- }
32
- /**
33
- * Get explanation for code span
34
- */
35
- getExplanation(sessionId, filepath, startLine, endLine) {
36
- const session = this.sessions.get(sessionId);
37
- if (!session) {
38
- return null;
39
- }
40
- const key = this.getExplanationKey(filepath, startLine, endLine);
41
- return session.explanations.get(key) || null;
42
- }
43
- /**
44
- * Register code explanation
45
- */
46
- registerExplanation(sessionId, explanation) {
47
- const session = this.sessions.get(sessionId);
48
- if (!session) {
49
- throw new Error(`Session ${sessionId} not found`);
50
- }
51
- const key = this.getExplanationKey(explanation.codeSpan.filepath, explanation.codeSpan.startLine, explanation.codeSpan.endLine);
52
- session.explanations.set(key, explanation);
53
- }
54
- /**
55
- * Generate explanation for code span (on-demand)
56
- */
57
- async generateExplanation(sessionId, filepath, startLine, endLine, code, context) {
58
- // Check if explanation already exists
59
- const existing = this.getExplanation(sessionId, filepath, startLine, endLine);
60
- if (existing) {
61
- return existing;
62
- }
63
- // Generate explanation
64
- const explanation = {
65
- codeSpan: {
66
- filepath,
67
- startLine,
68
- endLine,
69
- content: code,
70
- },
71
- explanation: {
72
- why: this.generateWhyExplanation(code, context.query),
73
- how: this.generateHowExplanation(code, context.query),
74
- confidence: this.calculateConfidence(context),
75
- uncertainty: context.uncertainty ? {
76
- epistemic: context.uncertainty.epistemic?.value || 0,
77
- aleatoric: context.uncertainty.aleatoric?.value,
78
- isHallucinationRisk: context.uncertainty.isHallucinationRisk || false,
79
- } : undefined,
80
- },
81
- reasoning: {
82
- cotStepId: this.findRelatedCoTStep(context.cotTrajectory, code),
83
- attentionSpans: this.findRelatedAttentionSpans(context.attentionMap, filepath, startLine, endLine),
84
- decisionPoint: this.findDecisionPoint(context.cotTrajectory, code),
85
- },
86
- metadata: {
87
- timestamp: Date.now(),
88
- },
89
- };
90
- // Register explanation
91
- this.registerExplanation(sessionId, explanation);
92
- return explanation;
93
- }
94
- /**
95
- * Get all explanations for a file
96
- */
97
- getFileExplanations(sessionId, filepath) {
98
- const session = this.sessions.get(sessionId);
99
- if (!session) {
100
- return [];
101
- }
102
- const explanations = [];
103
- for (const explanation of session.explanations.values()) {
104
- if (explanation.codeSpan.filepath === filepath) {
105
- explanations.push(explanation);
106
- }
107
- }
108
- return explanations.sort((a, b) => a.codeSpan.startLine - b.codeSpan.startLine);
109
- }
110
- /**
111
- * Format explanation for display
112
- */
113
- formatExplanation(explanation, format) {
114
- switch (format) {
115
- case 'console':
116
- return this.formatForConsole(explanation);
117
- case 'json':
118
- return JSON.stringify(explanation, null, 2);
119
- case 'markdown':
120
- return this.formatForMarkdown(explanation);
121
- }
122
- }
123
- /**
124
- * Get session state
125
- */
126
- getSession(sessionId) {
127
- return this.sessions.get(sessionId) || null;
128
- }
129
- // Private helpers
130
- getExplanationKey(filepath, startLine, endLine) {
131
- return `${filepath}:${startLine}:${endLine}`;
132
- }
133
- generateWhyExplanation(code, query) {
134
- // Simple heuristic-based explanation
135
- // In production, this would use LLM to generate explanation
136
- return `This code was generated to address: "${query.substring(0, 100)}". The implementation follows the requested functionality.`;
137
- }
138
- generateHowExplanation(code, query) {
139
- // Simple heuristic-based explanation
140
- // In production, this would use LLM to generate explanation
141
- return `This code relates to the query by implementing the core logic requested.`;
142
- }
143
- calculateConfidence(context) {
144
- // Calculate confidence based on uncertainty and context quality
145
- let confidence = 0.8; // Default
146
- if (context.uncertainty) {
147
- const epistemic = context.uncertainty.epistemic?.value || 0;
148
- confidence = 1 - epistemic; // Lower epistemic uncertainty = higher confidence
149
- }
150
- // Adjust based on attention map quality
151
- if (context.attentionMap) {
152
- const avgAttention = context.attentionMap.averageAttentionScore || 0;
153
- confidence = (confidence + avgAttention) / 2;
154
- }
155
- return Math.max(0, Math.min(1, confidence));
156
- }
157
- findRelatedCoTStep(cotTrajectory, code) {
158
- // Find CoT step that likely generated this code
159
- // In production, this would analyze trajectory and code content
160
- if (!cotTrajectory || !cotTrajectory.steps) {
161
- return undefined;
162
- }
163
- // Find action steps that match code generation
164
- for (const step of cotTrajectory.steps) {
165
- if (step.type === 'action' && step.metadata?.tool === 'edit' || step.metadata?.tool === 'create') {
166
- return step.stepId;
167
- }
168
- }
169
- return undefined;
170
- }
171
- findRelatedAttentionSpans(attentionMap, filepath, startLine, endLine) {
172
- if (!attentionMap || !attentionMap.spans) {
173
- return undefined;
174
- }
175
- // Find attention spans related to this file/region
176
- const related = [];
177
- for (const span of attentionMap.spans) {
178
- if (span.filepath === filepath) {
179
- // Check if spans overlap
180
- if (span.startLine <= endLine && span.endLine >= startLine) {
181
- related.push({
182
- filepath: span.filepath,
183
- lines: Array.from({ length: span.endLine - span.startLine + 1 }, (_, i) => span.startLine + i),
184
- relevanceScore: span.attentionScore,
185
- });
186
- }
187
- }
188
- }
189
- return related.length > 0 ? related : undefined;
190
- }
191
- findDecisionPoint(cotTrajectory, code) {
192
- // Find decision point that led to this code
193
- if (!cotTrajectory || !cotTrajectory.steps) {
194
- return undefined;
195
- }
196
- for (const step of cotTrajectory.steps) {
197
- if (step.type === 'decision') {
198
- return step.metadata?.decision || step.content;
199
- }
200
- }
201
- return undefined;
202
- }
203
- formatForConsole(explanation) {
204
- let output = '';
205
- output += `\n${'═'.repeat(80)}\n`;
206
- output += `Code Explanation: ${explanation.codeSpan.filepath} (lines ${explanation.codeSpan.startLine}-${explanation.codeSpan.endLine})\n`;
207
- output += `${'═'.repeat(80)}\n\n`;
208
- output += `Why:\n ${explanation.explanation.why}\n\n`;
209
- output += `How:\n ${explanation.explanation.how}\n\n`;
210
- output += `Confidence: ${(explanation.explanation.confidence * 100).toFixed(1)}%\n`;
211
- if (explanation.explanation.uncertainty) {
212
- output += `\nUncertainty:\n`;
213
- output += ` Epistemic: ${(explanation.explanation.uncertainty.epistemic * 100).toFixed(1)}%\n`;
214
- if (explanation.explanation.uncertainty.isHallucinationRisk) {
215
- output += ` ⚠️ Hallucination Risk Detected\n`;
216
- }
217
- }
218
- if (explanation.reasoning.cotStepNumber) {
219
- output += `\nRelated Reasoning Step: #${explanation.reasoning.cotStepNumber}\n`;
220
- }
221
- if (explanation.reasoning.attentionSpans && explanation.reasoning.attentionSpans.length > 0) {
222
- output += `\nContext Influences:\n`;
223
- for (const span of explanation.reasoning.attentionSpans.slice(0, 3)) {
224
- output += ` - ${span.filepath} (lines ${span.lines[0]}-${span.lines[span.lines.length - 1]}) - Relevance: ${(span.relevanceScore * 100).toFixed(1)}%\n`;
225
- }
226
- }
227
- output += `\n${'═'.repeat(80)}\n`;
228
- return output;
229
- }
230
- formatForMarkdown(explanation) {
231
- let output = '';
232
- output += `## Code Explanation\n\n`;
233
- output += `**File:** \`${explanation.codeSpan.filepath}\` (lines ${explanation.codeSpan.startLine}-${explanation.codeSpan.endLine})\n\n`;
234
- output += `### Why\n\n${explanation.explanation.why}\n\n`;
235
- output += `### How\n\n${explanation.explanation.how}\n\n`;
236
- output += `**Confidence:** ${(explanation.explanation.confidence * 100).toFixed(1)}%\n\n`;
237
- if (explanation.explanation.uncertainty) {
238
- output += `### Uncertainty\n\n`;
239
- output += `- Epistemic: ${(explanation.explanation.uncertainty.epistemic * 100).toFixed(1)}%\n`;
240
- if (explanation.explanation.uncertainty.isHallucinationRisk) {
241
- output += `- ⚠️ **Hallucination Risk Detected**\n`;
242
- }
243
- output += `\n`;
244
- }
245
- if (explanation.reasoning.cotStepNumber) {
246
- output += `### Related Reasoning\n\n`;
247
- output += `Part of reasoning step #${explanation.reasoning.cotStepNumber}\n\n`;
248
- }
249
- if (explanation.reasoning.attentionSpans && explanation.reasoning.attentionSpans.length > 0) {
250
- output += `### Context Influences\n\n`;
251
- for (const span of explanation.reasoning.attentionSpans.slice(0, 3)) {
252
- output += `- \`${span.filepath}\` (lines ${span.lines[0]}-${span.lines[span.lines.length - 1]}) - Relevance: ${(span.relevanceScore * 100).toFixed(1)}%\n`;
253
- }
254
- output += `\n`;
255
- }
256
- output += `\`\`\`\n${explanation.codeSpan.content}\n\`\`\`\n`;
257
- return output;
258
- }
259
- }
260
- //# sourceMappingURL=interactive-xai.js.map
@@ -1,198 +0,0 @@
1
- /**
2
- * INTERNAL ONLY — infrastructure helper, not a user-facing feature.
3
- *
4
- * Uncertainty Quantifier - Distinguishes Epistemic vs Aleatoric uncertainty.
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
- * Uncertainty Quantifier
13
- * Quantifies and communicates model uncertainty
14
- */
15
- export class UncertaintyQuantifier {
16
- epistemicThreshold = 0.7; // High epistemic = hallucination risk
17
- /**
18
- * Quantify uncertainty from LLM response
19
- * Uses multiple sampling approach (dropout method)
20
- */
21
- async quantifyUncertainty(query, response, context) {
22
- // For now, use heuristics based on response characteristics
23
- // In production, would use multiple sampling (dropout method)
24
- // 1. Epistemic Uncertainty (model knowledge gap)
25
- const epistemic = this.estimateEpistemicUncertainty(query, response, context);
26
- // 2. Aleatoric Uncertainty (inherent randomness)
27
- const aleatoric = this.estimateAleatoricUncertainty(response);
28
- // 3. Combined Uncertainty
29
- const combined = this.combineUncertainties(epistemic, aleatoric);
30
- return {
31
- epistemic,
32
- aleatoric,
33
- combined,
34
- isHallucinationRisk: epistemic.value > this.epistemicThreshold,
35
- };
36
- }
37
- /**
38
- * Estimate epistemic uncertainty (model knowledge gap)
39
- * High epistemic = query outside training distribution
40
- */
41
- estimateEpistemicUncertainty(query, response, context) {
42
- let epistemicValue = 0;
43
- const factors = [];
44
- // Factor 1: Query complexity (unknown patterns)
45
- if (this.hasUnknownPatterns(query)) {
46
- epistemicValue += 0.3;
47
- factors.push('Query contains unknown patterns');
48
- }
49
- // Factor 2: Context availability (low context = high uncertainty)
50
- const contextScore = this.calculateContextScore(context);
51
- if (contextScore < 0.3) {
52
- epistemicValue += 0.3;
53
- factors.push('Low context availability');
54
- }
55
- // Factor 3: Response confidence markers (hedging language)
56
- if (this.hasHedgingLanguage(response)) {
57
- epistemicValue += 0.2;
58
- factors.push('Response contains hedging language');
59
- }
60
- // Factor 4: Niche/proprietary API usage (outside training)
61
- if (this.hasNicheAPIs(response)) {
62
- epistemicValue += 0.4;
63
- factors.push('Niche or proprietary API usage detected');
64
- }
65
- epistemicValue = Math.min(epistemicValue, 1.0);
66
- const riskLevel = this.getRiskLevel(epistemicValue);
67
- const recommendation = epistemicValue > this.epistemicThreshold
68
- ? 'High epistemic uncertainty detected. This may indicate hallucination risk. Verify output carefully, especially for niche APIs or proprietary patterns.'
69
- : undefined;
70
- return {
71
- type: 'epistemic',
72
- value: epistemicValue,
73
- explanation: factors.length > 0
74
- ? `Epistemic uncertainty factors: ${factors.join('; ')}`
75
- : 'Low epistemic uncertainty - query appears within model knowledge',
76
- riskLevel,
77
- recommendation,
78
- };
79
- }
80
- /**
81
- * Estimate aleatoric uncertainty (inherent randomness)
82
- */
83
- estimateAleatoricUncertainty(response) {
84
- // Aleatoric uncertainty is harder to estimate from single response
85
- // Would require multiple samples in production
86
- // For now, estimate based on response variability markers
87
- let aleatoricValue = 0;
88
- // Multiple valid solutions increase aleatoric uncertainty
89
- if (response.includes('alternative') || response.includes('could also')) {
90
- aleatoricValue += 0.2;
91
- }
92
- // Default to low aleatoric (assuming deterministic generation)
93
- aleatoricValue = Math.min(aleatoricValue, 0.3);
94
- return {
95
- type: 'aleatoric',
96
- value: aleatoricValue,
97
- explanation: 'Inherent randomness in generation process',
98
- riskLevel: aleatoricValue < 0.2 ? 'low' : 'medium',
99
- };
100
- }
101
- /**
102
- * Combine uncertainties
103
- */
104
- combineUncertainties(epistemic, aleatoric) {
105
- const aleatoricValue = aleatoric?.value || 0;
106
- const combinedValue = Math.max(epistemic.value, aleatoricValue);
107
- return {
108
- type: 'combined',
109
- value: combinedValue,
110
- explanation: `Combined uncertainty: ${epistemic.value.toFixed(2)} epistemic, ${aleatoricValue.toFixed(2)} aleatoric`,
111
- riskLevel: this.getRiskLevel(combinedValue),
112
- recommendation: epistemic.recommendation,
113
- };
114
- }
115
- /**
116
- * Check for unknown patterns (outside training distribution)
117
- */
118
- hasUnknownPatterns(query) {
119
- // Heuristic: Very specific, niche terminology
120
- const nichePatterns = [
121
- /internal.*?api/i,
122
- /proprietary/i,
123
- /custom.*?framework/i,
124
- /company.*?specific/i,
125
- ];
126
- return nichePatterns.some(pattern => pattern.test(query));
127
- }
128
- /**
129
- * Calculate context availability score
130
- */
131
- calculateContextScore(context) {
132
- if (!context) {
133
- return 0;
134
- }
135
- const chunkCount = context.chunks?.length || 0;
136
- const memoryCount = context.memories?.length || 0;
137
- // More context = lower epistemic uncertainty
138
- if (chunkCount > 5 && memoryCount > 2) {
139
- return 0.8;
140
- }
141
- if (chunkCount > 3 || memoryCount > 1) {
142
- return 0.5;
143
- }
144
- if (chunkCount > 0 || memoryCount > 0) {
145
- return 0.3;
146
- }
147
- return 0;
148
- }
149
- /**
150
- * Check for hedging language (indicates uncertainty)
151
- */
152
- hasHedgingLanguage(response) {
153
- const hedging = [
154
- /might/i,
155
- /could/i,
156
- /possibly/i,
157
- /may/i,
158
- /perhaps/i,
159
- /probably/i,
160
- /likely/i,
161
- ];
162
- return hedging.some(pattern => pattern.test(response));
163
- }
164
- /**
165
- * Check for niche/proprietary APIs
166
- */
167
- hasNicheAPIs(response) {
168
- const nichePatterns = [
169
- /internal.*?sdk/i,
170
- /company.*?api/i,
171
- /custom.*?service/i,
172
- /proprietary.*?library/i,
173
- ];
174
- return nichePatterns.some(pattern => pattern.test(response));
175
- }
176
- /**
177
- * Get risk level from uncertainty value
178
- */
179
- getRiskLevel(value) {
180
- if (value >= 0.8) {
181
- return 'critical';
182
- }
183
- if (value >= 0.6) {
184
- return 'high';
185
- }
186
- if (value >= 0.4) {
187
- return 'medium';
188
- }
189
- return 'low';
190
- }
191
- /**
192
- * Set epistemic threshold
193
- */
194
- setEpistemicThreshold(threshold) {
195
- this.epistemicThreshold = threshold;
196
- }
197
- }
198
- //# sourceMappingURL=uncertainty-quantifier.js.map