rust-kgdb 0.6.4 → 0.6.5

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,4 +1,4 @@
1
- #!/usr/bin/env node
1
+ no#!/usr/bin/env node
2
2
  /**
3
3
  * ═══════════════════════════════════════════════════════════════════════════════
4
4
  * FRAUD DETECTION AGENT - Professional HyperMind Framework Implementation
@@ -331,19 +331,22 @@ async function main() {
331
331
  // ───────────────────────────────────────────────────────────────────────────
332
332
 
333
333
  console.log('┌─ PHASE 2: Agent Initialization ─────────────────────────────────────────┐')
334
- console.log('│ HyperMindAgent.spawn(AgentSpec) │')
334
+ console.log('│ new HyperMindAgent({ kg, memory, embeddings, ... }) │')
335
335
  console.log('└─────────────────────────────────────────────────────────────────────────┘')
336
336
 
337
- const agent = await HyperMindAgent.spawn({
337
+ // Initialize embedding service
338
+ const embeddingService = new EmbeddingService()
339
+
340
+ // Create agent with knowledge graph and embeddings
341
+ const agent = new HyperMindAgent({
342
+ kg: db,
343
+ embeddings: embeddingService,
338
344
  name: CONFIG.agent.name,
339
- model: CONFIG.llm.model,
340
- tools: CONFIG.agent.tools,
341
- endpoint: 'http://localhost:30080',
342
- tracing: CONFIG.agent.tracingEnabled
345
+ apiKey: process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY || null
343
346
  })
344
347
 
345
- console.log(` ✓ Agent spawned: "${agent.getName()}"`)
346
- console.log(` ✓ Model: ${agent.getModel()}`)
348
+ console.log(` ✓ Agent created: "${agent.name}"`)
349
+ console.log(` ✓ Model: ${CONFIG.llm.model}`)
347
350
  console.log(` ✓ Tools: ${CONFIG.agent.tools.join(', ')}`)
348
351
  console.log()
349
352
 
@@ -352,24 +355,12 @@ async function main() {
352
355
  // ───────────────────────────────────────────────────────────────────────────
353
356
 
354
357
  console.log('┌─ PHASE 2.5: Memory Layer Initialization ─────────────────────────────────┐')
355
- console.log('│ AgentRuntime + MemoryManager + GovernanceEngine + AgentScope │')
358
+ console.log('│ MemoryManager + GovernancePolicy + AgentScope │')
356
359
  console.log('└─────────────────────────────────────────────────────────────────────────┘')
357
360
 
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
- })
361
+ // Memory is automatically initialized via agent.memory
362
+ // Access it directly from the agent
363
+ const memoryManager = agent.memory
373
364
 
374
365
  // Create governance policy for fraud detection
375
366
  const policy = new GovernancePolicy({
@@ -390,24 +381,20 @@ async function main() {
390
381
  maxToolCalls: 50
391
382
  })
392
383
 
393
- // Transition to READY state
384
+ // Create agent runtime for execution tracking
385
+ const runtime = new AgentRuntime({
386
+ name: CONFIG.agent.name,
387
+ model: CONFIG.llm.model,
388
+ tools: CONFIG.agent.tools
389
+ })
394
390
  runtime.transitionTo(AgentState.READY)
395
391
 
396
- console.log(` ✓ Runtime ID: ${runtime.id}`)
397
- console.log(` ✓ State: ${runtime.state}`)
398
392
  console.log(` ✓ Memory Manager: recency=${memoryManager.weights.recency}, relevance=${memoryManager.weights.relevance}, importance=${memoryManager.weights.importance}`)
399
393
  console.log(` ✓ Governance: ${policy.capabilities.size} capabilities, ${policy.limits.maxToolCalls} max tool calls`)
400
394
  console.log(` ✓ Scope: ${scope.name} (graphs: ${scope.namespace.allowedGraphs.length})`)
395
+ console.log(` ✓ Runtime: ${runtime.name} (state: ${runtime.state})`)
401
396
  console.log()
402
397
 
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
-
411
398
  // ───────────────────────────────────────────────────────────────────────────
412
399
  // PHASE 3: Tool Execution Pipeline
413
400
  // ───────────────────────────────────────────────────────────────────────────
@@ -48,13 +48,14 @@
48
48
  // Import HyperMind SDK (exposed via NAPI-RS FFI)
49
49
  import {
50
50
  GraphDB,
51
- // HyperMind Agent Framework primitives
52
- spawn,
53
- AgentSpec,
54
- Model,
51
+ // HyperMind Agent Framework
52
+ HyperMindAgent,
53
+ HyperMindAgentSpec,
54
+ HyperMindModel,
55
+ HyperMindTool,
56
+ TraceEntry,
55
57
  // Type system
56
58
  TypeId,
57
- ExecutionWitness,
58
59
  // Graph algorithms
59
60
  GraphFrame,
60
61
  // Embeddings
@@ -160,47 +161,44 @@ class FraudDetectionAgent {
160
161
  * Create a fraud detection agent
161
162
  *
162
163
  * Uses HyperMind primitives:
163
- * - spawn() - Create agent with typed tools
164
- * - AgentSpec - Configure model, tools, limits
165
- * - Model - LLM provider abstraction
164
+ * - HyperMindAgent.spawn() - Create agent with typed tools
165
+ * - HyperMindAgentSpec - Configure model, tools, limits
166
+ * - HyperMindModel - LLM model type ('claude-sonnet-4', 'gpt-4o', etc.)
166
167
  */
