claude-flow 2.5.0-alpha.141 → 2.7.0-alpha

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 (149) hide show
  1. package/.claude/agents/reasoning/README.md +171 -0
  2. package/.claude/agents/reasoning/agent.md +816 -0
  3. package/.claude/agents/reasoning/example-reasoning-agent-template.md +362 -0
  4. package/.claude/agents/reasoning/goal-planner.md +73 -0
  5. package/.claude/commands/coordination/README.md +9 -0
  6. package/.claude/commands/memory/README.md +9 -0
  7. package/.claude/settings.json +3 -3
  8. package/.claude/sparc-modes.json +108 -0
  9. package/README.md +1 -6
  10. package/bin/claude-flow +1 -1
  11. package/dist/src/cli/command-registry.js +70 -6
  12. package/dist/src/cli/command-registry.js.map +1 -1
  13. package/dist/src/cli/help-formatter.js +0 -3
  14. package/dist/src/cli/help-formatter.js.map +1 -1
  15. package/dist/src/cli/help-text.js +53 -5
  16. package/dist/src/cli/help-text.js.map +1 -1
  17. package/dist/src/cli/simple-cli.js +182 -172
  18. package/dist/src/cli/simple-cli.js.map +1 -1
  19. package/dist/src/cli/simple-commands/agent-booster.js +415 -0
  20. package/dist/src/cli/simple-commands/agent-booster.js.map +1 -0
  21. package/dist/src/cli/simple-commands/agent.js +856 -13
  22. package/dist/src/cli/simple-commands/agent.js.map +1 -1
  23. package/dist/src/cli/simple-commands/env-template.js +180 -0
  24. package/dist/src/cli/simple-commands/env-template.js.map +1 -0
  25. package/dist/src/cli/simple-commands/init/help.js +23 -0
  26. package/dist/src/cli/simple-commands/init/help.js.map +1 -1
  27. package/dist/src/cli/simple-commands/init/index.js +63 -0
  28. package/dist/src/cli/simple-commands/init/index.js.map +1 -1
  29. package/dist/src/cli/simple-commands/memory.js +307 -16
  30. package/dist/src/cli/simple-commands/memory.js.map +1 -1
  31. package/dist/src/cli/simple-commands/proxy.js +304 -0
  32. package/dist/src/cli/simple-commands/proxy.js.map +1 -0
  33. package/dist/src/cli/simple-commands/sparc.js +16 -19
  34. package/dist/src/cli/simple-commands/sparc.js.map +1 -1
  35. package/dist/src/cli/validation-helper.js.map +1 -1
  36. package/dist/src/core/version.js +1 -1
  37. package/dist/src/execution/agent-executor.js +181 -0
  38. package/dist/src/execution/agent-executor.js.map +1 -0
  39. package/dist/src/execution/index.js +12 -0
  40. package/dist/src/execution/index.js.map +1 -0
  41. package/dist/src/execution/provider-manager.js +110 -0
  42. package/dist/src/execution/provider-manager.js.map +1 -0
  43. package/dist/src/hooks/redaction-hook.js +89 -0
  44. package/dist/src/hooks/redaction-hook.js.map +1 -0
  45. package/dist/src/memory/swarm-memory.js +340 -421
  46. package/dist/src/memory/swarm-memory.js.map +1 -1
  47. package/dist/src/utils/key-redactor.js +108 -0
  48. package/dist/src/utils/key-redactor.js.map +1 -0
  49. package/dist/src/utils/metrics-reader.js +37 -39
  50. package/dist/src/utils/metrics-reader.js.map +1 -1
  51. package/docs/AGENT-BOOSTER-INTEGRATION.md +407 -0
  52. package/docs/AGENTIC-FLOW-INTEGRATION-GUIDE.md +753 -0
  53. package/docs/AGENTIC_FLOW_EXECUTION_FIX_REPORT.md +474 -0
  54. package/docs/AGENTIC_FLOW_INTEGRATION_STATUS.md +143 -0
  55. package/docs/AGENTIC_FLOW_MVP_COMPLETE.md +367 -0
  56. package/docs/AGENTIC_FLOW_SECURITY_TEST_REPORT.md +369 -0
  57. package/docs/COMMAND-VERIFICATION-REPORT.md +441 -0
  58. package/docs/COMMIT_SUMMARY.md +247 -0
  59. package/docs/DEEP_REVIEW_COMPREHENSIVE_REPORT.md +922 -0
  60. package/docs/DOCKER-VALIDATION-REPORT.md +281 -0
  61. package/docs/ENV-SETUP-GUIDE.md +270 -0
  62. package/docs/FINAL_PRE_PUBLISH_VALIDATION.md +823 -0
  63. package/docs/FINAL_VALIDATION_REPORT.md +165 -0
  64. package/docs/HOOKS-V2-MODIFICATION.md +146 -0
  65. package/docs/INDEX.md +568 -0
  66. package/docs/INTEGRATION_COMPLETE.md +414 -0
  67. package/docs/MEMORY_REDACTION_TEST_REPORT.md +300 -0
  68. package/docs/PERFORMANCE-SYSTEMS-STATUS.md +340 -0
  69. package/docs/PRE_RELEASE_FIXES_REPORT.md +435 -0
  70. package/docs/README.md +35 -0
  71. package/docs/REASONING-AGENTS.md +482 -0
  72. package/docs/REASONINGBANK-AGENT-CREATION-GUIDE.md +813 -0
  73. package/docs/REASONINGBANK-ANALYSIS-COMPLETE.md +479 -0
  74. package/docs/REASONINGBANK-BENCHMARK-RESULTS.md +166 -0
  75. package/docs/REASONINGBANK-BENCHMARK.md +396 -0
  76. package/docs/REASONINGBANK-CLI-INTEGRATION.md +455 -0
  77. package/docs/REASONINGBANK-CORE-INTEGRATION.md +658 -0
  78. package/docs/REASONINGBANK-COST-OPTIMIZATION.md +329 -0
  79. package/docs/REASONINGBANK-DEMO.md +419 -0
  80. package/docs/REASONINGBANK-INTEGRATION-COMPLETE.md +249 -0
  81. package/docs/REASONINGBANK-VALIDATION.md +532 -0
  82. package/docs/REASONINGBANK_ARCHITECTURE.md +475 -0
  83. package/docs/REASONINGBANK_INTEGRATION_COMPLETE.md +558 -0
  84. package/docs/REASONINGBANK_INTEGRATION_PLAN.md +1188 -0
  85. package/docs/REGRESSION-ANALYSIS-REPORT.md +500 -0
  86. package/docs/RELEASE_v2.6.0-alpha.2.md +658 -0
  87. package/docs/api/API_DOCUMENTATION.md +721 -0
  88. package/docs/architecture/ARCHITECTURE.md +1690 -0
  89. package/docs/ci-cd/README.md +368 -0
  90. package/docs/development/DEPLOYMENT.md +2348 -0
  91. package/docs/development/DEVELOPMENT_WORKFLOW.md +1333 -0
  92. package/docs/development/build-analysis-report.md +252 -0
  93. package/docs/development/pair-optimization.md +156 -0
  94. package/docs/development/token-tracking-status.md +103 -0
  95. package/docs/development/training-pipeline-demo.md +163 -0
  96. package/docs/development/training-pipeline-real-only.md +196 -0
  97. package/docs/epic-sdk-integration.md +1269 -0
  98. package/docs/experimental/RIEMANN_HYPOTHESIS_PROOF.md +124 -0
  99. package/docs/experimental/computational_verification.py +436 -0
  100. package/docs/experimental/novel_approaches.md +560 -0
  101. package/docs/experimental/riemann_hypothesis_analysis.md +263 -0
  102. package/docs/experimental/riemann_proof_attempt.md +124 -0
  103. package/docs/experimental/riemann_synthesis.md +277 -0
  104. package/docs/experimental/verification_results.json +12 -0
  105. package/docs/experimental/visualization_insights.md +720 -0
  106. package/docs/guides/USER_GUIDE.md +1138 -0
  107. package/docs/guides/token-tracking-guide.md +291 -0
  108. package/docs/reference/AGENTS.md +1011 -0
  109. package/docs/reference/MCP_TOOLS.md +2188 -0
  110. package/docs/reference/SPARC.md +717 -0
  111. package/docs/reference/SWARM.md +2000 -0
  112. package/docs/sdk/CLAUDE-CODE-SDK-DEEP-ANALYSIS.md +649 -0
  113. package/docs/sdk/CLAUDE-FLOW-SDK-INTEGRATION-ANALYSIS.md +242 -0
  114. package/docs/sdk/INTEGRATION-ROADMAP.md +420 -0
  115. package/docs/sdk/MCP-TOOLS-UPDATE.md +270 -0
  116. package/docs/sdk/SDK-ADVANCED-FEATURES-INTEGRATION.md +723 -0
  117. package/docs/sdk/SDK-ALL-FEATURES-INTEGRATION-MATRIX.md +612 -0
  118. package/docs/sdk/SDK-INTEGRATION-COMPLETE.md +358 -0
  119. package/docs/sdk/SDK-INTEGRATION-PHASES-V2.5.md +750 -0
  120. package/docs/sdk/SDK-LEVERAGE-REAL-FEATURES.md +676 -0
  121. package/docs/sdk/SDK-VALIDATION-RESULTS.md +400 -0
  122. package/docs/sdk/epic-sdk-integration.md +1269 -0
  123. package/docs/setup/remote-setup.md +93 -0
  124. package/docs/validation/final-validation-summary.md +220 -0
  125. package/docs/validation/verification-integration.md +190 -0
  126. package/docs/validation/verification-validation.md +349 -0
  127. package/docs/wiki/background-commands.md +1213 -0
  128. package/docs/wiki/session-persistence.md +342 -0
  129. package/docs/wiki/stream-chain-command.md +537 -0
  130. package/package.json +4 -2
  131. package/src/cli/command-registry.js +70 -5
  132. package/src/cli/help-text.js +26 -5
  133. package/src/cli/simple-cli.ts +18 -7
  134. package/src/cli/simple-commands/agent-booster.js +515 -0
  135. package/src/cli/simple-commands/agent.js +1001 -12
  136. package/src/cli/simple-commands/agent.ts +137 -0
  137. package/src/cli/simple-commands/config.ts +127 -0
  138. package/src/cli/simple-commands/env-template.js +190 -0
  139. package/src/cli/simple-commands/init/help.js +23 -0
  140. package/src/cli/simple-commands/init/index.js +84 -6
  141. package/src/cli/simple-commands/memory.js +363 -16
  142. package/src/cli/simple-commands/proxy.js +384 -0
  143. package/src/cli/simple-commands/sparc.js +16 -19
  144. package/src/execution/agent-executor.ts +306 -0
  145. package/src/execution/index.ts +19 -0
  146. package/src/execution/provider-manager.ts +187 -0
  147. package/src/hooks/redaction-hook.ts +115 -0
  148. package/src/utils/key-redactor.js +178 -0
  149. package/src/utils/key-redactor.ts +184 -0
