groundswell 0.0.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 (120) hide show
  1. package/.claude/settings.local.json +9 -0
  2. package/.claude/system_prompts/task-breakdown.md +100 -0
  3. package/PRPs/001-hierarchical-workflow-engine.md +2438 -0
  4. package/PRPs/PRDs/001-hierarchical-workflow-engine.md +543 -0
  5. package/PRPs/PRDs/002-agent-prompt.md +390 -0
  6. package/PRPs/PRDs/003-agent-prompt.md +943 -0
  7. package/PRPs/PRDs/004-agent-prompt.md +1136 -0
  8. package/PRPs/PRDs/tasks-001.json +492 -0
  9. package/PRPs/README.md +83 -0
  10. package/PRPs/templates/prp_base.md +222 -0
  11. package/README.md +218 -0
  12. package/docs/agent.md +422 -0
  13. package/docs/prompt.md +419 -0
  14. package/docs/workflow.md +600 -0
  15. package/examples/README.md +244 -0
  16. package/examples/examples/01-basic-workflow.ts +100 -0
  17. package/examples/examples/02-decorator-options.ts +217 -0
  18. package/examples/examples/03-parent-child.ts +241 -0
  19. package/examples/examples/04-observers-debugger.ts +340 -0
  20. package/examples/examples/05-error-handling.ts +387 -0
  21. package/examples/examples/06-concurrent-tasks.ts +352 -0
  22. package/examples/examples/07-agent-loops.ts +432 -0
  23. package/examples/examples/08-sdk-features.ts +667 -0
  24. package/examples/examples/09-reflection.ts +573 -0
  25. package/examples/examples/10-introspection.ts +550 -0
  26. package/examples/index.ts +143 -0
  27. package/examples/utils/helpers.ts +57 -0
  28. package/llms_full.txt +5890 -0
  29. package/package.json +63 -0
  30. package/plan/P1P2/PRP.md +527 -0
  31. package/plan/P1P2/research/LRU_CACHE_BEST_PRACTICES.md +1929 -0
  32. package/plan/P1P2/research/LRU_CACHE_CODE_PATTERNS.md +857 -0
  33. package/plan/P1P2/research/LRU_CACHE_INTEGRATION_GUIDE.md +738 -0
  34. package/plan/P1P2/research/LRU_CACHE_RESEARCH_INDEX.md +424 -0
  35. package/plan/P1P2/research/REFLECTION_INDEX.md +291 -0
  36. package/plan/P1P2/research/REFLECTION_RESEARCH_REPORT.md +1342 -0
  37. package/plan/P1P2/research/RESEARCH_SUMMARY.md +342 -0
  38. package/plan/P1P2/research/anthropic-sdk.md +174 -0
  39. package/plan/P1P2/research/async-local-storage.md +200 -0
  40. package/plan/P1P2/research/reflection-code-patterns.md +1205 -0
  41. package/plan/P1P2/research/reflection-decision-matrix.md +421 -0
  42. package/plan/P1P2/research/reflection-implementation-guide.md +1341 -0
  43. package/plan/P1P2/research/reflection-integration-guide.md +834 -0
  44. package/plan/P1P2/research/reflection-patterns.md +1468 -0
  45. package/plan/P1P2/research/reflection-quick-reference.md +558 -0
  46. package/plan/P1P2/research/zod-schema.md +152 -0
  47. package/plan/P3P4/PRP.md +1388 -0
  48. package/plan/P3P4/research/caching-lru.md +116 -0
  49. package/plan/P3P4/research/introspection-tools.md +177 -0
  50. package/plan/P3P4/research/reflection-patterns.md +117 -0
  51. package/plan/P4P5/PRP.md +1136 -0
  52. package/plan/P4P5/research/RESEARCH_SUMMARY.md +151 -0
  53. package/plan/architecture/external_deps.md +358 -0
  54. package/plan/architecture/system_context.md +242 -0
  55. package/plan/backlog.json +867 -0
  56. package/plan/research/INTROSPECTION_RESEARCH_SUMMARY.md +378 -0
  57. package/plan/research/README-INTROSPECTION.md +352 -0
  58. package/plan/research/agent-introspection-patterns.md +1085 -0
  59. package/plan/research/introspection-security-guide.md +928 -0
  60. package/plan/research/introspection-tool-examples.md +875 -0
  61. package/scripts/generate-llms-full.ts +206 -0
  62. package/src/__tests__/integration/agent-workflow.test.ts +256 -0
  63. package/src/__tests__/integration/tree-mirroring.test.ts +114 -0
  64. package/src/__tests__/unit/agent.test.ts +169 -0
  65. package/src/__tests__/unit/cache-key.test.ts +182 -0
  66. package/src/__tests__/unit/cache.test.ts +172 -0
  67. package/src/__tests__/unit/context.test.ts +138 -0
  68. package/src/__tests__/unit/decorators.test.ts +100 -0
  69. package/src/__tests__/unit/introspection-tools.test.ts +277 -0
  70. package/src/__tests__/unit/prompt.test.ts +135 -0
  71. package/src/__tests__/unit/reflection.test.ts +210 -0
  72. package/src/__tests__/unit/tree-debugger.test.ts +85 -0
  73. package/src/__tests__/unit/workflow.test.ts +81 -0
  74. package/src/cache/cache-key.ts +244 -0
  75. package/src/cache/cache.ts +236 -0
  76. package/src/cache/index.ts +8 -0
  77. package/src/core/agent.ts +573 -0
  78. package/src/core/context.ts +119 -0
  79. package/src/core/event-tree.ts +260 -0
  80. package/src/core/factory.ts +123 -0
  81. package/src/core/index.ts +17 -0
  82. package/src/core/logger.ts +87 -0
  83. package/src/core/mcp-handler.ts +184 -0
  84. package/src/core/prompt.ts +150 -0
  85. package/src/core/workflow-context.ts +349 -0
  86. package/src/core/workflow.ts +302 -0
  87. package/src/debugger/index.ts +1 -0
  88. package/src/debugger/tree-debugger.ts +210 -0
  89. package/src/decorators/index.ts +3 -0
  90. package/src/decorators/observed-state.ts +95 -0
  91. package/src/decorators/step.ts +139 -0
  92. package/src/decorators/task.ts +96 -0
  93. package/src/examples/index.ts +2 -0
  94. package/src/examples/tdd-orchestrator.ts +65 -0
  95. package/src/examples/test-cycle-workflow.ts +64 -0
  96. package/src/index.ts +140 -0
  97. package/src/reflection/index.ts +5 -0
  98. package/src/reflection/reflection.ts +407 -0
  99. package/src/tools/index.ts +36 -0
  100. package/src/tools/introspection.ts +464 -0
  101. package/src/types/agent.ts +90 -0
  102. package/src/types/decorators.ts +25 -0
  103. package/src/types/error-strategy.ts +13 -0
  104. package/src/types/error.ts +20 -0
  105. package/src/types/events.ts +74 -0
  106. package/src/types/index.ts +55 -0
  107. package/src/types/logging.ts +24 -0
  108. package/src/types/observer.ts +18 -0
  109. package/src/types/prompt.ts +40 -0
  110. package/src/types/reflection.ts +117 -0
  111. package/src/types/sdk-primitives.ts +128 -0
  112. package/src/types/snapshot.ts +14 -0
  113. package/src/types/workflow-context.ts +163 -0
  114. package/src/types/workflow.ts +37 -0
  115. package/src/utils/id.ts +11 -0
  116. package/src/utils/index.ts +3 -0
  117. package/src/utils/observable.ts +77 -0
  118. package/tasks.json +0 -0
  119. package/tsconfig.json +22 -0
  120. package/vitest.config.ts +16 -0
@@ -0,0 +1,573 @@
1
+ /**
2
+ * Example 9: Multi-level Reflection
3
+ *
4
+ * Demonstrates:
5
+ * - Prompt-level reflection (enableReflection on prompt)
6
+ * - Agent-level reflection (agent.reflect() method)
7
+ * - Workflow-level reflection (step failure retry)
8
+ * - Reflection events in tree output
9
+ * - Error recovery with revised prompts
10
+ */
11
+
12
+ import { z } from 'zod';
13
+ import {
14
+ Workflow,
15
+ Step,
16
+ ObservedState,
17
+ WorkflowTreeDebugger,
18
+ ReflectionManager,
19
+ executeWithReflection,
20
+ DEFAULT_REFLECTION_CONFIG,
21
+ createReflectionConfig,
22
+ } from 'groundswell';
23
+ import type {
24
+ ReflectionConfig,
25
+ ReflectionEntry,
26
+ ReflectionContext,
27
+ WorkflowNode,
28
+ } from 'groundswell';
29
+ import { printHeader, printSection, sleep, simulateUnreliableTask } from '../utils/helpers.js';
30
+
31
+ // ============================================================================
32
+ // Response Schemas
33
+ // ============================================================================
34
+
35
+ const StrictAnswerSchema = z.object({
36
+ answer: z.string().min(10, 'Answer must be at least 10 characters'),
37
+ confidence: z.number().min(0.8, 'Confidence must be at least 0.8'),
38
+ reasoning: z.string().min(20, 'Reasoning must be detailed'),
39
+ });
40
+
41
+ const AnalysisSchema = z.object({
42
+ summary: z.string(),
43
+ keyPoints: z.array(z.string()).min(2, 'Must have at least 2 key points'),
44
+ recommendation: z.string(),
45
+ });
46
+
47
+ type StrictAnswer = z.infer<typeof StrictAnswerSchema>;
48
+ type Analysis = z.infer<typeof AnalysisSchema>;
49
+
50
+ // ============================================================================
51
+ // Simulated Responses (for demonstration without API calls)
52
+ // ============================================================================
53
+
54
+ /**
55
+ * Simulate a response that might fail schema validation
56
+ */
57
+ async function simulateStrictResponse(
58
+ attemptNumber: number
59
+ ): Promise<StrictAnswer> {
60
+ await sleep(50);
61
+
62
+ // First attempt might fail validation
63
+ if (attemptNumber === 1 && Math.random() > 0.3) {
64
+ return {
65
+ answer: 'Short', // Too short - will fail validation
66
+ confidence: 0.5, // Too low - will fail validation
67
+ reasoning: 'Brief', // Too short
68
+ };
69
+ }
70
+
71
+ // Subsequent attempts return valid data
72
+ return {
73
+ answer: 'This is a comprehensive answer that meets the minimum length requirement',
74
+ confidence: 0.92,
75
+ reasoning: 'Based on careful analysis of the input data and consideration of multiple factors',
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Simulate an analysis response
81
+ */
82
+ async function simulateAnalysis(): Promise<Analysis> {
83
+ await sleep(75);
84
+
85
+ return {
86
+ summary: 'The analysis shows positive trends across all metrics',
87
+ keyPoints: [
88
+ 'Revenue increased by 15%',
89
+ 'Customer satisfaction improved',
90
+ 'Operational efficiency gains',
91
+ ],
92
+ recommendation: 'Continue current strategy with minor adjustments',
93
+ };
94
+ }
95
+
96
+ // ============================================================================
97
+ // Workflow Definitions
98
+ // ============================================================================
99
+
100
+ /**
101
+ * Prompt-level reflection demonstration
102
+ */
103
+ class PromptReflectionWorkflow extends Workflow {
104
+ @ObservedState()
105
+ attemptCount: number = 0;
106
+
107
+ @ObservedState()
108
+ validationErrors: string[] = [];
109
+
110
+ @ObservedState()
111
+ finalResult: StrictAnswer | null = null;
112
+
113
+ private reflectionManager: ReflectionManager;
114
+
115
+ constructor(name: string) {
116
+ super(name);
117
+ this.reflectionManager = new ReflectionManager(
118
+ createReflectionConfig({ enabled: true, maxAttempts: 3 })
119
+ );
120
+ }
121
+
122
+ @Step({ trackTiming: true, snapshotState: true })
123
+ async executeWithSchemaValidation(): Promise<StrictAnswer> {
124
+ this.logger.info('Attempting prompt with strict schema validation');
125
+
126
+ // Simulate multiple attempts until schema validates
127
+ for (let attempt = 1; attempt <= 3; attempt++) {
128
+ this.attemptCount = attempt;
129
+ this.logger.info(`Attempt ${attempt}/3`);
130
+
131
+ const response = await simulateStrictResponse(attempt);
132
+
133
+ // Validate against schema
134
+ const result = StrictAnswerSchema.safeParse(response);
135
+
136
+ if (result.success) {
137
+ this.logger.info('Schema validation passed!');
138
+ this.finalResult = result.data;
139
+ return result.data;
140
+ }
141
+
142
+ // Collect validation errors
143
+ const errors = result.error.errors.map((e) => `${e.path.join('.')}: ${e.message}`);
144
+ this.validationErrors.push(...errors);
145
+ this.logger.warn(`Validation failed: ${errors.join(', ')}`);
146
+
147
+ if (attempt < 3) {
148
+ this.logger.info('Reflecting on error and retrying...');
149
+ await sleep(100); // Reflection delay
150
+ }
151
+ }
152
+
153
+ throw new Error('Max reflection attempts exceeded - schema validation failed');
154
+ }
155
+
156
+ async run(): Promise<StrictAnswer | null> {
157
+ this.setStatus('running');
158
+ this.logger.info('Starting prompt-level reflection demo');
159
+
160
+ try {
161
+ const result = await this.executeWithSchemaValidation();
162
+ this.setStatus('completed');
163
+ return result;
164
+ } catch (error) {
165
+ this.logger.error(`Failed after ${this.attemptCount} attempts`);
166
+ this.setStatus('failed');
167
+ return null;
168
+ }
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Agent-level reflection demonstration
174
+ */
175
+ class AgentReflectionWorkflow extends Workflow {
176
+ @ObservedState()
177
+ reflectionHistory: Array<{
178
+ attempt: number;
179
+ action: string;
180
+ result: string;
181
+ }> = [];
182
+
183
+ @ObservedState()
184
+ analysisResult: Analysis | null = null;
185
+
186
+ constructor(name: string) {
187
+ super(name);
188
+ }
189
+
190
+ @Step({ trackTiming: true, snapshotState: true, name: 'reflect-analysis' })
191
+ async reflectOnAnalysis(): Promise<Analysis> {
192
+ this.logger.info('Agent reflecting on analysis approach');
193
+
194
+ // Step 1: Initial reasoning
195
+ this.reflectionHistory.push({
196
+ attempt: 1,
197
+ action: 'Initial reasoning',
198
+ result: 'Considering multiple analysis angles',
199
+ });
200
+ await sleep(50);
201
+
202
+ // Step 2: Self-correction
203
+ this.reflectionHistory.push({
204
+ attempt: 2,
205
+ action: 'Self-correction',
206
+ result: 'Identified potential bias in initial approach',
207
+ });
208
+ await sleep(50);
209
+
210
+ // Step 3: Revised approach
211
+ this.reflectionHistory.push({
212
+ attempt: 3,
213
+ action: 'Revised analysis',
214
+ result: 'Applied broader perspective for balanced view',
215
+ });
216
+ await sleep(50);
217
+
218
+ // Final result after reflection
219
+ const result = await simulateAnalysis();
220
+ this.analysisResult = result;
221
+
222
+ return result;
223
+ }
224
+
225
+ @Step({ snapshotState: true })
226
+ async summarizeReflection(): Promise<string> {
227
+ const summary = `
228
+ Reflection Summary:
229
+ Total steps: ${this.reflectionHistory.length}
230
+ ${this.reflectionHistory.map((r) => ` - ${r.action}: ${r.result}`).join('\n')}
231
+ `.trim();
232
+
233
+ this.logger.info('Reflection process complete');
234
+ return summary;
235
+ }
236
+
237
+ async run(): Promise<Analysis | null> {
238
+ this.setStatus('running');
239
+ this.logger.info('Starting agent-level reflection demo');
240
+
241
+ // System prompt would include reflection instructions:
242
+ // "Before answering, reflect on your reasoning step by step.
243
+ // Consider alternative approaches and potential errors.
244
+ // Then provide your final answer."
245
+
246
+ const result = await this.reflectOnAnalysis();
247
+ await this.summarizeReflection();
248
+
249
+ this.setStatus('completed');
250
+ return result;
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Workflow-level reflection demonstration
256
+ */
257
+ class WorkflowReflectionWorkflow extends Workflow {
258
+ @ObservedState()
259
+ stepAttempts: Record<string, number> = {};
260
+
261
+ @ObservedState()
262
+ failureReasons: string[] = [];
263
+
264
+ @ObservedState()
265
+ successfulSteps: string[] = [];
266
+
267
+ private reflectionManager: ReflectionManager;
268
+
269
+ constructor(name: string) {
270
+ super(name);
271
+ this.reflectionManager = new ReflectionManager(
272
+ createReflectionConfig({ enabled: true, maxAttempts: 3, retryDelayMs: 100 })
273
+ );
274
+
275
+ // Set event emitter for reflection events
276
+ this.reflectionManager.setEventEmitter((event) => {
277
+ if (event.type === 'reflectionStart') {
278
+ this.logger.info(`Reflection started at ${event.level} level`);
279
+ } else if (event.type === 'reflectionEnd') {
280
+ this.logger.info(`Reflection ended: ${event.success ? 'will retry' : 'will abort'}`);
281
+ }
282
+ });
283
+ }
284
+
285
+ @Step({ trackTiming: true, snapshotState: true })
286
+ async unreliableStep(): Promise<string> {
287
+ const stepName = 'unreliableStep';
288
+ this.stepAttempts[stepName] = (this.stepAttempts[stepName] ?? 0) + 1;
289
+ const attempt = this.stepAttempts[stepName];
290
+
291
+ this.logger.info(`Executing unreliable step (attempt ${attempt})`);
292
+
293
+ // Simulate failure on first 2 attempts
294
+ if (attempt < 3) {
295
+ const reason = `Transient failure on attempt ${attempt}`;
296
+ this.failureReasons.push(reason);
297
+ throw new Error(reason);
298
+ }
299
+
300
+ this.successfulSteps.push(stepName);
301
+ return `Success on attempt ${attempt}`;
302
+ }
303
+
304
+ @Step({ trackTiming: true, snapshotState: true })
305
+ async reliableStep(): Promise<string> {
306
+ const stepName = 'reliableStep';
307
+ this.stepAttempts[stepName] = 1;
308
+ this.logger.info('Executing reliable step');
309
+ await sleep(50);
310
+ this.successfulSteps.push(stepName);
311
+ return 'Reliable step completed';
312
+ }
313
+
314
+ async run(): Promise<void> {
315
+ this.setStatus('running');
316
+ this.logger.info('Starting workflow-level reflection demo');
317
+
318
+ // Create mock node for reflection context
319
+ const mockNode: WorkflowNode = {
320
+ id: this.id,
321
+ name: this.name,
322
+ status: 'running',
323
+ children: [],
324
+ events: [],
325
+ };
326
+
327
+ // Execute unreliable step with reflection wrapper
328
+ try {
329
+ await executeWithReflection(
330
+ () => this.unreliableStep(),
331
+ this.reflectionManager,
332
+ (error, attempt, history) => ({
333
+ level: 'workflow',
334
+ failedNode: mockNode,
335
+ error,
336
+ attemptNumber: attempt,
337
+ previousAttempts: history,
338
+ })
339
+ );
340
+ } catch (error) {
341
+ this.logger.error(`Step failed after max attempts: ${(error as Error).message}`);
342
+ }
343
+
344
+ // Execute reliable step
345
+ await this.reliableStep();
346
+
347
+ this.logger.info(`Completed steps: ${this.successfulSteps.join(', ')}`);
348
+ this.logger.info(`Total failures: ${this.failureReasons.length}`);
349
+
350
+ this.setStatus('completed');
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Combined multi-level reflection demonstration
356
+ */
357
+ class MultiLevelReflectionWorkflow extends Workflow {
358
+ @ObservedState()
359
+ reflectionEvents: Array<{
360
+ level: string;
361
+ type: string;
362
+ timestamp: number;
363
+ }> = [];
364
+
365
+ private reflectionManager: ReflectionManager;
366
+
367
+ constructor(name: string) {
368
+ super(name);
369
+ this.reflectionManager = new ReflectionManager(
370
+ createReflectionConfig({ enabled: true, maxAttempts: 3 })
371
+ );
372
+
373
+ this.reflectionManager.setEventEmitter((event) => {
374
+ if (event.type === 'reflectionStart' || event.type === 'reflectionEnd') {
375
+ this.reflectionEvents.push({
376
+ level: (event as { level: string }).level,
377
+ type: event.type,
378
+ timestamp: Date.now(),
379
+ });
380
+ }
381
+ });
382
+ }
383
+
384
+ @Step({ trackTiming: true, snapshotState: true, name: 'prompt-level' })
385
+ async promptLevelReflection(): Promise<void> {
386
+ this.logger.info('Prompt-level: Schema validation with retry');
387
+ this.reflectionEvents.push({
388
+ level: 'prompt',
389
+ type: 'validation',
390
+ timestamp: Date.now(),
391
+ });
392
+ await sleep(50);
393
+ }
394
+
395
+ @Step({ trackTiming: true, snapshotState: true, name: 'agent-level' })
396
+ async agentLevelReflection(): Promise<void> {
397
+ this.logger.info('Agent-level: Self-correction before final answer');
398
+ this.reflectionEvents.push({
399
+ level: 'agent',
400
+ type: 'self-correction',
401
+ timestamp: Date.now(),
402
+ });
403
+ await sleep(50);
404
+ }
405
+
406
+ @Step({ trackTiming: true, snapshotState: true, name: 'workflow-level' })
407
+ async workflowLevelReflection(): Promise<void> {
408
+ this.logger.info('Workflow-level: Step retry on failure');
409
+ this.reflectionEvents.push({
410
+ level: 'workflow',
411
+ type: 'step-retry',
412
+ timestamp: Date.now(),
413
+ });
414
+ await sleep(50);
415
+ }
416
+
417
+ async run(): Promise<void> {
418
+ this.setStatus('running');
419
+ this.logger.info('Starting multi-level reflection demonstration');
420
+
421
+ await this.promptLevelReflection();
422
+ await this.agentLevelReflection();
423
+ await this.workflowLevelReflection();
424
+
425
+ this.logger.info(`Total reflection events: ${this.reflectionEvents.length}`);
426
+ this.setStatus('completed');
427
+ }
428
+ }
429
+
430
+ // ============================================================================
431
+ // Main Example Runner
432
+ // ============================================================================
433
+
434
+ /**
435
+ * Run the Multi-level Reflection example
436
+ */
437
+ export async function runReflectionExample(): Promise<void> {
438
+ printHeader('Example 9: Multi-level Reflection');
439
+
440
+ // Part 1: Prompt-Level Reflection
441
+ printSection('Part 1: Prompt-Level Reflection (Schema Validation)');
442
+ {
443
+ console.log('Demonstrates: enableReflection on prompt config');
444
+ console.log('Behavior: Auto-retry when schema validation fails\n');
445
+
446
+ const workflow = new PromptReflectionWorkflow('PromptReflection');
447
+ const debugger_ = new WorkflowTreeDebugger(workflow);
448
+
449
+ const result = await workflow.run();
450
+
451
+ console.log('\nExecution summary:');
452
+ console.log(` Attempts: ${workflow.attemptCount}`);
453
+ console.log(` Validation errors: ${workflow.validationErrors.length}`);
454
+ if (workflow.validationErrors.length > 0) {
455
+ console.log(` Errors encountered:`);
456
+ for (const error of workflow.validationErrors) {
457
+ console.log(` - ${error}`);
458
+ }
459
+ }
460
+
461
+ if (result) {
462
+ console.log(`\nFinal result:`);
463
+ console.log(` Answer: ${result.answer.slice(0, 50)}...`);
464
+ console.log(` Confidence: ${result.confidence}`);
465
+ }
466
+
467
+ console.log('\nTree:');
468
+ console.log(debugger_.toTreeString());
469
+ }
470
+
471
+ // Part 2: Agent-Level Reflection
472
+ printSection('Part 2: Agent-Level Reflection (Self-Correction)');
473
+ {
474
+ console.log('Demonstrates: agent.reflect() method with system prompt prefix');
475
+ console.log('Behavior: Agent reviews reasoning before final answer\n');
476
+
477
+ const workflow = new AgentReflectionWorkflow('AgentReflection');
478
+ const debugger_ = new WorkflowTreeDebugger(workflow);
479
+
480
+ const result = await workflow.run();
481
+
482
+ console.log('Reflection history:');
483
+ for (const entry of workflow.reflectionHistory) {
484
+ console.log(` ${entry.attempt}. ${entry.action}: ${entry.result}`);
485
+ }
486
+
487
+ if (result) {
488
+ console.log(`\nAnalysis result:`);
489
+ console.log(` Summary: ${result.summary}`);
490
+ console.log(` Key points: ${result.keyPoints.length}`);
491
+ console.log(` Recommendation: ${result.recommendation}`);
492
+ }
493
+
494
+ console.log('\nTree:');
495
+ console.log(debugger_.toTreeString());
496
+ }
497
+
498
+ // Part 3: Workflow-Level Reflection
499
+ printSection('Part 3: Workflow-Level Reflection (Step Retry)');
500
+ {
501
+ console.log('Demonstrates: executeWithReflection() wrapper');
502
+ console.log('Behavior: Retry failed steps with reflection analysis\n');
503
+
504
+ const workflow = new WorkflowReflectionWorkflow('WorkflowReflection');
505
+ const debugger_ = new WorkflowTreeDebugger(workflow);
506
+
507
+ await workflow.run();
508
+
509
+ console.log('\nStep attempt summary:');
510
+ for (const [step, attempts] of Object.entries(workflow.stepAttempts)) {
511
+ console.log(` ${step}: ${attempts} attempt(s)`);
512
+ }
513
+
514
+ console.log(`\nFailure reasons:`);
515
+ for (const reason of workflow.failureReasons) {
516
+ console.log(` - ${reason}`);
517
+ }
518
+
519
+ console.log(`\nSuccessful steps: ${workflow.successfulSteps.join(', ')}`);
520
+
521
+ // Show reflection history
522
+ const history = workflow['reflectionManager'].getReflectionHistory();
523
+ console.log(`\nReflection history entries: ${history.length}`);
524
+ for (const entry of history) {
525
+ console.log(` [${entry.level}] ${entry.reason} -> ${entry.resolution}`);
526
+ }
527
+
528
+ console.log('\nTree:');
529
+ console.log(debugger_.toTreeString());
530
+ }
531
+
532
+ // Part 4: Multi-Level Combined
533
+ printSection('Part 4: Multi-Level Reflection Overview');
534
+ {
535
+ console.log('All three levels working together:\n');
536
+
537
+ const workflow = new MultiLevelReflectionWorkflow('MultiLevelReflection');
538
+ const debugger_ = new WorkflowTreeDebugger(workflow);
539
+
540
+ await workflow.run();
541
+
542
+ console.log('Reflection events by level:');
543
+ const byLevel = workflow.reflectionEvents.reduce(
544
+ (acc, event) => {
545
+ acc[event.level] = (acc[event.level] ?? 0) + 1;
546
+ return acc;
547
+ },
548
+ {} as Record<string, number>
549
+ );
550
+
551
+ for (const [level, count] of Object.entries(byLevel)) {
552
+ console.log(` ${level}: ${count} event(s)`);
553
+ }
554
+
555
+ console.log('\nReflection configuration defaults:');
556
+ console.log(` Enabled: ${DEFAULT_REFLECTION_CONFIG.enabled}`);
557
+ console.log(` Max attempts: ${DEFAULT_REFLECTION_CONFIG.maxAttempts}`);
558
+ console.log(` Retry delay: ${DEFAULT_REFLECTION_CONFIG.retryDelayMs}ms`);
559
+
560
+ console.log('\nTree:');
561
+ console.log(debugger_.toTreeString());
562
+
563
+ const stats = debugger_.getStats();
564
+ console.log('\nFinal statistics:', stats);
565
+ }
566
+
567
+ console.log('\n=== Example 9 Complete ===');
568
+ }
569
+
570
+ // Allow direct execution
571
+ if (import.meta.url === `file://${process.argv[1]}`) {
572
+ runReflectionExample().catch(console.error);
573
+ }