agentic-flow 1.4.6 โ†’ 1.4.7

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.
@@ -1,58 +1,57 @@
1
- // ReasoningBank CLI command handlers
1
+ /**
2
+ * ReasoningBank CLI Commands
3
+ * Handles demo, test, init, benchmark, status, consolidate, list
4
+ */
2
5
  import { spawn } from 'child_process';
3
- import { resolve } from 'path';
6
+ import { join } from 'path';
7
+ import { fileURLToPath } from 'url';
8
+ import { dirname } from 'path';
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = dirname(__filename);
4
11
  export async function handleReasoningBankCommand(subcommand) {
5
- const rbPath = resolve(process.cwd(), 'src/reasoningbank');
6
- switch (subcommand) {
7
- case 'demo':
8
- console.log('\n๐ŸŽฏ Running ReasoningBank Demo Comparison...\n');
9
- console.log('This demo shows ReasoningBank learning from experience:');
10
- console.log('โ€ข Traditional: 0% success, repeats mistakes');
11
- console.log('โ€ข ReasoningBank: 100% success, learns & improves\n');
12
- await runScript(`${rbPath}/demo-comparison.ts`);
13
- break;
14
- case 'test':
15
- console.log('\n๐Ÿงช Running ReasoningBank Validation Tests...\n');
16
- await runScript(`${rbPath}/test-validation.ts`);
17
- console.log('\n');
18
- await runScript(`${rbPath}/test-retrieval.ts`);
19
- console.log('\n');
20
- await runScript(`${rbPath}/test-integration.ts`);
21
- break;
22
- case 'init':
23
- console.log('\n๐Ÿ“ฆ Initializing ReasoningBank Database...\n');
24
- console.log('Creating memory database at .swarm/memory.db\n');
25
- await runBashCommand('mkdir -p .swarm');
26
- await runBashCommand('sqlite3 .swarm/memory.db < src/reasoningbank/migrations/000_base_schema.sql');
27
- await runBashCommand('sqlite3 .swarm/memory.db < src/reasoningbank/migrations/001_reasoningbank_schema.sql');
28
- console.log('โœ… ReasoningBank database initialized!\n');
29
- break;
30
- case 'benchmark':
31
- console.log('\nโšก Running ReasoningBank Performance Benchmarks...\n');
32
- await runScript(`${rbPath}/benchmark.ts`);
33
- break;
34
- case 'status':
35
- console.log('\n๐Ÿ“Š ReasoningBank Memory Statistics\n');
36
- await runBashCommand(`sqlite3 .swarm/memory.db "SELECT
37
- (SELECT COUNT(*) FROM reasoning_memory) as total_memories,
38
- (SELECT COUNT(*) FROM reasoning_memory WHERE confidence > 0.7) as high_confidence,
39
- (SELECT COUNT(*) FROM task_trajectory) as total_tasks,
40
- (SELECT AVG(confidence) FROM reasoning_memory) as avg_confidence;"`);
41
- console.log('\n');
42
- break;
43
- case 'help':
44
- default:
45
- printReasoningBankHelp();
46
- break;
12
+ const args = process.argv.slice(4); // Get args after 'reasoningbank <subcommand>'
13
+ try {
14
+ switch (subcommand) {
15
+ case 'demo':
16
+ await runExternalScript('../reasoningbank/demo-comparison.js');
17
+ break;
18
+ case 'test':
19
+ await runExternalScript('../reasoningbank/test-validation.js');
20
+ break;
21
+ case 'init':
22
+ await initDatabase();
23
+ break;
24
+ case 'benchmark':
25
+ await runExternalScript('../reasoningbank/benchmark.js');
26
+ break;
27
+ case 'status':
28
+ await showStatus();
29
+ break;
30
+ case 'consolidate':
31
+ await runConsolidation();
32
+ break;
33
+ case 'list':
34
+ await listMemories(args);
35
+ break;
36
+ case 'help':
37
+ default:
38
+ printHelp();
39
+ break;
40
+ }
41
+ }
42
+ catch (error) {
43
+ console.error(`\nโŒ Error: ${error instanceof Error ? error.message : String(error)}\n`);
44
+ process.exit(1);
47
45
  }
48
46
  }
49
- async function runScript(scriptPath) {
47
+ async function runExternalScript(relativePath) {
48
+ const scriptPath = join(__dirname, relativePath);
50
49
  return new Promise((resolve, reject) => {
51
- const proc = spawn('npx', ['tsx', scriptPath], {
50
+ const child = spawn('node', [scriptPath], {
52
51
  stdio: 'inherit',
53
- shell: true
52
+ cwd: process.cwd()
54
53
  });
55
- proc.on('close', (code) => {
54
+ child.on('exit', (code) => {
56
55
  if (code === 0) {
57
56
  resolve();
58
57
  }
@@ -60,77 +59,145 @@ async function runScript(scriptPath) {
60
59
  reject(new Error(`Script exited with code ${code}`));
61
60
  }
62
61
  });
63
- proc.on('error', (err) => {
64
- reject(err);
62
+ child.on('error', (error) => {
63
+ reject(error);
65
64
  });
66
65
  });
67
66
  }
68
- async function runBashCommand(command) {
69
- return new Promise((resolve, reject) => {
70
- const proc = spawn(command, {
71
- stdio: 'inherit',
72
- shell: true
73
- });
74
- proc.on('close', (code) => {
75
- if (code === 0) {
76
- resolve();
77
- }
78
- else {
79
- reject(new Error(`Command exited with code ${code}`));
80
- }
81
- });
82
- proc.on('error', (err) => {
83
- reject(err);
84
- });
85
- });
67
+ async function initDatabase() {
68
+ console.log('\n๐Ÿ”ง Initializing ReasoningBank Database');
69
+ console.log('โ•'.repeat(50));
70
+ const { initialize } = await import('../reasoningbank/index.js');
71
+ console.log('\nInitializing database with migrations...\n');
72
+ await initialize();
73
+ console.log('\nโœ… Database initialized successfully!');
74
+ console.log('\nSchema created:');
75
+ console.log(' โ€ข patterns (reasoning memories)');
76
+ console.log(' โ€ข pattern_embeddings');
77
+ console.log(' โ€ข pattern_links');
78
+ console.log(' โ€ข task_trajectories');
79
+ console.log(' โ€ข matts_runs');
80
+ console.log(' โ€ข consolidation_runs');
81
+ console.log(' โ€ข metrics_log\n');
82
+ }
83
+ async function showStatus() {
84
+ console.log('\n๐Ÿ“Š ReasoningBank Status');
85
+ console.log('โ•'.repeat(50));
86
+ const { db } = await import('../reasoningbank/index.js');
87
+ const dbInstance = db.getDb();
88
+ const stats = {
89
+ totalMemories: dbInstance.prepare("SELECT COUNT(*) as count FROM patterns WHERE type = 'reasoning_memory'").get(),
90
+ avgConfidence: dbInstance.prepare("SELECT AVG(confidence) as avg FROM patterns WHERE type = 'reasoning_memory'").get(),
91
+ totalEmbeddings: dbInstance.prepare('SELECT COUNT(*) as count FROM pattern_embeddings').get(),
92
+ totalTrajectories: dbInstance.prepare('SELECT COUNT(*) as count FROM task_trajectories').get()
93
+ };
94
+ console.log(`\n๐Ÿ“ˆ Statistics:`);
95
+ console.log(` โ€ข Total memories: ${stats.totalMemories.count}`);
96
+ console.log(` โ€ข Average confidence: ${stats.avgConfidence.avg?.toFixed(2) || 'N/A'}`);
97
+ console.log(` โ€ข Total embeddings: ${stats.totalEmbeddings.count}`);
98
+ console.log(` โ€ข Total trajectories: ${stats.totalTrajectories.count}\n`);
86
99
  }
87
- function printReasoningBankHelp() {
100
+ async function runConsolidation() {
101
+ console.log('\n๐Ÿ”„ Running Memory Consolidation');
102
+ console.log('โ•'.repeat(50));
103
+ console.log('\nDeduplicating and pruning memories...\n');
104
+ const { consolidate } = await import('../reasoningbank/index.js');
105
+ const startTime = Date.now();
106
+ const result = await consolidate();
107
+ const duration = Date.now() - startTime;
108
+ console.log('โœ… Consolidation complete!\n');
109
+ console.log(`๐Ÿ“Š Results:`);
110
+ console.log(` โ€ข Memories processed: ${result.itemsProcessed}`);
111
+ console.log(` โ€ข Duplicates found: ${result.duplicatesFound}`);
112
+ console.log(` โ€ข Contradictions found: ${result.contradictionsFound}`);
113
+ console.log(` โ€ข Pruned: ${result.itemsPruned}`);
114
+ console.log(` โ€ข Duration: ${result.durationMs}ms\n`);
115
+ }
116
+ async function listMemories(args) {
117
+ const { db } = await import('../reasoningbank/index.js');
118
+ const dbInstance = db.getDb();
119
+ // Parse arguments
120
+ const sortBy = args.includes('--sort') ? args[args.indexOf('--sort') + 1] : 'created_at';
121
+ const limit = args.includes('--limit') ? parseInt(args[args.indexOf('--limit') + 1], 10) : 10;
122
+ console.log('\n๐Ÿ“š Memory Bank Contents');
123
+ console.log('โ•'.repeat(50));
124
+ console.log(`\nShowing top ${limit} memories (sorted by ${sortBy})\n`);
125
+ let orderBy = 'created_at DESC';
126
+ if (sortBy === 'confidence') {
127
+ orderBy = 'confidence DESC';
128
+ }
129
+ else if (sortBy === 'usage') {
130
+ orderBy = 'usage_count DESC';
131
+ }
132
+ const memories = dbInstance.prepare(`
133
+ SELECT
134
+ id,
135
+ json_extract(pattern_data, '$.title') as title,
136
+ json_extract(pattern_data, '$.description') as description,
137
+ json_extract(pattern_data, '$.domain') as domain,
138
+ confidence,
139
+ usage_count,
140
+ created_at
141
+ FROM patterns
142
+ WHERE type = 'reasoning_memory'
143
+ ORDER BY ${orderBy}
144
+ LIMIT ?
145
+ `).all(limit);
146
+ if (memories.length === 0) {
147
+ console.log('No memories found. Run `npx agentic-flow reasoningbank demo` to create some!\n');
148
+ return;
149
+ }
150
+ for (let i = 0; i < memories.length; i++) {
151
+ const mem = memories[i];
152
+ console.log(`${i + 1}. ${mem.title}`);
153
+ console.log(` Confidence: ${parseFloat(mem.confidence).toFixed(2)} | Usage: ${mem.usage_count} | Created: ${mem.created_at}`);
154
+ console.log(` Domain: ${mem.domain}`);
155
+ console.log(` ${mem.description}`);
156
+ console.log('');
157
+ }
158
+ }
159
+ function printHelp() {
88
160
  console.log(`
89
- ๐Ÿง  ReasoningBank - Memory System that Learns from Experience
161
+ ๐Ÿง  ReasoningBank - Closed-loop memory system for AI agents
90
162
 
91
163
  USAGE:
92
- npx agentic-flow reasoningbank <command>
164
+ npx agentic-flow reasoningbank <COMMAND>
93
165
 
94
166
  COMMANDS:
95
- demo Run interactive demo showing 0% โ†’ 100% success transformation
96
- test Run comprehensive validation suite (27 tests)
97
- init Initialize ReasoningBank database (.swarm/memory.db)
98
- benchmark Run performance benchmarks (retrieval, insertion, etc.)
99
- status Show memory statistics and database status
100
- help Show this help message
167
+ demo Run interactive demo showing learning progression
168
+ test Run validation test suite
169
+ init Initialize database schema
170
+ benchmark Run performance benchmarks
171
+ status Show memory statistics
172
+ consolidate Run memory consolidation now
173
+ list List memories with options
174
+ help Show this help message
175
+
176
+ LIST OPTIONS:
177
+ --sort <field> Sort by: confidence, usage, created_at (default)
178
+ --limit <n> Show top N memories (default: 10)
101
179
 
102
180
  EXAMPLES:
103
- # See the transformation from traditional to learning agents
181
+ # Run demo to see 0% โ†’ 100% success transformation
104
182
  npx agentic-flow reasoningbank demo
105
183
 
106
- # Validate installation and run all tests
107
- npx agentic-flow reasoningbank test
108
-
109
- # Setup database for first-time use
184
+ # Initialize database
110
185
  npx agentic-flow reasoningbank init
111
186
 
112
- # Check memory bank statistics
113
- npx agentic-flow reasoningbank status
187
+ # Run validation tests
188
+ npx agentic-flow reasoningbank test
114
189
 
115
- FEATURES:
116
- โœ… Learns from both successes and failures
117
- โœ… 100% success rate after learning (vs 0% for traditional)
118
- โœ… 46% faster execution over time
119
- โœ… Knowledge transfers across similar tasks
120
- โœ… Zero manual intervention needed
190
+ # Show current statistics
191
+ npx agentic-flow reasoningbank status
121
192
 
122
- REQUIREMENTS:
123
- โ€ข SQLite3 (for database operations)
124
- โ€ข ANTHROPIC_API_KEY (optional, for LLM-based learning)
193
+ # Consolidate memories (dedupe + prune)
194
+ npx agentic-flow reasoningbank consolidate
125
195
 
126
- Without API key: Uses heuristic fallbacks (70% accuracy)
127
- With API key: Uses LLM-based judgment (95% accuracy)
196
+ # List top 10 memories by confidence
197
+ npx agentic-flow reasoningbank list --sort confidence --limit 10
128
198
 
129
- DOCUMENTATION:
130
- โ€ข Full README: src/reasoningbank/README.md
131
- โ€ข Demo Report: docs/REASONINGBANK-DEMO.md
132
- โ€ข Integration: docs/REASONINGBANK-CLI-INTEGRATION.md
133
- โ€ข Paper: https://arxiv.org/html/2509.25140v1
199
+ # List top 5 most used memories
200
+ npx agentic-flow reasoningbank list --sort usage --limit 5
134
201
 
135
202
  For more information: https://github.com/ruvnet/agentic-flow
136
203
  `);