rust-kgdb 0.5.12 → 0.5.13

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,151 @@
2
2
 
3
3
  All notable changes to the rust-kgdb TypeScript SDK will be documented in this file.
4
4
 
5
+ ## [0.5.13] - 2025-12-15
6
+
7
+ ### Memory Layer - GraphDB-Powered Agent Memory
8
+
9
+ This release introduces a comprehensive Memory Layer for the HyperMind Agentic Framework, enabling agents to maintain state, recall past executions, and access knowledge graphs with weighted retrieval scoring.
10
+
11
+ #### New Memory Layer Components
12
+
13
+ **AgentState Enum**
14
+ - `CREATED` - Initial state after instantiation
15
+ - `READY` - Configured and ready to execute
16
+ - `RUNNING` - Currently executing a task
17
+ - `PAUSED` - Execution temporarily suspended
18
+ - `COMPLETED` - Successfully finished
19
+ - `FAILED` - Execution failed with error
20
+
21
+ **AgentRuntime Class**
22
+ - UUID-based agent identity (`agent_{uuid}`)
23
+ - State machine with valid transitions (CREATED→READY→RUNNING→COMPLETED/FAILED)
24
+ - Execution tracking with `startExecution(prompt)` and `completeExecution()`
25
+ - Memory management integration
26
+
27
+ **WorkingMemory Class**
28
+ - In-memory context storage with configurable capacity
29
+ - Variable bindings for agent reasoning
30
+ - Context item management with timestamps and IDs
31
+ - Automatic eviction of oldest items when over capacity
32
+
33
+ **EpisodicMemory Class**
34
+ - Execution history stored as RDF triples in GraphDB
35
+ - Query episodes by time range, tool, or success status
36
+ - Full execution metadata: tool, prompt, output, duration, success
37
+ - Episode limit configuration
38
+
39
+ **LongTermMemory Class**
40
+ - Read-only access to source-of-truth knowledge graph
41
+ - SPARQL query interface
42
+ - Explicit separation from agent memory graph
43
+
44
+ **MemoryManager Class**
45
+ - Unified retrieval across all memory types
46
+ - Weighted scoring: `Score = α × Recency + β × Relevance + γ × Importance`
47
+ - Default weights: recency=0.3, relevance=0.5, importance=0.2
48
+ - Configurable weighting for different use cases
49
+
50
+ #### New Governance Layer
51
+
52
+ **GovernancePolicy Class**
53
+ - Capability-based access control: `ReadKG`, `WriteKG`, `ExecuteTool`, `UseEmbeddings`
54
+ - Resource limits: `maxMemoryMB`, `maxExecutionTimeMs`, `maxToolCalls`
55
+ - Policy validation and enforcement
56
+
57
+ **GovernanceEngine Class**
58
+ - Policy enforcement with capability checking
59
+ - Complete audit trail via `auditLog` array
60
+ - Tool execution gating
61
+
62
+ #### New Scope Layer
63
+
64
+ **AgentScope Class**
65
+ - Namespace isolation between agents
66
+ - Resource tracking with `trackUsage(type, amount)`
67
+ - Remaining resource calculation via `getRemainingResources()`
68
+ - Memory and tool call budget management
69
+
70
+ #### Updated Examples
71
+
72
+ **fraud-detection-agent.js**
73
+ - Added Phase 2.5: Memory Layer initialization
74
+ - Episodic memory storage for each analysis step
75
+ - Memory Layer statistics in execution report
76
+
77
+ **underwriting-agent.js**
78
+ - Complete Memory Layer integration
79
+ - Governance policy enforcement
80
+ - Scope-based resource tracking
81
+
82
+ #### Test Coverage
83
+
84
+ - 65 comprehensive tests for Memory Layer components
85
+ - All tests passing (100%)
86
+ - Tests cover: AgentState, AgentRuntime, WorkingMemory, EpisodicMemory, LongTermMemory, MemoryManager, GovernancePolicy, GovernanceEngine, AgentScope
87
+
88
+ #### New Exports
89
+
90
+ ```javascript
91
+ const {
92
+ // Memory Layer (v0.5.13+)
93
+ AgentState,
94
+ AgentRuntime,
95
+ WorkingMemory,
96
+ EpisodicMemory,
97
+ LongTermMemory,
98
+ MemoryManager,
99
+ // Governance Layer (v0.5.13+)
100
+ GovernancePolicy,
101
+ GovernanceEngine,
102
+ // Scope Layer (v0.5.13+)
103
+ AgentScope,
104
+ } = require('rust-kgdb')
105
+ ```
106
+
107
+ #### Usage Example
108
+
109
+ ```javascript
110
+ const { GraphDB, AgentRuntime, MemoryManager, GovernancePolicy, AgentScope, AgentState } = require('rust-kgdb')
111
+
112
+ // Initialize GraphDB for memory storage
113
+ const db = new GraphDB('http://example.org/memory')
114
+
115
+ // Create agent runtime with identity
116
+ const runtime = new AgentRuntime({
117
+ name: 'fraud-detector',
118
+ model: 'claude-sonnet-4',
119
+ tools: ['kg.sparql.query', 'kg.motif.find'],
120
+ memoryCapacity: 100,
121
+ episodeLimit: 1000
122
+ })
123
+
124
+ // Initialize memory manager with weighted retrieval
125
+ const memory = new MemoryManager(runtime, db, {
126
+ recencyWeight: 0.3,
127
+ relevanceWeight: 0.5,
128
+ importanceWeight: 0.2
129
+ })
130
+
131
+ // Create governance policy
132
+ const policy = new GovernancePolicy({
133
+ capabilities: ['ReadKG', 'ExecuteTool'],
134
+ maxToolCalls: 100
135
+ })
136
+
137
+ // Create scoped execution environment
138
+ const scope = new AgentScope({
139
+ namespace: 'fraud-detection',
140
+ resources: { maxToolCalls: 50, maxMemoryMB: 256 }
141
+ })
142
+
143
+ // Execute with full Memory Layer
144
+ runtime.transitionTo(AgentState.READY)
145
+ const executionId = runtime.startExecution('Analyze claims for fraud patterns')
146
+ // ... agent execution ...
147
+ runtime.completeExecution()
148
+ ```
149
+
5
150
  ## [0.5.12] - 2025-12-15
