oneie 1.3.3 → 1.3.4

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 (179) hide show
  1. package/.claude/agents/engineering-architect.md +39 -56
  2. package/.claude/agents/engineering-developer.md +37 -57
  3. package/.claude/agents/engineering-director.md +37 -144
  4. package/.claude/agents/engineering-ingestor.md +229 -0
  5. package/.claude/agents/engineering-quality-assurance.md +40 -206
  6. package/.claude/agents/engineering-user-experience.md +36 -207
  7. package/.claude/agents/improver.md +454 -0
  8. package/.claude/agents/marketing-brand-identity.md +37 -48
  9. package/.claude/agents/marketing-director.md +9 -0
  10. package/.claude/agents/one-orchestrator.md +50 -136
  11. package/.claude/agents/story-teller.md +10 -0
  12. package/.claude/agents/task-master.md +10 -0
  13. package/.claude/agents/turbo-repo-builder.md +51 -0
  14. package/.claude/claude-code-hooks.json +20 -233
  15. package/.claude/commands/agent-balance +111 -0
  16. package/.claude/commands/agent.md +24 -7
  17. package/.claude/commands/cascade-status.md +128 -0
  18. package/.claude/commands/ingest.md +290 -0
  19. package/.claude/commands/ingestor.md +136 -0
  20. package/.claude/commands/mission.md +26 -8
  21. package/.claude/commands/one.md +351 -14
  22. package/.claude/commands/quality-check.md +204 -0
  23. package/.claude/commands/smart-route.md +220 -0
  24. package/.claude/commands/start.md +9 -8
  25. package/.claude/commands/story.md +18 -3
  26. package/.claude/commands/task.md +22 -1
  27. package/.claude/settings.local.json +18 -3
  28. package/.obsidian/core-plugins.json +3 -1
  29. package/.one/checklists/agent-quality-checklist.md +24 -15
  30. package/.one/checklists/story-quality-checklist.md +24 -15
  31. package/.one/checklists/task-quality-checklist.md +24 -15
  32. package/.one/templates/bun-workspace-guide-template.md +188 -0
  33. package/.one/templates/bunfig-template.toml +95 -0
  34. package/.one/templates/root-package-template.json +37 -21
  35. package/.one/templates/turbo-config-template.json +18 -3
  36. package/.one/tools/bump-core-version.js +0 -0
  37. package/.one/tools/bump-expansion-version.js +0 -0
  38. package/.one/tools/code-generators.js +0 -0
  39. package/.one/tools/compression-engine.js +638 -0
  40. package/.one/tools/content-deduplicator.js +336 -0
  41. package/.one/tools/convert-wav-to-mp3.js +0 -0
  42. package/.one/tools/foundation-wizard.js +0 -0
  43. package/.one/tools/generate-toc.js +0 -0
  44. package/.one/tools/ingestor/cascade-integration.js +523 -0
  45. package/.one/tools/ingestor/cli.ts +234 -0
  46. package/.one/tools/ingestor/context-mapper.ts +604 -0
  47. package/.one/tools/ingestor/error-handling-monitor.js +742 -0
  48. package/.one/tools/ingestor/file-discovery.ts +484 -0
  49. package/.one/tools/ingestor/file-transformer.ts +524 -0
  50. package/.one/tools/ingestor/ingestor-orchestrator.ts +416 -0
  51. package/.one/tools/ingestor/package.json +47 -0
  52. package/.one/tools/ingestor/usage-examples.md +458 -0
  53. package/.one/tools/lazy-loader.js +489 -0
  54. package/.one/tools/minimal-generators.js +0 -0
  55. package/.one/tools/performance-benchmark.js +300 -0
  56. package/.one/tools/premium-manager.js +0 -0
  57. package/.one/tools/semantic-release-sync-installer.js +0 -0
  58. package/.one/tools/size-memory-optimizer.js +475 -0
  59. package/.one/tools/sync-installer-version.js +0 -0
  60. package/.one/tools/text-to-speech.js +0 -0
  61. package/.one/tools/transformative-ai-engine.js +0 -0
  62. package/.one/workflows/safe-improvement-deployment.yaml +420 -0
  63. package/CLAUDE.md +30 -0
  64. package/README.md +41 -10
  65. package/one/cache/benchmark-results.json +43 -0
  66. package/one/cache/file-index.json +12480 -0
  67. package/one/config/agent-routing.yaml +124 -0
  68. package/one/config/agent-skills.yaml +451 -0
  69. package/one/config/cache-config.yaml +304 -0
  70. package/one/config/feedback-templates.yaml +152 -0
  71. package/one/config/performance-config.yaml +281 -0
  72. package/one/config/quality-automation.yaml +405 -0
  73. package/one/config/routing-logic.yaml +292 -0
  74. package/one/data/task-registry.yaml +224 -0
  75. package/one/stories/story-1.10-parallel-task-execution-orchestration.md +119 -0
  76. package/one/stories/story-3.1-external-repository-foundation.md +374 -0
  77. package/one/stories/story-3.2-3-levels-architecture-integration.md +449 -0
  78. package/one/stories/story-3.3-multi-platform-application-development.md +677 -0
  79. package/one/stories/story-3.4-shared-package-system-ui-components.md +854 -0
  80. package/one/stories/story-3.5-backend-integration-production-deployment.md +1034 -0
  81. package/one/tasks/task-1.10.1-design-parallel-execution-architecture.md +108 -0
  82. package/one/tasks/task-1.10.2-create-task-dependency-mapping-system.md +82 -0
  83. package/one/tasks/task-1.10.3-build-agent-spawning-orchestration-engine.md +120 -0
  84. package/one/tasks/task-1.10.4-implement-task-queue-dependency-resolution.md +125 -0
  85. package/one/tasks/task-1.10.5-create-task-numbering-convention-system.md +542 -0
  86. package/one/tasks/task-3.1.1-external-repository-creation.md +303 -0
  87. package/one/tasks/task-3.1.2-turborepo-configuration-optimization.md +402 -0
  88. package/one/tasks/task-3.1.3-shared-configuration-packages.md +571 -0
  89. package/one/tasks/task-3.1.4-bun-package-management-optimization.md +627 -0
  90. package/one/tools/task-numbering-validator.js +429 -0
  91. package/package.json +1 -1
  92. package/quality-gate-optimization-analysis.md +260 -0
  93. package/turbo-benchmark.js +268 -0
  94. package/turbo-optimization-guide.md +163 -0
  95. package/turbo-workspace-template.json +83 -0
  96. package/turbo.json +178 -0
  97. package/.claude/commands/analyst.md +0 -70
  98. package/.claude/commands/architect.md +0 -67
  99. package/.claude/commands/commander.md +0 -78
  100. package/.claude/commands/deploy.md +0 -68
  101. package/.claude/commands/dev.md +0 -60
  102. package/.claude/commands/playbook.md +0 -81
  103. package/.claude/commands/pm.md +0 -64
  104. package/.claude/commands/po.md +0 -68
  105. package/.claude/commands/qa.md +0 -59
  106. package/.claude/commands/taskmaster.md +0 -85
  107. package/.claude/commands/ux-expert.md +0 -58
  108. package/.one/stories/bullstamp-attract-module-complete.md +0 -255
  109. package/.one/stories/bullstamp-deployment-master-plan.md +0 -518
  110. package/.one/stories/bullstamp-executive-implementation-summary.md +0 -254
  111. package/.one/stories/bullstamp-project-status-complete.md +0 -257
  112. package/.one/stories/obsidian-pandoc-config.md +0 -159
  113. package/.one/stories/story-1.1-perfect-filesystem-organization.md +0 -270
  114. package/.one/stories/story-1.1.1.md +0 -136
  115. package/.one/stories/story-1.1.md +0 -131
  116. package/.one/stories/story-1.2.md +0 -420
  117. package/.one/stories/story-1.3.md +0 -177
  118. package/.one/stories/story-1.4.md +0 -356
  119. package/.one/stories/story-1.5.md +0 -572
  120. package/.one/stories/story-1.6.md +0 -481
  121. package/.one/stories/story-1.7.md +0 -923
  122. package/.one/stories/story-1.8.md +0 -404
  123. package/.one/stories/story-2.0.md +0 -132
  124. package/.one/stories/story-2.1.md +0 -110
  125. package/.one/stories/story-2.2.md +0 -110
  126. package/.one/stories/story-2.3.md +0 -112
  127. package/.one/stories/story-2.4.md +0 -116
  128. package/.one/stories/story-2.5.md +0 -114
  129. package/.one/stories/story-3.1.md +0 -298
  130. package/.one/stories/story-3.10.md +0 -302
  131. package/.one/stories/story-3.11.md +0 -167
  132. package/.one/stories/story-3.12.md +0 -235
  133. package/.one/stories/story-3.13.md +0 -235
  134. package/.one/stories/story-3.14.md +0 -225
  135. package/.one/stories/story-3.15.md +0 -238
  136. package/.one/stories/story-3.16.md +0 -244
  137. package/.one/stories/story-3.17.md +0 -245
  138. package/.one/stories/story-3.18.md +0 -248
  139. package/.one/stories/story-3.2.md +0 -226
  140. package/.one/stories/story-3.3.md +0 -226
  141. package/.one/stories/story-3.4.md +0 -226
  142. package/.one/stories/story-3.5.md +0 -167
  143. package/.one/stories/story-3.6.md +0 -167
  144. package/.one/stories/story-3.7.md +0 -181
  145. package/.one/stories/story-3.8.md +0 -198
  146. package/.one/stories/story-3.9.md +0 -169
  147. package/.one/stories/story-4.1.md +0 -245
  148. package/.one/stories/story-4.2.md +0 -314
  149. package/.one/stories/story-4.3.md +0 -610
  150. package/.one/stories/story-4.4.md +0 -931
  151. package/.one/stories/story-4.5.md +0 -727
  152. package/.one/stories/story-4.6-consistency.md +0 -175
  153. package/.one/stories/story-5.1.md +0 -508
  154. package/.one/stories/story-5.2.md +0 -451
  155. package/.one/stories/story-5.3.md +0 -405
  156. package/.one/stories/story-5.4.md +0 -447
  157. package/.one/stories/story-5.5.md +0 -349
  158. package/.one/stories/story-5.6.md +0 -445
  159. package/.one/stories/story-6.1-text-content-engine.md +0 -144
  160. package/.one/stories/story-6.2-audio-content-engine.md +0 -145
  161. package/.one/stories/story-6.3-video-content-engine.md +0 -145
  162. package/.one/stories/story-6.4-visual-content-engine.md +0 -177
  163. package/.one/stories/story-6.5-cross-platform-distribution.md +0 -188
  164. package/.one/stories/story-6.6.ai-content-generation-pipeline.md +0 -196
  165. package/.one/stories/story-6.7-character-consistency-quality-control.md +0 -216
  166. package/.one/stories/story-6.8-claude-code-content-integration.md +0 -181
  167. package/.one/stories/story-6.8-content-production-workflows.md +0 -247
  168. package/.one/stories/story-7.1-implementation.md +0 -128
  169. package/.one/stories/story-7.1.md +0 -203
  170. package/.one/stories/story-7.2-implementation.md +0 -147
  171. package/.one/stories/story-7.2.md +0 -415
  172. package/.one/stories/story-7.3-implementation.md +0 -159
  173. package/.one/stories/story-7.3.md +0 -463
  174. package/.one/stories/story-7.4-implementation.md +0 -154
  175. package/.one/stories/story-7.4.md +0 -500
  176. package/.one/stories/story-validation-report.md +0 -169
  177. package/one/archive-index.json +0 -91
  178. /package/one/stories/{story-3.1-npx-oneie-turbo-enhancement.md → story-2.1.1-npx-oneie-turbo-enhancement.md} +0 -0
  179. /package/one/stories/{story-3.2-npx-connection-implementation.md → story-2.21-npx-connection-implementation.md} +0 -0
@@ -0,0 +1,742 @@
1
+ /**
2
+ * Error Handling & Monitoring System for /ingest Command
3
+ * Integrates with CASCADE quality gates and real-time monitoring
4
+ */
5
+
6
+ const EventEmitter = require('events');
7
+
8
+ class IngestErrorHandler extends EventEmitter {
9
+ constructor() {
10
+ super();
11
+ this.errorPatterns = new Map();
12
+ this.recoveryStrategies = new Map();
13
+ this.qualityGateThresholds = {
14
+ agentFailureRate: 0.1, // Max 10% agent failures
15
+ taskTimeoutRate: 0.05, // Max 5% task timeouts
16
+ qualityScoreMin: 4.0, // Minimum 4.0 stars
17
+ criticalErrorsMax: 0 // No critical errors allowed
18
+ };
19
+ this.initializeErrorPatterns();
20
+ this.initializeRecoveryStrategies();
21
+ }
22
+
23
+ /**
24
+ * Initialize known error patterns and their classifications
25
+ */
26
+ initializeErrorPatterns() {
27
+ // Agent-specific error patterns
28
+ this.errorPatterns.set('AGENT_TIMEOUT', {
29
+ severity: 'high',
30
+ category: 'agent_performance',
31
+ recoverable: true,
32
+ impactLevel: 'task'
33
+ });
34
+
35
+ this.errorPatterns.set('AGENT_OVERLOAD', {
36
+ severity: 'medium',
37
+ category: 'resource_constraint',
38
+ recoverable: true,
39
+ impactLevel: 'story'
40
+ });
41
+
42
+ this.errorPatterns.set('DEPENDENCY_DEADLOCK', {
43
+ severity: 'critical',
44
+ category: 'coordination',
45
+ recoverable: true,
46
+ impactLevel: 'mission'
47
+ });
48
+
49
+ // Ingestion-specific error patterns
50
+ this.errorPatterns.set('SOURCE_INACCESSIBLE', {
51
+ severity: 'critical',
52
+ category: 'configuration',
53
+ recoverable: false,
54
+ impactLevel: 'mission'
55
+ });
56
+
57
+ this.errorPatterns.set('FRAMEWORK_DETECTION_FAILED', {
58
+ severity: 'medium',
59
+ category: 'analysis',
60
+ recoverable: true,
61
+ impactLevel: 'story'
62
+ });
63
+
64
+ this.errorPatterns.set('QUALITY_GATE_FAILURE', {
65
+ severity: 'high',
66
+ category: 'quality',
67
+ recoverable: true,
68
+ impactLevel: 'task'
69
+ });
70
+
71
+ this.errorPatterns.set('MEMORY_EXHAUSTION', {
72
+ severity: 'high',
73
+ category: 'resource_constraint',
74
+ recoverable: true,
75
+ impactLevel: 'story'
76
+ });
77
+
78
+ this.errorPatterns.set('CONCURRENT_TASK_COLLISION', {
79
+ severity: 'medium',
80
+ category: 'coordination',
81
+ recoverable: true,
82
+ impactLevel: 'task'
83
+ });
84
+ }
85
+
86
+ /**
87
+ * Initialize recovery strategies for different error types
88
+ */
89
+ initializeRecoveryStrategies() {
90
+ // Agent performance recovery
91
+ this.recoveryStrategies.set('AGENT_TIMEOUT', async (context) => {
92
+ return {
93
+ action: 'rescale_and_retry',
94
+ steps: [
95
+ 'Scale up agent pool capacity',
96
+ 'Redistribute workload',
97
+ 'Retry failed tasks with extended timeout',
98
+ 'Monitor performance metrics'
99
+ ],
100
+ expectedRecoveryTime: '2-3 minutes',
101
+ successProbability: 0.85
102
+ };
103
+ });
104
+
105
+ this.recoveryStrategies.set('AGENT_OVERLOAD', async (context) => {
106
+ return {
107
+ action: 'elastic_scaling',
108
+ steps: [
109
+ 'Trigger elastic agent scaling (43 → 430)',
110
+ 'Rebalance workload across expanded pool',
111
+ 'Implement priority queuing',
112
+ 'Monitor resource utilization'
113
+ ],
114
+ expectedRecoveryTime: '1-2 minutes',
115
+ successProbability: 0.90
116
+ };
117
+ });
118
+
119
+ this.recoveryStrategies.set('DEPENDENCY_DEADLOCK', async (context) => {
120
+ return {
121
+ action: 'dag_restructure',
122
+ steps: [
123
+ 'Analyze dependency graph for cycles',
124
+ 'Break deadlock with timeout mechanisms',
125
+ 'Restructure task dependencies using DAG',
126
+ 'Resume parallel execution'
127
+ ],
128
+ expectedRecoveryTime: '30 seconds',
129
+ successProbability: 0.95
130
+ };
131
+ });
132
+
133
+ // Configuration and analysis recovery
134
+ this.recoveryStrategies.set('SOURCE_INACCESSIBLE', async (context) => {
135
+ return {
136
+ action: 'fail_fast_with_guidance',
137
+ steps: [
138
+ 'Validate source directory permissions',
139
+ 'Provide clear error message with suggestions',
140
+ 'Abort mission gracefully',
141
+ 'Log detailed diagnostics for troubleshooting'
142
+ ],
143
+ expectedRecoveryTime: 'immediate',
144
+ successProbability: 0.0 // Not recoverable
145
+ };
146
+ });
147
+
148
+ this.recoveryStrategies.set('FRAMEWORK_DETECTION_FAILED', async (context) => {
149
+ return {
150
+ action: 'fallback_analysis',
151
+ steps: [
152
+ 'Switch to generic TypeScript/React analysis',
153
+ 'Reduce framework-specific optimizations',
154
+ 'Continue with basic file classification',
155
+ 'Flag for manual review'
156
+ ],
157
+ expectedRecoveryTime: '30 seconds',
158
+ successProbability: 0.75
159
+ };
160
+ });
161
+
162
+ this.recoveryStrategies.set('QUALITY_GATE_FAILURE', async (context) => {
163
+ return {
164
+ action: 'quality_improvement_cycle',
165
+ steps: [
166
+ 'Identify specific quality criteria failures',
167
+ 'Apply automated quality improvements',
168
+ 'Re-run quality validation',
169
+ 'Escalate to human review if needed'
170
+ ],
171
+ expectedRecoveryTime: '1-2 minutes',
172
+ successProbability: 0.70
173
+ };
174
+ });
175
+ }
176
+
177
+ /**
178
+ * Handle errors with CASCADE-aware recovery
179
+ */
180
+ async handleError(error, context) {
181
+ const errorInfo = this.classifyError(error, context);
182
+ const monitoringUpdate = this.updateMonitoringMetrics(errorInfo);
183
+
184
+ // Emit error event for real-time monitoring
185
+ this.emit('error_detected', {
186
+ error: errorInfo,
187
+ context,
188
+ timestamp: Date.now(),
189
+ monitoring: monitoringUpdate
190
+ });
191
+
192
+ // Determine if error violates quality gates
193
+ const qualityGateStatus = this.checkQualityGates(errorInfo, context);
194
+
195
+ if (!qualityGateStatus.passed) {
196
+ this.emit('quality_gate_violation', {
197
+ errorInfo,
198
+ qualityGateStatus,
199
+ context
200
+ });
201
+ }
202
+
203
+ // Attempt recovery if error is recoverable
204
+ if (errorInfo.recoverable) {
205
+ return await this.attemptRecovery(errorInfo, context);
206
+ } else {
207
+ return await this.gracefulDegradation(errorInfo, context);
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Classify error and determine handling strategy
213
+ */
214
+ classifyError(error, context) {
215
+ // Extract error pattern
216
+ const errorPattern = this.identifyErrorPattern(error);
217
+ const patternInfo = this.errorPatterns.get(errorPattern) || {
218
+ severity: 'unknown',
219
+ category: 'unclassified',
220
+ recoverable: false,
221
+ impactLevel: 'task'
222
+ };
223
+
224
+ return {
225
+ originalError: error,
226
+ pattern: errorPattern,
227
+ severity: patternInfo.severity,
228
+ category: patternInfo.category,
229
+ recoverable: patternInfo.recoverable,
230
+ impactLevel: patternInfo.impactLevel,
231
+ context: {
232
+ agent: context.agent,
233
+ task: context.task,
234
+ story: context.story,
235
+ mission: context.mission
236
+ },
237
+ timestamp: Date.now()
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Identify error pattern from error message and context
243
+ */
244
+ identifyErrorPattern(error) {
245
+ const message = error.message || error.toString();
246
+
247
+ // Pattern matching for common error types
248
+ if (message.includes('timeout') || message.includes('ETIMEDOUT')) {
249
+ return 'AGENT_TIMEOUT';
250
+ }
251
+ if (message.includes('ENOENT') || message.includes('cannot access')) {
252
+ return 'SOURCE_INACCESSIBLE';
253
+ }
254
+ if (message.includes('deadlock') || message.includes('circular dependency')) {
255
+ return 'DEPENDENCY_DEADLOCK';
256
+ }
257
+ if (message.includes('out of memory') || message.includes('heap limit')) {
258
+ return 'MEMORY_EXHAUSTION';
259
+ }
260
+ if (message.includes('overloaded') || message.includes('capacity exceeded')) {
261
+ return 'AGENT_OVERLOAD';
262
+ }
263
+ if (message.includes('quality gate') || message.includes('below threshold')) {
264
+ return 'QUALITY_GATE_FAILURE';
265
+ }
266
+ if (message.includes('framework') && message.includes('detect')) {
267
+ return 'FRAMEWORK_DETECTION_FAILED';
268
+ }
269
+ if (message.includes('task collision') || message.includes('resource conflict')) {
270
+ return 'CONCURRENT_TASK_COLLISION';
271
+ }
272
+
273
+ return 'UNKNOWN_ERROR';
274
+ }
275
+
276
+ /**
277
+ * Update monitoring metrics based on error
278
+ */
279
+ updateMonitoringMetrics(errorInfo) {
280
+ const metrics = {
281
+ totalErrors: 1,
282
+ errorsBySeverity: {},
283
+ errorsByCategory: {},
284
+ errorsByAgent: {},
285
+ impactAssessment: {
286
+ tasksAffected: 0,
287
+ storiesAffected: 0,
288
+ missionsAffected: 0
289
+ }
290
+ };
291
+
292
+ metrics.errorsBySeverity[errorInfo.severity] = 1;
293
+ metrics.errorsByCategory[errorInfo.category] = 1;
294
+
295
+ if (errorInfo.context.agent) {
296
+ metrics.errorsByAgent[errorInfo.context.agent] = 1;
297
+ }
298
+
299
+ // Calculate impact
300
+ switch (errorInfo.impactLevel) {
301
+ case 'task':
302
+ metrics.impactAssessment.tasksAffected = 1;
303
+ break;
304
+ case 'story':
305
+ metrics.impactAssessment.storiesAffected = 1;
306
+ break;
307
+ case 'mission':
308
+ metrics.impactAssessment.missionsAffected = 1;
309
+ break;
310
+ }
311
+
312
+ return metrics;
313
+ }
314
+
315
+ /**
316
+ * Check if error violates CASCADE quality gates
317
+ */
318
+ checkQualityGates(errorInfo, context) {
319
+ const violations = [];
320
+ let passed = true;
321
+
322
+ // Check critical error threshold
323
+ if (errorInfo.severity === 'critical') {
324
+ violations.push({
325
+ gate: 'critical_errors',
326
+ threshold: this.qualityGateThresholds.criticalErrorsMax,
327
+ actual: 1,
328
+ violated: true
329
+ });
330
+ passed = false;
331
+ }
332
+
333
+ // Check quality score impact
334
+ if (errorInfo.category === 'quality') {
335
+ violations.push({
336
+ gate: 'quality_score',
337
+ threshold: this.qualityGateThresholds.qualityScoreMin,
338
+ actual: context.currentQualityScore || 0,
339
+ violated: (context.currentQualityScore || 0) < this.qualityGateThresholds.qualityScoreMin
340
+ });
341
+ if ((context.currentQualityScore || 0) < this.qualityGateThresholds.qualityScoreMin) {
342
+ passed = false;
343
+ }
344
+ }
345
+
346
+ return {
347
+ passed,
348
+ violations,
349
+ timestamp: Date.now()
350
+ };
351
+ }
352
+
353
+ /**
354
+ * Attempt automated recovery using CASCADE patterns
355
+ */
356
+ async attemptRecovery(errorInfo, context) {
357
+ const recoveryStrategy = this.recoveryStrategies.get(errorInfo.pattern);
358
+
359
+ if (!recoveryStrategy) {
360
+ return await this.gracefulDegradation(errorInfo, context);
361
+ }
362
+
363
+ try {
364
+ this.emit('recovery_attempt_started', {
365
+ errorInfo,
366
+ strategy: recoveryStrategy,
367
+ context
368
+ });
369
+
370
+ const recoveryPlan = await recoveryStrategy(context);
371
+
372
+ // Execute recovery steps
373
+ const recoveryResult = await this.executeRecoveryPlan(recoveryPlan, context);
374
+
375
+ if (recoveryResult.success) {
376
+ this.emit('recovery_successful', {
377
+ errorInfo,
378
+ recoveryPlan,
379
+ recoveryResult,
380
+ context
381
+ });
382
+
383
+ return {
384
+ recovered: true,
385
+ strategy: recoveryPlan.action,
386
+ executionTime: recoveryResult.executionTime,
387
+ message: `Successfully recovered from ${errorInfo.pattern} using ${recoveryPlan.action}`
388
+ };
389
+ } else {
390
+ return await this.gracefulDegradation(errorInfo, context);
391
+ }
392
+ } catch (recoveryError) {
393
+ this.emit('recovery_failed', {
394
+ originalError: errorInfo,
395
+ recoveryError,
396
+ context
397
+ });
398
+
399
+ return await this.gracefulDegradation(errorInfo, context);
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Execute recovery plan with monitoring
405
+ */
406
+ async executeRecoveryPlan(recoveryPlan, context) {
407
+ const startTime = Date.now();
408
+
409
+ try {
410
+ // Simulate recovery execution based on strategy
411
+ switch (recoveryPlan.action) {
412
+ case 'rescale_and_retry':
413
+ await this.rescaleAndRetry(context);
414
+ break;
415
+ case 'elastic_scaling':
416
+ await this.triggerElasticScaling(context);
417
+ break;
418
+ case 'dag_restructure':
419
+ await this.restructureDependencyGraph(context);
420
+ break;
421
+ case 'fallback_analysis':
422
+ await this.switchToFallbackAnalysis(context);
423
+ break;
424
+ case 'quality_improvement_cycle':
425
+ await this.runQualityImprovementCycle(context);
426
+ break;
427
+ default:
428
+ throw new Error(`Unknown recovery action: ${recoveryPlan.action}`);
429
+ }
430
+
431
+ return {
432
+ success: true,
433
+ executionTime: Date.now() - startTime,
434
+ message: `Recovery plan ${recoveryPlan.action} executed successfully`
435
+ };
436
+ } catch (error) {
437
+ return {
438
+ success: false,
439
+ executionTime: Date.now() - startTime,
440
+ error: error.message
441
+ };
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Graceful degradation when recovery is not possible
447
+ */
448
+ async gracefulDegradation(errorInfo, context) {
449
+ const degradationPlan = {
450
+ action: 'graceful_degradation',
451
+ steps: [
452
+ 'Save current progress and state',
453
+ 'Generate partial results report',
454
+ 'Provide user with clear error explanation',
455
+ 'Suggest manual resolution steps'
456
+ ]
457
+ };
458
+
459
+ this.emit('graceful_degradation', {
460
+ errorInfo,
461
+ degradationPlan,
462
+ context
463
+ });
464
+
465
+ return {
466
+ recovered: false,
467
+ degraded: true,
468
+ reason: errorInfo.pattern,
469
+ partialResults: await this.generatePartialResults(context),
470
+ userGuidance: this.generateUserGuidance(errorInfo)
471
+ };
472
+ }
473
+
474
+ /**
475
+ * Generate partial results when full execution cannot complete
476
+ */
477
+ async generatePartialResults(context) {
478
+ return {
479
+ completedTasks: context.completedTasks || [],
480
+ partialAnalysis: context.partialAnalysis || {},
481
+ qualityScores: context.qualityScores || {},
482
+ recommendations: context.recommendations || [],
483
+ timestamp: Date.now()
484
+ };
485
+ }
486
+
487
+ /**
488
+ * Generate user guidance for error resolution
489
+ */
490
+ generateUserGuidance(errorInfo) {
491
+ const guidanceMap = {
492
+ 'SOURCE_INACCESSIBLE': [
493
+ 'Check that the source directory exists and is accessible',
494
+ 'Verify you have read permissions for the directory',
495
+ 'Ensure the path is correct and contains TypeScript/React projects'
496
+ ],
497
+ 'FRAMEWORK_DETECTION_FAILED': [
498
+ 'Manually specify the framework using --framework parameter',
499
+ 'Check that the project has standard framework configuration files',
500
+ 'Consider using generic analysis mode for non-standard projects'
501
+ ],
502
+ 'QUALITY_GATE_FAILURE': [
503
+ 'Review the specific quality criteria that failed',
504
+ 'Consider lowering quality thresholds if appropriate',
505
+ 'Manual review may be required for complex quality issues'
506
+ ]
507
+ };
508
+
509
+ return {
510
+ error: errorInfo.pattern,
511
+ severity: errorInfo.severity,
512
+ suggestions: guidanceMap[errorInfo.pattern] || ['Contact support with error details'],
513
+ contactInfo: 'Use /help for additional assistance'
514
+ };
515
+ }
516
+
517
+ // Recovery action implementations (placeholder for integration with CASCADE)
518
+ async rescaleAndRetry(context) {
519
+ // Integration with CASCADE elastic scaling
520
+ console.log('Triggering agent pool rescaling and task retry...');
521
+ await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate work
522
+ }
523
+
524
+ async triggerElasticScaling(context) {
525
+ // Integration with CASCADE dynamic agent pool
526
+ console.log('Triggering elastic agent scaling from 43 to expanded capacity...');
527
+ await new Promise(resolve => setTimeout(resolve, 1500)); // Simulate work
528
+ }
529
+
530
+ async restructureDependencyGraph(context) {
531
+ // Integration with CASCADE DAG engine
532
+ console.log('Restructuring dependency graph to resolve deadlock...');
533
+ await new Promise(resolve => setTimeout(resolve, 500)); // Simulate work
534
+ }
535
+
536
+ async switchToFallbackAnalysis(context) {
537
+ // Fallback to generic analysis mode
538
+ console.log('Switching to generic TypeScript/React analysis mode...');
539
+ await new Promise(resolve => setTimeout(resolve, 800)); // Simulate work
540
+ }
541
+
542
+ async runQualityImprovementCycle(context) {
543
+ // Integration with CASCADE quality gates
544
+ console.log('Running quality improvement cycle with automated fixes...');
545
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate work
546
+ }
547
+ }
548
+
549
+ /**
550
+ * Real-time monitoring dashboard for /ingest command
551
+ */
552
+ class IngestMonitor extends EventEmitter {
553
+ constructor() {
554
+ super();
555
+ this.metrics = {
556
+ execution: {
557
+ startTime: null,
558
+ duration: 0,
559
+ status: 'idle'
560
+ },
561
+ agents: {
562
+ total: 0,
563
+ active: 0,
564
+ completed: 0,
565
+ failed: 0
566
+ },
567
+ tasks: {
568
+ total: 0,
569
+ pending: 0,
570
+ running: 0,
571
+ completed: 0,
572
+ failed: 0
573
+ },
574
+ quality: {
575
+ overallScore: 0,
576
+ agentScores: {},
577
+ gatesPassed: 0,
578
+ gatesFailed: 0
579
+ },
580
+ performance: {
581
+ avgTaskTime: 0,
582
+ throughput: 0,
583
+ bottlenecks: []
584
+ },
585
+ errors: {
586
+ total: 0,
587
+ critical: 0,
588
+ recoverable: 0,
589
+ recovered: 0
590
+ }
591
+ };
592
+
593
+ this.realTimeUpdates = true;
594
+ this.updateInterval = 1000; // 1 second updates
595
+ }
596
+
597
+ /**
598
+ * Start monitoring ingestion execution
599
+ */
600
+ startMonitoring(config) {
601
+ this.metrics.execution.startTime = Date.now();
602
+ this.metrics.execution.status = 'running';
603
+
604
+ this.emit('monitoring_started', {
605
+ config,
606
+ startTime: this.metrics.execution.startTime
607
+ });
608
+
609
+ if (this.realTimeUpdates) {
610
+ this.startRealTimeUpdates();
611
+ }
612
+ }
613
+
614
+ /**
615
+ * Update metrics during execution
616
+ */
617
+ updateMetrics(updateData) {
618
+ // Update agent metrics
619
+ if (updateData.agents) {
620
+ Object.assign(this.metrics.agents, updateData.agents);
621
+ }
622
+
623
+ // Update task metrics
624
+ if (updateData.tasks) {
625
+ Object.assign(this.metrics.tasks, updateData.tasks);
626
+ }
627
+
628
+ // Update quality metrics
629
+ if (updateData.quality) {
630
+ Object.assign(this.metrics.quality, updateData.quality);
631
+ }
632
+
633
+ // Update performance metrics
634
+ if (updateData.performance) {
635
+ Object.assign(this.metrics.performance, updateData.performance);
636
+ }
637
+
638
+ // Update error metrics
639
+ if (updateData.errors) {
640
+ Object.assign(this.metrics.errors, updateData.errors);
641
+ }
642
+
643
+ // Calculate derived metrics
644
+ this.calculateDerivedMetrics();
645
+
646
+ this.emit('metrics_updated', {
647
+ metrics: this.metrics,
648
+ timestamp: Date.now()
649
+ });
650
+ }
651
+
652
+ /**
653
+ * Generate real-time dashboard display
654
+ */
655
+ generateDashboard() {
656
+ const duration = this.metrics.execution.startTime ?
657
+ Math.floor((Date.now() - this.metrics.execution.startTime) / 1000) : 0;
658
+
659
+ return `
660
+ ╭────────────────── INGESTION MONITOR ──────────────────╮
661
+ │ Status: ${this.metrics.execution.status.toUpperCase().padEnd(10)} │ Duration: ${this.formatDuration(duration).padEnd(8)} │
662
+ ├────────────────────────────────────────────────────────┤
663
+ │ AGENTS │ TASKS │
664
+ │ Total: ${String(this.metrics.agents.total).padStart(3)} │ Total: ${String(this.metrics.tasks.total).padStart(4)} │
665
+ │ Active: ${String(this.metrics.agents.active).padStart(3)} │ Running: ${String(this.metrics.tasks.running).padStart(4)} │
666
+ │ Completed: ${String(this.metrics.agents.completed).padStart(3)} │ Completed: ${String(this.metrics.tasks.completed).padStart(4)} │
667
+ │ Failed: ${String(this.metrics.agents.failed).padStart(3)} │ Failed: ${String(this.metrics.tasks.failed).padStart(4)} │
668
+ ├────────────────────────────────────────────────────────┤
669
+ │ QUALITY │ PERFORMANCE │
670
+ │ Overall: ${String(this.metrics.quality.overallScore.toFixed(1)).padStart(5)} ⭐ │ Throughput: ${String(this.metrics.performance.throughput).padStart(3)}/h │
671
+ │ Gates Passed: ${String(this.metrics.quality.gatesPassed).padStart(3)} │ Avg Task: ${String(this.metrics.performance.avgTaskTime).padStart(4)}s │
672
+ │ Gates Failed: ${String(this.metrics.quality.gatesFailed).padStart(3)} │ Bottlenecks: ${String(this.metrics.performance.bottlenecks.length).padStart(2)} │
673
+ ├────────────────────────────────────────────────────────┤
674
+ │ ERRORS: ${String(this.metrics.errors.total).padStart(2)} Total │ Critical: ${String(this.metrics.errors.critical).padStart(2)} │ Recovered: ${String(this.metrics.errors.recovered).padStart(2)} │
675
+ ╰────────────────────────────────────────────────────────╯`;
676
+ }
677
+
678
+ /**
679
+ * Start real-time dashboard updates
680
+ */
681
+ startRealTimeUpdates() {
682
+ this.updateTimer = setInterval(() => {
683
+ if (this.metrics.execution.status === 'running') {
684
+ console.clear();
685
+ console.log(this.generateDashboard());
686
+ }
687
+ }, this.updateInterval);
688
+ }
689
+
690
+ /**
691
+ * Stop monitoring
692
+ */
693
+ stopMonitoring(finalResults) {
694
+ this.metrics.execution.status = 'completed';
695
+ this.metrics.execution.duration = Date.now() - this.metrics.execution.startTime;
696
+
697
+ if (this.updateTimer) {
698
+ clearInterval(this.updateTimer);
699
+ }
700
+
701
+ console.clear();
702
+ console.log(this.generateDashboard());
703
+
704
+ this.emit('monitoring_completed', {
705
+ finalMetrics: this.metrics,
706
+ results: finalResults,
707
+ duration: this.metrics.execution.duration
708
+ });
709
+ }
710
+
711
+ /**
712
+ * Calculate derived performance metrics
713
+ */
714
+ calculateDerivedMetrics() {
715
+ // Calculate throughput (tasks per hour)
716
+ if (this.metrics.execution.startTime) {
717
+ const hoursElapsed = (Date.now() - this.metrics.execution.startTime) / (1000 * 60 * 60);
718
+ this.metrics.performance.throughput = hoursElapsed > 0 ?
719
+ Math.round(this.metrics.tasks.completed / hoursElapsed) : 0;
720
+ }
721
+
722
+ // Calculate average task time
723
+ if (this.metrics.tasks.completed > 0) {
724
+ const totalTime = (Date.now() - this.metrics.execution.startTime) / 1000;
725
+ this.metrics.performance.avgTaskTime = Math.round(totalTime / this.metrics.tasks.completed);
726
+ }
727
+ }
728
+
729
+ /**
730
+ * Format duration for display
731
+ */
732
+ formatDuration(seconds) {
733
+ const mins = Math.floor(seconds / 60);
734
+ const secs = seconds % 60;
735
+ return `${mins}:${secs.toString().padStart(2, '0')}`;
736
+ }
737
+ }
738
+
739
+ module.exports = {
740
+ IngestErrorHandler,
741
+ IngestMonitor
742
+ };