CortexDB
by cndoin
README.md
# CortexDB
[](https://github.com/cndoin/CortexDB/actions/workflows/ci.yml)
[](https://nodejs.org)
[](https://modelcontextprotocol.io)
[](LICENSE)
**A deterministic AI memory engine, powered by TC-SynPPR (Temporal-Causal Synaptic Personalized PageRank).**
An agent's memory is not a document store. Facts get *corrected*, vocabularies *migrate*, and chains of causation carry meaning that no single sentence contains. CortexDB is built around three claims about that problem, plus a benchmark that tries honestly to falsify them.
<p align="center">
<img src="screenshots/inspector-graph.png" alt="CortexDB inspector showing a graph walk with per-hop provenance" width="880">
</p>
<p align="center">
<img src="screenshots/inspector-benchmark.png" alt="Benchmark panel: two fairness tiers, per-kind recall, and the runner's own verdict including the losses" width="440">
<img src="screenshots/verifier.png" alt="Guardrail verifier showing a BLOCKED verdict with the matched text" width="440">
</p>
---
## Supported agents & 10-second setup
```bash
npx github:cndoin/CortexDB install # works straight from GitHub, no clone
npx github:cndoin/CortexDB init-rules # teaches the agent WHEN to call the memory tools
```
Because `dist/` is a build artifact and not committed, `package.json` carries a `prepare`
script that compiles **only** the CLI and MCP bundle on install — roughly two seconds, not the
Next.js web build. That is what makes the command above work on a machine that has never seen
this repository.
If you have already installed the package, the short forms are `npx cortexdb install` and
`npx cortexdb ui`.
`install` finds your agents by their standard config paths, backs up each file it touches as
`<name>.<timestamp>.bak`, and prints what it changed. `init-rules` appends a fenced protocol
block to `AGENTS.md`, `CLAUDE.md` and `.cursorrules`. Both are idempotent: run them twice and
the second run reports `unchanged`.
| Agent | Config file it writes | Format | One command |
|---|---|---|---|
| **Claude Code** | `~/.claude.json` | JSON | `npx cortexdb install --target claude-code` |
| **OpenAI Codex CLI** | `~/.codex/config.toml` | TOML | `npx cortexdb install --target codex` |
| **Cursor** | `~/.cursor/mcp.json` | JSON | `npx cortexdb install --target cursor` |
| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | JSON | `npx cortexdb install --target windsurf` |
| **Cline / Roo Code** | VS Code `globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` | JSON | `npx cortexdb install --target cline` |
| **Claude Desktop** | `claude_desktop_config.json` (OS-specific, below) | JSON | `npx cortexdb install --target claude-desktop` |
| **Hermes / any other MCP client** | you edit it | JSON | see the snippet below |
Run `npx cortexdb install --dry-run` to see what it would do, and `npx cortexdb doctor` to
check the server path, the database location and which agents were detected.
### See what your agents actually remembered
```bash
npx cortexdb ui # http://localhost:3333
npx cortexdb ui --port 4000 # somewhere else
```
The memories Claude Code, Codex and Cursor write live in `~/.cortexdb/memory.db`. `ui` points
the inspector at exactly that database and prints the URL, so you can watch the graph rather
than trusting that it works. On first run it builds the inspector (~1 minute); after that it
starts in under a second. `--db <path>` inspects a different database.
### All five commands
| Command | What it does |
|---|---|
| `cortexdb install` | Registers the MCP server with every agent it can detect |
| `cortexdb init-rules` | Writes the Memory & Guardrail Protocol into `AGENTS.md` / `CLAUDE.md` / `.cursorrules` |
| `cortexdb ui` | Opens the web inspector against your global memory database |
| `cortexdb mcp` | Runs the MCP server on stdio (what agents call, not what you call) |
| `cortexdb doctor` | Checks the server, database, Node version and detected agents |
<details>
<summary><b>Manual setup</b> — if you would rather edit the file yourself</summary>
Every client below uses the same entry, with two absolute paths substituted. The server is
`dist/mcp/server.js`; the database defaults to `~/.cortexdb/memory.db` and is created on
first use.
**JSON clients** (Claude Code, Cursor, Windsurf, Cline, Claude Desktop, Hermes):
```json
{
"mcpServers": {
"cortexdb": {
"command": "node",
"args": ["/absolute/path/to/CortexDB/dist/mcp/server.js"],
"env": { "CORTEXDB_PATH": "/absolute/path/to/.cortexdb/memory.db" }
}
}
}
```
Merge that `cortexdb` key into any existing `mcpServers` object. Do not replace the object:
the other servers in it are how the rest of your setup works.
**OpenAI Codex CLI** (`~/.codex/config.toml`):
```toml
[mcp_servers.cortexdb]
command = "node"
args = ["/absolute/path/to/CortexDB/dist/mcp/server.js"]
[mcp_servers.cortexdb.env]
CORTEXDB_PATH = "/absolute/path/to/.cortexdb/memory.db"
```
On Windows the paths need doubled backslashes inside the TOML strings
(`"C:\\Users\\you\\CortexDB\\dist\\mcp\\server.js"`). The installer does that escaping for you.
**Claude Desktop config locations:**
| OS | Path |
|---|---|
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |
Restart the client after editing. A config change is not picked up by a running process,
which is the single most common reason an install appears not to have worked.
</details>
<details>
<summary><b>What <code>init-rules</code> appends</b></summary>
The block is fenced by `<!-- cortexdb:protocol:start -->` and `<!-- cortexdb:protocol:end -->`,
so a second run replaces it rather than appending a copy. It is deliberately four call sites
long — a longer protocol gets skimmed and then ignored.
It covers: read memory before answering questions about prior decisions; write a fact when one
is established (and supersede rather than duplicate); record causation with typed edges; check
guardrails before destructive actions; and reinforce only what verifiably succeeded.
</details>
## The three claims
### 1. A correction is an interval, not an overwrite
Every fact carries `valid_from` and `invalidated_at`. Superseding a fact does **not** delete it: the old row keeps an end bound, and a `REPLACED_BY` edge points at the current truth.
This is not sentimentality about history. It is what makes stale-fact leakage a *measurable quantity* instead of an invisible one. A store that silently overwrites cannot tell you whether it answered with a fact that stopped being true three weeks ago — it has no record that the fact ever existed.
$$
\text{live}(n, t) = \begin{cases} 1 & \text{if } \text{invalidated\_at}(n) = \varnothing \ \lor\ t < \text{invalidated\_at}(n) \\ 0 & \text{otherwise} \end{cases}
$$
### 2. Recency matters, but not equally for every fact
$$
w_i = \mathbb{1}\!\left[\text{invalidated}_i = \varnothing\right] \cdot \alpha_i \cdot \left(0.15 + 0.85 \cdot e^{-\Delta t_i / \left(\tau_0 (1 + \gamma \ln(1 + c_i))\right)}\right)
$$
| symbol | meaning | default |
|---|---|---|
| $\alpha_i$ | source authority: `USER_STATED` → 1.0, `AI_INFERRED` → 0.6 | — |
| $\Delta t_i$ | seconds since last activation | — |
| $\tau_0$ | base timescale | 3600 s |
| $\gamma$ | validation stretch | 0.35 |
| $c_i$ | times this fact has been reconfirmed | — |
Two details are load-bearing:
- **The $0.15$ floor.** Decay approaches 15% of authority, never zero. A fact that is merely *old* must stay reachable; old is not the same as wrong.
- **$\ln(1 + c_i)$.** Reconfirmation extends the timescale logarithmically — diminishing returns, not immortality.
### 3. A rename must be walkable
This is the piece that earns its keep, and the one I got wrong first.
If "the events bucket" is renamed to "the audit stream", a user who has not seen the rename asks with the **old** words. A lexical or vector retriever then does one of two bad things: returns the dead fact, or returns nothing at all. Filtering dead rows is not a fix — it converts a wrong answer into a missing one.
TC-SynPPR splits "where does the query enter the graph" from "what may I show the user":
- An invalidated node **can be seeded**, so stale vocabulary still lands on it.
- ALL of its outgoing transition mass is then routed along `REPLACED_BY` to the live successor.
- It is **never returned** — the output ranking applies $w_i = 0$ to it.
$$
M_{ij} = \begin{cases} \dfrac{\phi(\text{kind}(i \to j))}{\sum_{k} \phi(\text{kind}(i \to k))} & \text{live } i \\[6pt] \mathbb{1}\!\left[j = \text{redirect}(i)\right] & \text{invalidated } i \text{ with a live successor} \end{cases}
$$
Causal edge weights $\phi$: `CAUSED_BY` 1.0, `SUPPORTS` 1.0, `CONSTRAINED_BY` 1.5, `REPLACED_BY` 2.0.
The walk itself is damped power iteration:
$$
r^{(t+1)} = (1 - d)\,p + d\,M\,r^{(t)}, \qquad d = 0.85
$$
---
## Architecture
```mermaid
flowchart TB
subgraph clients["Clients"]
MCP["MCP client<br/>(Claude Code, Codex, DSH)"]
UI["Web Inspector<br/>(Next.js)"]
CLI["Benchmark CLI"]
end
subgraph surface["Surfaces"]
SRV["MCP stdio server<br/>8 tools"]
API["REST routes<br/>5 endpoints"]
end
subgraph svc["MemoryService"]
direction TB
UP["upsert / recordCausal<br/>reinforce / rollback"]
QR["query / compileContext<br/>explain / timeline"]
end
subgraph engine["TC-SynPPR engine"]
direction TB
IDX["Corpus index<br/>inverted postings + IDF"]
SEED["Seed vector<br/>similarity × compressed decay"]
TRANS["Transition matrix<br/>φ weights + REPLACED_BY redirect"]
PPR["Power iteration<br/>d=0.85, ≤20 iters"]
COMP["Context compiler<br/>hard token ceiling"]
end
subgraph store["SQLite (WAL)"]
direction TB
NODES[("memory_nodes<br/>bi-temporal")]
EDGES[("memory_edges<br/>typed, weighted")]
FTS[("memory_fts<br/>FTS5 porter")]
COMMITS[("memory_commits<br/>+ commit_ops")]
VEC[("memory_embeddings<br/>Float32 blobs, content-keyed")]
end
MCP --> SRV
UI --> API
CLI --> QR
SRV --> UP
SRV --> QR
API --> UP
API --> QR
UP --> NODES
UP --> EDGES
UP --> COMMITS
QR --> IDX --> SEED --> TRANS --> PPR
QR --> COMP
NODES -.-> IDX
EDGES -.-> TRANS
EMB -.->|cached by content hash| VEC
COMMITS -.->|rollback replays ops| NODES
style engine fill:#12161f,stroke:#2f6fd0,color:#d7e0ee
style store fill:#12161f,stroke:#1f2633,color:#d7e0ee
style svc fill:#0f141c,stroke:#1f2633,color:#d7e0ee
```
---
## Benchmark
Six systems, one corpus, one grader, **two fairness tiers**. Run with `npm run benchmark`.
**Corpus:** 6,820 facts · 250 four-stage chains · 250 five-hop evolution chains · 1,950 edges · 5,000 distractors · **510 queries** (100 update, 200 multi-hop, 60 guardrail, 100 two-hop migration, 50 five-hop migration), deterministic under seed `0x5eed1234`.
**Embeddings:** real neural vectors, not TF-IDF. `Xenova/all-MiniLM-L6-v2` runs locally through ONNX (quantized, 384 dimensions, ~22 MB, no API key, no network after first download). Vectors are cached in SQLite as Float32 blobs keyed by a content hash, so a re-run reuses them. The benchmark prints which embedder produced its numbers, and a run without the model says `SPARSE TF-IDF` rather than quietly presenting sparse numbers as neural.
The 20 guardrail rules are stated early and buried under **5,000 later turns spanning 83 hours** of corpus time — a checked property of the timeline, not of the source order. An earlier version emitted the rules first and then the distractors, so nothing followed them and the decay term never had to work; the rule text was fine and the test was empty.
Query counts are fixed, not incidental. An earlier version had **6** multi-hop queries, where one unlucky case moves the mean by 17 points. That is not a measurement. The corpus now validates its own invariants at generation time — unique answer per query, genuine zero lexical overlap on multi-hop chains, guarded burial, unique generated terms, and a minimum sample size per kind — and **throws** rather than producing a corpus whose grader is wrong.
### Tier A — the fair comparison
Every system here knows about `invalidated_at` and refuses to return a superseded fact. The question: *given that everyone filters dead rows, does the graph traversal and the `REPLACED_BY` redirect add anything?* Denying the baselines that filter would manufacture a win rather than demonstrate one.
| System | R@5 | R@10 | NDCG@10 | MRR | Stale leak | Hijack | p50 | p99 |
|---|---:|---:|---:|---:|---:|---:|---:|---:|
| BM25-Filtered | 43.53% | 46.08% | 40.96% | 0.394 | 0.00% | **0.00%** | **9.04** | 18.06 |
| Dense-Neural-Filtered | 39.41% | 42.75% | 36.96% | 0.351 | 0.00% | **0.00%** | 5.11 | 19.18 |
| Static-Graph-PPR-Filtered | 83.73% | 86.27% | 65.17% | 0.583 | 0.00% | **0.00%** | 19.06 | 35.01 |
| **TC-SynPPR** | **95.88%** | **96.67%** | **71.97%** | **0.638** | 0.00% | **0.00%** | 7.50 | 41.38 |
`Static-Graph-PPR-Filtered` deliberately keeps **identical** text representation and damping — only the temporal layer and the redirect are absent. Degrading it would make the comparison meaningless.
**`Hijack` is the metric that stops "raise guardrail recall" from being free.** It counts how often a guardrail rule takes the **top rank** on a query that was not about rules. Zero is the only acceptable value, and it is measured rather than asserted.
### Tier B — the real-world default (not a fair fight)
No bi-temporal state at all: rows are appended and nothing knows the old version died. This tier exists to **quantify** what staleness costs, because with Tier A alone every system leaks 0% and the metric is decorative.
| System | R@5 | R@10 | NDCG@10 | MRR | Stale leak | Stale share | p50 |
|---|---:|---:|---:|---:|---:|---:|---:|
| BM25-Unfiltered | 40.39% | 43.73% | 28.74% | 0.240 | **32.35%** | 7.6% | 2.30 |
| Standard-Dense-RAG-Unfiltered | 35.69% | 40.00% | 25.89% | 0.213 | **28.92%** | 7.6% | 5.16 |
**An unfiltered store returns a superseded fact for one query in three.** Its NDCG collapses to ~26–29% because dead rows occupy the top slots and the live answer gets pushed down. Reported as a *measurement, not a victory* — beating a system that cannot see invalidation proves nothing about the algorithm.
### By query kind (Recall@10)
| System | update<br/>n=100 | multihop<br/>n=200 | migration<br/>old vocab<br/>n=50 | migration<br/>control<br/>n=50 | **5-hop<br/>n=50** | guardrail<br/>n=60 |
|---|---:|---:|---:|---:|---:|---:|
| BM25-Filtered | 100.0% | 0.0% | 18.0% | 100.0% | 80.0% | **75.0%** |
| Dense-Neural-Filtered | 100.0% | 0.0% | 6.0% | 100.0% | 34.0% | **83.3%** |
| Static-Graph-PPR-Filtered | 100.0% | 75.0% | **100.0%** | 100.0% | 98.0% | 71.7% |
| **TC-SynPPR** | 100.0% | **99.5%** | 98.0% | 100.0% | **100.0%** | 75.0% |
| BM25-Unfiltered | 100.0% | 0.0% | 0.0% | 100.0% | 58.0% | 73.3% |
| Standard-Dense-RAG-Unfiltered | 100.0% | 0.0% | 0.0% | 100.0% | 18.0% | 81.7% |
**The five-hop column is the one the two-hop migration could not produce.** A two-hop rename is handled correctly by a plain "blank the dead row" transition matrix, so both graph systems scored 100% and the redirect proved nothing. A five-hop chain changes that: the mass has to survive four intermediate invalidations, and each deprecated node also links to a plausible but abandoned branch, so a walker that follows *any* outbound edge from a dead node lands on the wrong terminus. Static-PPR gets 98% (it loses one chain to the branch); TC-SynPPR gets 100%. **That is the clean separation, and it is reported as its own query kind so a regression shows up by name instead of being averaged away.**
The **two-hop migration split** is still reported because it separates the graph systems from the lexical ones:
- **old vocab** names *only retired words*. The live answer contains none of them, so it is lexically unreachable — BM25 gets 18%, the dense baseline 6%, both unfiltered stores 0%. Only a system that follows `REPLACED_BY` from the dead vocabulary reaches it.
- **control** asks the same question in the *new* words. Everyone scores 100%. Reporting a single combined "migration" number would let that control success hide the real failure.
### Where CortexDB loses
Stated plainly, because a benchmark that only reports wins is marketing:
- **Latency, still.** The dense baseline is faster at both percentiles (5.14 ms vs 7.20 ms at p50; 14.06 ms vs 24.4 ms at p99). Inherent: a sparse cosine is one lookup, a PageRank walk is 20 sparse matrix-vector products plus a neural encode. This would matter for a high-QPS autocomplete; an agent's memory is called a handful of times per task. After the profiling work below it is no longer the 3× gap it was, but it is not gone.
- **Guardrail recall loses to Dense-Neural-Filtered**, 75.0% vs **83.3%** over 60 queries. It ties BM25 at 75.0%. RRF fusion genuinely recovers 5 of 60 queries the graph ranking misses (63.3% → 71.7% with fusion on versus off) and the hijack rate stays at 0.00%, but that is still 8.3 points behind a sparse cosine that matches rule vocabulary directly. Guardrail queries are paraphrases of short imperative rules, which is the case where exact-token matching is simply the right tool and a graph walk is not.
- **The unfiltered dense baseline also beats TC-SynPPR on guardrails** (81.7% vs 75.0%), which is the same effect from the other direction: rule text is lexically distinctive, so any similarity model over raw text does well. This is reported as the loss it is.
- **Two-hop migration old-vocab is a LOSS against Static-Graph-PPR**, 98.0% vs 100.0%. The blank-transition-row baseline already routes correctly on the two-hop case, so this corpus does not separate the two graph systems there — and TC-SynPPR gives up two points rather than tying. It is the five-hop chains that separate them, and on those TC-SynPPR wins 100% to 98%.
- **NDCG@10 of 71.97% is only 6.8 points above Static-PPR** despite 10.4 points of recall advantage: the walk finds the right fact, but intermediates on the chain carry real mass too, so it often sits at position 2 or 3. Reported, not smoothed.
- **The neural encoder does not help multi-hop, and the diagnostics say why.** The correct root-cause fact ranks ~1,504th of 1,820 by neural similarity to the symptom question — it is semantically unlike the symptom by construction, because "no shared vocabulary" also means "no shared meaning" to a sentence encoder. Multi-hop is reached by *walking edges*, not by embedding similarity. The encoder earns its place on migration and guardrail wording, not here.
## Quick start
```bash
npm install
npm run build # dist/cli.js + dist/mcp/server.js + the inspector
npx cortexdb install # wires yourself into every agent it can find
npx cortexdb init-rules
```
For the engine itself:
```bash
npm run benchmark # writes BENCHMARK_RESULTS.json + .md
npm test # 251 unit tests
npm run typecheck # tsc --noEmit, zero errors
npm run dev # inspector on http://127.0.0.1:3100
```
### Use it as an MCP server
The one-command path is at the top of this file. The manual equivalent, for any client:
```jsonc
// claude_desktop_config.json / .mcp.json / equivalents
{
"mcpServers": {
"cortexdb": {
"command": "node",
"args": ["/absolute/path/to/CortexDB/dist/mcp/server.js"],
"env": { "CORTEXDB_PATH": "/absolute/path/to/cortexdb.db" }
}
}
}
```
`npx cortexdb mcp` runs the same server on stdio without any config, which is the quickest
way to check that it starts on a machine where the paths are still unknown.
| Tool | What it does |
|---|---|
| `memory_upsert` | Store a fact; `replaces` invalidates predecessors and wires `REPLACED_BY` |
| `memory_record_causal` | Link two facts with a typed causal edge |
| `memory_compile_context` | Token-bounded XML fragment, guardrails reserved first |
| `memory_reinforce` | Raise `validation_count`, strengthen co-activated edges |
| `memory_rollback` | Exact undo by replaying commit ops in reverse |
| `memory_log` | Commit history, newest first |
| `memory_rollback_preview` | What a rollback *would* change, changing nothing |
| `memory_verify_action` | Check a proposed command against stored guardrails **before** running it |
The tool descriptions state what the engine **cannot** do. `memory_reinforce` says so explicitly: the engine cannot distinguish a task that succeeded from an agent that believes it succeeded, so reinforcing a wrong answer entrenches the wrong answer.
### Executable guardrails
Context injection is advice. `memory_verify_action` is an interlock:
```jsonc
// call
{ "proposed_code_or_command": "git push --force origin main",
"context_query": "pushing a fix to a shared branch" }
// result
{ "verdict": "BLOCKED",
"enforced": true,
"violations": [{
"ruleId": "guard-force-push",
"ruleText": "Never force-push to a shared branch.",
"kind": "anti-pattern",
"matched": "git push --force",
"pattern": "git\\s+push[^\\n]*--force(?![-a-z])",
"explanation": "a force-push rewrites history that other people have already pulled"
}]}
```
**Read `enforced` before treating `PASS` as approval.** When it is `false`, no stored rule could be expressed as a pattern, so `PASS` means *nothing was checked*, not *this is safe*. The payload says that in words too, because an agent that reads only the JSON will otherwise stop at the verdict.
Guardrails gain optional `anti_pattern_regex`, `required_pattern_regex` and `severity` (`block` / `warn` / `info`). A `block` match wins over a `warn`; an `info` match is reported and changes nothing. Patterns are compiled case-insensitively and without flags, so repeated verification is deterministic — a guardrail that can be argued with is not a guardrail, and neither is one whose verdict drifts.
Two real false positives are recorded as tests, because both would have taught a user to disable the interlock:
- `DELETE FROM orders WHERE id = 42` was blocked as an unfiltered delete. The negative lookahead `(?!WHERE)` let the regex engine backtrack to a shorter `\w+` match. Fixed by applying the lookahead to the statement tail.
- `rm -rf ./node_modules` was blocked as a root delete. The `\.` alternative matched the leading `.`. Fixed by anchoring the token end.
A rule that is only prose is reported as `enforceable: false` rather than silently passing. A malformed regex is reported as a **violation**, because a rule that cannot be compiled is broken, not satisfied.
---
## The Inspector
Six panels, each reading real engine state — nothing is fabricated at render time.
<p align="center">
<img src="screenshots/inspector-context.png" alt="Context compiler" width="880">
</p>
| Panel | Shows |
|---|---|
| **Graph walk** | Ranked memories with `via` provenance, seed vector, the `REPLACED_BY` redirects that fired with their transferred energy, and the per-iteration residual curve |
| **Context compiler** | The exact XML handed to the model, block-by-block token accounting, and the omissions |
| **Bi-temporal** | Live vs superseded, with each fact's activity weight and every typed edge with its $\phi$ |
| **Commits** | Hash, message, operation count, and one-click rollback |
| **Benchmark** | The measured table, by-kind breakdown, and the runner's own verdict — including the losses |
| **Guardrail verifier** | Type a command, get PASS/WARN/BLOCKED with the exact rule, pattern and matched text, plus which rules are actually enforceable |
<p align="center">
<img src="screenshots/verifier.png" alt="Guardrail verifier showing a BLOCKED verdict with the matched text" width="880">
</p>
---
## What is in the tests
251 unit tests and 17 Playwright tests. They assert **properties**, not fixtures:
- An invalidated node is never in the output ranking, **but can still seed a query** — the two halves of the redirect, which must hold simultaneously or the migration case silently degrades to "filter dead rows".
- Total mass is preserved at 1.0 across iterations, including dangling redistribution.
- `REPLACED_BY` sends **all** of an invalidated node's mass to its successor, and never to another corpse.
- A correction undoes to *exactly* the prior state — rollback replays recorded operations in reverse.
- The compiled context **never** exceeds its budget, swept across 14 budget sizes from 10 to 2,000 tokens.
- An unrelated guardrail does not outrank the fact that was asked for (this was a real bug; the regression test is named after it).
- **The CSR solver equals a dense reference multiply**, on five random graphs of increasing size plus a graph with dangling nodes and a 2-cycle, to 1e-12 on every rank. An optimisation that computes a different number is a bug, so the equivalence is checked rather than asserted.
- **The CSR solver does 5,000 nodes in under 3 ms**, measured in the test rather than claimed in a comment.
- **The real ONNX model produces 384-d unit vectors** and separates related from unrelated sentences that share no vocabulary. The test *skips* when the model is unavailable — a skipped test is honest; one that passes against the fallback embedder is not.
- **Embedding cache keys include the model id**, so switching models cannot silently serve the old vectors.
- **The guardrail verifier blocks what it should and only that**: real destructive commands block, `git push --force-with-lease` and `rm -rf ./node_modules` do not. Both false positives were found by these tests and fixed.
- **RRF does not lift a rule on a factual question.** This test caught a real design flaw: a decaying weight was not enough, because RRF compares *ranks* and a rank-1 lexical hit wins regardless of how small its weight is. Only a threshold gate fixed it.
- **The corpus validates itself with 24 tests, four of which are negative:** they mutate a valid corpus and assert the validator *catches* it — a leaked multi-hop term, a two-answer query, duplicate graded content, a too-small sample. A validator that always returns `[]` would pass a naive test suite and protect nothing.
- **Cross-tier separation is asserted through the API**, not by scraping the table: Tier B must have a non-zero stale-leakage figure while every Tier A system is exactly 0. If that invariant ever breaks, the "stale leakage" column has gone back to being decorative.
- **The installer refuses to damage a config it cannot parse**, and that refusal is tested. A user's `~/.claude.json` holds their history and their other MCP servers; an installer that "fixes" a file it does not understand is an installer that deletes it. Same rule for a TOML file that would not parse: it fails before writing rather than leaving the agent unable to start.
- **Every writer is idempotent, and the test asserts on the second run.** `install` gets run twice whenever a user is unsure whether it worked. A second run must report `unchanged` and make no backup, not rewrite the file. The rules block uses fenced markers for the same reason: appending on every run is the obvious implementation and it ruins a rules file after three runs.
- **The installer writes nothing outside the location it was told about.** This is a regression test for a real defect: with `--create` it wrote Cline and Claude Desktop configs into the tester's genuine `%APPDATA%` on a machine that has neither installed. `--create` now means "write the file for an agent whose root already exists", not "manufacture an installation tree".
```
tests 251 · pass 251 · fail 0
e2e 17 · pass 17 · fail 0
```
---
## Things that are honestly not done
- **The neural encoder does not improve multi-hop, and it actively hurts it if you let it dominate the seed.** Measured: multi-hop recall is 100% with a sparse seed, 17.5% with a pure neural seed, 62.5% with a mean-centred neural seed, and 96.7% once the two are blended. The root cause is in the diagnosis rather than the tuning — the correct root-cause fact ranks ~1,504th of 1,820 by semantic similarity to its own symptom query, because the corpus builds those pairs to share *no* meaning as well as no vocabulary. A sentence encoder is the wrong tool for that, and the code now says so instead of hiding a blend constant.
- **The vector baseline is still not a strong dense retriever.** It is `all-MiniLM-L6-v2`, a 22 MB quantized model. A larger encoder or a cross-encoder reranker would do better at every semantic task here. It is real and local and needs no API key, which is the claim being made — not that it is state of the art.
- **Token counts are estimated.** `⌈latin/3.6⌉ + wide_chars` with CJK/Hangul/Kana counted as one token each. MiniLM's tokenizer is available but the *context budget* is for the downstream model's tokenizer, which is unknown here. The estimate deliberately over-counts Latin text.
- **Convergence is not always reached in 20 iterations.** The spec's `maxIterations: 20` and `tolerance: 1e-6` are mutually unreachable for a concentrated seed: the $(1-d)p$ term re-injects the same mass every iteration, so the step bottoms out near $0.15\|p\|$ — measured at $\approx 0.0775$. The solver reports `converged: false` with the real residual rather than asserting success. The ranking is stable; the flag is truthful.
- **Guardrail recall is a loss, not a win.** The dense neural baseline scores 83.3% against TC-SynPPR's 75.0%, and BM25 ties at 75.0%. RRF fusion genuinely recovers 5 of 60 queries the graph ranking misses (63.3% → 71.7%) and the hijack rate is 0.00%, but the net result is still 8.3 points behind exact-token matching on queries that are paraphrases of short imperative rules. A graph walk is the wrong shape for that question, and the honest framing is "fusion helped and was not enough".
- **The 0.00% hijack rate is measured on this corpus, not guaranteed on yours.** It holds over the benchmark's 450 factual queries, and `scripts/diagnose-hijack-scope.ts` re-confirms 0/10 on a set of ordinary factual questions against the full 6,820-fact corpus. But the 14-fact demonstration corpus does hijack: *"Where does the events bucket store things?"* returns the guardrail *"Never run a schema migration without taking a verified backup first."* at rank 1, above the correct answer at rank 2. That is a real false positive. The mechanism is corpus size — with fourteen facts a rule needs to outrank only a handful of competitors, and with 6,820 it does not. The screenshot in this README was taken on a real query and does not hide it.
- **Guardrail enforcement is regex-only.** A rule expressible as a pattern is enforced deterministically; a rule stored as prose is `enforceable: false` and cannot block anything. There is no model judging intent, which is a deliberate tradeoff — a guardrail that can be argued with is not a guardrail — but it means most natural-language rules are advisory.
- **Latency: p50 is now competitive, p99 is not.** TC-SynPPR is 7.20 ms at p50 versus 8.92 ms for BM25 and 5.14 ms for the dense baseline; at p99 it is 24.4 ms versus 23.66 ms for BM25 (close) and 14.06 ms for the dense baseline (still behind). The tail is the ONNX encode plus a 20-iteration walk; a production deployment would cache query embeddings. An earlier draft of this README quoted pre-pruning numbers that were roughly twice these — exactly the kind of figure that silently survives a rewrite, which is why `verify-readme.ts` now rejects any latency claim that does not match a measurement.
- **The benchmark is synthetic.** It measures behaviour on a problem with known properties, not on anyone's real memory. A real distribution would have messier chains, ambiguous subjects, and facts that are partly true — none of which are modelled.
- **SQLite is single-writer.** WAL helps concurrent readers, but this is not a distributed system and does not pretend to be.
- **No authentication on the REST API.** It binds loopback only and is meant for local inspection.
- **The installer edits files it does not own, and that cannot be made risk-free.** A `~/.claude.json` may hold history, preferences and other MCP servers. The mitigations are real — timestamped backup first, textual splice instead of parse-and-reserialise for TOML, refusal to touch a file that will not parse, atomic rename — but a config format that changes shape will break this before it breaks anything else. `--dry-run` exists for that reason.
- **Agent detection is a path check, not a guarantee.** Six agents and their standard locations are covered; an agent installed somewhere unusual, or a config at a non-standard path, will be reported as not found. The manual snippets above exist for exactly that case, and `install` never silently decides you do not want an agent you named explicitly.
- **`init-rules` depends on the agent reading the file.** `AGENTS.md` and `CLAUDE.md` are conventions, not a protocol. An agent that ignores its instruction file will ignore this block too; the rules reduce the chance of the agent forgetting the tools, they do not enforce it. Only `memory_verify_action` enforces anything, and only rules with patterns.
---
## Layout
```
src/engine/ types, text layer, CSR graph, embedder, RRF, guardrails, TC-SynPPR, compiler
src/storage/ SQLite store with bi-temporal + commits, MemoryService
src/mcp/ MCP stdio server (8 tools)
src/cli/ agent registry, config writers, rules generator, command dispatch
src/benchmark/ corpus generator + validator, six retrievers, runner, CLI
app/ Next.js inspector (6 API routes + 6 panels)
tests/ engine, storage, corpus, CSR, embedder, RRF, guardrails, MCP, installer
e2e/ Playwright
scripts/ build steps + the diagnostics used to find the bugs described below
```
`scripts/` is kept on purpose. Every file in it is a measurement that disproved a guess — the seed collapse, the corpus aliasing bug, the guardrail boost, the residual mismatch. Deleting them would hide how the current behaviour was arrived at.
---
## Post-mortem: the bugs the benchmark found
The benchmark was written to test the algorithm. It mostly found bugs in the benchmark, the corpus, and my own text layer — which is the useful outcome and worth recording.
**1. A recency floor that drowned lexical evidence.** The seed vector added `0.05 × w_i` to *every* node as a tie-breaker. Over 844 nodes that floor was applied to all of them, L1 normalisation scaled the real signal down, and a query whose answer shared little vocabulary lost to unrelated but recent nodes. Recall collapsed to **8.41%**. Fixed by removing the floor entirely and pruning seeds to the top candidates.
**2. Dead nodes could not be seeded.** With `w_i` used for seeding, an invalidated node scored 0 and the query never landed on it — so the `REPLACED_BY` redirect could never fire. The mechanism was implemented and unreachable. Fixed by splitting `activityWeight` (ranking, zeroes dead nodes) from `seedWeight` (seeding, keeps them reachable).
**3. Age could overturn relevance.** Multiplying similarity by the full decay meant a fact written sixteen days later beat the one the query actually named. "billing rate limit" lost to "gateway rate limit" purely on recency. Fixed by compressing the seed decay to `0.5 + 0.5√w`, so recency breaks ties instead of deciding them.
**4. The corpus aliased its own answers.** Two independent bugs. First, several chains shared `(service, config)` pairs, so one query had many valid answers while the grader accepted one. Then, even with unique pairs, the *config name* alone was shared by ~15 chains, so a query naming only the config matched all of them near-equally and the newest won. Both produced numbers that looked like algorithm failures and were measurement failures. Fixed by making every `(qualifier, parameter)` pair unique.
**5. Plain Jaccard collapsed distinct facts.** Two memories sharing a sentence template ("The X procedure was revised after the Nth incident: it now requires…") scored 0.83 similarity and one was discarded, though the differing words carried all the meaning. Fixed with inverse-frequency weighting inside the compiler, where boilerplate counts for little and the subject counts for a lot.
A sixth was found by looking at a screenshot rather than by a test: the inspector displayed a residual curve ending at `1.7e-6` beside a reported residual of `7.75e-2`. `explain()` had been recomputing the trace from already-normalised seeds. Fixed by recording frames inside `solve()` so the curve is by construction the run that produced the ranking.
### Six more, found when the sample sizes were expanded
Every one of these was invisible at 6–16 samples and became obvious at 200.
**7. A migration question that named the subject.** The old-vocabulary question was originally *"How is the compliance archive configured through the events bucket?"* — and "compliance archive" appears verbatim in the **live** fact. A lexical retriever therefore found the correct answer without ever following the rename. The migration test would have measured nothing while looking like it measured everything. Fixed by naming *only* retired vocabulary in the question, and enforced by an invariant that the live fact may share no content term with it.
**8. A tie reported as a win.** The verdict used `mine >= bestOther`. When `migration_old_vocab` came out 100% for both TC-SynPPR and the static baseline, the table printed **WIN** with a margin of 0.00. A zero margin is not a win. Fixed with a three-state `outcome: win | tie | loss` and an explicit tie branch in both the CLI and the UI.
**9. A margin in the wrong units.** By-kind metrics are fractions while the summary metrics are percentage points. The verdict scaled one and not the other, so a **25-point** gap on multi-hop printed as `0.25` — which reads as a near-tie in the table. Fixed by scaling at the comparison site.
**10. Guardrails that were never buried.** The rules were emitted before the distractors, so they were the *newest* facts in the timeline with nothing after them — the exact opposite of "learned early, then buried under months of work". The rule text and the query set were both fine; the timeline made the test vacuous, and `last_activated_at` reads the timeline. Found by adding an invariant that asserts ≥100 turns follow the last rule, which immediately reported **0**. With the ordering corrected, the rules now sit under 5,000 later turns across 83 corpus hours.
Four of the ten were cases where the instrument was lying, not the thing being measured. Checking that the benchmark *can* fail was worth more than the benchmark.
### And four more, from the performance and embedding work
The upgrade round was supposed to be about speed and neural embeddings. It mostly found places where my own diagnostics were wrong.
**11. A neural seed that destroyed multi-hop recall, and the diagnosis that explained it.** Swapping the sparse seed for 384-d embeddings dropped multi-hop from 100% to **17.5%**. The instinct is to tune the constant until the number recovers. The measurement said something more useful: the best match to a symptom query scored 0.73, the relative floor sat at 0.11, and **1,509 of 1,820 nodes were above the floor**. Taking the top 24 of 1,509 near-identical scores is close to arbitrary, and the correct trigger was not among them.
The cause is that neural cosines have a common baseline — every pair of English sentences scores 0.1–0.3 — so a fixed top-k cut that works on sparse cosines (where unrelated documents score ~0) prunes nothing. Centring recovered 17.5% → 62.5%. Blending sparse and neural at 0.5 recovered it to 96.7%. The blend is documented as a measured compromise, not a discovery: the corpus's multi-hop pairs share no *meaning* either, so the encoder cannot help there and the sparse path does the work.
**12. A diagnostic that reported 73.3% for a configuration scoring 65.0%.** The gap came from building the index by hand instead of through the runner: the script never called `bulkLink`, so `edges: 0` and every system silently fell back to lexical ranking. A benchmark harness that measures a graph system with no graph is not a slightly wrong measurement, it is a different system. The script now creates the edges and prints the count, so the failure is visible next time.
**13. A "placeholder" regex that blocked everything.** One builtin rule carried `requiredPattern: "(?!)"` as a comment-documented no-op. `(?!)` is an always-*failing* assertion, not an always-passing one, so every action became a required-pattern violation and the verifier returned BLOCKED for `npm run build`. The lesson went into the suite: a pattern that is supposed to be inert needs a test, because it is indistinguishable from a bug.
**14. A guardrail gate that let unrelated rules win.** RRF with a plain specificity *weight* did not protect precision, and the test written to check that caught it immediately: at specificity 0.0 on "What is the billing timeout set to?", the rules still took ranks 1 and 2 — because RRF compares **ranks**, so a rank-1 lexical hit contributes the same `1/61` no matter how small its weight. A decaying weight cannot express "this signal is not applicable". Only a threshold gate could, and the measured false-positive hijack rate is 0.00% with the gate versus a rule at the top of every factual answer without it.
Every one of these four was found by measuring, not by reading. Three of them were bugs in the instrument rather than the thing being measured.
### Profiling, and the optimisation that was not where I expected
The CSR rewrite took the solve from ~4 ms to **1.26 ms** on 6,500 nodes, which is the number the module was written for. End-to-end latency did not move: it stayed at ~24 ms, and the breakdown said why —
```
buildTransitions (rebuilt every query) 0.69 ms
buildSeedVector 20.87 ms <-- the actual cost
solve (CSR) 1.15 ms
encode one query (ONNX) 1.33 ms
```
`buildSeedVector` was computing a cosine against all 6,820 nodes to discover that most were exactly zero. An inverted index fixed the sparse path (20.9 ms → **1.12 ms**), but not the neural one, until the same diagnostic that explained bug #11 justified pruning there too: the correct multi-hop answer ranks 1,504th by semantic similarity, so it is reached by *walking edges*, not by being semantically close. Pruning the neural candidate set to the vocabulary neighbourhood raised recall slightly (95.69% → 96.67%) and cut p50 from 24.4 ms to **7.5 ms**.
The honest summary is that the scheduled optimisation was worth 1.4 ms and the unscheduled one was worth 17 ms. Only the profiler knew that in advance, and I did not.
---
## Related project
[**OpenForge-30**](https://github.com/cndoin/OpenForge-30) — 30 self-hosted, full-stack SaaS
replacements, each verified by end-to-end tests (745 total). Same preference for measured
claims over asserted ones.
---
## License
MIT
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues