rust-kgdb 0.6.55 → 0.6.56

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 (2) hide show
  1. package/README.md +212 -1865
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -2,2006 +2,353 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/rust-kgdb.svg)](https://www.npmjs.com/package/rust-kgdb)
4
4
  [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
5
- [![W3C](https://img.shields.io/badge/W3C-SPARQL%201.1%20%7C%20RDF%201.2-blue)](https://www.w3.org/TR/sparql11-query/)
6
-
7
- ## What Is This?
8
-
9
- ### Have You Ever Wondered Why AI Agents Keep Lying?
10
-
11
- Here's the uncomfortable truth: **LLMs don't know your data**. They've read Wikipedia, Stack Overflow, and half the internet - but they've never seen your customer records, your claims database, or your internal knowledge graph.
12
-
13
- So when you ask "find suspicious providers," they do what humans do when they don't know the answer: **they make something up that sounds plausible**.
14
-
15
- The industry's response? "Add more guardrails!" "Use RAG!" "Fine-tune on your data!"
16
-
17
- We asked a different question: **What if the AI couldn't lie even if it wanted to?**
18
-
19
- Not through prompting. Not through fine-tuning. Through **architecture**.
20
-
21
- ### The Insight That Changes Everything
22
-
23
- What if instead of asking an LLM to generate answers, we asked it to generate **database queries**?
24
-
25
- The LLM doesn't need to know your data. It just needs to know:
26
- 1. What questions can be asked (your schema)
27
- 2. How to ask them (SPARQL/Datalog syntax)
28
-
29
- Then a **real database** - with your actual data - executes the query and returns facts. Not hallucinations. Facts.
30
-
31
- ```
32
- User: "Find suspicious providers"
33
-
34
- LLM generates: SELECT ?provider WHERE { ?provider :riskScore ?s . FILTER(?s > 0.8) }
35
-
36
- Database executes: Scans 47M triples in 449ns per lookup
37
-
38
- Returns: [PROV001, PROV847, PROV2201] ← These actually exist in YOUR data
39
- ```
40
-
41
- **The AI suggests what to look for. The database finds exactly that. No hallucination possible.**
42
-
43
- ### But Wait - Where's the Database?
44
-
45
- Here's where it gets interesting. Traditional approach:
46
- - Install Virtuoso/RDFox/Neo4j server
47
- - Configure connections
48
- - Pay for licenses
49
- - Hire a DBA
50
-
51
- Our approach: **The database is embedded in your app.**
52
-
53
- ```bash
54
- npm install rust-kgdb # That's it. You now have a full SPARQL database.
55
- ```
56
-
57
- 47.2MB native addon. Zero configuration. 449ns lookups. Embedded like SQLite, powerful like RDFox.
58
5
 
59
6
  ---
60
7
 
61
- **rust-kgdb** is two layers in one package:
8
+ ## The Trillion-Dollar Mistake
62
9
 
63
- ```
64
- ┌─────────────────────────────────────────────────────────────────────────────┐
65
- │ YOUR APPLICATION │
66
- └─────────────────────────────────┬───────────────────────────────────────────┘
67
-
68
- ┌─────────────────────────────────▼───────────────────────────────────────────┐
69
- │ HYPERMIND AGENT FRAMEWORK (JavaScript) │
70
- │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
71
- │ │ LLMPlanner │ │ MemoryMgr │ │ WASM │ │ ProofDAG │ │
72
- │ │ (Schema- │ │ (Working/ │ │ Sandbox │ │ (Audit │ │
73
- │ │ Aware) │ │ Episodic) │ │ (Secure) │ │ Trail) │ │
74
- │ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
75
- └─────────────────────────────────┬───────────────────────────────────────────┘
76
- │ NAPI-RS (zero-copy)
77
- ┌─────────────────────────────────▼───────────────────────────────────────────┐
78
- │ RUST CORE (Native Performance) │
79
- │ ┌──────────────────────────────────────────────────────────────────────┐ │
80
- │ │ QUERY ENGINE │ │
81
- │ │ • SPARQL 1.1 (449ns lookups) • WCOJ Joins (worst-case optimal) │ │
82
- │ │ • Datalog (semi-naive eval) • Sparse Matrix (CSR/CSC reasoning) │ │
83
- │ └──────────────────────────────────────────────────────────────────────┘ │
84
- │ ┌──────────────────────────────────────────────────────────────────────┐ │
85
- │ │ GRAPH ANALYTICS │ │
86
- │ │ • GraphFrames (PageRank, Components, Triangles, Motifs) │ │
87
- │ │ • Pregel BSP (Bulk Synchronous Parallel) │ │
88
- │ │ • Shortest Paths, Label Propagation │ │
89
- │ └──────────────────────────────────────────────────────────────────────┘ │
90
- │ ┌──────────────────────────────────────────────────────────────────────┐ │
91
- │ │ VECTOR & RETRIEVAL │ │
92
- │ │ • HNSW Index (O(log N) ANN) • ARCADE 1-Hop Cache (O(1) neighbors) │ │
93
- │ │ • Multi-provider Embeddings • RRF Reranking │ │
94
- │ └──────────────────────────────────────────────────────────────────────┘ │
95
- │ ┌──────────────────────────────────────────────────────────────────────┐ │
96
- │ │ STORAGE │ │
97
- │ │ • InMemory (dev) • RocksDB (prod) • LMDB (read-heavy) │ │
98
- │ │ • SPOC/POCS/OCSP/CSPO Indexes • 24 bytes/triple │ │
99
- │ └──────────────────────────────────────────────────────────────────────┘ │
100
- └─────────────────────────────────────────────────────────────────────────────┘
101
- ```
10
+ A lawyer asks AI: *"Has this contract clause ever been challenged in court?"*
102
11
 
103
- ### Layer 1: Rust Core (Native Performance)
104
-
105
- | Component | What It Does | Performance |
106
- |-----------|--------------|-------------|
107
- | **SPARQL 1.1** | W3C-compliant query engine, 64 builtin functions | 449ns lookups |
108
- | **RDF 1.2** | RDF-Star (quoted triples), TriG, N-Quads | W3C compliant |
109
- | **SHACL** | W3C Shapes Constraint Language validation | Constraint engine |
110
- | **PROV** | W3C Provenance ontology support | Audit trail |
111
- | **WCOJ Joins** | Worst-case optimal joins for multi-way patterns | O(N^(ρ/2)) |
112
- | **Datalog** | Semi-naive evaluation with recursion | Incremental |
113
- | **Sparse Matrix** | CSR/CSC-based reasoning for OWL 2 RL | Memory-efficient |
114
- | **GraphFrames** | PageRank, components, triangles, motifs | Parallel |
115
- | **Pregel** | Bulk Synchronous Parallel graph processing | Superstep-based |
116
- | **HNSW** | Hierarchical Navigable Small World index | O(log N) |
117
- | **ARCADE Cache** | 1-hop neighbor pre-caching | O(1) context |
118
- | **Storage** | InMemory, RocksDB, LMDB backends | 24 bytes/triple |
119
-
120
- **Scalability Numbers (Verified Benchmark)**:
121
-
122
- | Operation | 1 Worker | 16 Workers | Scaling |
123
- |-----------|----------|------------|---------|
124
- | Concurrent Writes | 66K ops/sec | 132K ops/sec | 2.0x |
125
- | GraphFrame Analytics | 6.0K ops/sec | 6.5K ops/sec | Thread-safe |
126
- | Memory per Triple | 24 bytes | 24 bytes | Constant |
127
-
128
- Reproduce: `node concurrency-benchmark.js`
129
-
130
- ### Layer 2: HyperMind Agent Framework (JavaScript)
131
-
132
- | Component | What It Does |
133
- |-----------|--------------|
134
- | **LLMPlanner** | Schema-aware query generation (auto-extracts from data) |
135
- | **MemoryManager** | Working memory + episodic memory + long-term KG |
136
- | **WASM Sandbox** | Secure execution with capability-based permissions |
137
- | **ProofDAG** | Audit trail with cryptographic hash for reproducibility |
138
- | **TypedTools** | Input/output validation prevents hallucination |
139
-
140
- ### WASM Sandbox Architecture
12
+ AI responds: *"Yes, in Smith v. Johnson (2019), the court ruled..."*
141
13
 
142
- ```
143
- ┌─────────────────────────────────────────────────────────────────────────────┐
144
- │ WASM SANDBOX (Secure Agent Execution) │
145
- ├─────────────────────────────────────────────────────────────────────────────┤
146
- │ │
147
- │ ┌─────────────────────┐ ┌─────────────────────┐ ┌────────────────┐ │
148
- │ │ CAPABILITIES │ │ FUEL METERING │ │ AUDIT LOG │ │
149
- │ │ • ReadKG │ │ • CPU budget limit │ │ • Every action │ │
150
- │ │ • ExecuteTool │ │ • Prevents infinite │ │ • Timestamps │ │
151
- │ │ • WriteKG (opt) │ │ loops │ │ • Arguments │ │
152
- │ └─────────────────────┘ └─────────────────────┘ └────────────────┘ │
153
- │ │
154
- │ Agent Code → WASM Runtime → Capability Check → Tool Execution → Audit │
155
- │ │
156
- └─────────────────────────────────────────────────────────────────────────────┘
157
- ```
14
+ The lawyer cites it. The judge looks confused. **That case doesn't exist.** The AI invented it.
158
15
 
159
- **Think of it as**: A knowledge graph database (Rust, native performance) with an AI agent runtime (JavaScript, WASM-sandboxed) on top. The database provides ground truth. The runtime makes it accessible via natural language with full security and audit trails.
16
+ This isn't rare. It happens every day:
160
17
 
161
- ### Game Changer: Embedded Database (No Installation)
18
+ **In Healthcare:**
19
+ > Doctor: "What drugs interact with this patient's current medications?"
20
+ > AI: "Avoid combining with Nexapril due to cardiac risks."
21
+ > *Nexapril isn't a real drug.*
162
22
 
163
- ```
164
- ┌─────────────────────────────────────────────────────────────────────────────┐
165
- │ TRADITIONAL APPROACH │
166
- │ ─────────────────────── │
167
- │ Your App → HTTP/gRPC → Database Server → Disk │
168
- │ │
169
- │ • Install database server (RDFox, Virtuoso, Neo4j) │
170
- │ • Configure connections, ports, authentication │
171
- │ • Network latency on every query │
172
- │ • DevOps overhead for maintenance │
173
- └─────────────────────────────────────────────────────────────────────────────┘
174
-
175
- ┌─────────────────────────────────────────────────────────────────────────────┐
176
- │ rust-kgdb: EMBEDDED │
177
- │ ────────────────────── │
178
- │ Your App ← contains → rust-kgdb (native addon) │
179
- │ │
180
- │ • npm install rust-kgdb - that's it │
181
- │ • No server, no Docker, no configuration │
182
- │ • Zero network latency (same process) │
183
- │ • Deploy as single binary │
184
- └─────────────────────────────────────────────────────────────────────────────┘
185
- ```
23
+ **In Insurance:**
24
+ > Claims Adjuster: "Has this provider shown suspicious billing patterns?"
25
+ > AI: "Provider #4521 has a history of duplicate billing..."
26
+ > *Provider #4521 has a perfect record.*
186
27
 
187
- **Why This Matters**:
188
- - **SQLite for RDF**: Like SQLite replaced MySQL for embedded use cases
189
- - **449ns lookups**: No network roundtrip - direct memory access
190
- - **Ship as one file**: Your app + database = single deployable
28
+ **In Fraud Detection:**
29
+ > Analyst: "Find transactions that look like money laundering."
30
+ > AI: "Account ending 7842 shows classic layering behavior..."
31
+ > *That account belongs to a charity. Now you've falsely accused them.*
191
32
 
192
- **Scale When You Need To**: Start embedded, scale to cluster when required:
193
- ```
194
- Embedded (single node) → Clustered (distributed)
195
- npm install K8s deployment
196
- No config HDRF partitioning
197
- Millions of triples Billions of triples
198
- ```
33
+ **The AI doesn't know your data. It guesses. And it sounds confident while lying.**
199
34
 
200
35
  ---
201
36
 
202
- ## Mathematical Foundations: Why This Actually Works
203
-
204
- ### The Problem with LLM Tool Calling
205
-
206
- Here's a dirty secret about AI agents: **most tool calls are prayers**.
207
-
208
- The LLM generates a function call, hopes the types match, and if it fails? Retry and pray harder. This is why production AI systems feel brittle.
209
-
210
- We took a different approach: **make incorrect tool calls impossible to express**.
211
-
212
- ### Category Theory: Not Academic Masturbation
213
-
214
- When you hear "category theory," you probably think of mathematicians drawing commutative diagrams that no one understands. Here's why it actually matters for AI agents:
215
-
216
- ```
217
- Every tool is a morphism: InputType → OutputType
218
-
219
- kg.sparql.query : Query → BindingSet
220
- kg.motif.find : Pattern → Matches
221
- kg.datalog.run : Rules → InferredFacts
222
- ```
223
-
224
- **The key insight**: If the LLM can only compose morphisms where types align, it *cannot* hallucinate invalid tool chains. It's not about "being careful" - it's about making mistakes unrepresentable.
225
-
226
- ```javascript
227
- // This composition type-checks: Query → BindingSet → Aggregation
228
- planner.compose(sparqlQuery, aggregator) // ✅ Valid
229
-
230
- // This doesn't even compile conceptually
231
- planner.compose(sparqlQuery, imageGenerator) // ❌ Type error
232
- ```
233
-
234
- ### Curry-Howard: Proofs You Can Execute
235
-
236
- The **Curry-Howard correspondence** says something profound: **proofs and programs are the same thing**.
237
-
238
- In our system:
239
- - A valid reasoning trace IS a mathematical proof that the answer is correct
240
- - The type signature of a tool IS a proposition about what it transforms
241
- - Composing tools IS constructing a proof by implication
242
-
243
- ```javascript
244
- result.proofDAG = {
245
- // This isn't just logging - it's a PROOF OBJECT
246
- steps: [
247
- { tool: 'kg.sparql.query', proves: '∃ provider P001 with 47 claims' },
248
- { tool: 'kg.datalog.rule', proves: 'P001 ∈ highRisk (by rule R3)' }
249
- ],
250
- hash: 'sha256:8f3a...', // Same proof = same hash, always
251
- valid: true // Type-checked, therefore valid
252
- }
253
- ```
254
-
255
- **Why this matters for compliance**: When a regulator asks "why did you flag this provider?", you don't show them chat logs. You show them a mathematical proof.
256
-
257
- ### WCOJ: When O(N²) is Unacceptable
258
-
259
- Finding triangles in a graph (A→B→C→A) seems simple. The naive approach:
260
- 1. For each edge A→B
261
- 2. For each edge B→C
262
- 3. Check if C→A exists
37
+ ## Why "Guardrails" Don't Fix This
263
38
 
264
- That's O(N²) - fine for toy graphs, death for production.
39
+ The industry response? Add guardrails. Use RAG. Fine-tune models.
265
40
 
266
- **Worst-Case Optimal Joins** (LeapFrog TrieJoin) do something clever:
267
- - Organize edges in tries by (subject, predicate, object)
268
- - Traverse all three tries simultaneously
269
- - Skip entire branches that can't possibly match
41
+ But here's what they don't tell you:
270
42
 
271
- ```
272
- Traditional: O(N²) for triangle query
273
- WCOJ: O(N^(ρ/2)) where ρ = fractional edge cover number
274
-
275
- For triangles: ρ = 1.5, so O(N^0.75) vs O(N²)
276
- At 1M edges: 31K operations vs 1T operations
277
- ```
43
+ **RAG (Retrieval-Augmented Generation)** finds *similar* documents. Similar isn't the same as *correct*. If your policy database has 10,000 documents about cardiac drugs, RAG might retrieve the wrong 5.
278
44
 
279
- ### Sparse Matrix: Why Your RAM Doesn't Explode
45
+ **Fine-tuning** teaches the model patterns from your data. But patterns aren't facts. It still can't look up "does Patient X have a penicillin allergy" because it doesn't have a database - it has patterns.
280
46
 
281
- A knowledge graph with 1M entities has a 1M × 1M adjacency matrix. That's 1 trillion cells. At 8 bytes each: 8 terabytes. For one matrix.
47
+ **Guardrails** catch obvious errors. But "Provider #4521 shows billing anomalies" sounds completely plausible. No guardrail catches it.
282
48
 
283
- **CSR (Compressed Sparse Row)** stores only non-zero entries:
284
- - Real graphs are ~99.99% sparse
285
- - 1M entities with 10M edges = 10M entries, not 1T
286
- - Transitive closure becomes matrix multiplication: A* = I + A + A² + ...
287
-
288
- ```
289
- rdfs:subClassOf closure in OWL:
290
- Dense: Impossible (terabytes of memory)
291
- CSR: Seconds (megabytes of memory)
292
- ```
293
-
294
- ### Semi-Naive Datalog: Don't Repeat Yourself
295
-
296
- Recursive rules need fixpoint iteration. The naive way recomputes everything:
297
-
298
- ```
299
- Iteration 1: Compute ALL ancestor relationships
300
- Iteration 2: Compute ALL ancestor relationships again ← wasteful
301
- Iteration 3: Compute ALL ancestor relationships again ← really wasteful
302
- ```
303
-
304
- **Semi-naive evaluation**: Only derive facts using NEW facts from the previous iteration.
305
-
306
- ```
307
- Iteration 1: Direct parents (new: 1000 facts)
308
- Iteration 2: Use only those 1000 new facts → grandparents (new: 800)
309
- Iteration 3: Use only those 800 new facts → great-grandparents (new: 400)
310
- ...converges in O(depth) iterations, not O(facts)
311
- ```
312
-
313
- ### HNSW: O(log N) Similarity in a World of Vectors
314
-
315
- Finding the nearest neighbor in a million vectors should take a million comparisons. It doesn't have to.
316
-
317
- **HNSW** builds a navigable graph where:
318
- - Top layers have few nodes with long-range connections
319
- - Bottom layers have all nodes with local connections
320
- - Search: Start at top, greedily descend, refine at bottom
321
-
322
- ```
323
- Layer 2: ●───────────────────● (sparse, long jumps)
324
- │ │
325
- Layer 1: ●────●────●────●────● (medium density)
326
- │ │ │ │ │
327
- Layer 0: ●─●─●─●─●─●─●─●─●─●─● (all nodes, local connections)
328
-
329
- Search path: Start top-left, jump to approximate region, refine locally
330
- Result: O(log N) comparisons, ~95% recall
331
- ```
332
-
333
- **Why this matters**: When your agent needs "similar past queries," it doesn't scan 10,000 embeddings. It finds the top 10 in 16 milliseconds.
49
+ The fundamental problem: **You're asking a language model to be a database. It's not.**
334
50
 
335
51
  ---
336
52
 
337
- ## Core Concepts: What We Bring and Why
53
+ ## The Insight That Changes Everything
338
54
 
339
- ### 1. Schema-Aware Query Generation
340
- **Problem**: LLMs generate SPARQL with made-up predicates (`?person :fakeProperty ?value`).
341
- **Solution**: We auto-extract your schema and inject it into prompts. The LLM can ONLY reference predicates that actually exist in your data.
55
+ What if we stopped asking AI for **answers** and started asking it for **questions**?
342
56
 
343
- ### 2. Built-in Database (Not BYODB)
344
- **Problem**: LangChain/DSPy generate queries, but you need to find a database to run them.
345
- **Solution**: rust-kgdb IS the database. Generate query → Execute query → Return results. All in one package.
57
+ Think about how a skilled legal researcher works:
346
58
 
347
- ### 3. Audit Trail (Provenance)
348
- **Problem**: LLM says "Provider P001 is suspicious" - where did that come from?
349
- **Solution**: Every answer includes a reasoning trace showing which SPARQL queries ran, which rules matched, and what data was found.
59
+ 1. **Lawyer asks:** "Has this clause been challenged?"
60
+ 2. **Researcher understands** the legal question
61
+ 3. **Researcher searches** actual case law databases
62
+ 4. **Returns cases** that actually exist, with citations
350
63
 
351
- ### 4. Deterministic Execution
352
- **Problem**: Ask the same question twice, get different answers.
353
- **Solution**: Same input → Same query → Same database → Same result → Same hash. Reproducible for compliance.
64
+ The AI should be the researcher - understanding intent and writing queries. The database should find facts.
354
65
 
355
- ### 5. ARCADE 1-Hop Cache
356
- **Problem**: Embedding lookups are slow when you need neighborhood context.
357
- **Solution**: Pre-cache 1-hop neighbors. When you find "Provider", instantly know its outgoing predicates (hasRiskScore, hasClaim) without another query.
358
-
359
- ---
360
-
361
- ## AI Answers You Can Trust
362
-
363
- **The Problem**: LLMs hallucinate. They make up facts, invent data, and confidently state falsehoods. In regulated industries (finance, healthcare, legal), this is not just annoying—it's a liability.
364
-
365
- **The Solution**: HyperMind grounds every AI answer in YOUR actual data. Every response includes a complete audit trail. Same question = Same answer = Same proof.
366
-
367
- ---
368
-
369
- ## Results (Verified December 2025)
370
-
371
- ### Benchmark Methodology
372
-
373
- **Dataset**: [LUBM (Lehigh University Benchmark)](http://swat.cse.lehigh.edu/projects/lubm/) - the industry-standard benchmark for RDF/SPARQL systems since 2005. Used by RDFox, Virtuoso, Jena, and all major triple stores.
374
-
375
- **Setup**:
376
- - 3,272 triples, 30 OWL classes, 23 properties
377
- - 7 query types: attribute (A1-A3), statistical (S1-S2), multi-hop (M1), existence (E1)
378
- - Model: GPT-4o with real API calls (no mocking)
379
- - Reproducible: `python3 benchmark-frameworks.py`
380
-
381
- **Evaluation Criteria**:
382
- - Query must parse (no markdown, no explanation text)
383
- - Query must use correct ontology terms (e.g., `ub:Professor` not `ub:Faculty`)
384
- - Query must return expected result count
385
-
386
- ### Honest Framework Comparison
387
-
388
- **Important**: HyperMind and LangChain/DSPy are **different product categories**.
389
-
390
- | Category | HyperMind | LangChain/DSPy |
391
- |----------|-----------|----------------|
392
- | **What It Is** | GraphDB + Agent Framework | LLM Orchestration Library |
393
- | **Core Function** | Execute queries on data | Chain LLM prompts |
394
- | **Data Storage** | Built-in QuadStore | None (BYODB) |
395
- | **Query Execution** | Native SPARQL/Datalog | External DB needed |
396
- | **Agent Memory** | Built-in (Working + Episodic + KG-backed) | External vector DB needed |
397
- | **Deep Flashback** | 94% Recall@10 at 10K query depth (16.7ms) | Limited by external provider |
398
-
399
- **Why Agent Memory Matters**: We can retrieve relevant past queries from 10,000+ history entries with 94% accuracy in 16.7ms. This enables "flashback" to any past interaction - LangChain/DSPy require external vector DBs for this capability.
400
-
401
- **Built-in Capabilities (No External Dependencies)**:
402
-
403
- | Capability | HyperMind | LangChain/DSPy |
404
- |------------|-----------|----------------|
405
- | **Recursive Reasoning** | Datalog semi-naive evaluation (native) | Manual implementation needed |
406
- | **Graph Propagation** | Pregel BSP (PageRank, shortest paths) | External library (NetworkX) |
407
- | **Multi-way Joins** | WCOJ algorithm O(N^(ρ/2)) | No native support |
408
- | **Pattern Matching** | Motif DSL `(a)-[]->(b); (b)-[]->(c)` | Manual graph traversal |
409
- | **OWL 2 RL Reasoning** | Sparse matrix CSR/CSC (native) | External reasoner needed |
410
- | **Vector Similarity** | HNSW + ARCADE 1-hop cache | External vector DB (Pinecone, etc.) |
411
- | **Transitive Closure** | `ancestor(?X,?Z) :- parent(?X,?Y), ancestor(?Y,?Z)` | Loop implementation |
412
- | **RDF-Star** | Native quoted triples (RDF 1.2) | Not supported |
413
- | **Data Validation** | SHACL constraints (W3C) | External validator needed |
414
- | **Provenance Tracking** | W3C PROV ontology (native) | Manual implementation |
415
-
416
- **Database Performance (vs Industry Leaders)**:
417
-
418
- | Metric | HyperMind | Comparison |
419
- |--------|-----------|------------|
420
- | **Triple Lookup** | 449 ns | 35x faster than RDFox |
421
- | **Memory/Triple** | 24 bytes | 25% less than RDFox |
422
- | **Concurrent Writes** | 132K ops/sec | Thread-safe at scale |
423
-
424
- **What Each Is Good For**:
425
-
426
- - **HyperMind**: When you need a knowledge graph database WITH agent capabilities. Deterministic execution, audit trails, graph analytics.
427
- - **LangChain**: When you need to orchestrate multiple LLM calls with prompts. Flexible, extensive integrations.
428
- - **DSPy**: When you need to optimize prompts programmatically. Research-focused.
429
-
430
- ### Our Unique Approach: ARCADE 1-Hop Cache
431
-
432
- ```
433
- ┌─────────────────────────────────────────────────────────────────────────────┐
434
- │ TEXT → INTENT → EMBEDDING → NEIGHBORS → ACCURATE SPARQL │
435
- │ (The ARCADE Pipeline) │
436
- ├─────────────────────────────────────────────────────────────────────────────┤
437
- │ │
438
- │ 1. TEXT INPUT │
439
- │ "Find high-risk providers" │
440
- │ ↓ │
441
- │ 2. INTENT CLASSIFICATION (Deterministic keyword matching) │
442
- │ Intent: QUERY_ENTITIES │
443
- │ Domain: insurance, Entity: provider, Filter: high-risk │
444
- │ ↓ │
445
- │ 3. EMBEDDING LOOKUP (HNSW index, 449ns) │
446
- │ Query: "provider" → Vector [0.23, 0.87, ...] │
447
- │ Similar entities: [:Provider, :Vendor, :Supplier] │
448
- │ ↓ │
449
- │ 4. 1-HOP NEIGHBOR RETRIEVAL (ARCADE Cache) │
450
- │ :Provider → outgoing: [:hasRiskScore, :hasClaim, :worksFor] │
451
- │ :Provider → incoming: [:submittedBy, :reviewedBy] │
452
- │ Cache hit: O(1) lookup, no SPARQL needed │
453
- │ ↓ │
454
- │ 5. SCHEMA-AWARE SPARQL GENERATION │
455
- │ Available predicates: {hasRiskScore, hasClaim, worksFor} │
456
- │ Filter mapping: "high-risk" → ?score > 0.7 │
457
- │ Generated: SELECT ?p WHERE { ?p :hasRiskScore ?s . FILTER(?s > 0.7) } │
458
- │ │
459
- ├─────────────────────────────────────────────────────────────────────────────┤
460
- │ WHY THIS WORKS: │
461
- │ • Step 2: NO LLM needed - deterministic pattern matching │
462
- │ • Step 3: Embedding similarity finds related concepts │
463
- │ • Step 4: ARCADE cache provides schema context in O(1) │
464
- │ • Step 5: Schema injection ensures only valid predicates used │
465
- │ │
466
- │ ARCADE = Adaptive Retrieval Cache for Approximate Dense Embeddings │
467
- │ Paper: https://arxiv.org/abs/2104.08663 │
468
- └─────────────────────────────────────────────────────────────────────────────┘
66
+ **Before (Dangerous):**
469
67
  ```
470
-
471
- **Embedding Trigger Setup** (automatic on triple insert):
472
- ```javascript
473
- const { EmbeddingService, GraphDB } = require('rust-kgdb')
474
-
475
- const db = new GraphDB('http://example.org/')
476
- const embeddings = new EmbeddingService()
477
-
478
- // On every triple insert, embedding cache is updated
479
- db.loadTtl(':Provider123 :hasRiskScore "0.87" .', null)
480
- // Triggers: embeddings.onTripleInsert('Provider123', 'hasRiskScore', '0.87', null)
481
- // 1-hop cache updated: Provider123 → outgoing: [hasRiskScore]
68
+ Lawyer: "Has this clause been challenged?"
69
+ AI: "Yes, in Smith v. Johnson (2019)..." ← FABRICATED
482
70
  ```
483
71
 
484
- ### End-to-End Capability Benchmark
485
-
72
+ **After (Safe):**
486
73
  ```
487
- ┌─────────────────────────────────────────────────────────────────────────────┐
488
- │ CAPABILITY COMPARISON: What Can Actually Execute on Data │
489
- ├─────────────────────────────────────────────────────────────────────────────┤
490
- │ │
491
- │ Capability │ HyperMind │ LangChain/DSPy │
492
- │ ───────────────────────────────────────────────────────── │
493
- │ Generate Motif Pattern │ ✅ │ ✅ │
494
- │ Generate Datalog Rules │ ✅ │ ✅ │
495
- │ Execute Motif on Data │ ✅ │ ❌ (no DB) │
496
- │ Execute Datalog Rules │ ✅ │ ❌ (no DB) │
497
- │ Execute SPARQL Queries │ ✅ │ ❌ (no DB) │
498
- │ GraphFrame Analytics │ ✅ │ ❌ (no DB) │
499
- │ Deterministic Results │ ✅ │ ❌ │
500
- │ Audit Trail/Provenance │ ✅ │ ❌ │
501
- │ ───────────────────────────────────────────────────────── │
502
- │ TOTAL │ 8/8 │ 2/8 │
503
- │ │
504
- │ NOTE: LangChain/DSPy CAN execute on data if you integrate a database. │
505
- │ HyperMind has the database BUILT-IN. │
506
- │ │
507
- │ Reproduce: node benchmark-e2e-execution.js │
508
- └─────────────────────────────────────────────────────────────────────────────┘
74
+ Lawyer: "Has this clause been challenged?"
75
+ AI: Generates query Searches case database
76
+ Database: Returns real cases that actually exist
77
+ Result: "Martinez v. Apex Corp (2021), Chen v. StateBank (2018)" ← VERIFIABLE
509
78
  ```
510
79
 
511
- ### Memory Retrieval Depth Benchmark
512
-
513
- Based on academic benchmarks: MemQ (arXiv 2503.05193), mKGQAgent (Text2SPARQL 2025), MTEB.
514
-
515
- ```
516
- ┌─────────────────────────────────────────────────────────────────────────────┐
517
- │ BENCHMARK: Memory Retrieval at Depth (50 queries per depth) │
518
- │ METHODOLOGY: LUBM schema-driven queries, HNSW index, random seed 42 │
519
- ├─────────────────────────────────────────────────────────────────────────────┤
520
- │ │
521
- │ DEPTH │ P50 LATENCY │ P95 LATENCY │ Recall@5 │ Recall@10 │ MRR │
522
- │ ──────────────────────────────────────────────────────────────────────────│
523
- │ 10 │ 0.06 ms │ 0.26 ms │ 78% │ 100% │ 0.68 │
524
- │ 100 │ 0.50 ms │ 0.75 ms │ 88% │ 98% │ 0.42 │
525
- │ 1,000 │ 1.59 ms │ 5.03 ms │ 80% │ 94% │ 0.50 │
526
- │ 10,000 │ 16.71 ms │ 17.37 ms │ 76% │ 94% │ 0.54 │
527
- │ ──────────────────────────────────────────────────────────────────────────│
528
- │ │
529
- │ KEY INSIGHT: Even at 10,000 stored queries, Recall@10 stays at 94% │
530
- │ Sub-17ms retrieval from 10K query pool = practical for production use │
531
- │ │
532
- │ Reproduce: node memory-retrieval-benchmark.js │
533
- └─────────────────────────────────────────────────────────────────────────────┘
534
- ```
535
-
536
- ### Where We Actually Outperform (Database Performance)
537
-
538
- ```
539
- ┌─────────────────────────────────────────────────────────────────────────────┐
540
- │ BENCHMARK: Triple Store Performance (vs Industry Leaders) │
541
- │ METHODOLOGY: Criterion.rs statistical benchmarking, LUBM dataset │
542
- ├─────────────────────────────────────────────────────────────────────────────┤
543
- │ │
544
- │ METRIC rust-kgdb RDFox Jena Neo4j │
545
- │ ───────────────────────────────────────────────────────────── │
546
- │ Lookup Speed 449 ns ~5 µs ~150 µs ~5 µs │
547
- │ Memory/Triple 24 bytes 36-89 bytes 50-60 bytes 70+ bytes │
548
- │ Bulk Insert 146K/sec ~200K/sec ~50K/sec ~100K/sec │
549
- │ Concurrent Writes 132K/sec N/A N/A N/A │
550
- │ ───────────────────────────────────────────────────────────── │
551
- │ │
552
- │ ADVANTAGE: 35x faster lookups than RDFox, 25% less memory │
553
- │ THIS IS WHERE WE GENUINELY WIN - raw database performance. │
554
- │ │
555
- └─────────────────────────────────────────────────────────────────────────────┘
556
- ```
557
-
558
- ### SPARQL Generation (Honest Assessment)
559
-
560
- ```
561
- ┌─────────────────────────────────────────────────────────────────────────────┐
562
- │ BENCHMARK: LUBM SPARQL Generation Accuracy │
563
- │ DATASET: 3,272 triples │ MODEL: GPT-4o │ Real API calls │
564
- ├─────────────────────────────────────────────────────────────────────────────┤
565
- │ │
566
- │ FRAMEWORK NO SCHEMA WITH SCHEMA │
567
- │ ───────────────────────────────────────────────────────────── │
568
- │ Vanilla OpenAI 0.0% 71.4% │
569
- │ LangChain 0.0% 71.4% │
570
- │ DSPy 14.3% 71.4% │
571
- │ ───────────────────────────────────────────────────────────── │
572
- │ │
573
- │ HONEST TRUTH: Schema injection improves ALL frameworks equally. │
574
- │ Any framework + schema context achieves ~71% accuracy. │
575
- │ │
576
- │ NOTE: DSPy gets 14.3% WITHOUT schema (vs 0% for others) due to │
577
- │ its structured output format. With schema, all converge to 71.4%. │
578
- │ │
579
- │ OUR REAL VALUE: We include the database. Others don't. │
580
- │ - LangChain generates SPARQL → you need to find a database │
581
- │ - HyperMind generates SPARQL → executes on built-in 449ns database │
582
- │ │
583
- │ Reproduce: python3 benchmark-frameworks.py │
584
- └─────────────────────────────────────────────────────────────────────────────┘
585
- ```
586
-
587
- ---
588
-
589
- ## The Difference: Manual vs Integrated
590
-
591
- ### Manual Approach (Works, But Tedious)
592
-
593
- ```javascript
594
- // STEP 1: Manually write your schema (takes hours for large ontologies)
595
- const LUBM_SCHEMA = `
596
- PREFIX ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#>
597
- Classes: University, Department, Professor, Student, Course, Publication
598
- Properties: teacherOf(Faculty→Course), worksFor(Faculty→Department)
599
- `;
600
-
601
- // STEP 2: Pass schema to LLM
602
- const answer = await openai.chat.completions.create({
603
- model: 'gpt-4o',
604
- messages: [
605
- { role: 'system', content: `${LUBM_SCHEMA}\nOutput raw SPARQL only.` },
606
- { role: 'user', content: 'Find suspicious providers' }
607
- ]
608
- });
609
-
610
- // STEP 3: Parse out the SPARQL (handle markdown, explanations, etc.)
611
- const sparql = extractSPARQL(answer.choices[0].message.content);
612
-
613
- // STEP 4: Find a SPARQL database (Jena? RDFox? Virtuoso?)
614
- // STEP 5: Connect to database
615
- // STEP 6: Execute query
616
- // STEP 7: Parse results
617
- // STEP 8: No audit trail - you'd have to build that yourself
618
-
619
- // RESULT: ~71% accuracy (same as HyperMind with schema)
620
- // BUT: 5-8 manual integration steps
621
- ```
622
-
623
- ### HyperMind Approach (Integrated)
624
-
625
- ```javascript
626
- // ONE-TIME SETUP: Load your data
627
- const { HyperMindAgent, GraphDB } = require('rust-kgdb');
628
-
629
- const db = new GraphDB('http://insurance.org/');
630
- db.loadTtl(yourActualData, null); // Schema auto-extracted from data
631
-
632
- const agent = new HyperMindAgent({ kg: db, model: 'gpt-4o' });
633
- const result = await agent.call('Find suspicious providers');
634
-
635
- console.log(result.answer);
636
- // "Provider PROV001 has risk score 0.87 with 47 claims over $50,000"
637
-
638
- // WHAT YOU GET (ALL AUTOMATIC):
639
- // ✅ Schema auto-extracted (no manual prompt engineering)
640
- // ✅ Query executed on built-in database (no external DB needed)
641
- // ✅ Full audit trail included
642
- // ✅ Reproducible hash for compliance
643
-
644
- console.log(result.reasoningTrace);
645
- // [
646
- // { tool: 'kg.sparql.query', input: 'SELECT ?p WHERE...', output: '[PROV001]' },
647
- // { tool: 'kg.datalog.apply', input: 'highRisk(?p) :- ...', output: 'MATCHED' }
648
- // ]
649
-
650
- console.log(result.hash);
651
- // "sha256:8f3a2b1c..." - Same question = Same answer = Same hash
652
- ```
653
-
654
- **Honest comparison**: Both approaches achieve ~71% accuracy on LUBM benchmark. The difference is integration effort:
655
- - **Manual**: Write schema, integrate database, build audit trail yourself
656
- - **HyperMind**: Database + schema extraction + audit trail built-in
657
-
658
- ---
659
-
660
- ## Our Approach vs Traditional (Why This Works)
661
-
662
- ```
663
- ┌───────────────────────────────────────────────────────────────────────────┐
664
- │ APPROACH COMPARISON │
665
- ├───────────────────────────────────────────────────────────────────────────┤
666
- │ │
667
- │ TRADITIONAL: CODE GENERATION OUR APPROACH: NO CODE GENERATION │
668
- │ ──────────────────────────── ──────────────────────────────── │
669
- │ │
670
- │ User → LLM → Generate Code User → Domain-Enriched Proxy │
671
- │ │
672
- │ ❌ SLOW: LLM generates text ✅ FAST: Pre-built typed tools │
673
- │ ❌ ERROR-PRONE: Syntax errors ✅ RELIABLE: Schema-validated │
674
- │ ❌ UNPREDICTABLE: Different ✅ DETERMINISTIC: Same every time │
675
- │ │
676
- ├───────────────────────────────────────────────────────────────────────────┤
677
- │ TRADITIONAL FLOW OUR FLOW │
678
- │ ──────────────── ──────── │
679
- │ │
680
- │ 1. User asks question 1. User asks question │
681
- │ 2. LLM generates code (SLOW) 2. Intent matched (INSTANT) │
682
- │ 3. Code has syntax error? 3. Schema object consulted │
683
- │ 4. Retry with LLM (SLOW) 4. Typed tool selected │
684
- │ 5. Code runs, wrong result? 5. Query built from schema │
685
- │ 6. Retry with LLM (SLOW) 6. Validated & executed │
686
- │ 7. Maybe works after 3-5 tries 7. Works first time │
687
- │ │
688
- ├───────────────────────────────────────────────────────────────────────────┤
689
- │ OUR DOMAIN-ENRICHED PROXY LAYER │
690
- │ ─────────────────────────────── │
691
- │ │
692
- │ ┌─────────────────────────────────────────────────────────────────────┐ │
693
- │ │ CONTEXT THEORY (Spivak's Ologs) │ │
694
- │ │ SchemaContext = { classes: Set, properties: Map, domains, ranges } │ │
695
- │ │ → Defines WHAT can be queried (schema as category) │ │
696
- │ └─────────────────────────────────────────────────────────────────────┘ │
697
- │ │ │
698
- │ ▼ │
699
- │ ┌─────────────────────────────────────────────────────────────────────┐ │
700
- │ │ TYPE THEORY (Hindley-Milner) │ │
701
- │ │ TOOL_REGISTRY = { 'kg.sparql.query': Query → BindingSet, ... } │ │
702
- │ │ → Defines HOW tools compose (typed morphisms) │ │
703
- │ └─────────────────────────────────────────────────────────────────────┘ │
704
- │ │ │
705
- │ ▼ │
706
- │ ┌─────────────────────────────────────────────────────────────────────┐ │
707
- │ │ PROOF THEORY (Curry-Howard) │ │
708
- │ │ ProofDAG = { derivations: [...], hash: "sha256:..." } │ │
709
- │ │ → Proves HOW answer was derived (audit trail) │ │
710
- │ └─────────────────────────────────────────────────────────────────────┘ │
711
- │ │
712
- ├───────────────────────────────────────────────────────────────────────────┤
713
- │ RESULTS: SPEED + ACCURACY │
714
- │ ───────────────────────── │
715
- │ │
716
- │ TRADITIONAL (Code Gen) OUR APPROACH (Proxy Layer) │
717
- │ • 2-5 seconds per query • <100ms per query (20-50x FASTER) │
718
- │ • 0-14% accuracy (no schema) • 71% accuracy (schema auto-injected) │
719
- │ • Retry loops on errors • No retries needed │
720
- │ • $0.01-0.05 per query • <$0.001 per query (cached patterns) │
721
- │ │
722
- ├───────────────────────────────────────────────────────────────────────────┤
723
- │ WHY NO CODE GENERATION: │
724
- │ ─────────────────────── │
725
- │ 1. CODE GEN IS SLOW: LLM takes 1-3 seconds per query │
726
- │ 2. CODE GEN IS ERROR-PRONE: Syntax errors, hallucination │
727
- │ 3. CODE GEN IS EXPENSIVE: Every query costs LLM tokens │
728
- │ 4. CODE GEN IS NON-DETERMINISTIC: Same question → different code │
729
- │ │
730
- │ OUR PROXY LAYER PROVIDES: │
731
- │ 1. SPEED: Deterministic planner runs in milliseconds │
732
- │ 2. ACCURACY: Schema object ensures only valid predicates │
733
- │ 3. COST: No LLM needed for query generation │
734
- │ 4. DETERMINISM: Same input → same query → same result → same hash │
735
- └───────────────────────────────────────────────────────────────────────────┘
736
- ```
737
-
738
- **Architecture Comparison**:
739
- ```
740
- TRADITIONAL: LLM → JSON → Tool
741
-
742
- └── LLM generates JSON/code (SLOW, ERROR-PRONE)
743
- Tool executes blindly (NO VALIDATION)
744
- Result returned (NO PROOF)
745
-
746
- (20-40% accuracy, 2-5 sec/query, $0.01-0.05/query)
747
-
748
- OUR APPROACH: User → Proxied Objects → WASM Sandbox → RPC → Real Systems
749
-
750
- ├── SchemaContext (Context Theory)
751
- │ └── Live object: { classes: Set, properties: Map }
752
- │ └── NOT serialized JSON string
753
-
754
- ├── TOOL_REGISTRY (Type Theory)
755
- │ └── Typed morphisms: Query → BindingSet
756
- │ └── Composition validated at compile-time
757
-
758
- ├── WasmSandbox (Secure Execution)
759
- │ └── Capability-based: ReadKG, ExecuteTool
760
- │ └── Fuel metering: prevents infinite loops
761
- │ └── Full audit log: every action traced
762
-
763
- ├── rust-kgdb via NAPI-RS (Native RPC)
764
- │ └── 449ns lookups (not HTTP round-trips)
765
- │ └── Zero-copy data transfer
766
-
767
- └── ProofDAG (Proof Theory)
768
- └── Every answer has derivation chain
769
- └── Deterministic hash for reproducibility
770
-
771
- (71% accuracy with schema, <100ms/query, <$0.001/query)
772
- ```
773
-
774
- **The Three Pillars** (all as OBJECTS, not strings):
775
- - **Context Theory**: `SchemaContext` object defines what CAN be queried
776
- - **Type Theory**: `TOOL_REGISTRY` object defines typed tool signatures
777
- - **Proof Theory**: `ProofDAG` object proves how answer was derived
778
-
779
- **Why Proxied Objects + WASM Sandbox**:
780
- - **Proxied Objects**: SchemaContext, TOOL_REGISTRY are live objects with methods, not serialized JSON
781
- - **RPC to Real Systems**: Queries execute on rust-kgdb (449ns native performance)
782
- - **WASM Sandbox**: Capability-based security, fuel metering, full audit trail
80
+ **The AI writes the question. The database finds the answer. No hallucination possible.**
783
81
 
784
82
  ---
785
83
 
786
- ## Quick Start
84
+ ## But Where's The Database?
787
85
 
788
- ### Installation
86
+ Traditional setup for a knowledge graph:
87
+ - Install graph database server (weeks)
88
+ - Configure connections, security, backups (days)
89
+ - Hire a DBA (expensive)
90
+ - Maintain infrastructure (forever)
91
+ - Worry about HIPAA/SOC2 compliance for hosted data
789
92
 
93
+ **Our setup:**
790
94
  ```bash
791
95
  npm install rust-kgdb
792
96
  ```
793
97
 
794
- **Platforms**: macOS (Intel/Apple Silicon), Linux (x64/ARM64), Windows (x64)
98
+ That's it. The database runs **inside your application**. No server. No Docker. No config. No data leaving your system.
795
99
 
796
- ### Basic Usage (5 Lines)
100
+ Like SQLite - but for knowledge graphs. HIPAA-friendly by default because data never leaves your infrastructure.
797
101
 
798
- ```javascript
799
- const { GraphDB } = require('rust-kgdb')
102
+ ---
800
103
 
801
- const db = new GraphDB('http://example.org/')
802
- db.loadTtl(':alice :knows :bob .', null)
803
- const results = db.querySelect('SELECT ?who WHERE { ?who :knows :bob }')
804
- console.log(results) // [{ bindings: { who: 'http://example.org/alice' } }]
805
- ```
104
+ ## Real Examples
806
105
 
807
- ### Complete Example with AI Agent
106
+ ### Legal: Contract Analysis
808
107
 
809
108
  ```javascript
810
- const { GraphDB, HyperMindAgent, createSchemaAwareGraphDB } = require('rust-kgdb')
109
+ const { GraphDB, HyperMindAgent } = require('rust-kgdb');
811
110
 
812
- // Load your data
813
- const db = createSchemaAwareGraphDB('http://insurance.org/')
111
+ const db = new GraphDB('http://lawfirm.com/');
814
112
  db.loadTtl(`
815
- @prefix : <http://insurance.org/> .
816
- :CLM001 a :Claim ; :amount "50000" ; :provider :PROV001 .
817
- :PROV001 a :Provider ; :riskScore "0.87" ; :name "MedCorp" .
818
- `, null)
819
-
820
- // Create AI agent
821
- const agent = new HyperMindAgent({
822
- kg: db,
823
- model: 'gpt-4o',
824
- apiKey: process.env.OPENAI_API_KEY
825
- })
826
-
827
- // Ask questions in plain English
828
- const result = await agent.call('Find high-risk providers')
829
-
830
- // Every answer includes:
831
- // - The SPARQL query that was generated
832
- // - The data that was retrieved
833
- // - A reasoning trace showing how the conclusion was reached
834
- // - A cryptographic hash for reproducibility
835
- console.log(result.answer)
836
- console.log(result.reasoningTrace) // Full audit trail
837
- ```
838
-
839
- ---
840
-
841
- ## Framework Comparison (Verified Benchmark Setup)
842
-
843
- The following code snippets show EXACTLY how each framework was tested. All tests use the same LUBM dataset (3,272 triples) and GPT-4o model with real API calls—no mocking.
844
-
845
- **Reproduce yourself**: `python3 benchmark-frameworks.py` (included in package)
846
-
847
- ### Vanilla OpenAI (0% → 71.4% with schema)
113
+ :Contract_2024_001 :hasClause :NonCompete_3yr ; :signedBy :ClientA .
114
+ :NonCompete_3yr :challengedIn :Martinez_v_Apex ; :upheldIn :Chen_v_StateBank .
115
+ :Martinez_v_Apex :court "9th Circuit" ; :year 2021 ; :outcome "partially_enforced" .
116
+ :Chen_v_StateBank :court "Delaware Chancery" ; :year 2018 ; :outcome "fully_enforced" .
117
+ `);
848
118
 
849
- ```python
850
- # WITHOUT SCHEMA: 0% accuracy
851
- from openai import OpenAI
852
- client = OpenAI()
119
+ const agent = new HyperMindAgent({ db });
120
+ const result = await agent.ask("Has the non-compete clause been challenged?");
853
121
 
854
- response = client.chat.completions.create(
855
- model="gpt-4o",
856
- messages=[{"role": "user", "content": "Find all teachers"}]
857
- )
858
- # Returns: Long explanation with markdown code blocks
859
- # FAILS: No usable SPARQL query
860
- ```
861
-
862
- ```python
863
- # WITH SCHEMA: 71.4% accuracy (+71.4 pp improvement)
864
- LUBM_SCHEMA = """
865
- PREFIX ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#>
866
- Classes: University, Department, Professor, Student, Course, Publication
867
- Properties: teacherOf(Faculty→Course), worksFor(Faculty→Department)
868
- """
869
-
870
- response = client.chat.completions.create(
871
- model="gpt-4o",
872
- messages=[{
873
- "role": "system",
874
- "content": f"{LUBM_SCHEMA}\nOutput raw SPARQL only, no markdown."
875
- }, {
876
- "role": "user",
877
- "content": "Find all teachers"
878
- }]
879
- )
880
- # Returns: SELECT DISTINCT ?teacher WHERE { ?teacher a ub:Professor . }
881
- # WORKS: Valid SPARQL using correct ontology terms
882
- ```
883
-
884
- ### LangChain (0% → 71.4% with schema)
885
-
886
- ```python
887
- # WITHOUT SCHEMA: 0% accuracy
888
- from langchain_openai import ChatOpenAI
889
- from langchain_core.prompts import PromptTemplate
890
- from langchain_core.output_parsers import StrOutputParser
891
-
892
- llm = ChatOpenAI(model="gpt-4o")
893
- template = PromptTemplate(
894
- input_variables=["question"],
895
- template="Generate SPARQL for: {question}"
896
- )
897
- chain = template | llm | StrOutputParser()
898
- result = chain.invoke({"question": "Find all teachers"})
899
- # Returns: Explanation + markdown code blocks
900
- # FAILS: Not executable SPARQL
901
- ```
902
-
903
- ```python
904
- # WITH SCHEMA: 71.4% accuracy (+71.4 pp improvement)
905
- template = PromptTemplate(
906
- input_variables=["question", "schema"],
907
- template="""You are a SPARQL query generator.
908
- {schema}
909
- TYPE CONTRACT: Output raw SPARQL only, NO markdown, NO explanation.
910
- Query: {question}
911
- Output raw SPARQL only:"""
912
- )
913
- chain = template | llm | StrOutputParser()
914
- result = chain.invoke({"question": "Find all teachers", "schema": LUBM_SCHEMA})
915
- # Returns: SELECT DISTINCT ?teacher WHERE { ?teacher a ub:Professor . }
916
- # WORKS: Schema injection guides correct predicate selection
917
- ```
918
-
919
- ### DSPy (14.3% → 71.4% with schema)
920
-
921
- ```python
922
- # WITHOUT SCHEMA: 14.3% accuracy (best without schema!)
923
- import dspy
924
- from dspy import LM
925
-
926
- lm = LM("openai/gpt-4o")
927
- dspy.configure(lm=lm)
928
-
929
- class SPARQLGenerator(dspy.Signature):
930
- """Generate SPARQL query."""
931
- question = dspy.InputField()
932
- sparql = dspy.OutputField(desc="Raw SPARQL query only")
933
-
934
- generator = dspy.Predict(SPARQLGenerator)
935
- result = generator(question="Find all teachers")
936
- # Returns: SELECT ?teacher WHERE { ?teacher a :Teacher . }
937
- # PARTIAL: Sometimes works due to DSPy's structured output
938
- ```
122
+ console.log(result.answer);
123
+ // "Yes - Martinez v. Apex (9th Circuit, 2021) partially enforced;
124
+ // Chen v. StateBank (Delaware, 2018) fully enforced"
939
125
 
940
- ```python
941
- # WITH SCHEMA: 71.4% accuracy (+57.1 pp improvement)
942
- class SchemaSPARQLGenerator(dspy.Signature):
943
- """Generate SPARQL query using the provided schema."""
944
- schema = dspy.InputField(desc="Database schema with classes and properties")
945
- question = dspy.InputField(desc="Natural language question")
946
- sparql = dspy.OutputField(desc="Raw SPARQL query, no markdown")
947
-
948
- generator = dspy.Predict(SchemaSPARQLGenerator)
949
- result = generator(schema=LUBM_SCHEMA, question="Find all teachers")
950
- # Returns: SELECT DISTINCT ?teacher WHERE { ?teacher a ub:Professor . }
951
- # WORKS: Schema + DSPy structured output = reliable queries
126
+ console.log(result.evidence);
127
+ // Full audit trail proving every fact came from your case database
952
128
  ```
953
129
 
954
- ### HyperMind (Built-in Schema Awareness)
130
+ ### Healthcare: Drug Interactions
955
131
 
956
132
  ```javascript
957
- // HyperMind auto-extracts schema from your data
958
- const { HyperMindAgent, createSchemaAwareGraphDB } = require('rust-kgdb');
959
-
960
- const db = createSchemaAwareGraphDB('http://university.org/');
961
- db.loadTtl(lubmData, null); // Load LUBM 3,272 triples
962
-
963
- const agent = new HyperMindAgent({
964
- kg: db,
965
- model: 'gpt-4o',
966
- apiKey: process.env.OPENAI_API_KEY
967
- });
968
-
969
- const result = await agent.call('Find all teachers');
970
- // Schema auto-extracted: { classes: Set(30), properties: Map(23) }
971
- // Query generated: SELECT ?x WHERE { ?x ub:teacherOf ?course . }
972
- // Result: 39 faculty members who teach courses
973
-
974
- console.log(result.reasoningTrace);
975
- // [{ tool: 'kg.sparql.query', query: 'SELECT...', bindings: 39 }]
976
- console.log(result.hash);
977
- // "sha256:a7b2c3..." - Reproducible answer
978
- ```
979
-
980
- **Key Insight**: All frameworks achieve the SAME accuracy (~71%) when given schema. HyperMind's value is that it extracts and injects schema AUTOMATICALLY from your data—no manual prompt engineering required. Plus it includes the database to actually execute queries.
981
-
982
- ---
983
-
984
- ## Use Cases
985
-
986
- ### Fraud Detection
133
+ const db = new GraphDB('http://hospital.org/');
134
+ db.loadTtl(`
135
+ :Patient_7291 :currentMedication :Warfarin ; :currentMedication :Lisinopril .
136
+ :Warfarin :interactsWith :Aspirin ; :interactionSeverity "high" .
137
+ :Warfarin :interactsWith :Ibuprofen ; :interactionSeverity "moderate" .
138
+ :Lisinopril :interactsWith :Potassium ; :interactionSeverity "high" .
139
+ `);
987
140
 
988
- ```javascript
989
- const agent = new HyperMindAgent({
990
- kg: insuranceDB,
991
- name: 'fraud-detector',
992
- model: 'claude-3-opus'
993
- })
994
-
995
- const result = await agent.call('Find providers with suspicious billing patterns')
996
- // Returns: List of providers with complete evidence trail
997
- // - SPARQL queries executed
998
- // - Rules that matched
999
- // - Similar entities found via embeddings
141
+ const result = await agent.ask("What should we avoid prescribing to Patient 7291?");
142
+ // Returns ONLY drugs that actually interact with their ACTUAL medications
143
+ // Not hallucinated drug names - real interactions from your formulary
1000
144
  ```
1001
145
 
1002
- ### Regulatory Compliance
146
+ ### Insurance: Claims Fraud Detection
1003
147
 
1004
148
  ```javascript
1005
- const agent = new HyperMindAgent({
1006
- kg: complianceDB,
1007
- scope: { allowedGraphs: ['http://compliance.org/'] } // Restrict access
1008
- })
149
+ const db = new GraphDB('http://insurer.com/');
150
+ db.loadTtl(`
151
+ :Provider_892 :totalClaims 1247 ; :avgClaimAmount 3200 ; :denialRate 0.02 .
152
+ :Provider_445 :totalClaims 89 ; :avgClaimAmount 47000 ; :denialRate 0.34 .
153
+ :Provider_445 :hasPattern :UnbundledBilling ; :flaggedBy :SIU_2024_Q1 .
154
+ :Claim_99281 :provider :Provider_445 ; :amount 52000 ; :diagnosis :LumbarFusion .
155
+ `);
1009
156
 
1010
- const result = await agent.call('Check GDPR compliance for customer data flows')
1011
- // Returns: Compliance status with verifiable reasoning chain
157
+ const result = await agent.ask("Which providers show suspicious billing patterns?");
158
+ // Returns Provider_445 with ACTUAL evidence:
159
+ // - High avg claim ($47K vs network avg)
160
+ // - 34% denial rate
161
+ // - SIU flag from Q1 2024
162
+ // NOT fabricated accusations against innocent providers
1012
163
  ```
1013
164
 
1014
- ### Risk Assessment
165
+ ### Fraud: Transaction Network Analysis
1015
166
 
1016
167
  ```javascript
1017
- const result = await agent.call('Calculate risk score for entity P001')
1018
- // Returns: Risk score with complete derivation
1019
- // - Which data points were used
1020
- // - Which rules were applied
1021
- // - Confidence intervals
168
+ const db = new GraphDB('http://bank.com/aml/');
169
+ db.loadTtl(`
170
+ :Acct_1001 :transferredTo :Acct_2002 ; :amount 9500 .
171
+ :Acct_2002 :transferredTo :Acct_3003 ; :amount 9400 .
172
+ :Acct_3003 :transferredTo :Acct_1001 ; :amount 9200 . # Circular!
173
+ :Acct_1001 :owner :Entity_A ; :jurisdiction "Cayman Islands" .
174
+ `);
175
+
176
+ // Datalog rule: Find circular payment chains (potential layering)
177
+ db.addRule(`
178
+ circularChain(X, Y, Z) :-
179
+ transfer(X, Y), transfer(Y, Z), transfer(Z, X),
180
+ amount(X, Y, A1), amount(Y, Z, A2), amount(Z, X, A3),
181
+ A1 > 9000, A2 > 9000, A3 > 9000.
182
+ `);
183
+
184
+ const result = await agent.ask("Find potential money laundering patterns");
185
+ // Returns the ACTUAL circular chain: 1001 → 2002 → 3003 → 1001
186
+ // With amounts just under $10K reporting threshold
187
+ // All verifiable from your transaction records
1022
188
  ```
1023
189
 
1024
190
  ---
1025
191
 
1026
- ## Features
1027
-
1028
- ### Core Database (SPARQL 1.1)
1029
- | Feature | Description |
1030
- |---------|-------------|
1031
- | **SELECT/CONSTRUCT/ASK** | Full SPARQL 1.1 query support |
1032
- | **INSERT/DELETE/UPDATE** | SPARQL Update operations |
1033
- | **64 Builtin Functions** | String, numeric, date/time, hash functions |
1034
- | **Named Graphs** | Quad-based storage with graph isolation |
1035
- | **RDF-Star** | Statements about statements |
1036
-
1037
- ### Rule-Based Reasoning (Datalog)
1038
- | Feature | Description |
1039
- |---------|-------------|
1040
- | **Facts & Rules** | Define base facts and inference rules |
1041
- | **Semi-naive Evaluation** | Efficient incremental computation |
1042
- | **Recursive Queries** | Transitive closure, ancestor chains |
1043
-
1044
- ### Graph Analytics (GraphFrames)
1045
- | Feature | Description |
1046
- |---------|-------------|
1047
- | **PageRank** | Iterative node importance ranking |
1048
- | **Connected Components** | Find isolated subgraphs |
1049
- | **Shortest Paths** | BFS path finding from landmarks |
1050
- | **Triangle Count** | Graph density measurement |
1051
- | **Motif Finding** | Structural pattern matching DSL |
1052
-
1053
- ### Vector Similarity (Embeddings)
1054
- | Feature | Description |
1055
- |---------|-------------|
1056
- | **HNSW Index** | O(log N) approximate nearest neighbor |
1057
- | **Multi-provider** | OpenAI, Anthropic, Ollama support |
1058
- | **Composite Search** | RRF aggregation across providers |
1059
-
1060
- ### AI Agent Framework (HyperMind)
1061
- | Feature | Description |
1062
- |---------|-------------|
1063
- | **Schema-Aware** | Auto-extracts schema from your data |
1064
- | **Typed Tools** | Input/output validation prevents errors |
1065
- | **Audit Trail** | Every answer is traceable |
1066
- | **Memory** | Working, episodic, and long-term memory |
1067
-
1068
- ### Schema-Aware Generation (Proxied Tools)
1069
-
1070
- Generate motif patterns and Datalog rules from natural language using schema injection:
192
+ ## The Math (Explained Simply)
1071
193
 
1072
- ```javascript
1073
- const { LLMPlanner, createSchemaAwareGraphDB } = require('rust-kgdb');
1074
-
1075
- const db = createSchemaAwareGraphDB('http://insurance.org/');
1076
- db.loadTtl(insuranceData, null);
1077
-
1078
- const planner = new LLMPlanner({ kg: db, model: 'gpt-4o' });
1079
-
1080
- // Generate motif pattern from text
1081
- const motif = await planner.generateMotifFromText('Find circular payment patterns');
1082
- // Returns: {
1083
- // pattern: "(a)-[transfers]->(b); (b)-[transfers]->(c); (c)-[transfers]->(a)",
1084
- // variables: ["a", "b", "c"],
1085
- // predicatesUsed: ["transfers"],
1086
- // confidence: 0.9
1087
- // }
1088
-
1089
- // Generate Datalog rules from text
1090
- const datalog = await planner.generateDatalogFromText(
1091
- 'High risk providers are those with risk score above 0.7'
1092
- );
1093
- // Returns: {
1094
- // rules: [{ name: "highRisk", head: {...}, body: [...] }],
1095
- // datalogSyntax: ["highRisk(?x) :- provider(?x), riskScore(?x, ?score), ?score > 0.7."],
1096
- // predicatesUsed: ["riskScore", "provider"],
1097
- // confidence: 0.85
1098
- // }
1099
- ```
194
+ ### Category Theory: The Lego Rule
1100
195
 
1101
- **Same approach as SPARQL benchmark**: Schema injection ensures only valid predicates are used. No hallucination.
1102
-
1103
- ### Available Tools
1104
- | Tool | Input → Output | Description |
1105
- |------|----------------|-------------|
1106
- | `kg.sparql.query` | Query → BindingSet | Execute SPARQL SELECT |
1107
- | `kg.sparql.update` | Update → Result | Execute SPARQL UPDATE |
1108
- | `kg.datalog.apply` | Rules → InferredFacts | Apply Datalog rules |
1109
- | `kg.motif.find` | Pattern → Matches | Find graph patterns |
1110
- | `kg.embeddings.search` | Entity → SimilarEntities | Vector similarity |
1111
- | `kg.graphframes.pagerank` | Graph → Scores | Rank nodes |
1112
- | `kg.graphframes.components` | Graph → Components | Find communities |
1113
-
1114
- ### Performance
1115
- | Metric | Value | Comparison |
1116
- |--------|-------|------------|
1117
- | **Lookup Speed** | 449 ns | 5-10x faster than RDFox (verified Dec 2025) |
1118
- | **Bulk Insert** | 146K triples/sec | Production-grade |
1119
- | **Memory** | 24 bytes/triple | Best-in-class efficiency |
1120
-
1121
- ### Join Optimization (WCOJ)
1122
- | Feature | Description |
1123
- |---------|-------------|
1124
- | **WCOJ Algorithm** | Worst-case optimal joins with O(N^(ρ/2)) complexity |
1125
- | **Multi-way Joins** | Process multiple patterns simultaneously |
1126
- | **Adaptive Plans** | Cost-based optimizer selects best strategy |
1127
-
1128
- **Research Foundation**: WCOJ algorithms are the state-of-the-art for graph pattern matching. See [Tentris WCOJ Update (ISWC 2025)](https://papers.dice-research.org/2025/ISWC_Tentris-WCOJ-Update/public.pdf) for latest research.
1129
-
1130
- ### Ontology & Reasoning
1131
- | Feature | Description |
1132
- |---------|-------------|
1133
- | **RDFS Reasoner** | Subclass/subproperty inference |
1134
- | **OWL 2 RL** | Rule-based OWL reasoning (prp-dom, prp-rng, prp-symp, prp-trp, cls-hv, cls-svf, cax-sco) |
1135
- | **SHACL** | W3C shapes constraint validation |
1136
-
1137
- ### Distribution (Clustered Mode)
1138
- | Feature | Description |
1139
- |---------|-------------|
1140
- | **HDRF Partitioning** | Streaming graph partitioning (subject-anchored) |
1141
- | **Raft Consensus** | Distributed coordination |
1142
- | **gRPC** | Inter-node communication |
1143
- | **Kubernetes-Native** | Helm charts, health checks |
1144
-
1145
- ### Storage Backends
1146
- | Backend | Use Case |
1147
- |---------|----------|
1148
- | **InMemory** | Development, testing, small datasets |
1149
- | **RocksDB** | Production, large datasets, ACID |
1150
- | **LMDB** | Read-heavy workloads, memory-mapped |
1151
-
1152
- ### Mobile Support
1153
- | Platform | Binding |
1154
- |----------|---------|
1155
- | **iOS** | Swift via UniFFI 0.30 |
1156
- | **Android** | Kotlin via UniFFI 0.30 |
1157
- | **Node.js** | NAPI-RS (this package) |
1158
- | **Python** | UniFFI (separate package) |
196
+ Imagine Lego blocks. A 2x4 brick only connects to compatible bricks.
1159
197
 
1160
- ---
198
+ We made AI tools work the same way:
199
+ - Query tool: takes a question, returns case citations
200
+ - Validation tool: takes citations, returns verified facts
1161
201
 
1162
- ## Complete Feature Overview
1163
-
1164
- | Category | Feature | What It Does |
1165
- |----------|---------|--------------|
1166
- | **Core** | GraphDB | High-performance RDF/SPARQL quad store |
1167
- | **Core** | SPOC Indexes | Four-way indexing (SPOC/POCS/OCSP/CSPO) |
1168
- | **Core** | Dictionary | String interning with 8-byte IDs |
1169
- | **Analytics** | GraphFrames | PageRank, connected components, triangles |
1170
- | **Analytics** | Motif Finding | Pattern matching DSL |
1171
- | **Analytics** | Pregel | BSP parallel graph processing |
1172
- | **AI** | Embeddings | HNSW similarity with 1-hop ARCADE cache |
1173
- | **AI** | HyperMind | Neuro-symbolic agent framework |
1174
- | **Reasoning** | Datalog | Semi-naive evaluation engine |
1175
- | **Reasoning** | RDFS Reasoner | Subclass/subproperty inference |
1176
- | **Reasoning** | OWL 2 RL | Rule-based OWL reasoning |
1177
- | **Ontology** | SHACL | W3C shapes constraint validation |
1178
- | **Joins** | WCOJ | Worst-case optimal join algorithm |
1179
- | **Distribution** | HDRF | Streaming graph partitioning |
1180
- | **Distribution** | Raft | Consensus for coordination |
1181
- | **Mobile** | iOS/Android | Swift and Kotlin bindings via UniFFI |
1182
- | **Storage** | InMemory/RocksDB/LMDB | Three backend options |
202
+ The AI can only chain tools where outputs match inputs. A "patient record" output can't connect to a "case citation" input. **The type system prevents nonsense combinations** - like Lego blocks that physically don't fit.
1183
203
 
1184
- ---
204
+ ### WCOJ: The Court Records Trick
1185
205
 
1186
- ## How It Works
206
+ Finding "all cases where Judge X ruled on Contract Type Y involving Company Z"?
1187
207
 
1188
- ### The Architecture
208
+ **Slow way:** Check every case with Judge X (50,000), every contract type (500K combinations), every company (25M checks).
1189
209
 
1190
- ```
1191
- ┌─────────────────────────────────────────────────────────────────────────────┐
1192
- │ YOUR QUESTION │
1193
- │ "Find suspicious providers" │
1194
- └─────────────────────────────────┬───────────────────────────────────────────┘
1195
-
1196
-
1197
- ┌─────────────────────────────────────────────────────────────────────────────┐
1198
- │ STEP 1: SCHEMA INJECTION │
1199
- │ │
1200
- │ LLM receives your question PLUS your actual data schema: │
1201
- │ • Classes: Claim, Provider, Policy (from YOUR database) │
1202
- │ • Properties: amount, riskScore, claimCount (from YOUR database) │
1203
- │ │
1204
- │ The LLM can ONLY reference things that actually exist in your data. │
1205
- └─────────────────────────────────┬───────────────────────────────────────────┘
1206
-
1207
-
1208
- ┌─────────────────────────────────────────────────────────────────────────────┐
1209
- │ STEP 2: TYPED EXECUTION PLAN │
1210
- │ │
1211
- │ LLM generates a plan using typed tools: │
1212
- │ 1. kg.sparql.query("SELECT ?p WHERE { ?p :riskScore ?r . FILTER(?r > 0.8)}")│
1213
- │ 2. kg.datalog.apply("suspicious(?p) :- highRisk(?p), highClaimCount(?p)") │
1214
- │ │
1215
- │ Each tool has defined inputs/outputs. Invalid combinations rejected. │
1216
- └─────────────────────────────────┬───────────────────────────────────────────┘
1217
-
1218
-
1219
- ┌─────────────────────────────────────────────────────────────────────────────┐
1220
- │ STEP 3: DATABASE EXECUTION │
1221
- │ │
1222
- │ The database executes the plan against YOUR ACTUAL DATA: │
1223
- │ • SPARQL query runs → finds 3 providers with riskScore > 0.8 │
1224
- │ • Datalog rules run → 1 provider matches "suspicious" pattern │
1225
- │ │
1226
- │ Every step is recorded in the reasoning trace. │
1227
- └─────────────────────────────────┬───────────────────────────────────────────┘
1228
-
1229
-
1230
- ┌─────────────────────────────────────────────────────────────────────────────┐
1231
- │ STEP 4: VERIFIED ANSWER │
1232
- │ │
1233
- │ Answer: "Provider PROV001 is suspicious (riskScore: 0.87, claims: 47)" │
1234
- │ │
1235
- │ + Reasoning Trace: Every query, every rule, every result │
1236
- │ + Hash: sha256:8f3a2b1c... (reproducible) │
1237
- │ │
1238
- │ Run the same question tomorrow → Same answer → Same hash │
1239
- └─────────────────────────────────────────────────────────────────────────────┘
1240
- ```
210
+ **Our way:** Keep sorted indexes of judges, contract types, and companies. Walk through all three simultaneously, skip impossible combinations. 50,000 checks instead of 25 million. This is called Worst-Case Optimal Join.
1241
211
 
1242
- ### Why Hallucination Is Impossible
212
+ ### HNSW: The Medical Specialist Network
1243
213
 
1244
- | Step | What Prevents Hallucination |
1245
- |------|----------------------------|
1246
- | Schema Injection | LLM only sees properties that exist in YOUR data |
1247
- | Typed Tools | Invalid query structures rejected before execution |
1248
- | Database Execution | Answers come from actual data, not LLM imagination |
1249
- | Reasoning Trace | Every claim is backed by recorded evidence |
214
+ Finding the right specialist for a rare condition from 50,000 doctors?
1250
215
 
1251
- **The key insight**: The LLM is a planner, not an oracle. It decides WHAT to look for. The database finds EXACTLY that. The answer is the intersection of LLM intelligence and database truth.
216
+ **Slow way:** Compare symptoms to all 50,000 doctor profiles.
1252
217
 
1253
- ---
218
+ **Our way:** Build a "referral network." Generalists connect to specialists who connect to sub-specialists. Start anywhere, hop toward the right match. ~20 hops instead of 50,000 comparisons.
1254
219
 
1255
- ## API Reference
220
+ We use this to find "similar past queries" - 10,000 historical questions searched in 16 milliseconds.
1256
221
 
1257
- ### GraphDB
222
+ ### Datalog: The Compliance Cascade
1258
223
 
1259
- ```typescript
1260
- class GraphDB {
1261
- constructor(appGraphUri: string)
1262
- loadTtl(ttlContent: string, graphName: string | null): void
1263
- querySelect(sparql: string): QueryResult[]
1264
- query(sparql: string): TripleResult[]
1265
- countTriples(): number
1266
- clear(): void
1267
- }
1268
- ```
224
+ Instead of manually listing every compliance requirement:
1269
225
 
1270
- ### HyperMindAgent
1271
-
1272
- ```typescript
1273
- class HyperMindAgent {
1274
- constructor(options: {
1275
- kg: GraphDB, // Your knowledge graph
1276
- model?: string, // 'gpt-4o' | 'claude-3-opus' | etc.
1277
- apiKey?: string, // LLM API key
1278
- memory?: MemoryManager,
1279
- scope?: AgentScope,
1280
- embeddings?: EmbeddingService
1281
- })
1282
-
1283
- call(prompt: string): Promise<AgentResponse>
1284
- }
1285
-
1286
- interface AgentResponse {
1287
- answer: string
1288
- reasoningTrace: ReasoningStep[] // Audit trail
1289
- hash: string // Reproducibility hash
1290
- }
1291
226
  ```
1292
-
1293
- ### GraphFrame
1294
-
1295
- ```typescript
1296
- class GraphFrame {
1297
- constructor(verticesJson: string, edgesJson: string)
1298
- pageRank(resetProb: number, maxIter: number): string
1299
- connectedComponents(): string
1300
- shortestPaths(landmarks: string[]): string
1301
- triangleCount(): number
1302
- find(pattern: string): string // Motif pattern matching
1303
- }
227
+ mustReport(X) :- transaction(X), amount(X, A), A > 10000.
228
+ mustReport(X) :- transaction(X), involves(X, PEP).
229
+ mustReport(X) :- relatedTo(X, Y), mustReport(Y). # Cascades!
1304
230
  ```
1305
231
 
1306
- ### EmbeddingService
1307
-
1308
- ```typescript
1309
- class EmbeddingService {
1310
- storeVector(entityId: string, vector: number[]): void
1311
- findSimilar(entityId: string, k: number, threshold: number): string
1312
- rebuildIndex(): void
1313
- }
1314
- ```
1315
-
1316
- ### DatalogProgram
1317
-
1318
- ```typescript
1319
- class DatalogProgram {
1320
- addFact(factJson: string): void
1321
- addRule(ruleJson: string): void
1322
- }
1323
-
1324
- function evaluateDatalog(program: DatalogProgram): string
1325
- function queryDatalog(program: DatalogProgram, query: string): string
1326
- ```
232
+ Three rules generate ALL reporting requirements automatically. Even for transactions connected to other suspicious transactions, going back as far as your data allows.
1327
233
 
1328
234
  ---
1329
235
 
1330
- ## More Examples
236
+ ## Why Our Agent Memory Is Different
1331
237
 
1332
- ### Knowledge Graph
238
+ Most AI agents have amnesia. Ask them the same question twice, they start from scratch.
1333
239
 
1334
- ```javascript
1335
- const { GraphDB } = require('rust-kgdb')
1336
-
1337
- const db = new GraphDB('http://example.org/')
1338
- db.loadTtl(`
1339
- @prefix : <http://example.org/> .
1340
- :alice :knows :bob .
1341
- :bob :knows :charlie .
1342
- :charlie :knows :alice .
1343
- `, null)
1344
-
1345
- console.log(`Loaded ${db.countTriples()} triples`) // 3
1346
-
1347
- const results = db.querySelect(`
1348
- PREFIX : <http://example.org/>
1349
- SELECT ?person WHERE { ?person :knows :bob }
1350
- `)
1351
- console.log(results) // [{ bindings: { person: 'http://example.org/alice' } }]
1352
- ```
1353
-
1354
- ### Graph Analytics
1355
-
1356
- ```javascript
1357
- const { GraphFrame } = require('rust-kgdb')
1358
-
1359
- const graph = new GraphFrame(
1360
- JSON.stringify([{id:'alice'}, {id:'bob'}, {id:'charlie'}]),
1361
- JSON.stringify([
1362
- {src:'alice', dst:'bob'},
1363
- {src:'bob', dst:'charlie'},
1364
- {src:'charlie', dst:'alice'}
1365
- ])
1366
- )
1367
-
1368
- // Built-in algorithms
1369
- console.log('Triangles:', graph.triangleCount()) // 1
1370
- console.log('PageRank:', JSON.parse(graph.pageRank(0.15, 20)))
1371
- console.log('Components:', JSON.parse(graph.connectedComponents()))
1372
- ```
1373
-
1374
- ### Motif Finding (Pattern Matching)
1375
-
1376
- ```javascript
1377
- const { GraphFrame } = require('rust-kgdb')
1378
-
1379
- // Create a graph with payment relationships
1380
- const graph = new GraphFrame(
1381
- JSON.stringify([
1382
- {id:'company_a'}, {id:'company_b'}, {id:'company_c'}, {id:'company_d'}
1383
- ]),
1384
- JSON.stringify([
1385
- {src:'company_a', dst:'company_b'}, // A pays B
1386
- {src:'company_b', dst:'company_c'}, // B pays C
1387
- {src:'company_c', dst:'company_a'}, // C pays A (circular!)
1388
- {src:'company_c', dst:'company_d'} // C also pays D
1389
- ])
1390
- )
1391
-
1392
- // Find simple edge pattern: (a)-[]->(b)
1393
- const edges = JSON.parse(graph.find('(a)-[]->(b)'))
1394
- console.log('All edges:', edges.length) // 4
1395
-
1396
- // Find two-hop path: (x)-[]->(y)-[]->(z)
1397
- const twoHops = JSON.parse(graph.find('(x)-[]->(y); (y)-[]->(z)'))
1398
- console.log('Two-hop paths:', twoHops.length) // 3
1399
-
1400
- // Find circular pattern (fraud detection!): A->B->C->A
1401
- const circles = JSON.parse(graph.find('(a)-[]->(b); (b)-[]->(c); (c)-[]->(a)'))
1402
- console.log('Circular patterns:', circles.length) // 1 (the fraud ring!)
1403
-
1404
- // Each match includes the bound variables
1405
- // circles[0] = { a: 'company_a', b: 'company_b', c: 'company_c' }
1406
- ```
1407
-
1408
- ### Rule-Based Reasoning
1409
-
1410
- ```javascript
1411
- const { DatalogProgram, evaluateDatalog } = require('rust-kgdb')
1412
-
1413
- const program = new DatalogProgram()
1414
- program.addFact(JSON.stringify({predicate: 'parent', terms: ['alice', 'bob']}))
1415
- program.addFact(JSON.stringify({predicate: 'parent', terms: ['bob', 'charlie']}))
1416
-
1417
- // grandparent(X, Z) :- parent(X, Y), parent(Y, Z)
1418
- program.addRule(JSON.stringify({
1419
- head: {predicate: 'grandparent', terms: ['?X', '?Z']},
1420
- body: [
1421
- {predicate: 'parent', terms: ['?X', '?Y']},
1422
- {predicate: 'parent', terms: ['?Y', '?Z']}
1423
- ]
1424
- }))
1425
-
1426
- console.log('Inferred:', JSON.parse(evaluateDatalog(program)))
1427
- // grandparent(alice, charlie)
1428
- ```
1429
-
1430
- ### Semantic Similarity
1431
-
1432
- ```javascript
1433
- const { EmbeddingService } = require('rust-kgdb')
240
+ **The Problem:**
241
+ - ChatGPT forgets your previous questions after context window fills
242
+ - LangChain agents rebuild context every call (~500ms overhead)
243
+ - Vector databases return "similar" docs, not the exact query you ran before
1434
244
 
1435
- const embeddings = new EmbeddingService()
245
+ **Our Approach: Deep Flashback**
1436
246
 
1437
- // Store 384-dimension vectors
1438
- embeddings.storeVector('claim_001', new Array(384).fill(0.5))
1439
- embeddings.storeVector('claim_002', new Array(384).fill(0.6))
1440
- embeddings.rebuildIndex()
247
+ When you ask "find suspicious providers", we:
248
+ 1. **Hash your intent** → Check if we've seen this exact question pattern before
249
+ 2. **HNSW lookup** → Search 10,000 historical queries in 16ms (not 500ms)
250
+ 3. **Return cached result** → If we've answered this before, return instantly with proof
1441
251
 
1442
- // HNSW similarity search
1443
- const similar = JSON.parse(embeddings.findSimilar('claim_001', 5, 0.7))
1444
- console.log('Similar:', similar)
1445
- ```
252
+ **Benchmarked Results (Verified):**
1446
253
 
1447
- ### Pregel (BSP Graph Processing)
254
+ | Metric | Result | What It Means |
255
+ |--------|--------|---------------|
256
+ | **Memory Retrieval** | 94% Recall@10 at 10K depth | Find the right past query 94% of the time |
257
+ | **Search Speed** | 16.7ms for 10K queries | 30x faster than typical RAG |
258
+ | **Write Throughput** | 132K ops/sec (16 workers) | Handle enterprise query volumes |
259
+ | **Read Throughput** | 302 ops/sec concurrent | Consistent under load |
1448
260
 
1449
- ```javascript
1450
- const { chainGraph, pregelShortestPaths } = require('rust-kgdb')
261
+ **Why This Matters:**
1451
262
 
1452
- // Create a chain: v0 -> v1 -> v2 -> v3 -> v4
1453
- const graph = chainGraph(5)
263
+ A claims adjuster asks about Provider #445 on Monday. On Friday, a different adjuster asks the same question. Without memory:
264
+ - Monday: 3 seconds to generate query, execute, format
265
+ - Friday: 3 seconds again (total waste)
1454
266
 
1455
- // Compute shortest paths from v0
1456
- const result = JSON.parse(pregelShortestPaths(graph, 'v0', 10))
1457
- console.log('Distances:', result.distances)
1458
- // { v0: 0, v1: 1, v2: 2, v3: 3, v4: 4 }
1459
- console.log('Supersteps:', result.supersteps) // 5
1460
- ```
1461
-
1462
- ---
267
+ With our memory:
268
+ - Monday: 3 seconds (first time)
269
+ - Friday: 16ms (cached, with full audit trail)
1463
270
 
1464
- ## Comprehensive Example Tables
1465
-
1466
- ### SPARQL Examples
1467
-
1468
- | Query Type | Example | Description |
1469
- |------------|---------|-------------|
1470
- | **SELECT** | `SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10` | Basic triple pattern |
1471
- | **FILTER** | `SELECT ?p WHERE { ?p :age ?a . FILTER(?a > 30) }` | Numeric filtering |
1472
- | **OPTIONAL** | `SELECT ?p ?email WHERE { ?p a :Person . OPTIONAL { ?p :email ?email } }` | Left outer join |
1473
- | **UNION** | `SELECT ?x WHERE { { ?x a :Cat } UNION { ?x a :Dog } }` | Pattern union |
1474
- | **CONSTRUCT** | `CONSTRUCT { ?s :knows ?o } WHERE { ?s :friend ?o }` | Create new triples |
1475
- | **ASK** | `ASK WHERE { :alice :knows :bob }` | Boolean existence check |
1476
- | **INSERT** | `INSERT DATA { :alice :knows :charlie }` | Add triples |
1477
- | **DELETE** | `DELETE WHERE { :alice :knows ?anyone }` | Remove triples |
1478
- | **Aggregation** | `SELECT (COUNT(?p) AS ?cnt) WHERE { ?p a :Person }` | Count/Sum/Avg/Min/Max |
1479
- | **GROUP BY** | `SELECT ?dept (COUNT(?e) AS ?cnt) WHERE { ?e :worksIn ?dept } GROUP BY ?dept` | Grouping |
1480
- | **HAVING** | `SELECT ?dept (COUNT(?e) AS ?cnt) WHERE { ?e :worksIn ?dept } GROUP BY ?dept HAVING (COUNT(?e) > 5)` | Filter groups |
1481
- | **ORDER BY** | `SELECT ?p ?age WHERE { ?p :age ?age } ORDER BY DESC(?age)` | Sorting |
1482
- | **DISTINCT** | `SELECT DISTINCT ?type WHERE { ?s a ?type }` | Remove duplicates |
1483
- | **VALUES** | `SELECT ?p WHERE { VALUES ?type { :Cat :Dog } ?p a ?type }` | Inline data |
1484
- | **BIND** | `SELECT ?p ?label WHERE { ?p :name ?n . BIND(CONCAT("Mr. ", ?n) AS ?label) }` | Computed values |
1485
- | **Subquery** | `SELECT ?p WHERE { { SELECT ?p WHERE { ?p :score ?s } ORDER BY DESC(?s) LIMIT 10 } }` | Nested queries |
1486
-
1487
- ### Datalog Examples
1488
-
1489
- | Pattern | Rule | Description |
1490
- |---------|------|-------------|
1491
- | **Transitive Closure** | `ancestor(?X,?Z) :- parent(?X,?Y), ancestor(?Y,?Z)` | Recursive ancestor |
1492
- | **Symmetric** | `knows(?X,?Y) :- knows(?Y,?X)` | Bidirectional relations |
1493
- | **Composition** | `grandparent(?X,?Z) :- parent(?X,?Y), parent(?Y,?Z)` | Two-hop relation |
1494
- | **Negation** | `lonely(?X) :- person(?X), NOT friend(?X,?Y)` | Absence check |
1495
- | **Aggregation** | `popular(?X) :- friend(?X,?Y), COUNT(?Y) > 10` | Count-based rules |
1496
- | **Path Finding** | `reachable(?X,?Y) :- edge(?X,?Y). reachable(?X,?Z) :- edge(?X,?Y), reachable(?Y,?Z)` | Graph connectivity |
1497
-
1498
- ### Motif Pattern Syntax
1499
-
1500
- | Pattern | Syntax | Matches |
1501
- |---------|--------|---------|
1502
- | **Single Edge** | `(a)-[]->(b)` | All directed edges |
1503
- | **Two-Hop** | `(a)-[]->(b); (b)-[]->(c)` | Paths of length 2 |
1504
- | **Triangle** | `(a)-[]->(b); (b)-[]->(c); (c)-[]->(a)` | Closed triangles |
1505
- | **Star** | `(center)-[]->(a); (center)-[]->(b); (center)-[]->(c)` | Hub patterns |
1506
- | **Named Edge** | `(a)-[e]->(b)` | Capture edge in variable `e` |
1507
- | **Negation** | `(a)-[]->(b); !(b)-[]->(a)` | One-way edges only |
1508
- | **Diamond** | `(a)-[]->(b); (a)-[]->(c); (b)-[]->(d); (c)-[]->(d)` | Diamond pattern |
1509
-
1510
- ### GraphFrame Algorithms
1511
-
1512
- | Algorithm | Method | Input | Output |
1513
- |-----------|--------|-------|--------|
1514
- | **PageRank** | `graph.pageRank(0.15, 20)` | damping, iterations | `{ ranks: {id: score}, iterations, converged }` |
1515
- | **Connected Components** | `graph.connectedComponents()` | - | `{ components: {id: componentId}, count }` |
1516
- | **Shortest Paths** | `graph.shortestPaths(['v0', 'v5'])` | landmark vertices | `{ distances: {id: {landmark: dist}} }` |
1517
- | **Label Propagation** | `graph.labelPropagation(10)` | max iterations | `{ labels: {id: label}, iterations }` |
1518
- | **Triangle Count** | `graph.triangleCount()` | - | Number of triangles |
1519
- | **Motif Finding** | `graph.find('(a)-[]->(b)')` | pattern string | Array of matches |
1520
- | **Degrees** | `graph.degrees()` / `inDegrees()` / `outDegrees()` | - | `{ id: degree }` |
1521
- | **Pregel** | `pregelShortestPaths(graph, 'v0', 10)` | landmark, maxSteps | `{ distances, supersteps }` |
1522
-
1523
- ### Embedding Operations
1524
-
1525
- | Operation | Method | Description |
1526
- |-----------|--------|-------------|
1527
- | **Store Vector** | `service.storeVector('id', [0.1, 0.2, ...])` | Store 384-dim embedding |
1528
- | **Find Similar** | `service.findSimilar('id', 10, 0.7)` | HNSW k-NN search |
1529
- | **Composite Store** | `service.storeComposite('id', JSON.stringify({openai: [...], voyage: [...]}))` | Multi-provider |
1530
- | **Composite Search** | `service.findSimilarComposite('id', 10, 0.7, 'rrf')` | RRF/max/voting aggregation |
1531
- | **1-Hop Cache** | `service.getNeighborsOut('id')` / `getNeighborsIn('id')` | ARCADE neighbor cache |
1532
- | **Rebuild Index** | `service.rebuildIndex()` | Rebuild HNSW index |
271
+ **The audit trail proves the Friday answer came from the same verified query as Monday** - not a new hallucination.
1533
272
 
1534
273
  ---
1535
274
 
1536
- ## Benchmarks
1537
-
1538
- ### Performance (Measured)
1539
-
1540
- | Metric | Value | Rate |
1541
- |--------|-------|------|
1542
- | **Triple Lookup** | 449 ns | 2.2M lookups/sec |
1543
- | **Bulk Insert (100K)** | 682 ms | 146K triples/sec |
1544
- | **Memory per Triple** | 24 bytes | Best-in-class |
1545
-
1546
- ### Industry Comparison
1547
-
1548
- | System | Lookup Speed | Memory/Triple | AI Framework |
1549
- |--------|-------------|---------------|--------------|
1550
- | **rust-kgdb** | **449 ns** | **24 bytes** | **Yes** |
1551
- | RDFox | ~5 µs | 36-89 bytes | No |
1552
- | Virtuoso | ~5 µs | 35-75 bytes | No |
1553
- | Blazegraph | ~100 µs | 100+ bytes | No |
1554
-
1555
- ### AI Agent Accuracy (Verified December 2025)
275
+ ## Embedding-Powered Similarity
1556
276
 
1557
- | Framework | No Schema | With Schema |
1558
- |-----------|-----------|-------------|
1559
- | **Vanilla OpenAI** | 0.0% | 71.4% |
1560
- | **LangChain** | 0.0% | 71.4% |
1561
- | **DSPy** | 14.3% | 71.4% |
277
+ Traditional keyword search fails when:
278
+ - Lawyer searches "breach of fiduciary duty" but case uses "violation of trust obligations"
279
+ - Doctor searches "heart attack" but records say "myocardial infarction"
280
+ - Fraud analyst searches "shell company" but data shows "SPV" or "holding entity"
1562
281
 
1563
- *Schema injection improves ALL frameworks equally. See `verified_benchmark_results.json` for raw data.*
282
+ **Our Approach:**
1564
283
 
1565
- *Tested: GPT-4o, 7 LUBM queries, real API calls.*
1566
-
1567
- ### AI Framework Architectural Comparison
1568
-
1569
- | Framework | Type Safety | Schema Aware | Symbolic Execution | Audit Trail |
1570
- |-----------|-------------|--------------|-------------------|-------------|
1571
- | **HyperMind** | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
1572
- | LangChain | ❌ No | ❌ No | ❌ No | ❌ No |
1573
- | DSPy | ⚠️ Partial | ❌ No | ❌ No | ❌ No |
1574
-
1575
- **Key Insight**: Schema injection (HyperMind's architecture) provides +66.7 pp improvement across ALL frameworks. The value is in the architecture, not the specific framework.
1576
-
1577
- ### Reproduce Benchmarks
1578
-
1579
- Two benchmark scripts are available for verification:
284
+ ```javascript
285
+ const embedding = new EmbeddingService();
1580
286
 
1581
- ```bash
1582
- # JavaScript: HyperMind vs Vanilla LLM on LUBM (12 queries)
1583
- ANTHROPIC_API_KEY=... OPENAI_API_KEY=... node vanilla-vs-hypermind-benchmark.js
287
+ // Store queries with their semantic embeddings
288
+ embedding.store("find_fraud_providers", queryEmbedding);
1584
289
 
1585
- # Python: Compare frameworks (Vanilla, LangChain, DSPy) with/without schema
1586
- OPENAI_API_KEY=... uv run --with openai --with langchain --with langchain-openai --with langchain-core --with dspy-ai python3 benchmark-frameworks.py
290
+ // Later: "which doctors are cheating" matches "find_fraud_providers"
291
+ // because embeddings capture meaning, not just keywords
292
+ const similar = embedding.findSimilar(newQueryEmbedding, 0.85);
1587
293
  ```
1588
294
 
1589
- Both scripts make real API calls and report actual results. No mocking.
295
+ **HNSW Index Performance:**
296
+ - 50,000 vectors: ~20 comparisons (not 50,000)
297
+ - O(log N) search time
298
+ - 16ms for 10K similarity lookups
1590
299
 
1591
- **Why These Features Matter**:
1592
- - **Type Safety**: Tools have typed signatures (Query → BindingSet), invalid combinations rejected
1593
- - **Schema Awareness**: Planner sees your actual data structure, can only reference real properties
1594
- - **Symbolic Execution**: Queries run against real database, not LLM imagination
1595
- - **Audit Trail**: Every answer has cryptographic hash for reproducibility
300
+ **This is how "cases like this one" returns relevant precedents even when the exact words differ.**
1596
301
 
1597
302
  ---
1598
303
 
1599
- ## W3C Standards Compliance
304
+ ## What's In The Box
1600
305
 
1601
- | Standard | Status |
1602
- |----------|--------|
1603
- | **SPARQL 1.1 Query** | 100% |
1604
- | **SPARQL 1.1 Update** | 100% |
1605
- | **RDF 1.2** | 100% |
1606
- | **RDF-Star** | 100% |
1607
- | **Turtle** | 100% |
306
+ | Feature | What It Does | Why It Matters |
307
+ |---------|--------------|----------------|
308
+ | **SPARQL Engine** | Query knowledge graphs (449ns) | Faster than any hosted graph DB |
309
+ | **Datalog Rules** | Derive new facts from rules | Compliance cascades, fraud chains |
310
+ | **GraphFrames** | PageRank, shortest paths, motifs | Find hidden network structures |
311
+ | **Pregel BSP** | Process billion-edge graphs | Scale to enterprise transaction volumes |
312
+ | **HNSW Search** | Find similar items in milliseconds | "Cases like this one" in 16ms |
313
+ | **Audit Trail** | Prove every answer's source | Regulatory compliance, legal discovery |
314
+ | **WASM Sandbox** | Secure agent execution | Run untrusted code safely |
315
+ | **RDF 1.2 + SHACL** | W3C standards compliance | Interop with existing enterprise data |
1608
316
 
1609
317
  ---
1610
318
 
1611
- ## Links
319
+ ## Performance
1612
320
 
1613
- - **npm**: [rust-kgdb](https://www.npmjs.com/package/rust-kgdb)
1614
- - **GitHub**: [gonnect-uk/rust-kgdb](https://github.com/gonnect-uk/rust-kgdb)
1615
- - **Benchmark Report**: [HYPERMIND_BENCHMARK_REPORT.md](./HYPERMIND_BENCHMARK_REPORT.md)
1616
- - **Changelog**: [CHANGELOG.md](./CHANGELOG.md)
321
+ | Metric | rust-kgdb | Typical Graph DB |
322
+ |--------|-----------|------------------|
323
+ | Lookup | 449 ns | 5,000+ ns |
324
+ | Memory | 24 bytes/triple | 60+ bytes |
325
+ | Setup | `npm install` | Days/weeks |
326
+ | Server | None (embedded) | Required |
327
+ | Data Location | Your infrastructure | Their cloud |
1617
328
 
1618
329
  ---
1619
330
 
1620
- ## Advanced Topics
1621
-
1622
- For those interested in the technical foundations of why HyperMind achieves deterministic AI reasoning.
331
+ ## Install
1623
332
 
1624
- ### Why It Works: The Technical Foundation
1625
-
1626
- HyperMind's reliability comes from three mathematical foundations:
1627
-
1628
- | Foundation | What It Does | Practical Benefit |
1629
- |------------|--------------|-------------------|
1630
- | **Schema Awareness** | Auto-extracts your data structure | LLM only generates valid queries |
1631
- | **Typed Tools** | Input/output validation | Prevents invalid tool combinations |
1632
- | **Reasoning Trace** | Records every step | Complete audit trail for compliance |
1633
-
1634
- ### The Reasoning Trace (Audit Trail)
1635
-
1636
- Every HyperMind answer includes a cryptographically-signed derivation showing exactly how the conclusion was reached:
1637
-
1638
- ```
1639
- ┌─────────────────────────────────────────────────────────────────────────────┐
1640
- │ REASONING TRACE │
1641
- │ │
1642
- │ ┌────────────────────────────────┐ │
1643
- │ │ CONCLUSION (Root) │ │
1644
- │ │ "Provider P001 is suspicious" │ │
1645
- │ │ Confidence: 94% │ │
1646
- │ └───────────────┬────────────────┘ │
1647
- │ │ │
1648
- │ ┌───────────────┼───────────────┐ │
1649
- │ │ │ │ │
1650
- │ ▼ ▼ ▼ │
1651
- │ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
1652
- │ │ Database Query │ │ Rule Application │ │ Similarity Match │ │
1653
- │ │ │ │ │ │ │ │
1654
- │ │ Tool: SPARQL │ │ Tool: Datalog │ │ Tool: Embeddings │ │
1655
- │ │ Result: 47 claims│ │ Result: MATCHED │ │ Result: 87% │ │
1656
- │ │ Time: 2.3ms │ │ Rule: fraud(?P) │ │ similar to known │ │
1657
- │ └──────────────────┘ └──────────────────┘ └──────────────────┘ │
1658
- │ │
1659
- │ HASH: sha256:8f3a2b1c4d5e... (Reproducible, Auditable, Verifiable) │
1660
- └─────────────────────────────────────────────────────────────────────────────┘
1661
- ```
1662
-
1663
- ### For Academics: Mathematical Foundations
1664
-
1665
- HyperMind is built on rigorous mathematical foundations:
1666
-
1667
- - **Context Theory** (Spivak's Ologs): Schema represented as a category where objects are classes and morphisms are properties
1668
- - **Type Theory** (Hindley-Milner): Every tool has a typed signature enabling compile-time validation
1669
- - **Proof Theory** (Curry-Howard): Proofs are programs, types are propositions - every conclusion has a derivation
1670
- - **Category Theory**: Tools as morphisms with validated composition
1671
-
1672
- These foundations ensure that HyperMind transforms probabilistic LLM outputs into deterministic, verifiable reasoning chains.
1673
-
1674
- ### Architecture Layers
1675
-
1676
- ```
1677
- ┌─────────────────────────────────────────────────────────────────────────────┐
1678
- │ INTELLIGENCE CONTROL PLANE │
1679
- │ │
1680
- │ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │
1681
- │ │ Schema │ │ Tool │ │ Reasoning │ │
1682
- │ │ Awareness │ │ Validation │ │ Trace │ │
1683
- │ └───────┬────────┘ └───────┬────────┘ └───────┬────────┘ │
1684
- │ └────────────────────┼────────────────────┘ │
1685
- │ ▼ │
1686
- │ ┌─────────────────────────────────────────────────────────────────────┐ │
1687
- │ │ HYPERMIND AGENT │ │
1688
- │ │ User Query → LLM Planner → Typed Execution Plan → Tools → Answer │ │
1689
- │ └─────────────────────────────────────────────────────────────────────┘ │
1690
- │ ▼ │
1691
- │ ┌─────────────────────────────────────────────────────────────────────┐ │
1692
- │ │ rust-kgdb ENGINE │ │
1693
- │ │ • GraphDB (SPARQL 1.1) • GraphFrames (Analytics) │ │
1694
- │ │ • Datalog (Rules) • Embeddings (Similarity) │ │
1695
- │ └─────────────────────────────────────────────────────────────────────┘ │
1696
- └─────────────────────────────────────────────────────────────────────────────┘
1697
- ```
1698
-
1699
- ### Security Model
1700
-
1701
- HyperMind includes capability-based security:
1702
-
1703
- ```javascript
1704
- const agent = new HyperMindAgent({
1705
- kg: db,
1706
- scope: new AgentScope({
1707
- allowedGraphs: ['http://insurance.org/'], // Restrict graph access
1708
- allowedPredicates: ['amount', 'provider'], // Restrict predicates
1709
- maxResultSize: 1000 // Limit result size
1710
- }),
1711
- sandbox: {
1712
- capabilities: ['ReadKG', 'ExecuteTool'], // No WriteKG = read-only
1713
- fuelLimit: 1_000_000 // CPU budget
1714
- }
1715
- })
1716
- ```
1717
-
1718
- ### Distributed Deployment (Kubernetes)
1719
-
1720
- rust-kgdb scales from single-node to distributed cluster on the same codebase.
1721
-
1722
- ```
1723
- ┌─────────────────────────────────────────────────────────────────────────────┐
1724
- │ DISTRIBUTED ARCHITECTURE │
1725
- │ │
1726
- │ ┌─────────────────────────────────────────────────────────────────────┐ │
1727
- │ │ COORDINATOR NODE │ │
1728
- │ │ • Query planning & optimization │ │
1729
- │ │ • HDRF streaming partitioner (subject-anchored) │ │
1730
- │ │ • Raft consensus leader │ │
1731
- │ │ • gRPC routing to executors │ │
1732
- │ └──────────────────────────────┬──────────────────────────────────────┘ │
1733
- │ │ │
1734
- │ ┌───────────────────────┼───────────────────────┐ │
1735
- │ │ │ │ │
1736
- │ ▼ ▼ ▼ │
1737
- │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
1738
- │ │ EXECUTOR 1 │ │ EXECUTOR 2 │ │ EXECUTOR 3 │ │
1739
- │ │ │ │ │ │ │ │
1740
- │ │ Partition 0 │ │ Partition 1 │ │ Partition 2 │ │
1741
- │ │ RocksDB │ │ RocksDB │ │ RocksDB │ │
1742
- │ │ Embeddings │ │ Embeddings │ │ Embeddings │ │
1743
- │ └─────────────┘ └─────────────┘ └─────────────┘ │
1744
- │ │
1745
- └─────────────────────────────────────────────────────────────────────────────┘
1746
- ```
1747
-
1748
- **Deployment with Helm:**
1749
333
  ```bash
1750
- # Deploy to Kubernetes
1751
- helm install rust-kgdb ./infra/helm -n rust-kgdb --create-namespace
1752
-
1753
- # Scale executors
1754
- kubectl scale deployment rust-kgdb-executor --replicas=5 -n rust-kgdb
1755
-
1756
- # Check cluster health
1757
- kubectl get pods -n rust-kgdb
1758
- ```
1759
-
1760
- **Key Distributed Features:**
1761
- | Feature | Description |
1762
- |---------|-------------|
1763
- | **HDRF Partitioning** | Subject-anchored streaming partitioner minimizes edge cuts |
1764
- | **Raft Consensus** | Leader election, log replication, consistency |
1765
- | **gRPC Communication** | Efficient inter-node query routing |
1766
- | **Shadow Partitions** | Zero-downtime rebalancing (~10ms pause) |
1767
- | **DataFusion OLAP** | Arrow-native analytical queries |
1768
-
1769
- ### Memory System
1770
-
1771
- Agents have persistent memory across sessions:
1772
-
1773
- ```javascript
1774
- const agent = new HyperMindAgent({
1775
- kg: db,
1776
- memory: new MemoryManager({
1777
- workingMemorySize: 10, // Current session cache
1778
- episodicRetentionDays: 30, // Episode history
1779
- longTermGraph: 'http://memory/' // Persistent knowledge
1780
- })
1781
- })
1782
- ```
1783
-
1784
- ### Memory Hypergraph: How AI Agents Remember
1785
-
1786
- rust-kgdb introduces the **Memory Hypergraph** - a temporal knowledge graph where agent memory is stored in the *same* quad store as your domain knowledge, with hyper-edges connecting episodes to KG entities.
1787
-
1788
- ```
1789
- ┌─────────────────────────────────────────────────────────────────────────────────┐
1790
- │ MEMORY HYPERGRAPH ARCHITECTURE │
1791
- │ │
1792
- │ ┌─────────────────────────────────────────────────────────────────────────┐ │
1793
- │ │ AGENT MEMORY LAYER (am: graph) │ │
1794
- │ │ │ │
1795
- │ │ Episode:001 Episode:002 Episode:003 │ │
1796
- │ │ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ │
1797
- │ │ │ Fraud ring │ │ Underwriting │ │ Follow-up │ │ │
1798
- │ │ │ detected in │ │ denied claim │ │ investigation │ │ │
1799
- │ │ │ Provider P001 │ │ from P001 │ │ on P001 │ │ │
1800
- │ │ │ │ │ │ │ │ │ │
1801
- │ │ │ Dec 10, 14:30 │ │ Dec 12, 09:15 │ │ Dec 15, 11:00 │ │ │
1802
- │ │ │ Score: 0.95 │ │ Score: 0.87 │ │ Score: 0.92 │ │ │
1803
- │ │ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘ │ │
1804
- │ │ │ │ │ │ │
1805
- │ └───────────┼─────────────────────────┼─────────────────────────┼─────────┘ │
1806
- │ │ HyperEdge: │ HyperEdge: │ │
1807
- │ │ "QueriedKG" │ "DeniedClaim" │ │
1808
- │ ▼ ▼ ▼ │
1809
- │ ┌─────────────────────────────────────────────────────────────────────────┐ │
1810
- │ │ KNOWLEDGE GRAPH LAYER (domain graph) │ │
1811
- │ │ │ │
1812
- │ │ Provider:P001 ──────────────▶ Claim:C123 ◀────────── Claimant:C001 │ │
1813
- │ │ │ │ │ │ │
1814
- │ │ │ :hasRiskScore │ :amount │ :name │ │
1815
- │ │ ▼ ▼ ▼ │ │
1816
- │ │ "0.87" "50000" "John Doe" │ │
1817
- │ │ │ │
1818
- │ │ ┌─────────────────────────────────────────────────────────────┐ │ │
1819
- │ │ │ SAME QUAD STORE - Single SPARQL query traverses BOTH │ │ │
1820
- │ │ │ memory graph AND knowledge graph! │ │ │
1821
- │ │ └─────────────────────────────────────────────────────────────┘ │ │
1822
- │ │ │ │
1823
- │ └─────────────────────────────────────────────────────────────────────────┘ │
1824
- │ │
1825
- │ ┌─────────────────────────────────────────────────────────────────────────┐ │
1826
- │ │ TEMPORAL SCORING FORMULA │ │
1827
- │ │ │ │
1828
- │ │ Score = α × Recency + β × Relevance + γ × Importance │ │
1829
- │ │ │ │
1830
- │ │ where: │ │
1831
- │ │ Recency = 0.995^hours (12% decay/day) │ │
1832
- │ │ Relevance = cosine_similarity(query, episode) │ │
1833
- │ │ Importance = log10(access_count + 1) / log10(max + 1) │ │
1834
- │ │ │ │
1835
- │ │ Default: α=0.3, β=0.5, γ=0.2 │ │
1836
- │ └─────────────────────────────────────────────────────────────────────────┘ │
1837
- │ │
1838
- └─────────────────────────────────────────────────────────────────────────────────┘
1839
- ```
1840
-
1841
- **Without Memory Hypergraph** (LangChain, LlamaIndex):
1842
- ```javascript
1843
- // Ask about last week's findings
1844
- agent.chat("What fraud patterns did we find with Provider P001?")
1845
- // Response: "I don't have that information. Could you describe what you're looking for?"
1846
- // Cost: Re-run entire fraud detection pipeline ($5 in API calls, 30 seconds)
1847
- ```
1848
-
1849
- **With Memory Hypergraph** (rust-kgdb HyperMind Framework):
1850
- ```javascript
1851
- // HyperMind API: Recall memories with KG context
1852
- const enrichedMemories = await agent.recallWithKG({
1853
- query: "Provider P001 fraud",
1854
- kgFilter: { predicate: ":amount", operator: ">", value: 25000 },
1855
- limit: 10
1856
- })
1857
-
1858
- // Returns typed results with linked KG context:
1859
- // {
1860
- // episode: "Episode:001",
1861
- // finding: "Fraud ring detected in Provider P001",
1862
- // kgContext: {
1863
- // provider: "Provider:P001",
1864
- // claims: [{ id: "Claim:C123", amount: 50000 }],
1865
- // riskScore: 0.87
1866
- // },
1867
- // semanticHash: "semhash:fraud-provider-p001-ring-detection"
1868
- // }
1869
- ```
1870
-
1871
- #### Semantic Hashing for Idempotent Responses
1872
-
1873
- Same question = Same answer. Even with **different wording**. Critical for compliance.
1874
-
1875
- ```javascript
1876
- // First call: Compute answer, cache with semantic hash
1877
- const result1 = await agent.call("Analyze claims from Provider P001")
1878
- // Semantic Hash: semhash:fraud-provider-p001-claims-analysis
1879
-
1880
- // Second call (different wording, same intent): Cache HIT!
1881
- const result2 = await agent.call("Show me P001's claim patterns")
1882
- // Cache HIT - same semantic hash
1883
-
1884
- // Compliance officer: "Why are these identical?"
1885
- // You: "Semantic hashing - same meaning, same output, regardless of phrasing."
1886
- ```
1887
-
1888
- **How it works**: Query embeddings are hashed via **Locality-Sensitive Hashing (LSH)** with random hyperplane projections. Semantically similar queries map to the same bucket.
1889
-
1890
- ### HyperMind vs MCP (Model Context Protocol)
1891
-
1892
- Why domain-enriched proxies beat generic function calling:
1893
-
1894
- ```
1895
- ┌───────────────────────┬──────────────────────┬──────────────────────────┐
1896
- │ Feature │ MCP │ HyperMind Proxy │
1897
- ├───────────────────────┼──────────────────────┼──────────────────────────┤
1898
- │ Type Safety │ ❌ String only │ ✅ Full type system │
1899
- │ Domain Knowledge │ ❌ Generic │ ✅ Domain-enriched │
1900
- │ Tool Composition │ ❌ Isolated │ ✅ Morphism composition │
1901
- │ Validation │ ❌ Runtime │ ✅ Compile-time │
1902
- │ Security │ ❌ None │ ✅ WASM sandbox │
1903
- │ Audit Trail │ ❌ None │ ✅ Execution witness │
1904
- │ LLM Context │ ❌ Generic schema │ ✅ Rich domain hints │
1905
- │ Capability Control │ ❌ All or nothing │ ✅ Fine-grained caps │
1906
- ├───────────────────────┼──────────────────────┼──────────────────────────┤
1907
- │ Result │ 60% accuracy │ 95%+ accuracy │
1908
- └───────────────────────┴──────────────────────┴──────────────────────────┘
334
+ npm install rust-kgdb
1909
335
  ```
1910
336
 
1911
- **MCP**: LLM generates query → hope it works
1912
- **HyperMind**: LLM selects tools → type system validates → guaranteed correct
1913
-
1914
337
  ```javascript
1915
- // MCP APPROACH (Generic function calling)
1916
- // Tool: search_database(query: string)
1917
- // LLM generates: "SELECT * FROM claims WHERE suspicious = true"
1918
- // Result: ❌ SQL injection risk, "suspicious" column doesn't exist
1919
-
1920
- // HYPERMIND APPROACH (Domain-enriched proxy)
1921
- // Tool: kg.datalog.infer with fraud rules
1922
- const result = await agent.call('Find collusion patterns')
1923
- // Result: ✅ Type-safe, domain-aware, auditable
1924
- ```
338
+ const { GraphDB } = require('rust-kgdb');
1925
339
 
1926
- ### Why Vanilla LLMs Fail
340
+ const db = new GraphDB('http://example.org/');
341
+ db.loadTtl(':Alice :knows :Bob . :Bob :knows :Charlie .');
1927
342
 
1928
- When you ask an LLM to query a knowledge graph, it produces **broken SPARQL 85% of the time**:
1929
-
1930
- ```
1931
- User: "Find all professors"
1932
-
1933
- Vanilla LLM Output:
1934
- ┌───────────────────────────────────────────────────────────────────────┐
1935
- │ ```sparql │
1936
- │ PREFIX ub: <http://swat.cse.lehigh.edu/onto/univ-bench.owl#> │
1937
- │ SELECT ?professor WHERE { │
1938
- │ ?professor a ub:Faculty . ← WRONG! Schema has "Professor" │
1939
- │ } │
1940
- │ ``` ← Parser rejects markdown │
1941
- │ │
1942
- │ This query retrieves all faculty members from the LUBM dataset. │
1943
- │ ↑ Explanation text breaks parsing │
1944
- └───────────────────────────────────────────────────────────────────────┘
1945
- Result: ❌ PARSER ERROR - Invalid SPARQL syntax
1946
- ```
1947
-
1948
- **Why it fails:**
1949
- 1. LLM wraps query in markdown code blocks → parser chokes
1950
- 2. LLM adds explanation text → mixed with query syntax
1951
- 3. LLM hallucinates class names → `ub:Faculty` doesn't exist (it's `ub:Professor`)
1952
- 4. LLM has no schema awareness → guesses predicates and classes
1953
-
1954
- **HyperMind fixes all of this** with schema injection and typed tools, achieving **71% accuracy** vs **0% for vanilla LLMs without schema**.
1955
-
1956
- ### Competitive Landscape
1957
-
1958
- #### Triple Stores Comparison
1959
-
1960
- | System | Lookup Speed | Memory/Triple | WCOJ | Mobile | AI Framework |
1961
- |--------|-------------|---------------|------|--------|--------------|
1962
- | **rust-kgdb** | **449 ns** | **24 bytes** | ✅ Yes | ✅ Yes | ✅ HyperMind |
1963
- | Tentris | ~5 µs | ~30 bytes | ✅ Yes | ❌ No | ❌ No |
1964
- | RDFox | ~5 µs | 36-89 bytes | ❌ No | ❌ No | ❌ No |
1965
- | AllegroGraph | ~10 µs | 50+ bytes | ❌ No | ❌ No | ❌ No |
1966
- | Virtuoso | ~5 µs | 35-75 bytes | ❌ No | ❌ No | ❌ No |
1967
- | Blazegraph | ~100 µs | 100+ bytes | ❌ No | ❌ No | ❌ No |
1968
- | Apache Jena | 150+ µs | 50-60 bytes | ❌ No | ❌ No | ❌ No |
1969
- | Neo4j | ~5 µs | 70+ bytes | ❌ No | ❌ No | ❌ No |
1970
- | Amazon Neptune | ~5 µs | N/A (managed) | ❌ No | ❌ No | ❌ No |
1971
-
1972
- **Note**: Tentris implements WCOJ (see [ISWC 2025 paper](https://papers.dice-research.org/2025/ISWC_Tentris-WCOJ-Update/public.pdf)). rust-kgdb is the only system combining WCOJ with mobile support and integrated AI framework.
1973
-
1974
- #### AI Framework Architectural Comparison
1975
-
1976
- | Framework | Type Safety | Schema Aware | Symbolic Execution | Audit Trail |
1977
- |-----------|-------------|--------------|-------------------|-------------|
1978
- | **HyperMind** | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
1979
- | LangChain | ❌ No | ❌ No | ❌ No | ❌ No |
1980
- | DSPy | ⚠️ Partial | ❌ No | ❌ No | ❌ No |
1981
-
1982
- **Note**: This compares architectural features. Benchmark (Dec 2025): Schema injection brings all frameworks to ~71% accuracy equally.
1983
-
1984
- ```
1985
- ┌─────────────────────────────────────────────────────────────────┐
1986
- │ COMPETITIVE LANDSCAPE │
1987
- ├─────────────────────────────────────────────────────────────────┤
1988
- │ │
1989
- │ Tentris: WCOJ-optimized, but no mobile or AI framework │
1990
- │ RDFox: Fast commercial, but expensive, no mobile │
1991
- │ AllegroGraph: Enterprise features, but slower, no mobile │
1992
- │ Apache Jena: Great features, but 150+ µs lookups │
1993
- │ Neo4j: Popular, but no SPARQL/RDF standards │
1994
- │ Amazon Neptune: Managed, but cloud-only vendor lock-in │
1995
- │ │
1996
- │ rust-kgdb: 449 ns lookups, WCOJ joins, mobile-native │
1997
- │ Standalone → Clustered on same codebase │
1998
- │ Deterministic planner, audit-ready │
1999
- │ │
2000
- └─────────────────────────────────────────────────────────────────┘
343
+ const results = db.query('SELECT ?x WHERE { :Alice :knows ?x }');
344
+ // [{x: ':Bob'}]
2001
345
  ```
2002
346
 
2003
347
  ---
2004
348
 
2005
- ## License
349
+ ## Links
350
+
351
+ - [Examples](./examples/)
352
+ - [GitHub](https://github.com/gonnect-uk/rust-kgdb)
2006
353
 
2007
- Apache 2.0
354
+ Apache 2.0 License