@nahisaho/musubix-core 1.0.0

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 (214) hide show
  1. package/bin/musubix.js +18 -0
  2. package/dist/__tests__/index.test.d.ts +2 -0
  3. package/dist/__tests__/index.test.d.ts.map +1 -0
  4. package/dist/__tests__/index.test.js +27 -0
  5. package/dist/__tests__/index.test.js.map +1 -0
  6. package/dist/auth/auth-manager.d.ts +320 -0
  7. package/dist/auth/auth-manager.d.ts.map +1 -0
  8. package/dist/auth/auth-manager.js +580 -0
  9. package/dist/auth/auth-manager.js.map +1 -0
  10. package/dist/cli/base.d.ts +58 -0
  11. package/dist/cli/base.d.ts.map +1 -0
  12. package/dist/cli/base.js +93 -0
  13. package/dist/cli/base.js.map +1 -0
  14. package/dist/cli/commands/help.d.ts +17 -0
  15. package/dist/cli/commands/help.d.ts.map +1 -0
  16. package/dist/cli/commands/help.js +228 -0
  17. package/dist/cli/commands/help.js.map +1 -0
  18. package/dist/cli/commands/index.d.ts +14 -0
  19. package/dist/cli/commands/index.d.ts.map +1 -0
  20. package/dist/cli/commands/index.js +25 -0
  21. package/dist/cli/commands/index.js.map +1 -0
  22. package/dist/cli/commands/init.d.ts +38 -0
  23. package/dist/cli/commands/init.d.ts.map +1 -0
  24. package/dist/cli/commands/init.js +258 -0
  25. package/dist/cli/commands/init.js.map +1 -0
  26. package/dist/cli/index.d.ts +9 -0
  27. package/dist/cli/index.d.ts.map +1 -0
  28. package/dist/cli/index.js +9 -0
  29. package/dist/cli/index.js.map +1 -0
  30. package/dist/codegen/coding-standards.d.ts +250 -0
  31. package/dist/codegen/coding-standards.d.ts.map +1 -0
  32. package/dist/codegen/coding-standards.js +976 -0
  33. package/dist/codegen/coding-standards.js.map +1 -0
  34. package/dist/codegen/coverage-reporter.d.ts +264 -0
  35. package/dist/codegen/coverage-reporter.d.ts.map +1 -0
  36. package/dist/codegen/coverage-reporter.js +697 -0
  37. package/dist/codegen/coverage-reporter.js.map +1 -0
  38. package/dist/codegen/dependency-analyzer.d.ts +271 -0
  39. package/dist/codegen/dependency-analyzer.d.ts.map +1 -0
  40. package/dist/codegen/dependency-analyzer.js +661 -0
  41. package/dist/codegen/dependency-analyzer.js.map +1 -0
  42. package/dist/codegen/generator.d.ts +275 -0
  43. package/dist/codegen/generator.d.ts.map +1 -0
  44. package/dist/codegen/generator.js +781 -0
  45. package/dist/codegen/generator.js.map +1 -0
  46. package/dist/codegen/index.d.ts +18 -0
  47. package/dist/codegen/index.d.ts.map +1 -0
  48. package/dist/codegen/index.js +27 -0
  49. package/dist/codegen/index.js.map +1 -0
  50. package/dist/codegen/integration-test-generator.d.ts +312 -0
  51. package/dist/codegen/integration-test-generator.d.ts.map +1 -0
  52. package/dist/codegen/integration-test-generator.js +765 -0
  53. package/dist/codegen/integration-test-generator.js.map +1 -0
  54. package/dist/codegen/pattern-conformance.d.ts +309 -0
  55. package/dist/codegen/pattern-conformance.d.ts.map +1 -0
  56. package/dist/codegen/pattern-conformance.js +590 -0
  57. package/dist/codegen/pattern-conformance.js.map +1 -0
  58. package/dist/codegen/quality-metrics.d.ts +235 -0
  59. package/dist/codegen/quality-metrics.d.ts.map +1 -0
  60. package/dist/codegen/quality-metrics.js +439 -0
  61. package/dist/codegen/quality-metrics.js.map +1 -0
  62. package/dist/codegen/security-scanner.d.ts +179 -0
  63. package/dist/codegen/security-scanner.d.ts.map +1 -0
  64. package/dist/codegen/security-scanner.js +495 -0
  65. package/dist/codegen/security-scanner.js.map +1 -0
  66. package/dist/codegen/static-analyzer.d.ts +188 -0
  67. package/dist/codegen/static-analyzer.d.ts.map +1 -0
  68. package/dist/codegen/static-analyzer.js +490 -0
  69. package/dist/codegen/static-analyzer.js.map +1 -0
  70. package/dist/codegen/unit-test-generator.d.ts +289 -0
  71. package/dist/codegen/unit-test-generator.d.ts.map +1 -0
  72. package/dist/codegen/unit-test-generator.js +634 -0
  73. package/dist/codegen/unit-test-generator.js.map +1 -0
  74. package/dist/design/adr-generator.d.ts +227 -0
  75. package/dist/design/adr-generator.d.ts.map +1 -0
  76. package/dist/design/adr-generator.js +423 -0
  77. package/dist/design/adr-generator.js.map +1 -0
  78. package/dist/design/c4-generator.d.ts +267 -0
  79. package/dist/design/c4-generator.d.ts.map +1 -0
  80. package/dist/design/c4-generator.js +453 -0
  81. package/dist/design/c4-generator.js.map +1 -0
  82. package/dist/design/framework-optimizer.d.ts +190 -0
  83. package/dist/design/framework-optimizer.d.ts.map +1 -0
  84. package/dist/design/framework-optimizer.js +589 -0
  85. package/dist/design/framework-optimizer.js.map +1 -0
  86. package/dist/design/index.d.ts +12 -0
  87. package/dist/design/index.d.ts.map +1 -0
  88. package/dist/design/index.js +13 -0
  89. package/dist/design/index.js.map +1 -0
  90. package/dist/design/pattern-detector.d.ts +270 -0
  91. package/dist/design/pattern-detector.d.ts.map +1 -0
  92. package/dist/design/pattern-detector.js +621 -0
  93. package/dist/design/pattern-detector.js.map +1 -0
  94. package/dist/design/solid-validator.d.ts +188 -0
  95. package/dist/design/solid-validator.d.ts.map +1 -0
  96. package/dist/design/solid-validator.js +579 -0
  97. package/dist/design/solid-validator.js.map +1 -0
  98. package/dist/error/data-persistence.d.ts +311 -0
  99. package/dist/error/data-persistence.d.ts.map +1 -0
  100. package/dist/error/data-persistence.js +586 -0
  101. package/dist/error/data-persistence.js.map +1 -0
  102. package/dist/error/graceful-degradation.d.ts +309 -0
  103. package/dist/error/graceful-degradation.d.ts.map +1 -0
  104. package/dist/error/graceful-degradation.js +510 -0
  105. package/dist/error/graceful-degradation.js.map +1 -0
  106. package/dist/error/index.d.ts +11 -0
  107. package/dist/error/index.d.ts.map +1 -0
  108. package/dist/error/index.js +19 -0
  109. package/dist/error/index.js.map +1 -0
  110. package/dist/explanation/explanation-generator.d.ts +228 -0
  111. package/dist/explanation/explanation-generator.d.ts.map +1 -0
  112. package/dist/explanation/explanation-generator.js +662 -0
  113. package/dist/explanation/explanation-generator.js.map +1 -0
  114. package/dist/explanation/index.d.ts +11 -0
  115. package/dist/explanation/index.d.ts.map +1 -0
  116. package/dist/explanation/index.js +19 -0
  117. package/dist/explanation/index.js.map +1 -0
  118. package/dist/explanation/reasoning-chain.d.ts +314 -0
  119. package/dist/explanation/reasoning-chain.d.ts.map +1 -0
  120. package/dist/explanation/reasoning-chain.js +414 -0
  121. package/dist/explanation/reasoning-chain.js.map +1 -0
  122. package/dist/explanation/visual-explanation.d.ts +315 -0
  123. package/dist/explanation/visual-explanation.d.ts.map +1 -0
  124. package/dist/explanation/visual-explanation.js +667 -0
  125. package/dist/explanation/visual-explanation.js.map +1 -0
  126. package/dist/index.d.ts +33 -0
  127. package/dist/index.d.ts.map +1 -0
  128. package/dist/index.js +47 -0
  129. package/dist/index.js.map +1 -0
  130. package/dist/requirements/decomposer.d.ts +235 -0
  131. package/dist/requirements/decomposer.d.ts.map +1 -0
  132. package/dist/requirements/decomposer.js +587 -0
  133. package/dist/requirements/decomposer.js.map +1 -0
  134. package/dist/requirements/related-finder.d.ts +261 -0
  135. package/dist/requirements/related-finder.d.ts.map +1 -0
  136. package/dist/requirements/related-finder.js +629 -0
  137. package/dist/requirements/related-finder.js.map +1 -0
  138. package/dist/traceability/impact.d.ts +196 -0
  139. package/dist/traceability/impact.d.ts.map +1 -0
  140. package/dist/traceability/impact.js +438 -0
  141. package/dist/traceability/impact.js.map +1 -0
  142. package/dist/traceability/index.d.ts +9 -0
  143. package/dist/traceability/index.d.ts.map +1 -0
  144. package/dist/traceability/index.js +10 -0
  145. package/dist/traceability/index.js.map +1 -0
  146. package/dist/traceability/manager.d.ts +266 -0
  147. package/dist/traceability/manager.d.ts.map +1 -0
  148. package/dist/traceability/manager.js +412 -0
  149. package/dist/traceability/manager.js.map +1 -0
  150. package/dist/types/common.d.ts +294 -0
  151. package/dist/types/common.d.ts.map +1 -0
  152. package/dist/types/common.js +15 -0
  153. package/dist/types/common.js.map +1 -0
  154. package/dist/types/ears.d.ts +158 -0
  155. package/dist/types/ears.d.ts.map +1 -0
  156. package/dist/types/ears.js +33 -0
  157. package/dist/types/ears.js.map +1 -0
  158. package/dist/types/errors.d.ts +176 -0
  159. package/dist/types/errors.d.ts.map +1 -0
  160. package/dist/types/errors.js +55 -0
  161. package/dist/types/errors.js.map +1 -0
  162. package/dist/types/index.d.ts +10 -0
  163. package/dist/types/index.d.ts.map +1 -0
  164. package/dist/types/index.js +10 -0
  165. package/dist/types/index.js.map +1 -0
  166. package/dist/utils/data-protector.d.ts +122 -0
  167. package/dist/utils/data-protector.d.ts.map +1 -0
  168. package/dist/utils/data-protector.js +275 -0
  169. package/dist/utils/data-protector.js.map +1 -0
  170. package/dist/utils/error-handler.d.ts +101 -0
  171. package/dist/utils/error-handler.d.ts.map +1 -0
  172. package/dist/utils/error-handler.js +324 -0
  173. package/dist/utils/error-handler.js.map +1 -0
  174. package/dist/utils/i18n-manager.d.ts +259 -0
  175. package/dist/utils/i18n-manager.d.ts.map +1 -0
  176. package/dist/utils/i18n-manager.js +554 -0
  177. package/dist/utils/i18n-manager.js.map +1 -0
  178. package/dist/utils/index.d.ts +10 -0
  179. package/dist/utils/index.d.ts.map +1 -0
  180. package/dist/utils/index.js +10 -0
  181. package/dist/utils/index.js.map +1 -0
  182. package/dist/utils/logger.d.ts +120 -0
  183. package/dist/utils/logger.d.ts.map +1 -0
  184. package/dist/utils/logger.js +237 -0
  185. package/dist/utils/logger.js.map +1 -0
  186. package/dist/utils/performance-profiler.d.ts +251 -0
  187. package/dist/utils/performance-profiler.d.ts.map +1 -0
  188. package/dist/utils/performance-profiler.js +458 -0
  189. package/dist/utils/performance-profiler.js.map +1 -0
  190. package/dist/utils/scalability-optimizer.d.ts +294 -0
  191. package/dist/utils/scalability-optimizer.d.ts.map +1 -0
  192. package/dist/utils/scalability-optimizer.js +606 -0
  193. package/dist/utils/scalability-optimizer.js.map +1 -0
  194. package/dist/utils/structured-logger.d.ts +294 -0
  195. package/dist/utils/structured-logger.d.ts.map +1 -0
  196. package/dist/utils/structured-logger.js +630 -0
  197. package/dist/utils/structured-logger.js.map +1 -0
  198. package/dist/utils/version-compatibility.d.ts +217 -0
  199. package/dist/utils/version-compatibility.d.ts.map +1 -0
  200. package/dist/utils/version-compatibility.js +443 -0
  201. package/dist/utils/version-compatibility.js.map +1 -0
  202. package/dist/validators/ears-validator.d.ts +182 -0
  203. package/dist/validators/ears-validator.d.ts.map +1 -0
  204. package/dist/validators/ears-validator.js +357 -0
  205. package/dist/validators/ears-validator.js.map +1 -0
  206. package/dist/validators/index.d.ts +8 -0
  207. package/dist/validators/index.d.ts.map +1 -0
  208. package/dist/validators/index.js +9 -0
  209. package/dist/validators/index.js.map +1 -0
  210. package/dist/version.d.ts +8 -0
  211. package/dist/version.d.ts.map +1 -0
  212. package/dist/version.js +8 -0
  213. package/dist/version.js.map +1 -0
  214. package/package.json +100 -0