6
151
 
7
152
  ### Benchmark Section Cleanup
@@ -41,7 +41,19 @@ const {
41
41
  DatalogProgram,
42
42
  evaluateDatalog,
43
43
  GraphFrame,
44
- getVersion
44
+ getVersion,
45
+ // Memory Layer (v0.5.13+) - GraphDB-Powered Agent Memory
46
+ AgentState,
47
+ AgentRuntime,
48
+ WorkingMemory,
49
+ EpisodicMemory,
50
+ LongTermMemory,
51
+ MemoryManager,
52
+ // Governance Layer
53
+ GovernancePolicy,
54
+ GovernanceEngine,
55
+ // Scope Layer
56
+ AgentScope
45
57
  } = require('../index.js')
46
58
 
47
59
  // ═══════════════════════════════════════════════════════════════════════════════
@@ -335,6 +347,67 @@ async function main() {
335
347
  console.log(` ✓ Tools: ${CONFIG.agent.tools.join(', ')}`)
336
348
  console.log()
337
349
 
350
+ // ───────────────────────────────────────────────────────────────────────────
351
+ // PHASE 2.5: Memory Layer Initialization (NEW in v0.5.13)
352
+ // ───────────────────────────────────────────────────────────────────────────
353
+
354
+ console.log('┌─ PHASE 2.5: Memory Layer Initialization ─────────────────────────────────┐')
355
+ console.log('│ AgentRuntime + MemoryManager + GovernanceEngine + AgentScope │')
356
+ console.log('└─────────────────────────────────────────────────────────────────────────┘')
357
+
358
+ // Create agent runtime with identity
359
+ const runtime = new AgentRuntime({
360
+ name: CONFIG.agent.name,
361
+ model: CONFIG.llm.model,
362
+ tools: CONFIG.agent.tools,
363
+ memoryCapacity: 100,
364
+ episodeLimit: 1000
365
+ })
366
+
367
+ // Initialize memory manager with GraphDB
368
+ const memoryManager = new MemoryManager(runtime, db, {
369
+ recencyWeight: 0.3,
370
+ relevanceWeight: 0.5,
371
+ importanceWeight: 0.2
372
+ })
373
+
374
+ // Create governance policy for fraud detection
375
+ const policy = new GovernancePolicy({
376
+ capabilities: ['ReadKG', 'WriteKG', 'ExecuteTool', 'UseEmbeddings'],
377
+ maxMemoryMB: 256,
378
+ maxExecutionTimeMs: 60000,
379
+ maxToolCalls: 100
380
+ })
381
+
382
+ // Initialize governance engine
383
+ const governance = new GovernanceEngine(policy)
384
+
385
+ // Create agent scope with namespace isolation
386
+ const scope = new AgentScope({
387
+ name: 'fraud-detection-scope',
388
+ graphUri: CONFIG.kg.graphUri,
389
+ allowedGraphs: [CONFIG.kg.graphUri, `${CONFIG.kg.graphUri}/memory`],
390
+ maxToolCalls: 50
391
+ })
392
+
393
+ // Transition to READY state
394
+ runtime.transitionTo(AgentState.READY)
395
+
396
+ console.log(` ✓ Runtime ID: ${runtime.id}`)
397
+ console.log(` ✓ State: ${runtime.state}`)
398
+ console.log(` ✓ Memory Manager: recency=${memoryManager.weights.recency}, relevance=${memoryManager.weights.relevance}, importance=${memoryManager.weights.importance}`)
399
+ console.log(` ✓ Governance: ${policy.capabilities.size} capabilities, ${policy.limits.maxToolCalls} max tool calls`)
400
+ console.log(` ✓ Scope: ${scope.name} (graphs: ${scope.namespace.allowedGraphs.length})`)
401
+ console.log()
402
+
403
+ // Store initial context in working memory
404
+ memoryManager.addToWorking({
405
+ type: 'session_start',
406
+ task: 'fraud_detection',
407
+ target_graph: CONFIG.kg.graphUri,
408
+ triple_count: tripleCount
409
+ })
410
+
338
411
  // ───────────────────────────────────────────────────────────────────────────
339
412
  // PHASE 3: Tool Execution Pipeline
340
413
  // ───────────────────────────────────────────────────────────────────────────
@@ -527,6 +600,62 @@ async function main() {
527
600
  }
528
601
  console.log()
529
602
 
603
+ // ───────────────────────────────────────────────────────────────────────────
604
+ // Memory Layer: Store Tool Executions as Episodes (NEW in v0.5.13)
605
+ // ───────────────────────────────────────────────────────────────────────────
606
+
607
+ // Store each tool execution in episodic memory for audit trail
608
+ const executionId = runtime.startExecution('Fraud detection analysis on insurance claims')
609
+
610
+ await memoryManager.storeExecution({
611
+ id: `${executionId}-sparql`,
612
+ prompt: 'SELECT high-risk claimants',
613
+ tool: 'kg.sparql.query',
614
+ output: { count: highRiskResults.length },
615
+ success: true,
616
+ durationMs: 50
617
+ })
618
+
619
+ await memoryManager.storeExecution({
620
+ id: `${executionId}-triangles`,
621
+ prompt: 'Triangle detection on fraud network',
622
+ tool: 'kg.graphframe.triangles',
623
+ output: { triangles: triangleCount, pageRank: Object.keys(pageRank).length },
624
+ success: true,
625
+ durationMs: 30
626
+ })
627
+
628
+ await memoryManager.storeExecution({
629
+ id: `${executionId}-embeddings`,
630
+ prompt: 'Find similar claims to CLM001',
631
+ tool: 'kg.embeddings.search',
632
+ output: { similarCount: similarClaims.length },
633
+ success: true,
634
+ durationMs: 25
635
+ })
636
+
637
+ await memoryManager.storeExecution({
638
+ id: `${executionId}-datalog`,
639
+ prompt: 'NICB fraud detection rules',
640
+ tool: 'kg.datalog.infer',
641
+ output: { collusions: collusions.length, addressFraud: addressFraud.length },
642
+ success: true,
643
+ durationMs: 15
644
+ })
645
+
646
+ // Track resource usage in scope
647
+ scope.trackUsage('toolCalls', 4)
648
+ scope.trackUsage('graphQueries', 2)
649
+
650
+ // Add findings to working memory
651
+ memoryManager.addToWorking({
652
+ type: 'findings',
653
+ highRiskCount: highRiskResults.length,
654
+ triangles: triangleCount,
655
+ collusions: collusions.length,
656
+ addressFraud: addressFraud.length
657
+ })
658
+
530
659
  // ───────────────────────────────────────────────────────────────────────────
531
660
  // PHASE 4: LLM-Powered Analysis (if API key available)
532
661
  // ───────────────────────────────────────────────────────────────────────────
@@ -589,6 +718,24 @@ async function main() {
589
718
  console.log()
590
719
  }
591
720
 
721
+ // Complete execution and get memory statistics
722
+ runtime.completeExecution({ riskLevel, findings }, true)
723
+ const memStats = memoryManager.getStats()
724
+ const remaining = scope.getRemainingResources()
725
+
726
+ // Memory Layer Report (NEW in v0.5.13)
727
+ console.log(' ┌──────────────────────────────────────────────────────────────────────┐')
728
+ console.log(' │ MEMORY LAYER STATISTICS (v0.5.13+) │')
729
+ console.log(' ├──────────────────────────────────────────────────────────────────────┤')
730
+ console.log(` │ Agent Runtime ID: ${(runtime.id || 'unknown').substring(0, 36).padEnd(46)}│`)
731
+ console.log(` │ Final State: ${runtime.state.padEnd(46)}│`)
732
+ console.log(` │ Working Memory Items: ${memStats.working.contextSize.toString().padEnd(46)}│`)
733
+ console.log(` │ Episodic Memory Episodes: ${memStats.episodic.episodeCount.toString().padEnd(46)}│`)
734
+ console.log(` │ Tool Calls Remaining: ${remaining.toolCalls.toString().padEnd(46)}│`)
735
+ console.log(` │ Graph Queries Remaining: ${remaining.graphQueries.toString().padEnd(46)}│`)
736
+ console.log(' └──────────────────────────────────────────────────────────────────────┘')
737
+ console.log()
738
+
592
739
  // Execution Witness (Proof Theory: Curry-Howard Correspondence)
593
740
  const witness = {
594
741
  agent: agent.getName(),
@@ -609,6 +756,15 @@ async function main() {
609
756
  triangles: findings.triangles,
610
757
  collusions: findings.collusions.length,
611
758
  addressFraud: findings.addressFraud.length
759
+ },
760
+ // Memory Layer (v0.5.13+)
761
+ memory: {
762
+ runtimeId: runtime.id,
763
+ finalState: runtime.state,
764
+ workingMemoryItems: memStats.working.contextSize,
765
+ episodicMemoryEpisodes: memStats.episodic.episodeCount,
766
+ toolCallsUsed: scope.usage.toolCalls,
767
+ governanceAuditEntries: governance.auditLog.length
612
768
  }
613
769
  }
614
770
 
@@ -35,7 +35,19 @@ const {
35
35
  DatalogProgram,
36
36
  evaluateDatalog,
37
37
  GraphFrame,
38
- getVersion
38
+ getVersion,
39
+ // Memory Layer (v0.5.13+) - GraphDB-Powered Agent Memory
40
+ AgentState,
41
+ AgentRuntime,
42
+ WorkingMemory,
43
+ EpisodicMemory,
44
+ LongTermMemory,
45
+ MemoryManager,
46
+ // Governance Layer
47
+ GovernancePolicy,
48
+ GovernanceEngine,
49
+ // Scope Layer
50
+ AgentScope
39
51
  } = require('../index.js')
40
52
 
41
53
  // ═══════════════════════════════════════════════════════════════════════════
@@ -283,6 +295,67 @@ async function main() {
283
295
  console.log(` Agent "${agent.getName()}" spawned with model: ${agent.getModel()}`)
284
296
  console.log()
285
297
 
298
+ // ─────────────────────────────────────────────────────────────────────────
299
+ // PHASE 2.5: Memory Layer Initialization (NEW in v0.5.13)
300
+ // ─────────────────────────────────────────────────────────────────────────
301
+
302
+ console.log('┌─ MEMORY: AgentRuntime + MemoryManager + Governance ────────────────────┐')
303
+ console.log('│ Memory Layer: Working + Episodic + LongTerm (GraphDB-backed) │')
304
+ console.log('└─────────────────────────────────────────────────────────────────────────┘')
305
+
306
+ // Create agent runtime with identity
307
+ const runtime = new AgentRuntime({
308
+ name: 'underwriter',
309
+ model: MODEL,
310
+ tools: ['kg.sparql.query', 'kg.datalog.apply', 'kg.embeddings.search'],
311
+ memoryCapacity: 100,
312
+ episodeLimit: 1000
313
+ })
314
+
315
+ // Initialize memory manager with GraphDB
316
+ const memoryManager = new MemoryManager(runtime, db, {
317
+ recencyWeight: 0.3,
318
+ relevanceWeight: 0.5,
319
+ importanceWeight: 0.2
320
+ })
321
+
322
+ // Create governance policy for underwriting
323
+ const policy = new GovernancePolicy({
324
+ capabilities: ['ReadKG', 'ExecuteTool', 'UseEmbeddings', 'AccessMemory'],
325
+ maxMemoryMB: 256,
326
+ maxExecutionTimeMs: 60000,
327
+ maxToolCalls: 100
328
+ })
329
+
330
+ // Initialize governance engine
331
+ const governance = new GovernanceEngine(policy)
332
+
333
+ // Create agent scope with namespace isolation
334
+ const scope = new AgentScope({
335
+ name: 'underwriting-scope',
336
+ graphUri: 'http://underwriting.org/data',
337
+ allowedGraphs: ['http://underwriting.org/data', 'http://underwriting.org/memory'],
338
+ maxToolCalls: 50
339
+ })
340
+
341
+ console.log(` Runtime ID: ${runtime.id}`)
342
+ console.log(` Memory: recency=${memoryManager.weights.recency}, relevance=${memoryManager.weights.relevance}, importance=${memoryManager.weights.importance}`)
343
+ console.log(` Governance: ${policy.capabilities.size} capabilities, ${policy.limits.maxToolCalls} max tool calls`)
344
+ console.log()
345
+
346
+ // Store initial context in working memory
347
+ memoryManager.addToWorking({
348
+ type: 'session_start',
349
+ task: 'underwriting_analysis',
350
+ triple_count: tripleCount
351
+ })
352
+
353
+ // Transition to READY state first
354
+ runtime.transitionTo(AgentState.READY)
355
+
356
+ // Start execution for episodic tracking
357
+ const executionId = runtime.startExecution('Commercial underwriting risk analysis')
358
+
286
359
  // ─────────────────────────────────────────────────────────────────────────
287
360
  // PHASE 3: Execute Underwriting Tools
288
361
  // ─────────────────────────────────────────────────────────────────────────
@@ -475,6 +548,54 @@ async function main() {
475
548
  console.log()
476
549
  }
477
550
 
551
+ // ─────────────────────────────────────────────────────────────────────────
552
+ // Memory Layer: Store Tool Executions as Episodes (NEW in v0.5.13)
553
+ // ─────────────────────────────────────────────────────────────────────────
554
+
555
+ await memoryManager.storeExecution({
556
+ id: `${executionId}-sparql`,
557
+ prompt: 'Query all business accounts',
558
+ tool: 'kg.sparql.query',
559
+ output: { accountCount: accounts.length },
560
+ success: true,
561
+ durationMs: 50
562
+ })
563
+
564
+ await memoryManager.storeExecution({
565
+ id: `${executionId}-graphframe`,
566
+ prompt: 'Risk network analysis',
567
+ tool: 'kg.graphframe.analyze',
568
+ output: { vertices: riskVertices.length, pageRank: 'complete' },
569
+ success: true,
570
+ durationMs: 30
571
+ })
572
+
573
+ await memoryManager.storeExecution({
574
+ id: `${executionId}-datalog`,
575
+ prompt: 'Apply underwriting rules',
576
+ tool: 'kg.datalog.infer',
577
+ output: { decisions: decisions.length, autoApprove: autoApprove.length, referToUW: referToUW.length },
578
+ success: true,
579
+ durationMs: 20
580
+ })
581
+
582
+ // Track resource usage in scope
583
+ scope.trackUsage('toolCalls', 4)
584
+ scope.trackUsage('graphQueries', 2)
585
+
586
+ // Add findings to working memory
587
+ memoryManager.addToWorking({
588
+ type: 'findings',
589
+ accountsProcessed: accounts.length,
590
+ autoApproveCount: autoApprove.length,
591
+ referToUWCount: referToUW.length
592
+ })
593
+
594
+ // Complete execution
595
+ runtime.completeExecution({ accounts: accounts.length, decisions: decisions.length }, true)
596
+ const memStats = memoryManager.getStats()
597
+ const remaining = scope.getRemainingResources()
598
+
478
599
  // ─────────────────────────────────────────────────────────────────────────
479
600
  // PHASE 5: Generate Execution Witness (Proof Theory)
480
601
  // ─────────────────────────────────────────────────────────────────────────
@@ -498,6 +619,16 @@ async function main() {
498
619
  console.log(' - BUS004 (Downtown): MODERATE - flood exposure, established')
499
620
  console.log()
500
621
 
622
+ // Memory Layer Statistics (NEW in v0.5.13)
623
+ console.log(' MEMORY LAYER STATISTICS (v0.5.13+):')
624
+ console.log(` Runtime ID: ${(runtime.id || 'unknown').substring(0, 36)}`)
625
+ console.log(` Final State: ${runtime.state}`)
626
+ console.log(` Working Memory Items: ${memStats.working.contextSize}`)
627
+ console.log(` Episodic Episodes: ${memStats.episodic.episodeCount}`)
628
+ console.log(` Tool Calls Remaining: ${remaining.toolCalls}`)
629
+ console.log(` Graph Queries Used: ${scope.usage.graphQueries}`)
630
+ console.log()
631
+
501
632
  // Execution Witness
502
633
  const witness = {
503
634
  agent: agent.getName(),
@@ -515,7 +646,16 @@ async function main() {
515
646
  referToUW: referToUW.map(d => d.args[0])
516
647
  },
517
648
  premiums: premiums.map(p => ({ id: p.id, premium: p.premium, decision: p.decision })),
518
- trace: agent.getTrace()
649
+ trace: agent.getTrace(),
650
+ // Memory Layer (v0.5.13+)
651
+ memory: {
652
+ runtimeId: runtime.id,
653
+ finalState: runtime.state,
654
+ workingMemoryItems: memStats.working.contextSize,
655
+ episodicMemoryEpisodes: memStats.episodic.episodeCount,
656
+ toolCallsUsed: scope.usage.toolCalls,
657
+ governanceAuditEntries: governance.auditLog.length
658
+ }
519
659
  }
520
660
 
521
661
  // Generate deterministic hash