@@ -0,0 +1,813 @@
1
+ # ReasoningBank Agent Creation Guide
2
+
3
+ ## 🎯 Overview
4
+
5
+ This guide explains how to create custom AI agents that leverage ReasoningBank's closed-loop learning system. ReasoningBank enables agents to learn from experience and improve over time through a 4-phase cycle: **RETRIEVE → JUDGE → DISTILL → CONSOLIDATE**.
6
+
7
+ ## 📊 Key Performance Benefits
8
+
9
+ When agents integrate with ReasoningBank, they achieve:
10
+ - **+26% success rate** (70% → 88%)
11
+ - **-25% token usage** (cost savings)
12
+ - **3.2x learning velocity** (faster improvement)
13
+ - **0% → 95% success** over 5 iterations
14
+
15
+ ## 🏗️ ReasoningBank Architecture
16
+
17
+ ### Database Schema
18
+
19
+ ReasoningBank uses SQLite with the following tables:
20
+
21
+ ```sql
22
+ -- Core memory storage
23
+ patterns (
24
+ id TEXT PRIMARY KEY,
25
+ type TEXT NOT NULL, -- 'reasoning_memory'
26
+ pattern_data TEXT NOT NULL, -- JSON with title, description, content
27
+ confidence REAL DEFAULT 0.5, -- 0.0 to 1.0
28
+ usage_count INTEGER DEFAULT 0,
29
+ created_at TEXT,
30
+ last_used TEXT
31
+ )
32
+
33
+ -- Vector embeddings for similarity search
34
+ pattern_embeddings (
35
+ id TEXT PRIMARY KEY,
36
+ model TEXT NOT NULL, -- 'claude', 'openai', etc.
37
+ dims INTEGER NOT NULL,
38
+ vector BLOB NOT NULL, -- Binary vector data
39
+ FOREIGN KEY (id) REFERENCES patterns(id)
40
+ )
41
+
42
+ -- Memory relationships
43
+ pattern_links (
44
+ src_id TEXT,
45
+ dst_id TEXT,
46
+ relation TEXT NOT NULL, -- 'similar_to', 'contradicts', etc.
47
+ weight REAL DEFAULT 1.0,
48
+ PRIMARY KEY (src_id, dst_id, relation)
49
+ )
50
+
51
+ -- Task execution history
52
+ task_trajectories (
53
+ task_id TEXT PRIMARY KEY,
54
+ agent_id TEXT NOT NULL,
55
+ query TEXT NOT NULL,
56
+ trajectory_json TEXT NOT NULL, -- JSON of execution steps
57
+ judge_label TEXT, -- 'Success' or 'Failure'
58
+ judge_conf REAL,
59
+ judge_reasons TEXT
60
+ )
61
+ ```
62
+
63
+ ### Memory Scoring Formula
64
+
65
+ ReasoningBank uses a 4-factor scoring model for memory retrieval:
66
+
67
+ ```javascript
68
+ score = α·similarity + β·recency + γ·reliability + δ·diversity
69
+
70
+ Where:
71
+ - α (alpha) = 0.7 // Weight for semantic similarity
72
+ - β (beta) = 0.2 // Weight for recency
73
+ - γ (gamma) = 0.1 // Weight for reliability (confidence)
74
+ - δ (delta) = 0.3 // Weight for diversity (MMR)
75
+
76
+ Components:
77
+ - similarity: cosine similarity between query embedding and memory embedding
78
+ - recency: exp(-age_days / half_life_days)
79
+ - reliability: min(confidence, 1.0)
80
+ - diversity: Maximal Marginal Relevance selection
81
+ ```
82
+
83
+ ## 🔌 ReasoningBank API Reference
84
+
85
+ ### Core Functions
86
+
87
+ #### 1. Initialize Database
88
+
89
+ ```javascript
90
+ import { initialize } from 'agentic-flow/reasoningbank';
91
+
92
+ await initialize();
93
+ // Creates .swarm/memory.db and runs migrations
94
+ ```
95
+
96
+ #### 2. Retrieve Memories (RETRIEVE phase)
97
+
98
+ ```javascript
99
+ import { retrieveMemories, formatMemoriesForPrompt } from 'agentic-flow/reasoningbank';
100
+
101
+ const memories = await retrieveMemories(query, {
102
+ domain: 'authentication', // Optional: filter by domain
103
+ agent: 'auth-agent', // Optional: filter by agent
104
+ k: 3, // Optional: number of memories (default: 3)
105
+ minConfidence: 0.5 // Optional: minimum confidence threshold
106
+ });
107
+
108
+ // Format for system prompt injection
109
+ const formattedMemories = formatMemoriesForPrompt(memories);
110
+
111
+ // Memory object structure:
112
+ {
113
+ id: 'ulid',
114
+ title: 'CSRF Token Extraction Strategy',
115
+ description: 'How to handle CSRF validation',
116
+ content: 'Always extract CSRF token from meta tag before form submission',
117
+ score: 0.85,
118
+ components: {
119
+ similarity: 0.9,
120
+ recency: 0.8,
121
+ reliability: 0.85
122
+ }
123
+ }
124
+ ```
125
+
126
+ #### 3. Judge Trajectory (JUDGE phase)
127
+
128
+ ```javascript
129
+ import { judgeTrajectory } from 'agentic-flow/reasoningbank';
130
+
131
+ const trajectory = {
132
+ steps: [
133
+ { action: 'fetch_csrf_token', result: 'success' },
134
+ { action: 'submit_form', result: 'success' }
135
+ ]
136
+ };
137
+
138
+ const verdict = await judgeTrajectory(trajectory, query);
139
+
140
+ // Verdict object structure:
141
+ {
142
+ label: 'Success' | 'Failure',
143
+ confidence: 0.95,
144
+ reasons: [
145
+ 'All steps completed successfully',
146
+ 'No error indicators found'
147
+ ]
148
+ }
149
+ ```
150
+
151
+ #### 4. Distill Memories (DISTILL phase)
152
+
153
+ ```javascript
154
+ import { distillMemories } from 'agentic-flow/reasoningbank';
155
+
156
+ const newMemories = await distillMemories(trajectory, verdict, query, {
157
+ taskId: 'task-123',
158
+ agentId: 'my-agent',
159
+ domain: 'authentication'
160
+ });
161
+
162
+ // Returns array of memory IDs that were created
163
+ // ['01K7AX1ZP43E88SRZHNX6YD1YG', '01K7AX1ZP7CPECXHVTHSMSAXRA']
164
+ ```
165
+
166
+ #### 5. Consolidate Memories (CONSOLIDATE phase)
167
+
168
+ ```javascript
169
+ import { consolidate, shouldConsolidate } from 'agentic-flow/reasoningbank';
170
+
171
+ // Check if consolidation should run
172
+ if (shouldConsolidate()) {
173
+ const result = await consolidate();
174
+
175
+ // Result structure:
176
+ {
177
+ itemsProcessed: 50,
178
+ duplicatesFound: 5,
179
+ contradictionsFound: 2,
180
+ itemsPruned: 3,
181
+ durationMs: 1234
182
+ }
183
+ }
184
+ ```
185
+
186
+ #### 6. Full Task Execution (All phases combined)
187
+
188
+ ```javascript
189
+ import { runTask } from 'agentic-flow/reasoningbank';
190
+
191
+ const result = await runTask({
192
+ taskId: 'task-123',
193
+ agentId: 'my-agent',
194
+ domain: 'authentication',
195
+ query: 'Login with CSRF validation',
196
+
197
+ // Your execution function
198
+ executeFn: async (memories) => {
199
+ // 1. Use memories to inform your task execution
200
+ console.log(`Using ${memories.length} relevant memories`);
201
+
202
+ // 2. Execute your task logic
203
+ const steps = [];
204
+
205
+ // Example: Check if memories suggest extracting CSRF token
206
+ if (memories.some(m => m.title.includes('CSRF'))) {
207
+ steps.push({ action: 'fetch_csrf_token', result: 'success' });
208
+ }
209
+
210
+ // 3. Return trajectory
211
+ return { steps };
212
+ }
213
+ });
214
+
215
+ // Result structure:
216
+ {
217
+ verdict: { label: 'Success', confidence: 0.95, reasons: [...] },
218
+ usedMemories: [...], // Memories that were retrieved
219
+ newMemories: [...], // New memory IDs created
220
+ consolidated: false // Whether consolidation ran
221
+ }
222
+ ```
223
+
224
+ ## 🎨 Creating a Custom Reasoning Agent
225
+
226
+ ### Step 1: Define Agent Specification
227
+
228
+ Create `.claude/agents/your-category/your-agent.md`:
229
+
230
+ ```markdown
231
+ ---
232
+ name: adaptive-debugger
233
+ description: "Debugging specialist that learns from past bug fixes and adapts strategies based on error patterns. Uses ReasoningBank to accumulate debugging knowledge across sessions."
234
+ category: debugging
235
+ color: red
236
+ reasoning_enabled: true
237
+ ---
238
+
239
+ You are an adaptive debugging specialist that learns from experience. Your core capability is to leverage ReasoningBank's memory system to continuously improve your debugging strategies.
240
+
241
+ ## Core Capabilities
242
+
243
+ - **Pattern Recognition**: Identify recurring bug patterns from past fixes
244
+ - **Strategy Adaptation**: Adjust debugging approach based on memory
245
+ - **Root Cause Analysis**: Use historical data to find underlying issues
246
+ - **Prevention Learning**: Store successful fixes for future reference
247
+
248
+ ## ReasoningBank Integration
249
+
250
+ You integrate with ReasoningBank through the following workflow:
251
+
252
+ 1. **RETRIEVE**: Pull relevant debugging memories before starting
253
+ 2. **EXECUTE**: Apply learned strategies to current bug
254
+ 3. **JUDGE**: Evaluate if the fix was successful
255
+ 4. **DISTILL**: Extract learnable patterns from the attempt
256
+ 5. **CONSOLIDATE**: Optimize memory bank periodically
257
+
258
+ ## Domain Tags
259
+
260
+ Use these domain tags for memory organization:
261
+ - `debugging/frontend` - UI/UX bugs
262
+ - `debugging/backend` - Server-side issues
263
+ - `debugging/database` - Data persistence bugs
264
+ - `debugging/performance` - Speed/memory issues
265
+ - `debugging/security` - Vulnerability fixes
266
+
267
+ ## Memory Usage Pattern
268
+
269
+ Before debugging:
270
+ ```
271
+ I notice from memory that similar NullPointerException errors
272
+ in authentication flows were previously solved by checking token
273
+ expiration. Let me apply that strategy first.
274
+ ```
275
+
276
+ After debugging:
277
+ ```
278
+ Successfully fixed the issue using token validation.
279
+ Storing this pattern in ReasoningBank for future reference:
280
+ "Always validate JWT expiration before database queries"
281
+ ```
282
+ ```
283
+
284
+ ### Step 2: Implement Agent Logic with ReasoningBank
285
+
286
+ Create `src/agents/adaptive-debugger.js`:
287
+
288
+ ```javascript
289
+ import { initialize, runTask } from 'agentic-flow/reasoningbank';
290
+ import { ModelRouter } from 'agentic-flow/router';
291
+
292
+ export class AdaptiveDebugger {
293
+ constructor() {
294
+ this.router = new ModelRouter();
295
+ this.agentId = 'adaptive-debugger';
296
+ }
297
+
298
+ async init() {
299
+ await initialize();
300
+ }
301
+
302
+ async debug(errorContext) {
303
+ const query = `Debug error: ${errorContext.error} in ${errorContext.file}`;
304
+
305
+ // Use ReasoningBank's full cycle
306
+ const result = await runTask({
307
+ taskId: `debug-${Date.now()}`,
308
+ agentId: this.agentId,
309
+ domain: `debugging/${errorContext.category}`,
310
+ query,
311
+
312
+ executeFn: async (memories) => {
313
+ return await this._executeDebug(errorContext, memories);
314
+ }
315
+ });
316
+
317
+ return result;
318
+ }
319
+
320
+ async _executeDebug(errorContext, memories) {
321
+ const steps = [];
322
+
323
+ // 1. Analyze memories for similar past fixes
324
+ const relevantFixes = memories.filter(m =>
325
+ m.title.toLowerCase().includes(errorContext.error.toLowerCase())
326
+ );
327
+
328
+ steps.push({
329
+ action: 'retrieve_memories',
330
+ result: `Found ${relevantFixes.length} similar past fixes`,
331
+ memories: relevantFixes.map(m => m.title)
332
+ });
333
+
334
+ // 2. Apply learned strategies
335
+ if (relevantFixes.length > 0) {
336
+ const topStrategy = relevantFixes[0].content;
337
+ steps.push({
338
+ action: 'apply_learned_strategy',
339
+ strategy: topStrategy,
340
+ result: 'Attempting fix based on past success'
341
+ });
342
+
343
+ // Apply the fix
344
+ const fixResult = await this._applyFix(errorContext, topStrategy);
345
+ steps.push(fixResult);
346
+ } else {
347
+ // No memories found, try standard debugging
348
+ steps.push({
349
+ action: 'standard_debugging',
350
+ result: 'No past experience found, using general strategies'
351
+ });
352
+
353
+ const fixResult = await this._standardDebug(errorContext);
354
+ steps.push(fixResult);
355
+ }
356
+
357
+ return { steps };
358
+ }
359
+
360
+ async _applyFix(errorContext, strategy) {
361
+ // Your fix implementation logic here
362
+ // Return step object with action and result
363
+ return {
364
+ action: 'apply_fix',
365
+ result: 'Fix applied successfully',
366
+ details: { strategy, context: errorContext }
367
+ };
368
+ }
369
+
370
+ async _standardDebug(errorContext) {
371
+ // Fallback debugging logic
372
+ return {
373
+ action: 'standard_fix',
374
+ result: 'Applied standard debugging approach',
375
+ details: errorContext
376
+ };
377
+ }
378
+ }
379
+ ```
380
+
381
+ ### Step 3: Create Agent Hooks for Automatic Learning
382
+
383
+ Create hooks that automatically trigger ReasoningBank cycles:
384
+
385
+ ```javascript
386
+ // hooks/pre-debug.js
387
+ import { retrieveMemories, formatMemoriesForPrompt } from 'agentic-flow/reasoningbank';
388
+
389
+ export async function preDebug(context) {
390
+ const query = context.errorMessage;
391
+ const domain = `debugging/${context.errorType}`;
392
+
393
+ // Retrieve relevant memories
394
+ const memories = await retrieveMemories(query, { domain });
395
+
396
+ // Inject into context for agent to use
397
+ context.memories = memories;
398
+ context.memoriesPrompt = formatMemoriesForPrompt(memories);
399
+
400
+ console.log(`[PreDebug] Retrieved ${memories.length} relevant debugging patterns`);
401
+
402
+ return context;
403
+ }
404
+
405
+ // hooks/post-debug.js
406
+ import { judgeTrajectory, distillMemories } from 'agentic-flow/reasoningbank';
407
+
408
+ export async function postDebug(context, result) {
409
+ const trajectory = {
410
+ steps: result.debugSteps
411
+ };
412
+
413
+ // Judge if the debug was successful
414
+ const verdict = await judgeTrajectory(trajectory, context.errorMessage);
415
+
416
+ console.log(`[PostDebug] Verdict: ${verdict.label} (confidence: ${verdict.confidence})`);
417
+
418
+ // Distill learnings if successful
419
+ if (verdict.label === 'Success') {
420
+ const newMemories = await distillMemories(trajectory, verdict, context.errorMessage, {
421
+ taskId: result.taskId,
422
+ agentId: 'adaptive-debugger',
423
+ domain: `debugging/${context.errorType}`
424
+ });
425
+
426
+ console.log(`[PostDebug] Stored ${newMemories.length} new debugging patterns`);
427
+ }
428
+
429
+ return result;
430
+ }
431
+ ```
432
+
433
+ ## 📖 Complete Example: Adaptive Code Reviewer
434
+
435
+ ### Agent Definition
436
+
437
+ `.claude/agents/quality/adaptive-reviewer.md`:
438
+
439
+ ```markdown
440
+ ---
441
+ name: adaptive-reviewer
442
+ description: "Code review specialist that learns from past review feedback and adapts quality standards. Uses ReasoningBank to build institutional knowledge about code quality."
443
+ category: quality
444
+ reasoning_enabled: true
445
+ ---
446
+
447
+ You are an adaptive code review specialist. You learn from every review to improve your assessment criteria and provide increasingly valuable feedback.
448
+
449
+ ## Learning Domains
450
+
451
+ - `review/security` - Security vulnerability patterns
452
+ - `review/performance` - Performance anti-patterns
453
+ - `review/maintainability` - Code quality issues
454
+ - `review/testing` - Test coverage patterns
455
+
456
+ ## Review Strategy
457
+
458
+ 1. RETRIEVE memories about similar code patterns
459
+ 2. Apply learned quality standards
460
+ 3. JUDGE if code meets quality bar
461
+ 4. DISTILL new patterns from the review
462
+ 5. CONSOLIDATE knowledge periodically
463
+ ```
464
+
465
+ ### Implementation
466
+
467
+ ```javascript
468
+ import { runTask } from 'agentic-flow/reasoningbank';
469
+
470
+ export async function reviewCode(codeContext) {
471
+ const query = `Review ${codeContext.language} code for ${codeContext.purpose}`;
472
+
473
+ const result = await runTask({
474
+ taskId: `review-${codeContext.prNumber}`,
475
+ agentId: 'adaptive-reviewer',
476
+ domain: 'review/security',
477
+ query,
478
+
479
+ executeFn: async (memories) => {
480
+ const steps = [];
481
+
482
+ // 1. Check for known security patterns from memory
483
+ const securityPatterns = memories.filter(m =>
484
+ m.domain === 'review/security'
485
+ );
486
+
487
+ steps.push({
488
+ action: 'security_check',
489
+ result: `Checking ${securityPatterns.length} known security patterns`,
490
+ patterns: securityPatterns.map(p => p.title)
491
+ });
492
+
493
+ // 2. Apply memory-informed review
494
+ const issues = [];
495
+
496
+ for (const pattern of securityPatterns) {
497
+ if (codeContext.code.includes(pattern.content.trigger)) {
498
+ issues.push({
499
+ type: 'security',
500
+ pattern: pattern.title,
501
+ severity: 'high',
502
+ suggestion: pattern.content.fix
503
+ });
504
+ }
505
+ }
506
+
507
+ steps.push({
508
+ action: 'apply_patterns',
509
+ result: `Found ${issues.length} issues`,
510
+ issues
511
+ });
512
+
513
+ // 3. Standard review if no memories matched
514
+ if (issues.length === 0) {
515
+ steps.push({
516
+ action: 'standard_review',
517
+ result: 'No known patterns matched, applying standard checks'
518
+ });
519
+ }
520
+
521
+ return { steps };
522
+ }
523
+ });
524
+
525
+ return {
526
+ approved: result.verdict.label === 'Success',
527
+ issues: result.usedMemories,
528
+ learned: result.newMemories.length
529
+ };
530
+ }
531
+ ```
532
+
533
+ ## 🔧 Configuration
534
+
535
+ ### Environment Variables
536
+
537
+ ```bash
538
+ # Enable ReasoningBank
539
+ export REASONINGBANK_ENABLED=true
540
+
541
+ # Database location
542
+ export CLAUDE_FLOW_DB_PATH=".swarm/memory.db"
543
+
544
+ # API Keys (choose one)
545
+ export ANTHROPIC_API_KEY="sk-ant-..." # Recommended
546
+ export OPENROUTER_API_KEY="sk-or-v1-..." # Alternative
547
+ export GOOGLE_GEMINI_API_KEY="..." # Alternative
548
+
549
+ # Retrieval settings
550
+ export REASONINGBANK_K=3 # Top-k memories
551
+ export REASONINGBANK_MIN_CONFIDENCE=0.5 # Minimum confidence
552
+ export REASONINGBANK_RECENCY_HALFLIFE=7 # Days for recency decay
553
+
554
+ # Scoring weights (α, β, γ)
555
+ export REASONINGBANK_ALPHA=0.7 # Similarity weight
556
+ export REASONINGBANK_BETA=0.2 # Recency weight
557
+ export REASONINGBANK_GAMMA=0.1 # Reliability weight
558
+ export REASONINGBANK_DELTA=0.3 # Diversity weight (MMR)
559
+ ```
560
+
561
+ ### Config File
562
+
563
+ `.reasoningbank.config.json`:
564
+
565
+ ```json
566
+ {
567
+ "database": {
568
+ "path": ".swarm/memory.db",
569
+ "backup_interval_hours": 24
570
+ },
571
+ "embeddings": {
572
+ "provider": "claude",
573
+ "model": "claude-3-sonnet-20240229",
574
+ "cache_size": 1000
575
+ },
576
+ "retrieve": {
577
+ "k": 3,
578
+ "min_score": 0.5,
579
+ "alpha": 0.7,
580
+ "beta": 0.2,
581
+ "gamma": 0.1,
582
+ "delta": 0.3,
583
+ "recency_half_life_days": 7
584
+ },
585
+ "judge": {
586
+ "model": "claude-3-sonnet-20240229",
587
+ "temperature": 0.3,
588
+ "max_tokens": 1024
589
+ },
590
+ "distill": {
591
+ "model": "claude-3-sonnet-20240229",
592
+ "temperature": 0.3,
593
+ "max_tokens": 2048,
594
+ "confidence_prior_success": 0.8,
595
+ "confidence_prior_failure": 0.6,
596
+ "max_items_success": 3,
597
+ "max_items_failure": 2
598
+ },
599
+ "consolidate": {
600
+ "interval_hours": 24,
601
+ "similarity_threshold": 0.95,
602
+ "min_usage_to_keep": 2
603
+ }
604
+ }
605
+ ```
606
+
607
+ ## 🎯 Best Practices
608
+
609
+ ### 1. Domain Organization
610
+
611
+ Organize memories with clear domain hierarchies:
612
+
613
+ ```javascript
614
+ const domains = {
615
+ authentication: ['login', 'oauth', 'jwt', 'csrf'],
616
+ database: ['queries', 'migrations', 'optimization'],
617
+ testing: ['unit', 'integration', 'e2e'],
618
+ deployment: ['docker', 'k8s', 'cicd']
619
+ };
620
+ ```
621
+
622
+ ### 2. Memory Quality
623
+
624
+ Create high-quality memories with:
625
+ - Clear, descriptive titles
626
+ - Specific, actionable content
627
+ - Relevant domain tags
628
+ - Evidence-based confidence scores
629
+
630
+ ```javascript
631
+ const goodMemory = {
632
+ title: 'JWT Expiration Validation Pattern',
633
+ description: 'Validate JWT expiration before database operations',
634
+ content: 'Check exp claim < Date.now()/1000 before proceeding',
635
+ domain: 'authentication/jwt',
636
+ confidence: 0.9 // High confidence from multiple successes
637
+ };
638
+ ```
639
+
640
+ ### 3. Consolidation Strategy
641
+
642
+ Run consolidation regularly to maintain memory quality:
643
+
644
+ ```javascript
645
+ // Periodic consolidation (e.g., nightly job)
646
+ setInterval(async () => {
647
+ if (shouldConsolidate()) {
648
+ const result = await consolidate();
649
+ console.log(`Consolidated: removed ${result.itemsPruned} low-value memories`);
650
+ }
651
+ }, 24 * 60 * 60 * 1000); // Daily
652
+ ```
653
+
654
+ ### 4. Error Handling
655
+
656
+ Always handle ReasoningBank failures gracefully:
657
+
658
+ ```javascript
659
+ try {
660
+ const memories = await retrieveMemories(query);
661
+ } catch (error) {
662
+ console.warn('ReasoningBank unavailable, proceeding without memories');
663
+ // Continue with standard agent logic
664
+ }
665
+ ```
666
+
667
+ ## 📊 Monitoring and Metrics
668
+
669
+ ### Database Queries
670
+
671
+ ```sql
672
+ -- Top performing memories
673
+ SELECT
674
+ json_extract(pattern_data, '$.title') as title,
675
+ confidence,
676
+ usage_count,
677
+ created_at
678
+ FROM patterns
679
+ WHERE type = 'reasoning_memory'
680
+ ORDER BY confidence DESC, usage_count DESC
681
+ LIMIT 10;
682
+
683
+ -- Memory growth over time
684
+ SELECT
685
+ DATE(created_at) as date,
686
+ COUNT(*) as memories_created
687
+ FROM patterns
688
+ WHERE type = 'reasoning_memory'
689
+ GROUP BY DATE(created_at)
690
+ ORDER BY date DESC;
691
+
692
+ -- Success rate by domain
693
+ SELECT
694
+ json_extract(pattern_data, '$.domain') as domain,
695
+ AVG(CASE WHEN judge_label = 'Success' THEN 1 ELSE 0 END) as success_rate,
696
+ COUNT(*) as total_tasks
697
+ FROM task_trajectories
698
+ GROUP BY domain
699
+ ORDER BY success_rate DESC;
700
+ ```
701
+
702
+ ### CLI Commands
703
+
704
+ ```bash
705
+ # Show current statistics
706
+ npx agentic-flow reasoningbank status
707
+
708
+ # List top memories by confidence
709
+ npx agentic-flow reasoningbank list --sort confidence --limit 10
710
+
711
+ # List most used memories
712
+ npx agentic-flow reasoningbank list --sort usage --limit 10
713
+
714
+ # Run consolidation
715
+ npx agentic-flow reasoningbank consolidate
716
+
717
+ # Validate system
718
+ npx agentic-flow reasoningbank test
719
+ ```
720
+
721
+ ## 🚀 Quick Start Template
722
+
723
+ Copy this template to get started quickly:
724
+
725
+ ```javascript
726
+ // my-reasoning-agent.js
727
+ import { initialize, runTask } from 'agentic-flow/reasoningbank';
728
+
729
+ async function main() {
730
+ // 1. Initialize ReasoningBank
731
+ await initialize();
732
+
733
+ // 2. Define your task
734
+ const query = 'Your task description';
735
+
736
+ // 3. Run with ReasoningBank
737
+ const result = await runTask({
738
+ taskId: `task-${Date.now()}`,
739
+ agentId: 'my-agent',
740
+ domain: 'your-domain',
741
+ query,
742
+
743
+ // 4. Implement your execution logic
744
+ executeFn: async (memories) => {
745
+ console.log(`Using ${memories.length} relevant memories`);
746
+
747
+ // Your agent logic here
748
+ const steps = [
749
+ { action: 'step1', result: 'success' },
750
+ { action: 'step2', result: 'success' }
751
+ ];
752
+
753
+ return { steps };
754
+ }
755
+ });
756
+
757
+ // 5. Check results
758
+ console.log(`Verdict: ${result.verdict.label}`);
759
+ console.log(`Used ${result.usedMemories.length} memories`);
760
+ console.log(`Created ${result.newMemories.length} new memories`);
761
+ }
762
+
763
+ main().catch(console.error);
764
+ ```
765
+
766
+ ## 📚 Resources
767
+
768
+ - **Paper**: [ReasoningBank on arXiv](https://arxiv.org/html/2509.25140v1)
769
+ - **Source**: `/node_modules/agentic-flow/dist/reasoningbank/`
770
+ - **Demo**: `npx agentic-flow reasoningbank demo`
771
+ - **Tests**: `npx agentic-flow reasoningbank test`
772
+ - **Docs**: `.claude/agents/reasoning/README.md`
773
+
774
+ ## 🆘 Troubleshooting
775
+
776
+ ### Issue: "No memories found"
777
+
778
+ **Solution**: Seed initial memories or run more tasks to build memory bank.
779
+
780
+ ```javascript
781
+ import { db } from 'agentic-flow/reasoningbank';
782
+
783
+ db.upsertMemory({
784
+ id: ulid(),
785
+ type: 'reasoning_memory',
786
+ pattern_data: {
787
+ title: 'Seed Memory',
788
+ description: 'Initial knowledge',
789
+ content: 'Strategy details',
790
+ domain: 'your-domain'
791
+ },
792
+ confidence: 0.7,
793
+ usage_count: 0
794
+ });
795
+ ```
796
+
797
+ ### Issue: "Database locked"
798
+
799
+ **Solution**: Only one process can write at a time. Use connection pooling or queue writes.
800
+
801
+ ### Issue: "Low confidence scores"
802
+
803
+ **Solution**: Let the agent run more tasks. Confidence increases with successful usage.
804
+
805
+ ### Issue: "Memory not improving performance"
806
+
807
+ **Solution**: Check memory quality, adjust scoring weights, or increase consolidation frequency.
808
+
809
+ ---
810
+
811
+ **Created**: 2025-10-12
812
+ **Version**: 1.0.0
813
+ **Status**: Production-ready