@@ -0,0 +1,662 @@
1
+ /**
2
+ * Explanation Generator
3
+ *
4
+ * Generates human-readable explanations from reasoning chains
5
+ *
6
+ * @packageDocumentation
7
+ * @module explanation/explanation-generator
8
+ *
9
+ * @see REQ-EXP-002 - Explanation Generation
10
+ * @see Article VIII - Transparency Standards
11
+ */
12
+ /**
13
+ * Default options
14
+ */
15
+ export const DEFAULT_GENERATOR_OPTIONS = {
16
+ level: 'detailed',
17
+ format: 'markdown',
18
+ audience: 'technical',
19
+ includeEvidence: true,
20
+ includeAlternatives: true,
21
+ includeConfidenceScores: true,
22
+ includeTimestamps: false,
23
+ maxSections: 10,
24
+ language: 'en',
25
+ };
26
+ /**
27
+ * Localized strings
28
+ */
29
+ const LOCALE_STRINGS = {
30
+ en: {
31
+ processOverview: 'Process Overview',
32
+ reasoningProcess: 'Reasoning Process',
33
+ keyDecisions: 'Key Decisions',
34
+ evidenceUsed: 'Evidence Used',
35
+ alternativesConsidered: 'Alternatives Considered',
36
+ conclusion: 'Conclusion',
37
+ confidenceAssessment: 'Confidence Assessment',
38
+ uncertainties: 'Uncertainties and Limitations',
39
+ stepTypes: {
40
+ input: 'Input',
41
+ analysis: 'Analysis',
42
+ inference: 'Inference',
43
+ decision: 'Decision',
44
+ action: 'Action',
45
+ validation: 'Validation',
46
+ output: 'Output',
47
+ error: 'Error',
48
+ fallback: 'Fallback',
49
+ },
50
+ confidenceLevels: {
51
+ high: 'High confidence',
52
+ medium: 'Medium confidence',
53
+ low: 'Low confidence',
54
+ uncertain: 'Uncertain',
55
+ },
56
+ },
57
+ ja: {
58
+ processOverview: 'プロセス概要',
59
+ reasoningProcess: '推論プロセス',
60
+ keyDecisions: '主要な決定事項',
61
+ evidenceUsed: '使用した証拠',
62
+ alternativesConsidered: '検討した代替案',
63
+ conclusion: '結論',
64
+ confidenceAssessment: '信頼度評価',
65
+ uncertainties: '不確実性と制限事項',
66
+ stepTypes: {
67
+ input: '入力',
68
+ analysis: '分析',
69
+ inference: '推論',
70
+ decision: '決定',
71
+ action: 'アクション',
72
+ validation: '検証',
73
+ output: '出力',
74
+ error: 'エラー',
75
+ fallback: 'フォールバック',
76
+ },
77
+ confidenceLevels: {
78
+ high: '高信頼度',
79
+ medium: '中信頼度',
80
+ low: '低信頼度',
81
+ uncertain: '不確実',
82
+ },
83
+ },
84
+ };
85
+ /**
86
+ * Explanation Generator
87
+ */
88
+ export class ExplanationGenerator {
89
+ options;
90
+ explanationCounter = 0;
91
+ constructor(options) {
92
+ this.options = { ...DEFAULT_GENERATOR_OPTIONS, ...options };
93
+ }
94
+ /**
95
+ * Generate explanation from reasoning chain
96
+ */
97
+ generate(chain, options) {
98
+ const opts = { ...this.options, ...options };
99
+ const locale = LOCALE_STRINGS[opts.language];
100
+ const sections = this.generateSections(chain, opts, locale);
101
+ const keyInsights = this.extractKeyInsights(chain, locale);
102
+ const confidenceAssessment = this.generateConfidenceAssessment(chain, locale);
103
+ const uncertainties = this.extractUncertainties(chain);
104
+ const explanation = {
105
+ id: this.generateId(),
106
+ chainId: chain.id,
107
+ title: this.generateTitle(chain),
108
+ summary: this.generateSummary(chain, opts),
109
+ sections: sections.slice(0, opts.maxSections),
110
+ keyInsights,
111
+ confidenceAssessment,
112
+ uncertainties,
113
+ format: opts.format,
114
+ level: opts.level,
115
+ audience: opts.audience,
116
+ generatedAt: new Date(),
117
+ };
118
+ return explanation;
119
+ }
120
+ /**
121
+ * Format explanation to string
122
+ */
123
+ format(explanation) {
124
+ switch (explanation.format) {
125
+ case 'text':
126
+ return this.formatAsText(explanation);
127
+ case 'markdown':
128
+ return this.formatAsMarkdown(explanation);
129
+ case 'html':
130
+ return this.formatAsHtml(explanation);
131
+ case 'json':
132
+ return JSON.stringify(explanation, null, 2);
133
+ default:
134
+ return this.formatAsMarkdown(explanation);
135
+ }
136
+ }
137
+ /**
138
+ * Generate explanation and format in one step
139
+ */
140
+ explain(chain, options) {
141
+ const explanation = this.generate(chain, options);
142
+ return this.format(explanation);
143
+ }
144
+ /**
145
+ * Generate sections based on reasoning chain
146
+ */
147
+ generateSections(chain, opts, locale) {
148
+ const sections = [];
149
+ // Process Overview
150
+ if (opts.level !== 'minimal') {
151
+ sections.push({
152
+ title: locale.processOverview,
153
+ content: this.generateProcessOverview(chain, opts),
154
+ level: 1,
155
+ });
156
+ }
157
+ // Reasoning Process
158
+ const reasoningSection = this.generateReasoningSection(chain, opts, locale);
159
+ if (reasoningSection.subsections?.length || reasoningSection.content) {
160
+ sections.push(reasoningSection);
161
+ }
162
+ // Key Decisions
163
+ const decisions = chain.steps.filter((s) => s.type === 'decision');
164
+ if (decisions.length > 0 && opts.level !== 'minimal') {
165
+ sections.push({
166
+ title: locale.keyDecisions,
167
+ content: this.formatDecisions(decisions, opts, locale),
168
+ level: 1,
169
+ });
170
+ }
171
+ // Evidence Used
172
+ if (opts.includeEvidence && opts.level === 'comprehensive') {
173
+ const allEvidence = chain.steps.flatMap((s) => s.evidence ?? []);
174
+ if (allEvidence.length > 0) {
175
+ sections.push({
176
+ title: locale.evidenceUsed,
177
+ content: this.formatEvidence(allEvidence),
178
+ level: 1,
179
+ });
180
+ }
181
+ }
182
+ // Alternatives Considered
183
+ if (opts.includeAlternatives && opts.level === 'comprehensive') {
184
+ const allAlternatives = chain.steps.flatMap((s) => s.alternatives ?? []);
185
+ if (allAlternatives.length > 0) {
186
+ sections.push({
187
+ title: locale.alternativesConsidered,
188
+ content: this.formatAlternatives(allAlternatives),
189
+ level: 1,
190
+ });
191
+ }
192
+ }
193
+ // Conclusion
194
+ if (chain.outcome) {
195
+ sections.push({
196
+ title: locale.conclusion,
197
+ content: this.formatConclusion(chain),
198
+ level: 1,
199
+ });
200
+ }
201
+ return sections;
202
+ }
203
+ /**
204
+ * Generate process overview
205
+ */
206
+ generateProcessOverview(chain, opts) {
207
+ const stepCount = chain.steps.length;
208
+ const duration = chain.endTime
209
+ ? chain.endTime.getTime() - chain.startTime.getTime()
210
+ : Date.now() - chain.startTime.getTime();
211
+ let overview = `Task: ${chain.task}\n`;
212
+ overview += `Steps: ${stepCount}\n`;
213
+ overview += `Duration: ${this.formatDuration(duration)}\n`;
214
+ overview += `Status: ${chain.status}\n`;
215
+ if (opts.includeConfidenceScores) {
216
+ overview += `Overall Confidence: ${(chain.overallConfidence * 100).toFixed(1)}%\n`;
217
+ }
218
+ return overview;
219
+ }
220
+ /**
221
+ * Generate reasoning section
222
+ */
223
+ generateReasoningSection(chain, opts, locale) {
224
+ const subsections = [];
225
+ // Group steps by type for summary and detailed levels
226
+ if (opts.level === 'summary' || opts.level === 'detailed') {
227
+ const stepsByType = this.groupStepsByType(chain.steps);
228
+ for (const [type, steps] of Object.entries(stepsByType)) {
229
+ if (steps.length > 0) {
230
+ subsections.push({
231
+ title: locale.stepTypes[type],
232
+ content: this.formatStepGroup(steps, opts, locale),
233
+ level: 2,
234
+ });
235
+ }
236
+ }
237
+ }
238
+ // Include all steps for comprehensive level
239
+ if (opts.level === 'comprehensive') {
240
+ for (const step of chain.steps) {
241
+ subsections.push({
242
+ title: `${locale.stepTypes[step.type]}: ${step.description}`,
243
+ content: this.formatStepDetail(step, opts, locale),
244
+ level: 2,
245
+ });
246
+ }
247
+ }
248
+ return {
249
+ title: locale.reasoningProcess,
250
+ content: opts.level === 'minimal'
251
+ ? this.formatMinimalReasoning(chain.steps, locale)
252
+ : '',
253
+ level: 1,
254
+ subsections: opts.level !== 'minimal' ? subsections : undefined,
255
+ };
256
+ }
257
+ /**
258
+ * Group steps by type
259
+ */
260
+ groupStepsByType(steps) {
261
+ const grouped = {
262
+ input: [],
263
+ analysis: [],
264
+ inference: [],
265
+ decision: [],
266
+ action: [],
267
+ validation: [],
268
+ output: [],
269
+ error: [],
270
+ fallback: [],
271
+ };
272
+ for (const step of steps) {
273
+ grouped[step.type].push(step);
274
+ }
275
+ return grouped;
276
+ }
277
+ /**
278
+ * Format step group
279
+ */
280
+ formatStepGroup(steps, opts, locale) {
281
+ return steps
282
+ .map((step) => {
283
+ let line = `- ${step.description}`;
284
+ if (opts.includeConfidenceScores) {
285
+ line += ` (${locale.confidenceLevels[step.confidence]})`;
286
+ }
287
+ return line;
288
+ })
289
+ .join('\n');
290
+ }
291
+ /**
292
+ * Format step detail
293
+ */
294
+ formatStepDetail(step, opts, locale) {
295
+ let detail = '';
296
+ if (opts.includeTimestamps) {
297
+ detail += `Time: ${step.timestamp.toISOString()}\n`;
298
+ }
299
+ if (step.duration) {
300
+ detail += `Duration: ${this.formatDuration(step.duration)}\n`;
301
+ }
302
+ if (opts.includeConfidenceScores) {
303
+ detail += `Confidence: ${locale.confidenceLevels[step.confidence]} (${(step.confidenceScore * 100).toFixed(1)}%)\n`;
304
+ }
305
+ if (step.input !== undefined) {
306
+ detail += `Input: ${this.formatValue(step.input)}\n`;
307
+ }
308
+ if (step.output !== undefined) {
309
+ detail += `Output: ${this.formatValue(step.output)}\n`;
310
+ }
311
+ if (step.evidence?.length) {
312
+ detail += `Evidence: ${step.evidence.length} item(s)\n`;
313
+ }
314
+ if (step.alternatives?.length) {
315
+ detail += `Alternatives considered: ${step.alternatives.length}\n`;
316
+ }
317
+ return detail;
318
+ }
319
+ /**
320
+ * Format minimal reasoning
321
+ */
322
+ formatMinimalReasoning(steps, locale) {
323
+ const keySteps = steps.filter((s) => s.type === 'decision' || s.type === 'inference' || s.type === 'output');
324
+ return keySteps
325
+ .map((step) => `${locale.stepTypes[step.type]}: ${step.description}`)
326
+ .join('\n');
327
+ }
328
+ /**
329
+ * Format decisions
330
+ */
331
+ formatDecisions(decisions, opts, locale) {
332
+ return decisions
333
+ .map((d, i) => {
334
+ let text = `${i + 1}. ${d.description}`;
335
+ if (opts.includeConfidenceScores) {
336
+ text += ` [${locale.confidenceLevels[d.confidence]}]`;
337
+ }
338
+ if (d.alternatives?.length && opts.includeAlternatives) {
339
+ text += `\n Alternatives: ${d.alternatives.map((a) => a.description).join(', ')}`;
340
+ }
341
+ return text;
342
+ })
343
+ .join('\n');
344
+ }
345
+ /**
346
+ * Format evidence
347
+ */
348
+ formatEvidence(evidence) {
349
+ return evidence
350
+ .map((e) => `- [${e.type}] ${e.source}: ${e.content} (relevance: ${(e.relevance * 100).toFixed(0)}%)`)
351
+ .join('\n');
352
+ }
353
+ /**
354
+ * Format alternatives
355
+ */
356
+ formatAlternatives(alternatives) {
357
+ return alternatives
358
+ .map((a) => `- ${a.description}\n Rejected: ${a.rejectionReason}`)
359
+ .join('\n');
360
+ }
361
+ /**
362
+ * Format conclusion
363
+ */
364
+ formatConclusion(chain) {
365
+ if (!chain.outcome)
366
+ return '';
367
+ let conclusion = chain.outcome.summary + '\n';
368
+ if (chain.outcome.keyDecisions.length > 0) {
369
+ conclusion += '\nKey decisions:\n';
370
+ conclusion += chain.outcome.keyDecisions.map((d) => `- ${d}`).join('\n');
371
+ }
372
+ return conclusion;
373
+ }
374
+ /**
375
+ * Generate summary
376
+ */
377
+ generateSummary(chain, _opts) {
378
+ if (chain.outcome) {
379
+ return chain.outcome.summary;
380
+ }
381
+ const lastOutput = [...chain.steps].reverse().find((s) => s.type === 'output');
382
+ if (lastOutput) {
383
+ return lastOutput.description;
384
+ }
385
+ return `Reasoning chain for: ${chain.task}`;
386
+ }
387
+ /**
388
+ * Generate title
389
+ */
390
+ generateTitle(chain) {
391
+ const maxLength = 80;
392
+ if (chain.task.length <= maxLength) {
393
+ return chain.task;
394
+ }
395
+ return chain.task.substring(0, maxLength - 3) + '...';
396
+ }
397
+ /**
398
+ * Extract key insights
399
+ */
400
+ extractKeyInsights(chain, _locale) {
401
+ const insights = [];
402
+ // High confidence decisions
403
+ const highConfDecisions = chain.steps.filter((s) => s.type === 'decision' && s.confidence === 'high');
404
+ for (const d of highConfDecisions.slice(0, 3)) {
405
+ insights.push(`Decision: ${d.description}`);
406
+ }
407
+ // Key inferences
408
+ const inferences = chain.steps.filter((s) => s.type === 'inference');
409
+ for (const i of inferences.slice(0, 2)) {
410
+ insights.push(`Inference: ${i.description}`);
411
+ }
412
+ // Outcome key decisions
413
+ if (chain.outcome?.keyDecisions) {
414
+ for (const kd of chain.outcome.keyDecisions.slice(0, 2)) {
415
+ if (!insights.includes(`Decision: ${kd}`)) {
416
+ insights.push(kd);
417
+ }
418
+ }
419
+ }
420
+ return insights.slice(0, 5);
421
+ }
422
+ /**
423
+ * Generate confidence assessment
424
+ */
425
+ generateConfidenceAssessment(chain, locale) {
426
+ const overall = chain.overallConfidence;
427
+ const level = this.scoreToLevel(overall);
428
+ const lowConfSteps = chain.steps.filter((s) => s.confidence === 'low' || s.confidence === 'uncertain');
429
+ let assessment = `${locale.confidenceLevels[level]} (${(overall * 100).toFixed(1)}%)`;
430
+ if (lowConfSteps.length > 0) {
431
+ assessment += `\n${lowConfSteps.length} step(s) with low confidence.`;
432
+ }
433
+ return assessment;
434
+ }
435
+ /**
436
+ * Extract uncertainties
437
+ */
438
+ extractUncertainties(chain) {
439
+ const uncertainties = [];
440
+ // Low confidence steps
441
+ const lowConfSteps = chain.steps.filter((s) => s.confidence === 'low' || s.confidence === 'uncertain');
442
+ for (const step of lowConfSteps) {
443
+ uncertainties.push(`Uncertain ${step.type}: ${step.description}`);
444
+ }
445
+ // Outcome uncertainties
446
+ if (chain.outcome?.uncertainties) {
447
+ uncertainties.push(...chain.outcome.uncertainties);
448
+ }
449
+ // Errors
450
+ if (chain.error) {
451
+ uncertainties.push(`Error: ${chain.error}`);
452
+ }
453
+ return uncertainties;
454
+ }
455
+ /**
456
+ * Format as text
457
+ */
458
+ formatAsText(explanation) {
459
+ let text = `${explanation.title}\n${'='.repeat(explanation.title.length)}\n\n`;
460
+ text += `${explanation.summary}\n\n`;
461
+ for (const section of explanation.sections) {
462
+ text += this.formatSectionAsText(section);
463
+ }
464
+ if (explanation.keyInsights.length > 0) {
465
+ text += `Key Insights:\n${explanation.keyInsights.map((i) => ` - ${i}`).join('\n')}\n\n`;
466
+ }
467
+ if (explanation.uncertainties.length > 0) {
468
+ text += `Uncertainties:\n${explanation.uncertainties.map((u) => ` - ${u}`).join('\n')}\n\n`;
469
+ }
470
+ text += `Confidence: ${explanation.confidenceAssessment}\n`;
471
+ return text;
472
+ }
473
+ /**
474
+ * Format section as text
475
+ */
476
+ formatSectionAsText(section, indent = '') {
477
+ let text = `${indent}${section.title}\n`;
478
+ text += `${indent}${'-'.repeat(section.title.length)}\n`;
479
+ if (section.content) {
480
+ text += `${section.content.split('\n').map((l) => `${indent}${l}`).join('\n')}\n`;
481
+ }
482
+ if (section.subsections) {
483
+ for (const sub of section.subsections) {
484
+ text += this.formatSectionAsText(sub, indent + ' ');
485
+ }
486
+ }
487
+ text += '\n';
488
+ return text;
489
+ }
490
+ /**
491
+ * Format as markdown
492
+ */
493
+ formatAsMarkdown(explanation) {
494
+ let md = `# ${explanation.title}\n\n`;
495
+ md += `${explanation.summary}\n\n`;
496
+ for (const section of explanation.sections) {
497
+ md += this.formatSectionAsMarkdown(section);
498
+ }
499
+ if (explanation.keyInsights.length > 0) {
500
+ md += `## Key Insights\n\n`;
501
+ md += explanation.keyInsights.map((i) => `- ${i}`).join('\n') + '\n\n';
502
+ }
503
+ if (explanation.uncertainties.length > 0) {
504
+ md += `## Uncertainties\n\n`;
505
+ md += explanation.uncertainties.map((u) => `- ${u}`).join('\n') + '\n\n';
506
+ }
507
+ md += `---\n\n*Confidence: ${explanation.confidenceAssessment}*\n`;
508
+ return md;
509
+ }
510
+ /**
511
+ * Format section as markdown
512
+ */
513
+ formatSectionAsMarkdown(section) {
514
+ const heading = '#'.repeat(section.level + 1);
515
+ let md = `${heading} ${section.title}\n\n`;
516
+ if (section.content) {
517
+ md += `${section.content}\n\n`;
518
+ }
519
+ if (section.subsections) {
520
+ for (const sub of section.subsections) {
521
+ md += this.formatSectionAsMarkdown(sub);
522
+ }
523
+ }
524
+ return md;
525
+ }
526
+ /**
527
+ * Format as HTML
528
+ */
529
+ formatAsHtml(explanation) {
530
+ let html = `<!DOCTYPE html>
531
+ <html>
532
+ <head>
533
+ <meta charset="utf-8">
534
+ <title>${this.escapeHtml(explanation.title)}</title>
535
+ <style>
536
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
537
+ h1, h2, h3, h4 { color: #333; }
538
+ .summary { font-size: 1.1em; color: #666; margin-bottom: 20px; }
539
+ .section { margin-bottom: 20px; }
540
+ .insights { background: #f0f7ff; padding: 15px; border-radius: 5px; }
541
+ .uncertainties { background: #fff5f0; padding: 15px; border-radius: 5px; }
542
+ .confidence { font-style: italic; color: #888; margin-top: 20px; }
543
+ ul { margin: 10px 0; }
544
+ </style>
545
+ </head>
546
+ <body>
547
+ <h1>${this.escapeHtml(explanation.title)}</h1>
548
+ <p class="summary">${this.escapeHtml(explanation.summary)}</p>
549
+ `;
550
+ for (const section of explanation.sections) {
551
+ html += this.formatSectionAsHtml(section);
552
+ }
553
+ if (explanation.keyInsights.length > 0) {
554
+ html += ` <div class="insights">
555
+ <h2>Key Insights</h2>
556
+ <ul>
557
+ ${explanation.keyInsights.map((i) => `<li>${this.escapeHtml(i)}</li>`).join('\n ')}
558
+ </ul>
559
+ </div>
560
+ `;
561
+ }
562
+ if (explanation.uncertainties.length > 0) {
563
+ html += ` <div class="uncertainties">
564
+ <h2>Uncertainties</h2>
565
+ <ul>
566
+ ${explanation.uncertainties.map((u) => `<li>${this.escapeHtml(u)}</li>`).join('\n ')}
567
+ </ul>
568
+ </div>
569
+ `;
570
+ }
571
+ html += ` <p class="confidence">Confidence: ${this.escapeHtml(explanation.confidenceAssessment)}</p>
572
+ </body>
573
+ </html>`;
574
+ return html;
575
+ }
576
+ /**
577
+ * Format section as HTML
578
+ */
579
+ formatSectionAsHtml(section) {
580
+ const tag = `h${Math.min(section.level + 1, 6)}`;
581
+ let html = ` <div class="section">
582
+ <${tag}>${this.escapeHtml(section.title)}</${tag}>
583
+ `;
584
+ if (section.content) {
585
+ html += ` <p>${this.escapeHtml(section.content).replace(/\n/g, '<br>')}</p>\n`;
586
+ }
587
+ if (section.subsections) {
588
+ for (const sub of section.subsections) {
589
+ html += this.formatSectionAsHtml(sub);
590
+ }
591
+ }
592
+ html += ` </div>\n`;
593
+ return html;
594
+ }
595
+ /**
596
+ * Escape HTML
597
+ */
598
+ escapeHtml(text) {
599
+ return text
600
+ .replace(/&/g, '&amp;')
601
+ .replace(/</g, '&lt;')
602
+ .replace(/>/g, '&gt;')
603
+ .replace(/"/g, '&quot;')
604
+ .replace(/'/g, '&#039;');
605
+ }
606
+ /**
607
+ * Format value
608
+ */
609
+ formatValue(value) {
610
+ if (value === null)
611
+ return 'null';
612
+ if (value === undefined)
613
+ return 'undefined';
614
+ if (typeof value === 'string')
615
+ return value;
616
+ if (typeof value === 'number' || typeof value === 'boolean')
617
+ return String(value);
618
+ try {
619
+ const json = JSON.stringify(value);
620
+ return json.length > 100 ? json.substring(0, 97) + '...' : json;
621
+ }
622
+ catch {
623
+ return String(value);
624
+ }
625
+ }
626
+ /**
627
+ * Format duration
628
+ */
629
+ formatDuration(ms) {
630
+ if (ms < 1000)
631
+ return `${ms}ms`;
632
+ if (ms < 60000)
633
+ return `${(ms / 1000).toFixed(2)}s`;
634
+ return `${(ms / 60000).toFixed(2)}min`;
635
+ }
636
+ /**
637
+ * Score to level
638
+ */
639
+ scoreToLevel(score) {
640
+ if (score >= 0.8)
641
+ return 'high';
642
+ if (score >= 0.5)
643
+ return 'medium';
644
+ if (score >= 0.2)
645
+ return 'low';
646
+ return 'uncertain';
647
+ }
648
+ /**
649
+ * Generate ID
650
+ */
651
+ generateId() {
652
+ this.explanationCounter++;
653
+ return `exp-${Date.now()}-${this.explanationCounter}`;
654
+ }
655
+ }
656
+ /**
657
+ * Create explanation generator instance
658
+ */
659
+ export function createExplanationGenerator(options) {
660
+ return new ExplanationGenerator(options);
661
+ }
662
+ //# sourceMappingURL=explanation-generator.js.map