rust-kgdb 0.4.1 → 0.4.3

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.
@@ -0,0 +1,502 @@
1
+ #!/usr/bin/env npx ts-node
2
+ /**
3
+ * Core Concepts Demo - rust-kgdb TypeScript SDK
4
+ *
5
+ * This demo walks through ALL core concepts from data ingestion to AI agent execution:
6
+ *
7
+ * 1. DATA MODEL: RDF triples, quads, and hypergraphs
8
+ * 2. DATA INGESTION (Step 0): Loading data with trigger-based embedding generation
9
+ * 3. SPARQL QUERIES: Declarative graph querying
10
+ * 4. DATALOG REASONING: Recursive rule evaluation
11
+ * 5. EMBEDDINGS: Similarity search with HNSW
12
+ * 6. GRAPHFRAMES: Graph algorithms (PageRank, connected components)
13
+ * 7. CONCEPT LOOKUP: How agents find schema types (Cmd+/ analogy)
14
+ * 8. HYPERMIND AGENTS: Natural language to SPARQL execution
15
+ *
16
+ * See docs/CORE_CONCEPTS.md for detailed explanations of each concept.
17
+ */
18
+
19
+ import {
20
+ GraphDB,
21
+ DatalogEngine,
22
+ EmbeddingService,
23
+ GraphFrame,
24
+ } from 'rust-kgdb';
25
+
26
+ // =============================================================================
27
+ // 1. DATA MODEL: RDF Triples and Named Graphs
28
+ // =============================================================================
29
+
30
+ function demoDataModel(): any {
31
+ console.log('='.repeat(70));
32
+ console.log(' 1. DATA MODEL: RDF Triples and Named Graphs');
33
+ console.log('='.repeat(70));
34
+ console.log();
35
+
36
+ // Create a knowledge graph database
37
+ const db = new GraphDB('http://example.org/company');
38
+
39
+ // Load RDF data in Turtle format
40
+ // Each statement is a TRIPLE: (Subject, Predicate, Object)
41
+ const ttlData = `
42
+ @prefix ex: <http://example.org/> .
43
+ @prefix foaf: <http://xmlns.com/foaf/0.1/> .
44
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
45
+
46
+ # Triple: (ex:alice, rdf:type, foaf:Person)
47
+ ex:alice a foaf:Person ;
48
+ foaf:name "Alice Smith" ;
49
+ foaf:age 30 .
50
+
51
+ # Triple: (ex:bob, foaf:knows, ex:alice)
52
+ ex:bob a foaf:Person ;
53
+ foaf:name "Bob Jones" ;
54
+ foaf:knows ex:alice .
55
+
56
+ # Triple with typed literal
57
+ ex:acme a ex:Company ;
58
+ ex:name "Acme Corp" ;
59
+ ex:revenue "5000000"^^xsd:decimal .
60
+ `;
61
+
62
+ db.loadTtl(ttlData, null);
63
+
64
+ console.log(' Loaded RDF triples:');
65
+ console.log(' (ex:alice, a, foaf:Person)');
66
+ console.log(" (ex:alice, foaf:name, 'Alice Smith')");
67
+ console.log(' (ex:bob, foaf:knows, ex:alice)');
68
+ console.log(' (ex:acme, ex:revenue, 5000000^^xsd:decimal)');
69
+ console.log();
70
+
71
+ // Named graph (QUAD) - data isolation
72
+ console.log(' Named Graphs (Quads):');
73
+ console.log(' Data can be isolated in named graphs for access control');
74
+
75
+ const hrData = `
76
+ @prefix ex: <http://example.org/> .
77
+ ex:alice ex:salary 120000 .
78
+ `;
79
+
80
+ // Load into named graph (4th element)
81
+ db.loadTtl(hrData, 'http://example.org/hr-confidential');
82
+
83
+ console.log(' (ex:alice, ex:salary, 120000) -> GRAPH <hr-confidential>');
84
+ console.log();
85
+
86
+ // Count triples
87
+ const count = db.countTriples();
88
+ console.log(` Total triples in database: ${count}`);
89
+ console.log();
90
+
91
+ return db;
92
+ }
93
+
94
+ // =============================================================================
95
+ // 2. DATA INGESTION (Step 0): Trigger-Based Embedding Generation
96
+ // =============================================================================
97
+
98
+ function demoDataIngestion(db: any): any {
99
+ console.log('='.repeat(70));
100
+ console.log(' 2. DATA INGESTION (Step 0): Trigger-Based Embeddings');
101
+ console.log('='.repeat(70));
102
+ console.log();
103
+
104
+ console.log(' Data Ingestion Flow:');
105
+ console.log();
106
+ console.log(' Raw RDF Data');
107
+ console.log(' |');
108
+ console.log(' v');
109
+ console.log(' +------------------+');
110
+ console.log(' | RDF Parser | TTL/N-Triples/JSON-LD');
111
+ console.log(' +------------------+');
112
+ console.log(' |');
113
+ console.log(' v');
114
+ console.log(' +------------------+');
115
+ console.log(' | Dictionary | String interning (8-byte IDs)');
116
+ console.log(' +------------------+');
117
+ console.log(' |');
118
+ console.log(' +--------+--------+');
119
+ console.log(' | | |');
120
+ console.log(' v v v');
121
+ console.log(' +------+ +------+ +------+');
122
+ console.log(' | SPOC | |Trigger| |Schema|');
123
+ console.log(' |Index | |System | |Index |');
124
+ console.log(' +------+ +------+ +------+');
125
+ console.log(' |');
126
+ console.log(' v');
127
+ console.log(' +------------------+');
128
+ console.log(' | Embedding | OpenAI / Anthropic / Ollama');
129
+ console.log(' | Providers |');
130
+ console.log(' +------------------+');
131
+ console.log(' |');
132
+ console.log(' v');
133
+ console.log(' +------------------+');
134
+ console.log(' | HNSW Index | O(log N) similarity search');
135
+ console.log(' +------------------+');
136
+ console.log();
137
+
138
+ // Load fraud detection data
139
+ const fraudData = `
140
+ @prefix fraud: <http://example.org/fraud/> .
141
+ @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
142
+
143
+ fraud:tx001 a fraud:Transaction ;
144
+ fraud:sender fraud:account001 ;
145
+ fraud:receiver fraud:account002 ;
146
+ fraud:amount "50000"^^xsd:decimal ;
147
+ fraud:timestamp "2024-12-14T10:30:00Z"^^xsd:dateTime .
148
+
149
+ fraud:tx002 a fraud:Transaction ;
150
+ fraud:sender fraud:account002 ;
151
+ fraud:receiver fraud:account003 ;
152
+ fraud:amount "48000"^^xsd:decimal .
153
+
154
+ fraud:tx003 a fraud:Transaction ;
155
+ fraud:sender fraud:account003 ;
156
+ fraud:receiver fraud:account001 ;
157
+ fraud:amount "45000"^^xsd:decimal .
158
+
159
+ fraud:account001 a fraud:Account ;
160
+ fraud:holder "Entity A" ;
161
+ fraud:jurisdiction "Panama" .
162
+
163
+ fraud:account002 a fraud:Account ;
164
+ fraud:holder "Entity B" ;
165
+ fraud:jurisdiction "BVI" .
166
+
167
+ fraud:account003 a fraud:Account ;
168
+ fraud:holder "Entity C" ;
169
+ fraud:jurisdiction "Cayman Islands" .
170
+ `;
171
+
172
+ db.loadTtl(fraudData, null);
173
+
174
+ console.log(' Loaded fraud detection data:');
175
+ console.log(' - 3 transactions (circular payment pattern)');
176
+ console.log(' - 3 accounts (offshore jurisdictions)');
177
+ console.log();
178
+ console.log(' In production, triggers would:');
179
+ console.log(' 1. Generate embeddings for each entity');
180
+ console.log(' 2. Update HNSW index for similarity search');
181
+ console.log(' 3. Populate 1-hop neighbor cache');
182
+ console.log();
183
+
184
+ return db;
185
+ }
186
+
187
+ // =============================================================================
188
+ // 3. SPARQL QUERIES: Declarative Graph Querying
189
+ // =============================================================================
190
+
191
+ function demoSparqlQueries(db: any): void {
192
+ console.log('='.repeat(70));
193
+ console.log(' 3. SPARQL QUERIES: Declarative Graph Querying');
194
+ console.log('='.repeat(70));
195
+ console.log();
196
+
197
+ // Basic SELECT query
198
+ console.log(' Example 1: Basic SELECT');
199
+ console.log(' -------------------------');
200
+ const query1 = `
201
+ PREFIX foaf: <http://xmlns.com/foaf/0.1/>
202
+ SELECT ?name ?age WHERE {
203
+ ?person a foaf:Person ;
204
+ foaf:name ?name .
205
+ OPTIONAL { ?person foaf:age ?age }
206
+ }
207
+ `;
208
+ console.log(` Query: ${query1.trim()}`);
209
+
210
+ const results = db.querySelect(query1);
211
+ console.log(' Results:');
212
+ for (const r of results) {
213
+ console.log(` - ${JSON.stringify(r.bindings)}`);
214
+ }
215
+ console.log();
216
+
217
+ // Pattern matching - circular payments
218
+ console.log(' Example 2: Pattern Matching (Circular Payments)');
219
+ console.log(' ------------------------------------------------');
220
+ const query2 = `
221
+ PREFIX fraud: <http://example.org/fraud/>
222
+ SELECT ?a ?b ?c WHERE {
223
+ ?tx1 fraud:sender ?a ; fraud:receiver ?b .
224
+ ?tx2 fraud:sender ?b ; fraud:receiver ?c .
225
+ ?tx3 fraud:sender ?c ; fraud:receiver ?a .
226
+ }
227
+ `;
228
+ console.log(' Query: Find A -> B -> C -> A patterns');
229
+
230
+ const results2 = db.querySelect(query2);
231
+ console.log(` Found ${results2.length} circular pattern(s)`);
232
+ console.log();
233
+ }
234
+
235
+ // =============================================================================
236
+ // 4. DATALOG REASONING: Recursive Rules
237
+ // =============================================================================
238
+
239
+ function demoDatalogReasoning(): void {
240
+ console.log('='.repeat(70));
241
+ console.log(' 4. DATALOG REASONING: Recursive Rules');
242
+ console.log('='.repeat(70));
243
+ console.log();
244
+
245
+ const engine = new DatalogEngine();
246
+
247
+ // Add facts
248
+ console.log(' Facts (parent relationship):');
249
+ engine.addFact('parent', ['alice', 'bob']);
250
+ engine.addFact('parent', ['bob', 'charlie']);
251
+ engine.addFact('parent', ['charlie', 'david']);
252
+ console.log(' parent(alice, bob)');
253
+ console.log(' parent(bob, charlie)');
254
+ console.log(' parent(charlie, david)');
255
+ console.log();
256
+
257
+ // Add recursive rules
258
+ console.log(' Rules (transitive closure):');
259
+ console.log(' ancestor(X, Y) :- parent(X, Y) % base case');
260
+ console.log(' ancestor(X, Z) :- parent(X, Y), ancestor(Y, Z) % recursive');
261
+ console.log();
262
+
263
+ // Base case
264
+ engine.addRule('ancestor', ['X', 'Y'], [
265
+ { predicate: 'parent', args: ['X', 'Y'] }
266
+ ]);
267
+
268
+ // Recursive case
269
+ engine.addRule('ancestor', ['X', 'Z'], [
270
+ { predicate: 'parent', args: ['X', 'Y'] },
271
+ { predicate: 'ancestor', args: ['Y', 'Z'] }
272
+ ]);
273
+
274
+ // Evaluate
275
+ const iterations = engine.evaluateSemiNaive();
276
+ console.log(` Semi-naive evaluation completed in ${iterations} iterations`);
277
+ console.log();
278
+
279
+ // Query
280
+ const results = engine.query('ancestor', ['alice', '?descendant']);
281
+ console.log(' Query: ancestor(alice, ?descendant)');
282
+ console.log(' Results:');
283
+ for (const r of results) {
284
+ console.log(` - alice is ancestor of ${r.descendant}`);
285
+ }
286
+ console.log();
287
+ }
288
+
289
+ // =============================================================================
290
+ // 5. EMBEDDINGS: Similarity Search
291
+ // =============================================================================
292
+
293
+ function demoEmbeddings(): void {
294
+ console.log('='.repeat(70));
295
+ console.log(' 5. EMBEDDINGS: Similarity Search');
296
+ console.log('='.repeat(70));
297
+ console.log();
298
+
299
+ console.log(' Embedding Space Visualization (2D):');
300
+ console.log();
301
+ console.log(' ^ dim2');
302
+ console.log(' |');
303
+ console.log(' * FraudPattern1');
304
+ console.log(' * FraudPattern2');
305
+ console.log(' |');
306
+ console.log(' o Person1 |');
307
+ console.log(' o Person2 | + Company1');
308
+ console.log(' | + Company2');
309
+ console.log(' ----------------+-------------------> dim1');
310
+ console.log();
311
+ console.log(' Similar entities cluster together!');
312
+ console.log();
313
+
314
+ console.log(' HNSW Index:');
315
+ console.log(' - O(log N) search instead of O(N) brute force');
316
+ console.log(' - Multi-layer navigable small world graph');
317
+ console.log(' - ~50-100 bytes per vector + graph structure');
318
+ console.log();
319
+ }
320
+
321
+ // =============================================================================
322
+ // 6. GRAPHFRAMES: Graph Algorithms
323
+ // =============================================================================
324
+
325
+ function demoGraphFrames(): void {
326
+ console.log('='.repeat(70));
327
+ console.log(' 6. GRAPHFRAMES: Graph Algorithms');
328
+ console.log('='.repeat(70));
329
+ console.log();
330
+
331
+ console.log(' Available Algorithms:');
332
+ console.log(' - pageRank(): Node importance ranking');
333
+ console.log(' - connectedComponents(): Find isolated subgraphs');
334
+ console.log(' - shortestPaths(): Path finding');
335
+ console.log(' - triangleCount(): Clustering coefficient');
336
+ console.log(' - labelPropagation(): Community detection');
337
+ console.log(' - find(): Motif pattern matching');
338
+ console.log();
339
+
340
+ console.log(' Motif Pattern Matching:');
341
+ console.log(' Pattern: (a)-[e1]->(b); (b)-[e2]->(c); (c)-[e3]->(a)');
342
+ console.log(' Finds: All triangles in the graph');
343
+ console.log();
344
+ }
345
+
346
+ // =============================================================================
347
+ // 7. CONCEPT LOOKUP: The Cmd+/ Analogy
348
+ // =============================================================================
349
+
350
+ function demoConceptLookup(): void {
351
+ console.log('='.repeat(70));
352
+ console.log(' 7. CONCEPT LOOKUP: The Cmd+/ Analogy');
353
+ console.log('='.repeat(70));
354
+ console.log();
355
+
356
+ console.log(' IDE Symbol Search (Cmd+/):');
357
+ console.log(' ---------------------------');
358
+ console.log(" Developer: 'I need to validate an email'");
359
+ console.log(' IDE: Searches symbol table');
360
+ console.log(' Results: validateEmail(), isEmailValid(), EmailValidator');
361
+ console.log();
362
+
363
+ console.log(' HyperMind Concept Lookup:');
364
+ console.log(' ---------------------------');
365
+ console.log(" Agent: 'Find circular payment patterns'");
366
+ console.log();
367
+ console.log(' Step 1: Extract concepts');
368
+ console.log(" -> ['circular', 'payment', 'pattern']");
369
+ console.log();
370
+ console.log(' Step 2: Embed concepts');
371
+ console.log(' -> [0.12, 0.45, ...], [0.08, 0.51, ...]');
372
+ console.log();
373
+ console.log(' Step 3: Search schema index');
374
+ console.log(' -> HNSW similarity search');
375
+ console.log();
376
+ console.log(' Step 4: Return matches');
377
+ console.log(' -> Transaction (0.92), CircularTransfer (0.95)');
378
+ console.log();
379
+ }
380
+
381
+ // =============================================================================
382
+ // 8. HYPERMIND AGENTS: Natural Language to Execution
383
+ // =============================================================================
384
+
385
+ function demoHyperMindAgents(): void {
386
+ console.log('='.repeat(70));
387
+ console.log(' 8. HYPERMIND AGENTS: Natural Language to Execution');
388
+ console.log('='.repeat(70));
389
+ console.log();
390
+
391
+ console.log(' Agent Execution Flow:');
392
+ console.log(' ----------------------');
393
+ console.log();
394
+ console.log(" 'Find circular payment patterns over $10,000'");
395
+ console.log(' |');
396
+ console.log(' v');
397
+ console.log(' +-----------------------------------+');
398
+ console.log(' | LLM Planning Layer |');
399
+ console.log(' | Generate typed tool sequence |');
400
+ console.log(' +-----------------------------------+');
401
+ console.log(' |');
402
+ console.log(' +-----------+-----------+');
403
+ console.log(' | | |');
404
+ console.log(' v v v');
405
+ console.log(' +--------+ +--------+ +--------+');
406
+ console.log(' |sparql. | | motif. | |datalog.|');
407
+ console.log(' | query | | find | | apply |');
408
+ console.log(' +--------+ +--------+ +--------+');
409
+ console.log();
410
+
411
+ console.log(' Category Theory - Tools as Morphisms:');
412
+ console.log(' --------------------------------------');
413
+ console.log(' kg.sparql.query : Query -> BindingSet');
414
+ console.log(' kg.motif.find : Pattern -> PatternSet');
415
+ console.log(' Composition: (f ; g) : A -> C');
416
+ console.log();
417
+
418
+ console.log(' Agent Creation (TypeScript):');
419
+ console.log(' ------------------------------');
420
+ console.log(`
421
+ import { spawn, AgentSpec, Model } from 'rust-kgdb';
422
+
423
+ const agent = await spawn({
424
+ name: 'fraud-detector',
425
+ model: Model.Claude('claude-3-opus'),
426
+ tools: [
427
+ 'kg.sparql.query',
428
+ 'kg.motif.find',
429
+ 'kg.datalog.apply',
430
+ ],
431
+ maxIterations: 10,
432
+ tracingEnabled: true,
433
+ wasmSandbox: true,
434
+ });
435
+
436
+ const result = await agent.call('Find circular payments');
437
+ await agent.exportTrace('audit.json');
438
+ `);
439
+ console.log();
440
+ }
441
+
442
+ // =============================================================================
443
+ // MAIN
444
+ // =============================================================================
445
+
446
+ async function main() {
447
+ console.log();
448
+ console.log('#'.repeat(70));
449
+ console.log('#' + ' '.repeat(68) + '#');
450
+ console.log('#' + ' RUST-KGDB CORE CONCEPTS DEMO'.padStart(47).padEnd(68) + '#');
451
+ console.log('#' + ' '.repeat(68) + '#');
452
+ console.log('#' + ' A complete walkthrough of all core concepts'.padStart(55).padEnd(68) + '#');
453
+ console.log('#' + ' See docs/CORE_CONCEPTS.md for detailed explanations'.padStart(60).padEnd(68) + '#');
454
+ console.log('#' + ' '.repeat(68) + '#');
455
+ console.log('#'.repeat(70));
456
+ console.log();
457
+
458
+ try {
459
+ // 1. Data Model
460
+ let db = demoDataModel();
461
+
462
+ // 2. Data Ingestion (Step 0)
463
+ db = demoDataIngestion(db);
464
+
465
+ // 3. SPARQL Queries
466
+ demoSparqlQueries(db);
467
+
468
+ // 4. Datalog Reasoning
469
+ demoDatalogReasoning();
470
+
471
+ // 5. Embeddings
472
+ demoEmbeddings();
473
+
474
+ // 6. GraphFrames
475
+ demoGraphFrames();
476
+
477
+ // 7. Concept Lookup
478
+ demoConceptLookup();
479
+
480
+ // 8. HyperMind Agents
481
+ demoHyperMindAgents();
482
+
483
+ console.log();
484
+ console.log('#'.repeat(70));
485
+ console.log('#' + ' '.repeat(68) + '#');
486
+ console.log('#' + ' ALL CONCEPTS DEMONSTRATED SUCCESSFULLY!'.padStart(52).padEnd(68) + '#');
487
+ console.log('#' + ' '.repeat(68) + '#');
488
+ console.log('#' + ' Next steps:'.padStart(25).padEnd(68) + '#');
489
+ console.log('#' + ' - Read docs/CORE_CONCEPTS.md for details'.padStart(48).padEnd(68) + '#');
490
+ console.log('#' + ' - See sdks/*/examples/ for more examples'.padStart(48).padEnd(68) + '#');
491
+ console.log('#' + ' - Try hypermind-fraud-underwriter.ts'.padStart(45).padEnd(68) + '#');
492
+ console.log('#' + ' '.repeat(68) + '#');
493
+ console.log('#'.repeat(70));
494
+ console.log();
495
+
496
+ } catch (error) {
497
+ console.error('Error:', error);
498
+ process.exit(1);
499
+ }
500
+ }
501
+
502
+ main();