167
168
  static async create(config: KGDBConfig): Promise<FraudDetectionAgent> {
168
- // Initialize database based on deployment mode
169
- let db: any;
170
- if (config.mode === 'in-memory') {
171
- db = new GraphDB(config.namespace || 'http://hypermind.ai/fraud/');
172
- console.log('📦 Using in-memory GraphDB');
173
- } else {
174
- db = await GraphDB.connect(config.endpoint!);
175
- console.log(`🌐 Connected to K8s cluster at ${config.endpoint}`);
169
+ // Initialize database (always in-memory for SDK)
170
+ const db = new GraphDB(config.namespace || 'http://hypermind.ai/fraud/');
171
+ console.log('📦 Using in-memory GraphDB');
172
+ if (config.mode === 'k8s-cluster') {
173
+ console.log(`🌐 Agent will target K8s cluster at ${config.endpoint}`);
176
174
  }
177
175
 
178
- // Create agent using HyperMind spawn() primitive
179
- const agent = await spawn({
176
+ // Create agent using HyperMindAgent.spawn()
177
+ // Tools are typed morphisms (A -> B) with category theory composition
178
+ const agent = await HyperMindAgent.spawn({
180
179
  name: 'fraud-detection-agent',
181
- description: 'Detects fraud patterns using knowledge graph analysis with WASM sandbox',
182
180
 
183
- // LLM Model (supports Claude, GPT-4, Ollama, etc.)
184
- model: Model.Claude('claude-3-opus'),
181
+ // LLM Model: 'claude-sonnet-4' | 'claude-opus-4' | 'gpt-4o' | 'gpt-4' | 'mock'
182
+ model: 'claude-sonnet-4' as HyperMindModel,
185
183
 
186
- // Tools are typed morphisms (A -> B) with category theory composition
184
+ // Available tools:
185
+ // 'kg.sparql.query' | 'kg.sparql.update' | 'kg.motif.find' |
186
+ // 'kg.datalog.apply' | 'kg.semantic.search' | 'kg.traversal.oneHop' | 'kg.traversal.paths'
187
187
  tools: [
188
- 'kg.sparql.query', // Query -> BindingSet
189
- 'kg.motif.find', // Graph -> PatternSet
190
- 'kg.datalog.apply', // Rules -> InferredFacts
191
- 'kg.embeddings.search', // Entity -> SimilarEntities
192
- 'kg.graphframes.pagerank', // Graph -> Rankings
193
- 'kg.graphframes.connected_components', // Graph -> Components
188
+ 'kg.sparql.query' as HyperMindTool, // Query -> BindingSet
189
+ 'kg.motif.find' as HyperMindTool, // Graph -> PatternSet
190
+ 'kg.datalog.apply' as HyperMindTool, // Rules -> InferredFacts
191
+ 'kg.semantic.search' as HyperMindTool, // Entity -> SimilarEntities
194
192
  ],
195
193
 
196
- // Execution limits
197
- maxIterations: 10,
194
+ // K8s cluster endpoint (optional for in-memory mode)
195
+ endpoint: config.endpoint,
198
196
 
199
- // Enable full provenance tracking (Curry-Howard witnesses)
200
- tracingEnabled: true,
197
+ // Execution timeout (optional)
198
+ timeout: 30000,
201
199
 
202
- // Execute tools in WASM sandbox (wasmtime)
203
- wasmSandbox: true,
200
+ // Enable full provenance tracking
201
+ tracing: true,
204
202
  });
205
203
 
206
204
  return new FraudDetectionAgent(agent, db, config);
@@ -412,26 +410,31 @@ class UnderwritingAgent {
412
410
  * Create an underwriting agent
413
411
  */
414
412
  static async create(config: KGDBConfig): Promise<UnderwritingAgent> {
415
- let db: any;
416
- if (config.mode === 'in-memory') {
417
- db = new GraphDB(config.namespace || 'http://hypermind.ai/underwriting/');
418
- } else {
419
- db = await GraphDB.connect(config.endpoint!);
420
- }
413
+ // Initialize database (in-memory)
414
+ const db = new GraphDB(config.namespace || 'http://hypermind.ai/underwriting/');
421
415
 
422
- const agent = await spawn({
416
+ // Create agent using HyperMindAgent.spawn()
417
+ const agent = await HyperMindAgent.spawn({
423
418
  name: 'underwriting-agent',
424
- description: 'Insurance underwriting with risk assessment using knowledge graph',
425
- model: Model.Claude('claude-3-opus'),
419
+
420
+ // LLM Model
421
+ model: 'claude-sonnet-4' as HyperMindModel,
422
+
423
+ // Available tools for underwriting
426
424
  tools: [
427
- 'kg.sparql.query',
428
- 'kg.datalog.apply',
429
- 'kg.embeddings.search',
430
- 'kg.graphframes.pagerank',
425
+ 'kg.sparql.query' as HyperMindTool,
426
+ 'kg.datalog.apply' as HyperMindTool,
427
+ 'kg.semantic.search' as HyperMindTool,
431
428
  ],
432
- maxIterations: 8,
433
- tracingEnabled: true,
434
- wasmSandbox: true,
429
+
430
+ // K8s cluster endpoint
431
+ endpoint: config.endpoint,
432
+
433
+ // Execution timeout
434
+ timeout: 30000,
435
+
436
+ // Enable tracing for audit
437
+ tracing: true,
435
438
  });
436
439
 
437
440
  return new UnderwritingAgent(agent, db);
@@ -504,7 +507,7 @@ interface FraudAnalysisReport {
504
507
  patterns: DetectedPattern[];
505
508
  suspiciousEntities: SuspiciousEntity[];
506
509
  recommendedActions: string[];
507
- executionWitness: ExecutionWitness;
510
+ trace: TraceEntry[]; // Execution trace for audit
508
511
  }
509
512
 
510
513
  interface DetectedPattern {
@@ -275,24 +275,26 @@ async function main() {
275
275
  // PHASE 2: Spawn HyperMind Agent
276
276
  // ─────────────────────────────────────────────────────────────────────────
277
277
 
278
- console.log('┌─ AGENT: HyperMindAgent.spawn() ──────────────────────────────────────┐')
279
- console.log('│ AgentSpec: { │')
278
+ console.log('┌─ AGENT: new HyperMindAgent() ──────────────────────────────────────────┐')
279
+ console.log('│ Config: { │')
280
280
  console.log('│ name: "underwriter", │')
281
281
  console.log(`│ model: "${MODEL}", │`)
282
282
  console.log('│ tools: [kg.sparql.query, kg.datalog.apply, kg.embeddings.search],│')
283
- console.log('│ tracing: true │')
284
283
  console.log('│ } │')
285
284
  console.log('└─────────────────────────────────────────────────────────────────────┘')
286
285
 
287
- const agent = await HyperMindAgent.spawn({
286
+ // Initialize embedding service
287
+ const embeddingService = new EmbeddingService()
288
+
289
+ // Create agent with knowledge graph and embeddings
290
+ const agent = new HyperMindAgent({
291
+ kg: db,
292
+ embeddings: embeddingService,
288
293
  name: 'underwriter',
289
- model: MODEL,
290
- tools: ['kg.sparql.query', 'kg.datalog.apply', 'kg.embeddings.search'],
291
- endpoint: 'http://localhost:30080',
292
- tracing: true
294
+ apiKey: process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY || null
293
295
  })
294
296
 
295
- console.log(` Agent "${agent.getName()}" spawned with model: ${agent.getModel()}`)
297
+ console.log(` Agent "${agent.getName()}" created with model: ${agent.getModel()}`)
296
298
  console.log()
297
299
 
298
300
  // ─────────────────────────────────────────────────────────────────────────
@@ -311,13 +313,10 @@ async function main() {
311
313
  memoryCapacity: 100,
312
314
  episodeLimit: 1000
313
315
  })
316
+ runtime.transitionTo(AgentState.READY)
314
317
 
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
- })
318
+ // Memory is automatically initialized via agent.memory
319
+ const memoryManager = agent.memory
321
320
 
322
321
  // Create governance policy for underwriting
323
322
  const policy = new GovernancePolicy({
@@ -350,10 +349,7 @@ async function main() {
350
349
  triple_count: tripleCount
351
350
  })
352
351
 
353
- // Transition to READY state first
354
- runtime.transitionTo(AgentState.READY)
355
-
356
- // Start execution for episodic tracking
352
+ // Start execution for episodic tracking (runtime is already in READY state)
357
353
  const executionId = runtime.startExecution('Commercial underwriting risk analysis')
358
354
 
359
355
  // ─────────────────────────────────────────────────────────────────────────
@@ -646,7 +642,7 @@ async function main() {
646
642
  referToUW: referToUW.map(d => d.args[0])
647
643
  },
648
644
  premiums: premiums.map(p => ({ id: p.id, premium: p.premium, decision: p.decision })),
649
- trace: agent.getTrace(),
645
+ trace: agent.getAuditLog(),
650
646
  // Memory Layer (v0.5.13+)
651
647
  memory: {
652
648
  runtimeId: runtime.id,